clang-tools 23.0.0git
PassByValueCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "PassByValueCheck.h"
10#include "clang/AST/ASTContext.h"
11#include "clang/AST/RecursiveASTVisitor.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/ASTMatchers/ASTMatchers.h"
14#include "clang/Frontend/CompilerInstance.h"
15#include "clang/Lex/Lexer.h"
16#include "clang/Lex/Preprocessor.h"
17
18using namespace clang::ast_matchers;
19using namespace llvm;
20
21namespace clang::tidy::modernize {
22
23static bool isFirstFriendOfSecond(const CXXRecordDecl *Friend,
24 const CXXRecordDecl *Class) {
25 return llvm::any_of(
26 Class->friends(), [Friend](FriendDecl *FriendDecl) -> bool {
27 if (const TypeSourceInfo *FriendTypeSource =
28 FriendDecl->getFriendType()) {
29 const QualType FriendType = FriendTypeSource->getType();
30 return FriendType->getAsCXXRecordDecl() == Friend;
31 }
32 return false;
33 });
34}
35
36namespace {
37/// Matches move-constructible classes whose constructor can be called inside
38/// a CXXRecordDecl with a bound ID.
39///
40/// Given
41/// \code
42/// // POD types are trivially move constructible.
43/// struct Foo { int a; };
44///
45/// struct Bar {
46/// Bar(Bar &&) = deleted;
47/// int a;
48/// };
49///
50/// class Buz {
51/// Buz(Buz &&);
52/// int a;
53/// friend class Outer;
54/// };
55///
56/// class Outer {
57/// };
58/// \endcode
59/// recordDecl(isMoveConstructibleInBoundCXXRecordDecl("Outer"))
60/// matches "Foo", "Buz".
61AST_MATCHER_P(CXXRecordDecl, isMoveConstructibleInBoundCXXRecordDecl, StringRef,
62 RecordDeclID) {
63 return Builder->removeBindings(
64 [this,
65 &Node](const ast_matchers::internal::BoundNodesMap &Nodes) -> bool {
66 const auto *BoundClass =
67 Nodes.getNode(this->RecordDeclID).get<CXXRecordDecl>();
68 for (const CXXConstructorDecl *Ctor : Node.ctors())
69 if (Ctor->isMoveConstructor() && !Ctor->isDeleted() &&
70 (Ctor->getAccess() == AS_public ||
71 (BoundClass && isFirstFriendOfSecond(BoundClass, &Node))))
72 return false;
73 return true;
74 });
75}
76} // namespace
77
78static TypeMatcher notTemplateSpecConstRefType() {
79 return lValueReferenceType(
80 pointee(unless(templateSpecializationType()), isConstQualified()));
81}
82
83static TypeMatcher nonConstValueType() {
84 return qualType(unless(anyOf(referenceType(), isConstQualified())));
85}
86
87/// Whether or not \p ParamDecl is used exactly one time in \p Ctor.
88///
89/// Checks both in the init-list and the body of the constructor.
90static bool paramReferredExactlyOnce(const CXXConstructorDecl *Ctor,
91 const ParmVarDecl *ParamDecl) {
92 /// \c clang::RecursiveASTVisitor that checks that the given
93 /// \c ParmVarDecl is used exactly one time.
94 ///
95 /// \see ExactlyOneUsageVisitor::hasExactlyOneUsageIn()
96 class ExactlyOneUsageVisitor
97 : public RecursiveASTVisitor<ExactlyOneUsageVisitor> {
98 friend class RecursiveASTVisitor<ExactlyOneUsageVisitor>;
99
100 public:
101 ExactlyOneUsageVisitor(const ParmVarDecl *ParamDecl)
102 : ParamDecl(ParamDecl) {}
103
104 /// Whether or not the parameter variable is referred only once in
105 /// the
106 /// given constructor.
107 bool hasExactlyOneUsageIn(const CXXConstructorDecl *Ctor) {
108 Count = 0U;
109 TraverseDecl(const_cast<CXXConstructorDecl *>(Ctor));
110 return Count == 1U;
111 }
112
113 private:
114 /// Counts the number of references to a variable.
115 ///
116 /// Stops the AST traversal if more than one usage is found.
117 bool VisitDeclRefExpr(DeclRefExpr *D) {
118 if (const ParmVarDecl *To = dyn_cast<ParmVarDecl>(D->getDecl())) {
119 if (To == ParamDecl) {
120 ++Count;
121 if (Count > 1U) {
122 // No need to look further, used more than once.
123 return false;
124 }
125 }
126 }
127 return true;
128 }
129
130 const ParmVarDecl *ParamDecl;
131 unsigned Count = 0U;
132 };
133
134 return ExactlyOneUsageVisitor(ParamDecl).hasExactlyOneUsageIn(Ctor);
135}
136
137/// Returns true if the given constructor is part of a lvalue/rvalue reference
138/// pair, i.e. `Param` is of lvalue reference type, and there exists another
139/// constructor such that:
140/// - it has the same number of parameters as `Ctor`.
141/// - the parameter at the same index as `Param` is an rvalue reference
142/// of the same pointee type
143/// - all other parameters have the same type as the corresponding parameter in
144/// `Ctor` or are rvalue references with the same pointee type.
145/// Examples:
146/// A::A(const B& Param)
147/// A::A(B&&)
148///
149/// A::A(const B& Param, const C&)
150/// A::A(B&& Param, C&&)
151///
152/// A::A(const B&, const C& Param)
153/// A::A(B&&, C&& Param)
154///
155/// A::A(const B&, const C& Param)
156/// A::A(const B&, C&& Param)
157///
158/// A::A(const B& Param, int)
159/// A::A(B&& Param, int)
160static bool hasRValueOverload(const CXXConstructorDecl *Ctor,
161 const ParmVarDecl *Param) {
162 if (!Param->getType().getCanonicalType()->isLValueReferenceType()) {
163 // The parameter is passed by value.
164 return false;
165 }
166 const int ParamIdx = Param->getFunctionScopeIndex();
167 const CXXRecordDecl *Record = Ctor->getParent();
168
169 // Check whether a ctor `C` forms a pair with `Ctor` under the aforementioned
170 // rules.
171 const auto IsRValueOverload = [&Ctor, ParamIdx](const CXXConstructorDecl *C) {
172 if (C == Ctor || C->isDeleted() ||
173 C->getNumParams() != Ctor->getNumParams())
174 return false;
175 for (int I = 0, E = C->getNumParams(); I < E; ++I) {
176 const QualType CandidateParamType =
177 C->parameters()[I]->getType().getCanonicalType();
178 const QualType CtorParamType =
179 Ctor->parameters()[I]->getType().getCanonicalType();
180 const bool IsLValueRValuePair =
181 CtorParamType->isLValueReferenceType() &&
182 CandidateParamType->isRValueReferenceType() &&
183 CandidateParamType->getPointeeType()->getUnqualifiedDesugaredType() ==
184 CtorParamType->getPointeeType()->getUnqualifiedDesugaredType();
185 if (I == ParamIdx) {
186 // The parameter of interest must be paired.
187 if (!IsLValueRValuePair)
188 return false;
189 } else {
190 // All other parameters can be similar or paired.
191 if (!(CandidateParamType == CtorParamType || IsLValueRValuePair))
192 return false;
193 }
194 }
195 return true;
196 };
197
198 return llvm::any_of(Record->ctors(), IsRValueOverload);
199}
200
201/// Find all references to \p ParamDecl across all of the
202/// redeclarations of \p Ctor.
204collectParamDecls(const CXXConstructorDecl *Ctor,
205 const ParmVarDecl *ParamDecl) {
207 const unsigned ParamIdx = ParamDecl->getFunctionScopeIndex();
208
209 for (const FunctionDecl *Redecl : Ctor->redecls())
210 Results.push_back(Redecl->getParamDecl(ParamIdx));
211 return Results;
212}
213
215 : ClangTidyCheck(Name, Context),
216 Inserter(Options.getLocalOrGlobal("IncludeStyle",
217 utils::IncludeSorter::IS_LLVM),
218 areDiagsSelfContained()),
219 ValuesOnly(Options.get("ValuesOnly", false)),
220 IgnoreMacros(Options.get("IgnoreMacros", false)) {}
221
223 Options.store(Opts, "IncludeStyle", Inserter.getStyle());
224 Options.store(Opts, "ValuesOnly", ValuesOnly);
225 Options.store(Opts, "IgnoreMacros", IgnoreMacros);
226}
227
228void PassByValueCheck::registerMatchers(MatchFinder *Finder) {
229 Finder->addMatcher(
230 traverse(
231 TK_AsIs,
232 cxxConstructorDecl(
233 ofClass(cxxRecordDecl().bind("outer")),
234 forEachConstructorInitializer(
235 cxxCtorInitializer(
236 unless(isBaseInitializer()),
237 // Clang builds a CXXConstructExpr only when it knows
238 // which constructor will be called. In dependent contexts
239 // a ParenListExpr is generated instead of a
240 // CXXConstructExpr, filtering out templates automatically
241 // for us.
242 withInitializer(cxxConstructExpr(
243 has(ignoringParenImpCasts(declRefExpr(to(
244 parmVarDecl(
245 hasType(qualType(
246 // Match only const-ref or a non-const
247 // value parameters. Rvalues,
248 // TemplateSpecializationValues and
249 // const-values shouldn't be modified.
250 ValuesOnly
254 .bind("Param"))))),
255 hasDeclaration(cxxConstructorDecl(
256 isCopyConstructor(), unless(isDeleted()),
257 hasDeclContext(cxxRecordDecl(
258 isMoveConstructibleInBoundCXXRecordDecl(
259 "outer"))))))))
260 .bind("Initializer")))
261 .bind("Ctor")),
262 this);
263}
264
265void PassByValueCheck::registerPPCallbacks(const SourceManager &SM,
266 Preprocessor *PP,
267 Preprocessor *ModuleExpanderPP) {
268 Inserter.registerPreprocessor(PP);
269}
270
271void PassByValueCheck::check(const MatchFinder::MatchResult &Result) {
272 const auto *Ctor = Result.Nodes.getNodeAs<CXXConstructorDecl>("Ctor");
273 const auto *ParamDecl = Result.Nodes.getNodeAs<ParmVarDecl>("Param");
274 const auto *Initializer =
275 Result.Nodes.getNodeAs<CXXCtorInitializer>("Initializer");
276 const SourceManager &SM = *Result.SourceManager;
277
278 if (IgnoreMacros && ParamDecl->getBeginLoc().isMacroID())
279 return;
280
281 // If the parameter is used or anything other than the copy, do not apply
282 // the changes.
283 if (!paramReferredExactlyOnce(Ctor, ParamDecl))
284 return;
285
286 // If the parameter is trivial to copy, don't move it. Moving a trivially
287 // copyable type will cause a problem with performance-move-const-arg
288 if (ParamDecl->getType().getNonReferenceType().isTriviallyCopyableType(
289 *Result.Context))
290 return;
291
292 // Do not trigger if we find a paired constructor with an rvalue.
293 if (hasRValueOverload(Ctor, ParamDecl))
294 return;
295
296 auto Diag = diag(ParamDecl->getBeginLoc(), "pass by value and use std::move");
297
298 // If we received a `const&` type, we need to rewrite the function
299 // declarations.
300 if (ParamDecl->getType()->isLValueReferenceType()) {
301 // Check if we can succesfully rewrite all declarations of the constructor.
302 for (const ParmVarDecl *ParmDecl : collectParamDecls(Ctor, ParamDecl)) {
303 const TypeLoc ParamTL = ParmDecl->getTypeSourceInfo()->getTypeLoc();
304 auto RefTL = ParamTL.getAs<ReferenceTypeLoc>();
305 if (RefTL.isNull()) {
306 // We cannot rewrite this instance. The type is probably hidden behind
307 // some `typedef`. Do not offer a fix-it in this case.
308 return;
309 }
310 }
311 // Rewrite all declarations.
312 for (const ParmVarDecl *ParmDecl : collectParamDecls(Ctor, ParamDecl)) {
313 const TypeLoc ParamTL = ParmDecl->getTypeSourceInfo()->getTypeLoc();
314 auto RefTL = ParamTL.getAs<ReferenceTypeLoc>();
315
316 const TypeLoc ValueTL = RefTL.getPointeeLoc();
317 const CharSourceRange TypeRange = CharSourceRange::getTokenRange(
318 ParmDecl->getBeginLoc(), ParamTL.getEndLoc());
319 std::string ValueStr =
320 Lexer::getSourceText(
321 CharSourceRange::getTokenRange(ValueTL.getSourceRange()), SM,
322 getLangOpts())
323 .str();
324 ValueStr += ' ';
325 Diag << FixItHint::CreateReplacement(TypeRange, ValueStr);
326 }
327 }
328
329 // Use std::move in the initialization list.
330 Diag << FixItHint::CreateInsertion(Initializer->getRParenLoc(), ")")
331 << FixItHint::CreateInsertion(
332 Initializer->getLParenLoc().getLocWithOffset(1), "std::move(")
333 << Inserter.createIncludeInsertion(
334 Result.SourceManager->getFileID(Initializer->getSourceLocation()),
335 "<utility>");
336}
337
338} // namespace clang::tidy::modernize
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
PassByValueCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
static SmallVector< const ParmVarDecl *, 2 > collectParamDecls(const CXXConstructorDecl *Ctor, const ParmVarDecl *ParamDecl)
Find all references to ParamDecl across all of the redeclarations of Ctor.
static bool hasRValueOverload(const CXXConstructorDecl *Ctor, const ParmVarDecl *Param)
Returns true if the given constructor is part of a lvalue/rvalue reference pair, i....
static bool isFirstFriendOfSecond(const CXXRecordDecl *Friend, const CXXRecordDecl *Class)
static bool paramReferredExactlyOnce(const CXXConstructorDecl *Ctor, const ParmVarDecl *ParamDecl)
Whether or not ParamDecl is used exactly one time in Ctor.
static TypeMatcher nonConstValueType()
static TypeMatcher notTemplateSpecConstRefType()
Some operations such as code completion produce a set of candidates.
Definition Generators.h:150
llvm::StringMap< ClangTidyValue > OptionMap