bump product version to 6.4.0.3
[LibreOffice.git] / compilerplugins / clang / passparamsbyref.cxx
blob7de7133f3aed9f95cd827a8bc08e0e732657742c
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
9 #ifndef LO_CLANG_SHARED_PLUGINS
11 #include <string>
12 #include <unordered_set>
14 #include "check.hxx"
15 #include "compat.hxx"
16 #include "plugin.hxx"
18 // Find places where parameters are passed by value
19 // It's not very efficient, because we generally end up copying it twice - once into the parameter and
20 // again into the destination.
21 // They should rather be passed by reference.
23 // Generally recommending lambda capture by-ref rather than by-copy is even more
24 // problematic than with function parameters, as a lambda instance can easily
25 // outlive a referenced variable. So once lambdas start to get used in more
26 // sophisticated ways than passing them into standard algorithms, this plugin's
27 // advice, at least for explicit captures, will need to be revisited.
29 namespace {
31 class PassParamsByRef:
32 public loplugin::FilteringPlugin<PassParamsByRef>
34 public:
35 explicit PassParamsByRef(loplugin::InstantiationData const & data): FilteringPlugin(data), mbInsideFunctionDecl(false) {}
37 virtual void run() override { TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); }
39 // When warning about function params of primitive type that could be passed
40 // by value instead of by reference, make sure not to warn if the parameter
41 // is ever bound to a reference; on the one hand, this needs scaffolding in
42 // all Traverse*Decl functions (indirectly) derived from FunctionDecl; and
43 // on the other hand, use a hack of ignoring just the DeclRefExprs nested in
44 // LValueToRValue ImplicitCastExprs when determining whether a param is
45 // bound to a reference:
46 bool PreTraverseFunctionDecl(FunctionDecl *);
47 bool PostTraverseFunctionDecl(FunctionDecl *, bool);
48 bool TraverseFunctionDecl(FunctionDecl *);
49 bool PreTraverseImplicitCastExpr(ImplicitCastExpr *);
50 bool TraverseImplicitCastExpr(ImplicitCastExpr *);
52 bool VisitBinAssign(BinaryOperator const *);
53 bool VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *);
55 private:
56 bool isFat(QualType type);
58 bool mbInsideFunctionDecl;
59 std::unordered_set<ParmVarDecl const *> mParamExclusions;
62 bool PassParamsByRef::PreTraverseFunctionDecl(FunctionDecl* functionDecl)
64 if (ignoreLocation(functionDecl))
65 return false;
66 if (functionDecl->isDeleted()
67 || functionDecl->isFunctionTemplateSpecialization())
69 return false;
71 // only consider base declarations, not overridden ones, or we warn on methods that
72 // are overriding stuff from external libraries
73 const CXXMethodDecl * methodDecl = dyn_cast<CXXMethodDecl>(functionDecl);
74 if (methodDecl && methodDecl->size_overridden_methods() > 0)
75 return false;
77 // Only warn on the definition of the function:
78 if (!functionDecl->doesThisDeclarationHaveABody())
79 return false;
81 mbInsideFunctionDecl = true;
82 mParamExclusions.clear();
83 return true;
86 bool PassParamsByRef::PostTraverseFunctionDecl(FunctionDecl* functionDecl, bool)
88 mbInsideFunctionDecl = false;
90 auto cxxConstructorDecl = dyn_cast<CXXConstructorDecl>(functionDecl);
91 unsigned n = functionDecl->getNumParams();
92 for (unsigned i = 0; i != n; ++i) {
93 const ParmVarDecl * pvDecl = functionDecl->getParamDecl(i);
94 auto const t = pvDecl->getType();
95 if (!isFat(t))
96 continue;
97 if (mParamExclusions.find(pvDecl) != mParamExclusions.end())
98 continue;
99 // Ignore cases where the parameter is std::move'd.
100 // This is a fairly simple check, might need some more complexity if the parameter is std::move'd
101 // somewhere else in the constructor.
102 bool bFoundMove = false;
103 if (cxxConstructorDecl) {
104 for (CXXCtorInitializer const * cxxCtorInitializer : cxxConstructorDecl->inits()) {
105 if (cxxCtorInitializer->isMemberInitializer())
107 auto cxxConstructExpr = dyn_cast<CXXConstructExpr>(cxxCtorInitializer->getInit()->IgnoreParenImpCasts());
108 if (cxxConstructExpr && cxxConstructExpr->getNumArgs() == 1)
110 if (auto callExpr = dyn_cast<CallExpr>(cxxConstructExpr->getArg(0)->IgnoreParenImpCasts())) {
111 if (loplugin::DeclCheck(callExpr->getCalleeDecl()).Function("move").StdNamespace()) {
112 bFoundMove = true;
113 break;
120 if (bFoundMove)
121 continue;
122 report(
123 DiagnosticsEngine::Warning,
124 ("passing %0 by value, rather pass by const lvalue reference"),
125 pvDecl->getLocation())
126 << t << pvDecl->getSourceRange();
127 auto can = functionDecl->getCanonicalDecl();
128 if (can->getLocation() != functionDecl->getLocation()) {
129 report(
130 DiagnosticsEngine::Note, "function is declared here:",
131 can->getLocation())
132 << can->getSourceRange();
135 return true;
138 bool PassParamsByRef::TraverseFunctionDecl(FunctionDecl* functionDecl)
140 bool ret = true;
141 if (PreTraverseFunctionDecl(functionDecl))
143 ret = RecursiveASTVisitor::TraverseFunctionDecl(functionDecl);
144 PostTraverseFunctionDecl(functionDecl, ret);
146 return ret;
149 bool PassParamsByRef::PreTraverseImplicitCastExpr(ImplicitCastExpr * expr)
151 if (ignoreLocation(expr))
152 return false;
153 if (expr->getCastKind() == CK_LValueToRValue
154 && isa<DeclRefExpr>(expr->getSubExpr()->IgnoreParenImpCasts()))
155 return false;
156 return true;
159 bool PassParamsByRef::TraverseImplicitCastExpr(ImplicitCastExpr * expr)
161 bool ret = true;
162 if (PreTraverseImplicitCastExpr(expr))
164 ret = RecursiveASTVisitor::TraverseImplicitCastExpr(expr);
166 return ret;
169 bool PassParamsByRef::VisitBinAssign(const BinaryOperator * binaryOperator)
171 if (!mbInsideFunctionDecl)
172 return true;
173 // if we are assigning to a parameter, it can be inconvenient to make the param pass-by-ref
174 if (auto declRefExpr = dyn_cast<DeclRefExpr>(binaryOperator->getLHS()))
176 if (auto parmVarDecl = dyn_cast<ParmVarDecl>(declRefExpr->getDecl()))
177 mParamExclusions.emplace(parmVarDecl);
179 return true;
182 bool PassParamsByRef::VisitCXXOperatorCallExpr(const CXXOperatorCallExpr * cxxOperatorCallExpr )
184 if (!mbInsideFunctionDecl)
185 return true;
186 // if we are assigning to a parameter, it can be inconvenient to make the param pass-by-ref
187 auto op = cxxOperatorCallExpr->getOperator();
188 if ( op != clang::OverloadedOperatorKind::OO_Equal
189 && op != clang::OverloadedOperatorKind::OO_SlashEqual
190 && op != clang::OverloadedOperatorKind::OO_StarEqual
191 && op != clang::OverloadedOperatorKind::OO_MinusEqual
192 && op != clang::OverloadedOperatorKind::OO_PlusEqual)
193 return true;
194 auto declRefExpr = dyn_cast<DeclRefExpr>(cxxOperatorCallExpr->getArg(0));
195 if (!declRefExpr)
196 return true;
197 if (auto parmVarDecl = dyn_cast<ParmVarDecl>(declRefExpr->getDecl()))
198 mParamExclusions.emplace(parmVarDecl);
199 return true;
202 bool PassParamsByRef::isFat(QualType type) {
203 if (!type->isRecordType()) {
204 return false;
206 loplugin::TypeCheck tc(type);
207 if ((tc.Class("Reference").Namespace("uno").Namespace("star")
208 .Namespace("sun").Namespace("com").GlobalNamespace())
209 || (tc.Class("Sequence").Namespace("uno").Namespace("star")
210 .Namespace("sun").Namespace("com").GlobalNamespace())
211 || tc.Class("OString").Namespace("rtl").GlobalNamespace()
212 || tc.Class("OUString").Namespace("rtl").GlobalNamespace()
213 || tc.Class("Reference").Namespace("rtl").GlobalNamespace())
215 return true;
217 if (type->isIncompleteType()) {
218 return false;
220 clang::Type const * t2 = type.getTypePtrOrNull();
221 return t2 != nullptr
222 && compiler.getASTContext().getTypeSizeInChars(t2).getQuantity() > 64;
225 loplugin::Plugin::Registration< PassParamsByRef > passparamsbyref("passparamsbyref");
227 } // namespace
229 #endif // LO_CLANG_SHARED_PLUGINS
231 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */