clang-tools 22.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 }
74 return true;
75 });
76}
77} // namespace
78
79static TypeMatcher notTemplateSpecConstRefType() {
80 return lValueReferenceType(
81 pointee(unless(templateSpecializationType()), isConstQualified()));
82}
83
84static TypeMatcher nonConstValueType() {
85 return qualType(unless(anyOf(referenceType(), isConstQualified())));
86}
87
88/// Whether or not \p ParamDecl is used exactly one time in \p Ctor.
89///
90/// Checks both in the init-list and the body of the constructor.
91static bool paramReferredExactlyOnce(const CXXConstructorDecl *Ctor,
92 const ParmVarDecl *ParamDecl) {
93 /// \c clang::RecursiveASTVisitor that checks that the given
94 /// \c ParmVarDecl is used exactly one time.
95 ///
96 /// \see ExactlyOneUsageVisitor::hasExactlyOneUsageIn()
97 class ExactlyOneUsageVisitor
98 : public RecursiveASTVisitor<ExactlyOneUsageVisitor> {
99 friend class RecursiveASTVisitor<ExactlyOneUsageVisitor>;
100
101 public:
102 ExactlyOneUsageVisitor(const ParmVarDecl *ParamDecl)
103 : ParamDecl(ParamDecl) {}
104
105 /// Whether or not the parameter variable is referred only once in
106 /// the
107 /// given constructor.
108 bool hasExactlyOneUsageIn(const CXXConstructorDecl *Ctor) {
109 Count = 0U;
110 TraverseDecl(const_cast<CXXConstructorDecl *>(Ctor));
111 return Count == 1U;
112 }
113
114 private:
115 /// Counts the number of references to a variable.
116 ///
117 /// Stops the AST traversal if more than one usage is found.
118 bool VisitDeclRefExpr(DeclRefExpr *D) {
119 if (const ParmVarDecl *To = dyn_cast<ParmVarDecl>(D->getDecl())) {
120 if (To == ParamDecl) {
121 ++Count;
122 if (Count > 1U) {
123 // No need to look further, used more than once.
124 return false;
125 }
126 }
127 }
128 return true;
129 }
130
131 const ParmVarDecl *ParamDecl;
132 unsigned Count = 0U;
133 };
134
135 return ExactlyOneUsageVisitor(ParamDecl).hasExactlyOneUsageIn(Ctor);
136}
137
138/// Returns true if the given constructor is part of a lvalue/rvalue reference
139/// pair, i.e. `Param` is of lvalue reference type, and there exists another
140/// constructor such that:
141/// - it has the same number of parameters as `Ctor`.
142/// - the parameter at the same index as `Param` is an rvalue reference
143/// of the same pointee type
144/// - all other parameters have the same type as the corresponding parameter in
145/// `Ctor` or are rvalue references with the same pointee type.
146/// Examples:
147/// A::A(const B& Param)
148/// A::A(B&&)
149///
150/// A::A(const B& Param, const C&)
151/// A::A(B&& Param, C&&)
152///
153/// A::A(const B&, const C& Param)
154/// A::A(B&&, C&& Param)
155///
156/// A::A(const B&, const C& Param)
157/// A::A(const B&, C&& Param)
158///
159/// A::A(const B& Param, int)
160/// A::A(B&& Param, int)
161static bool hasRValueOverload(const CXXConstructorDecl *Ctor,
162 const ParmVarDecl *Param) {
163 if (!Param->getType().getCanonicalType()->isLValueReferenceType()) {
164 // The parameter is passed by value.
165 return false;
166 }
167 const int ParamIdx = Param->getFunctionScopeIndex();
168 const CXXRecordDecl *Record = Ctor->getParent();
169
170 // Check whether a ctor `C` forms a pair with `Ctor` under the aforementioned
171 // rules.
172 const auto IsRValueOverload = [&Ctor, ParamIdx](const CXXConstructorDecl *C) {
173 if (C == Ctor || C->isDeleted() ||
174 C->getNumParams() != Ctor->getNumParams())
175 return false;
176 for (int I = 0, E = C->getNumParams(); I < E; ++I) {
177 const clang::QualType CandidateParamType =
178 C->parameters()[I]->getType().getCanonicalType();
179 const clang::QualType CtorParamType =
180 Ctor->parameters()[I]->getType().getCanonicalType();
181 const bool IsLValueRValuePair =
182 CtorParamType->isLValueReferenceType() &&
183 CandidateParamType->isRValueReferenceType() &&
184 CandidateParamType->getPointeeType()->getUnqualifiedDesugaredType() ==
185 CtorParamType->getPointeeType()->getUnqualifiedDesugaredType();
186 if (I == ParamIdx) {
187 // The parameter of interest must be paired.
188 if (!IsLValueRValuePair)
189 return false;
190 } else {
191 // All other parameters can be similar or paired.
192 if (!(CandidateParamType == CtorParamType || IsLValueRValuePair))
193 return false;
194 }
195 }
196 return true;
197 };
198
199 return llvm::any_of(Record->ctors(), IsRValueOverload);
200}
201
202/// Find all references to \p ParamDecl across all of the
203/// redeclarations of \p Ctor.
204static SmallVector<const ParmVarDecl *, 2>
205collectParamDecls(const CXXConstructorDecl *Ctor,
206 const ParmVarDecl *ParamDecl) {
207 SmallVector<const ParmVarDecl *, 2> Results;
208 const unsigned ParamIdx = ParamDecl->getFunctionScopeIndex();
209
210 for (const FunctionDecl *Redecl : Ctor->redecls())
211 Results.push_back(Redecl->getParamDecl(ParamIdx));
212 return Results;
213}
214
216 : ClangTidyCheck(Name, Context),
217 Inserter(Options.getLocalOrGlobal("IncludeStyle",
218 utils::IncludeSorter::IS_LLVM),
219 areDiagsSelfContained()),
220 ValuesOnly(Options.get("ValuesOnly", false)) {}
221
223 Options.store(Opts, "IncludeStyle", Inserter.getStyle());
224 Options.store(Opts, "ValuesOnly", ValuesOnly);
225}
226
227void PassByValueCheck::registerMatchers(MatchFinder *Finder) {
228 Finder->addMatcher(
229 traverse(
230 TK_AsIs,
231 cxxConstructorDecl(
232 ofClass(cxxRecordDecl().bind("outer")),
233 forEachConstructorInitializer(
234 cxxCtorInitializer(
235 unless(isBaseInitializer()),
236 // Clang builds a CXXConstructExpr only when it knows
237 // which constructor will be called. In dependent contexts
238 // a ParenListExpr is generated instead of a
239 // CXXConstructExpr, filtering out templates automatically
240 // for us.
241 withInitializer(cxxConstructExpr(
242 has(ignoringParenImpCasts(declRefExpr(to(
243 parmVarDecl(
244 hasType(qualType(
245 // Match only const-ref or a non-const
246 // value parameters. Rvalues,
247 // TemplateSpecializationValues and
248 // const-values shouldn't be modified.
249 ValuesOnly
253 .bind("Param"))))),
254 hasDeclaration(cxxConstructorDecl(
255 isCopyConstructor(), unless(isDeleted()),
256 hasDeclContext(cxxRecordDecl(
257 isMoveConstructibleInBoundCXXRecordDecl(
258 "outer"))))))))
259 .bind("Initializer")))
260 .bind("Ctor")),
261 this);
262}
263
264void PassByValueCheck::registerPPCallbacks(const SourceManager &SM,
265 Preprocessor *PP,
266 Preprocessor *ModuleExpanderPP) {
267 Inserter.registerPreprocessor(PP);
268}
269
270void PassByValueCheck::check(const MatchFinder::MatchResult &Result) {
271 const auto *Ctor = Result.Nodes.getNodeAs<CXXConstructorDecl>("Ctor");
272 const auto *ParamDecl = Result.Nodes.getNodeAs<ParmVarDecl>("Param");
273 const auto *Initializer =
274 Result.Nodes.getNodeAs<CXXCtorInitializer>("Initializer");
275 const SourceManager &SM = *Result.SourceManager;
276
277 // If the parameter is used or anything other than the copy, do not apply
278 // the changes.
279 if (!paramReferredExactlyOnce(Ctor, ParamDecl))
280 return;
281
282 // If the parameter is trivial to copy, don't move it. Moving a trivially
283 // copyable type will cause a problem with performance-move-const-arg
284 if (ParamDecl->getType().getNonReferenceType().isTriviallyCopyableType(
285 *Result.Context))
286 return;
287
288 // Do not trigger if we find a paired constructor with an rvalue.
289 if (hasRValueOverload(Ctor, ParamDecl))
290 return;
291
292 auto Diag = diag(ParamDecl->getBeginLoc(), "pass by value and use std::move");
293
294 // If we received a `const&` type, we need to rewrite the function
295 // declarations.
296 if (ParamDecl->getType()->isLValueReferenceType()) {
297 // Check if we can succesfully rewrite all declarations of the constructor.
298 for (const ParmVarDecl *ParmDecl : collectParamDecls(Ctor, ParamDecl)) {
299 const TypeLoc ParamTL = ParmDecl->getTypeSourceInfo()->getTypeLoc();
300 auto RefTL = ParamTL.getAs<ReferenceTypeLoc>();
301 if (RefTL.isNull()) {
302 // We cannot rewrite this instance. The type is probably hidden behind
303 // some `typedef`. Do not offer a fix-it in this case.
304 return;
305 }
306 }
307 // Rewrite all declarations.
308 for (const ParmVarDecl *ParmDecl : collectParamDecls(Ctor, ParamDecl)) {
309 const TypeLoc ParamTL = ParmDecl->getTypeSourceInfo()->getTypeLoc();
310 auto RefTL = ParamTL.getAs<ReferenceTypeLoc>();
311
312 const TypeLoc ValueTL = RefTL.getPointeeLoc();
313 const CharSourceRange TypeRange = CharSourceRange::getTokenRange(
314 ParmDecl->getBeginLoc(), ParamTL.getEndLoc());
315 std::string ValueStr =
316 Lexer::getSourceText(
317 CharSourceRange::getTokenRange(ValueTL.getSourceRange()), SM,
318 getLangOpts())
319 .str();
320 ValueStr += ' ';
321 Diag << FixItHint::CreateReplacement(TypeRange, ValueStr);
322 }
323 }
324
325 // Use std::move in the initialization list.
326 Diag << FixItHint::CreateInsertion(Initializer->getRParenLoc(), ")")
327 << FixItHint::CreateInsertion(
328 Initializer->getLParenLoc().getLocWithOffset(1), "std::move(")
329 << Inserter.createIncludeInsertion(
330 Result.SourceManager->getFileID(Initializer->getSourceLocation()),
331 "<utility>");
332}
333
334} // 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:146
llvm::StringMap< ClangTidyValue > OptionMap