clang-tools 23.0.0git
UseAfterMoveCheck.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 "UseAfterMoveCheck.h"
10
11#include "clang/AST/Attr.h"
12#include "clang/AST/Expr.h"
13#include "clang/AST/ExprCXX.h"
14#include "clang/ASTMatchers/ASTMatchers.h"
15#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
16#include "clang/Analysis/CFG.h"
17#include "clang/Lex/Lexer.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallPtrSet.h"
20
22#include "../utils/Matchers.h"
24#include <optional>
25
26using namespace clang::ast_matchers;
27using namespace clang::tidy::utils;
28
29namespace clang::tidy::bugprone {
30
31using matchers::hasUnevaluatedContext;
32
33namespace {
34AST_MATCHER_P(Expr, hasParentIgnoringParenImpCasts,
35 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
36 const Expr *E = &Node;
37 do {
38 const DynTypedNodeList Parents = Finder->getASTContext().getParents(*E);
39 if (Parents.size() != 1)
40 return false;
41 E = Parents[0].get<Expr>();
42 if (!E)
43 return false;
44 } while (isa<ImplicitCastExpr, ParenExpr>(E));
45
46 return InnerMatcher.matches(*E, Finder, Builder);
47}
48
49/// Contains information about a use-after-move.
50struct UseAfterMove {
51 // The DeclRefExpr that constituted the use of the object.
52 const DeclRefExpr *DeclRef;
53
54 // Is the order in which the move and the use are evaluated undefined?
55 bool EvaluationOrderUndefined = false;
56
57 // Does the use happen in a later loop iteration than the move?
58 //
59 // We default to false and change it to true if required in find().
60 bool UseHappensInLaterLoopIteration = false;
61};
62
63/// Finds uses of a variable after a move (and maintains state required by the
64/// various internal helper functions).
65class UseAfterMoveFinder {
66public:
67 UseAfterMoveFinder(ASTContext *TheContext,
68 llvm::ArrayRef<StringRef> InvalidationFunctions,
69 llvm::ArrayRef<StringRef> ReinitializationFunctions,
70 const CXXRecordDecl *MovedAs);
71
72 // Within the given code block, finds the first use of 'MovedVariable' that
73 // occurs after 'MovingCall' (the expression that performs the move). If a
74 // use-after-move is found, writes information about it to 'TheUseAfterMove'.
75 // Returns whether a use-after-move was found.
76 std::optional<UseAfterMove> find(Stmt *CodeBlock, const Expr *MovingCall,
77 const DeclRefExpr *MovedVariable);
78
79private:
80 std::optional<UseAfterMove> findInternal(const CFGBlock *Block,
81 const Expr *MovingCall,
82 const ValueDecl *MovedVariable);
83 void getUsesAndReinits(const CFGBlock *Block, const ValueDecl *MovedVariable,
84 SmallVectorImpl<const DeclRefExpr *> *Uses,
85 llvm::SmallPtrSetImpl<const Stmt *> *Reinits);
86 void getDeclRefs(const CFGBlock *Block, const Decl *MovedVariable,
87 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs);
88 void getReinits(const CFGBlock *Block, const ValueDecl *MovedVariable,
89 llvm::SmallPtrSetImpl<const Stmt *> *Stmts,
90 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs);
91
92 ASTContext *Context;
93 llvm::ArrayRef<StringRef> InvalidationFunctions;
94 llvm::ArrayRef<StringRef> ReinitializationFunctions;
95 const CXXRecordDecl *MovedAs;
96 std::unique_ptr<ExprSequence> Sequence;
97 std::unique_ptr<StmtToBlockMap> BlockMap;
98 llvm::SmallPtrSet<const CFGBlock *, 8> Visited;
99};
100
101} // namespace
102
103static auto getNameMatcher(llvm::ArrayRef<StringRef> InvalidationFunctions) {
104 return anyOf(hasAnyName("::std::move", "::std::forward"),
105 matchers::matchesAnyListedRegexName(InvalidationFunctions));
106}
107
108static StatementMatcher
109makeReinitMatcher(const ValueDecl *MovedVariable,
110 llvm::ArrayRef<StringRef> InvalidationFunctions,
111 llvm::ArrayRef<StringRef> ReinitializationFunctions) {
112 const auto DeclRefMatcher =
113 declRefExpr(hasDeclaration(equalsNode(MovedVariable))).bind("declref");
114
115 const auto StandardContainerTypeMatcher = hasType(hasUnqualifiedDesugaredType(
116 recordType(hasDeclaration(cxxRecordDecl(hasAnyName(
117 "::std::basic_string", "::std::vector", "::std::deque",
118 "::std::forward_list", "::std::list", "::std::set", "::std::map",
119 "::std::multiset", "::std::multimap", "::std::unordered_set",
120 "::std::unordered_map", "::std::unordered_multiset",
121 "::std::unordered_multimap"))))));
122
123 const auto StandardResettableOwnerTypeMatcher = hasType(
124 hasUnqualifiedDesugaredType(recordType(hasDeclaration(cxxRecordDecl(
125 hasAnyName("::std::unique_ptr", "::std::shared_ptr",
126 "::std::weak_ptr", "::std::optional", "::std::any"))))));
127
128 // Matches different types of reinitialization.
129 return stmt(
130 anyOf(
131 // Assignment. In addition to the overloaded assignment
132 // operator, test for built-in assignment as well, since
133 // template functions may be instantiated to use std::move() on
134 // built-in types.
135 binaryOperation(hasOperatorName("="), hasLHS(DeclRefMatcher)),
136 // Declaration. We treat this as a type of reinitialization
137 // too, so we don't need to treat it separately.
138 declStmt(hasDescendant(equalsNode(MovedVariable))),
139 // clear() and assign() on standard containers.
140 cxxMemberCallExpr(
141 on(expr(DeclRefMatcher, StandardContainerTypeMatcher)),
142 // To keep the matcher simple, we check for assign() calls
143 // on all standard containers, even though only vector,
144 // deque, forward_list and list have assign(). If assign()
145 // is called on any of the other containers, this will be
146 // flagged by a compile error anyway.
147 callee(cxxMethodDecl(hasAnyName("clear", "assign")))),
148 // reset() on standard smart pointers.
149 cxxMemberCallExpr(on(expr(DeclRefMatcher,
150 StandardResettableOwnerTypeMatcher)),
151 callee(cxxMethodDecl(hasName("reset")))),
152 // Methods that have the [[clang::reinitializes]] attribute.
153 cxxMemberCallExpr(
154 on(DeclRefMatcher),
155 callee(cxxMethodDecl(hasAttr(attr::Reinitializes)))),
156 // Functions that are specified in ReinitializationFunctions
157 // option.
158 callExpr(
159 callee(functionDecl(matchers::matchesAnyListedRegexName(
160 ReinitializationFunctions))),
161 anyOf(cxxMemberCallExpr(on(DeclRefMatcher)),
162 callExpr(unless(cxxMemberCallExpr()),
163 hasArgument(0, DeclRefMatcher)))),
164 // Passing variable to a function as a non-const pointer.
165 callExpr(forEachArgumentWithParam(
166 unaryOperator(hasOperatorName("&"),
167 hasUnaryOperand(DeclRefMatcher)),
168 unless(
169 parmVarDecl(hasType(pointsTo(isConstQualified())))))),
170 // Passing variable to a function as a non-const lvalue
171 // reference (unless that function is std::move()).
172 callExpr(forEachArgumentWithParam(
173 traverse(TK_AsIs, DeclRefMatcher),
174 unless(parmVarDecl(hasType(
175 references(qualType(isConstQualified())))))),
176 unless(callee(functionDecl(
177 getNameMatcher(InvalidationFunctions)))))))
178 .bind("reinit");
179}
180
181// Matches nodes that are
182// - Part of a decltype argument or class template argument (we check this by
183// seeing if they are children of a TypeLoc), or
184// - Part of a function template argument (we check this by seeing if they are
185// children of a DeclRefExpr that references a function template).
186// DeclRefExprs that fulfill these conditions should not be counted as a use or
187// move.
188static StatementMatcher inDecltypeOrTemplateArg() {
189 return anyOf(hasAncestor(typeLoc()),
190 hasAncestor(declRefExpr(
191 to(functionDecl(ast_matchers::isTemplateInstantiation())))),
192 hasAncestor(expr(hasUnevaluatedContext())));
193}
194
195UseAfterMoveFinder::UseAfterMoveFinder(
196 ASTContext *TheContext, llvm::ArrayRef<StringRef> InvalidationFunctions,
197 llvm::ArrayRef<StringRef> ReinitializationFunctions,
198 const CXXRecordDecl *MovedAs)
199 : Context(TheContext), InvalidationFunctions(InvalidationFunctions),
200 ReinitializationFunctions(ReinitializationFunctions), MovedAs(MovedAs) {}
201
202std::optional<UseAfterMove>
203UseAfterMoveFinder::find(Stmt *CodeBlock, const Expr *MovingCall,
204 const DeclRefExpr *MovedVariable) {
205 // Generate the CFG manually instead of through an AnalysisDeclContext because
206 // it seems the latter can't be used to generate a CFG for the body of a
207 // lambda.
208 //
209 // We include implicit and temporary destructors in the CFG so that
210 // destructors marked [[noreturn]] are handled correctly in the control flow
211 // analysis. (These are used in some styles of assertion macros.)
212 CFG::BuildOptions Options;
213 Options.AddImplicitDtors = true;
214 Options.AddTemporaryDtors = true;
215 std::unique_ptr<CFG> TheCFG =
216 CFG::buildCFG(nullptr, CodeBlock, Context, Options);
217 if (!TheCFG)
218 return std::nullopt;
219
220 Sequence = std::make_unique<ExprSequence>(TheCFG.get(), CodeBlock, Context);
221 BlockMap = std::make_unique<StmtToBlockMap>(TheCFG.get(), Context);
222 Visited.clear();
223
224 const CFGBlock *MoveBlock = BlockMap->blockContainingStmt(MovingCall);
225 if (!MoveBlock) {
226 // This can happen if MovingCall is in a constructor initializer, which is
227 // not included in the CFG because the CFG is built only from the function
228 // body.
229 MoveBlock = &TheCFG->getEntry();
230 }
231
232 auto TheUseAfterMove =
233 findInternal(MoveBlock, MovingCall, MovedVariable->getDecl());
234
235 if (TheUseAfterMove) {
236 if (const CFGBlock *UseBlock =
237 BlockMap->blockContainingStmt(TheUseAfterMove->DeclRef)) {
238 // Does the use happen in a later loop iteration than the move?
239 // - If they are in the same CFG block, we know the use happened in a
240 // later iteration if we visited that block a second time.
241 // - Otherwise, we know the use happened in a later iteration if the
242 // move is reachable from the use.
243 CFGReverseBlockReachabilityAnalysis CFA(*TheCFG);
244 TheUseAfterMove->UseHappensInLaterLoopIteration =
245 UseBlock == MoveBlock ? Visited.contains(UseBlock)
246 : CFA.isReachable(UseBlock, MoveBlock);
247 }
248 }
249 return TheUseAfterMove;
250}
251
252std::optional<UseAfterMove>
253UseAfterMoveFinder::findInternal(const CFGBlock *Block, const Expr *MovingCall,
254 const ValueDecl *MovedVariable) {
255 if (Visited.contains(Block))
256 return std::nullopt;
257
258 // Mark the block as visited (except if this is the block containing the
259 // std::move() and it's being visited the first time).
260 if (!MovingCall)
261 Visited.insert(Block);
262
263 // Get all uses and reinits in the block.
264 SmallVector<const DeclRefExpr *, 1> Uses;
265 llvm::SmallPtrSet<const Stmt *, 1> Reinits;
266 getUsesAndReinits(Block, MovedVariable, &Uses, &Reinits);
267
268 // Ignore all reinitializations where the move potentially comes after the
269 // reinit.
270 // If `Reinit` is identical to `MovingCall`, we're looking at a move-to-self
271 // (e.g. `a = std::move(a)`). Count these as reinitializations.
272 SmallVector<const Stmt *, 1> ReinitsToDelete;
273 for (const Stmt *Reinit : Reinits)
274 if (MovingCall && Reinit != MovingCall &&
275 Sequence->potentiallyAfter(MovingCall, Reinit))
276 ReinitsToDelete.push_back(Reinit);
277 for (const Stmt *Reinit : ReinitsToDelete)
278 Reinits.erase(Reinit);
279
280 // Find all uses that potentially come after the move.
281 for (const DeclRefExpr *Use : Uses) {
282 if (!MovingCall || Sequence->potentiallyAfter(Use, MovingCall)) {
283 // Does the use have a saving reinit? A reinit is saving if it definitely
284 // comes before the use, i.e. if there's no potential that the reinit is
285 // after the use.
286 bool HaveSavingReinit = false;
287 for (const Stmt *Reinit : Reinits)
288 if (!Sequence->potentiallyAfter(Reinit, Use))
289 HaveSavingReinit = true;
290
291 if (!HaveSavingReinit) {
292 UseAfterMove TheUseAfterMove;
293 TheUseAfterMove.DeclRef = Use;
294
295 // Is this a use-after-move that depends on order of evaluation?
296 // This is the case if the move potentially comes after the use (and we
297 // already know that use potentially comes after the move, which taken
298 // together tells us that the ordering is unclear).
299 TheUseAfterMove.EvaluationOrderUndefined =
300 MovingCall != nullptr &&
301 Sequence->potentiallyAfter(MovingCall, Use);
302
303 return TheUseAfterMove;
304 }
305 }
306 }
307
308 // If the object wasn't reinitialized, call ourselves recursively on all
309 // successors.
310 if (Reinits.empty()) {
311 for (const auto &Succ : Block->succs()) {
312 if (Succ) {
313 if (auto Found = findInternal(Succ, nullptr, MovedVariable))
314 return Found;
315 }
316 }
317 }
318
319 return std::nullopt;
320}
321
322void UseAfterMoveFinder::getUsesAndReinits(
323 const CFGBlock *Block, const ValueDecl *MovedVariable,
324 SmallVectorImpl<const DeclRefExpr *> *Uses,
325 llvm::SmallPtrSetImpl<const Stmt *> *Reinits) {
326 llvm::SmallPtrSet<const DeclRefExpr *, 1> DeclRefs;
327 llvm::SmallPtrSet<const DeclRefExpr *, 1> ReinitDeclRefs;
328
329 getDeclRefs(Block, MovedVariable, &DeclRefs);
330 getReinits(Block, MovedVariable, Reinits, &ReinitDeclRefs);
331
332 // All references to the variable that aren't reinitializations are uses.
333 Uses->clear();
334 for (const DeclRefExpr *DeclRef : DeclRefs)
335 if (!ReinitDeclRefs.contains(DeclRef))
336 Uses->push_back(DeclRef);
337
338 // Sort the uses by their occurrence in the source code.
339 llvm::sort(*Uses, [](const DeclRefExpr *D1, const DeclRefExpr *D2) {
340 return D1->getExprLoc() < D2->getExprLoc();
341 });
342}
343
344static std::optional<StringRef> getStringLiteral(const Expr *E) {
345 assert(E);
346 if (const auto *SL = dyn_cast<StringLiteral>(E->IgnoreParenImpCasts()))
347 return SL->getString();
348 return std::nullopt;
349}
350
351// User defined types can use [[clang::annotate]] to mark smart-pointer-like
352// types with a specified move from state that matches the standard smart
353// pointer's moved-from state (nullptr).
354static bool isNullAfterMoveAnnotate(const AnnotateAttr *Attr) {
355 if (Attr->getAnnotation() != "clang-tidy")
356 return false;
357
358 if (Attr->args_size() != 2)
359 return false;
360
361 std::optional<StringRef> Plugin = getStringLiteral(Attr->args_begin()[0]);
362 std::optional<StringRef> Annotation = getStringLiteral(Attr->args_begin()[1]);
363
364 return Plugin && Annotation && *Plugin == "bugprone-use-after-move" &&
365 *Annotation == "null_after_move";
366}
367
368static bool isSpecifiedAfterMove(const ValueDecl *VD) {
369 const Type *TheType = VD->getType().getNonReferenceType().getTypePtrOrNull();
370 if (!TheType)
371 return false;
372
373 const CXXRecordDecl *RecordDecl = TheType->getAsCXXRecordDecl();
374 if (!RecordDecl)
375 return false;
376
377 // Use the definition for the declaration, as it is the expected place to add
378 // the annotations.
379 if (const CXXRecordDecl *DefinitionDecl = RecordDecl->getDefinition()) {
380 for (const auto *Attr : DefinitionDecl->specific_attrs<AnnotateAttr>())
381 if (isNullAfterMoveAnnotate(Attr))
382 return true;
383 }
384
385 // Standard smart pointers have a well-specified moved-from state (nullptr).
386 const IdentifierInfo *ID = RecordDecl->getIdentifier();
387 if (!ID)
388 return false;
389
390 const StringRef Name = ID->getName();
391 if (Name != "unique_ptr" && Name != "shared_ptr" && Name != "weak_ptr")
392 return false;
393
394 return RecordDecl->getDeclContext()->isStdNamespace();
395}
396
397void UseAfterMoveFinder::getDeclRefs(
398 const CFGBlock *Block, const Decl *MovedVariable,
399 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs) {
400 DeclRefs->clear();
401 for (const auto &Elem : *Block) {
402 std::optional<CFGStmt> S = Elem.getAs<CFGStmt>();
403 if (!S)
404 continue;
405
406 auto AddDeclRefs = [this, Block,
407 DeclRefs](const ArrayRef<BoundNodes> Matches) {
408 for (const auto &Match : Matches) {
409 const auto *DeclRef = Match.getNodeAs<DeclRefExpr>("declref");
410 const auto *Member = Match.getNodeAs<MemberExpr>("member-expr");
411 const auto *Operator = Match.getNodeAs<CXXOperatorCallExpr>("operator");
412 // Non-moved member as the move only implies a base class.
413 if (Member && MovedAs && !isa<CXXMethodDecl>(Member->getMemberDecl()) &&
414 !MovedAs->hasMemberName(Member->getMemberDecl()->getIdentifier())) {
415 continue;
416 }
417 if (DeclRef && BlockMap->blockContainingStmt(DeclRef) == Block) {
418 // Ignore uses of a standard smart pointer or classes annotated as
419 // "null_after_move" (smart-pointer-like behavior) that don't
420 // dereference the pointer.
421 if (Operator || !isSpecifiedAfterMove(DeclRef->getDecl()))
422 DeclRefs->insert(DeclRef);
423 }
424 }
425 };
426
427 auto DeclRefMatcher =
428 declRefExpr(hasDeclaration(equalsNode(MovedVariable)),
429 unless(inDecltypeOrTemplateArg()),
430 unless(hasParentIgnoringParenImpCasts(
431 memberExpr(hasDeclaration(cxxDestructorDecl())))),
432 optionally(hasParentIgnoringParenImpCasts(
433 memberExpr().bind("member-expr"))))
434 .bind("declref");
435
436 AddDeclRefs(match(traverse(TK_AsIs, findAll(DeclRefMatcher)), *S->getStmt(),
437 *Context));
438 AddDeclRefs(match(findAll(cxxOperatorCallExpr(
439 hasAnyOverloadedOperatorName("*", "->", "[]"),
440 hasArgument(0, DeclRefMatcher))
441 .bind("operator")),
442 *S->getStmt(), *Context));
443 }
444}
445
446void UseAfterMoveFinder::getReinits(
447 const CFGBlock *Block, const ValueDecl *MovedVariable,
448 llvm::SmallPtrSetImpl<const Stmt *> *Stmts,
449 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs) {
450 const auto ReinitMatcher = makeReinitMatcher(
451 MovedVariable, InvalidationFunctions, ReinitializationFunctions);
452
453 Stmts->clear();
454 DeclRefs->clear();
455 for (const auto &Elem : *Block) {
456 std::optional<CFGStmt> S = Elem.getAs<CFGStmt>();
457 if (!S)
458 continue;
459
460 const SmallVector<BoundNodes, 1> Matches =
461 match(findAll(ReinitMatcher), *S->getStmt(), *Context);
462
463 for (const auto &Match : Matches) {
464 const auto *TheStmt = Match.getNodeAs<Stmt>("reinit");
465 const auto *TheDeclRef = Match.getNodeAs<DeclRefExpr>("declref");
466 if (TheStmt && BlockMap->blockContainingStmt(TheStmt) == Block) {
467 Stmts->insert(TheStmt);
468
469 // We count DeclStmts as reinitializations, but they don't have a
470 // DeclRefExpr associated with them -- so we need to check 'TheDeclRef'
471 // before adding it to the set.
472 if (TheDeclRef)
473 DeclRefs->insert(TheDeclRef);
474 }
475 }
476 }
477}
478
479namespace {
480
481enum MoveType {
482 Forward = 0, // std::forward
483 Move = 1, // std::move
484 Invalidation = 2, // other
485};
486
487} // namespace
488
489static MoveType determineMoveType(const FunctionDecl *FuncDecl) {
490 if (FuncDecl->isInStdNamespace()) {
491 if (FuncDecl->getName() == "move")
492 return MoveType::Move;
493 if (FuncDecl->getName() == "forward")
494 return MoveType::Forward;
495 }
496
497 return MoveType::Invalidation;
498}
499
500static void emitDiagnostic(const Expr *MovingCall, const DeclRefExpr *MoveArg,
501 const UseAfterMove &Use, ClangTidyCheck *Check,
502 ASTContext *Context, MoveType Type,
503 const FunctionDecl *MoveDecl) {
504 const SourceLocation UseLoc = Use.DeclRef->getExprLoc();
505 const SourceLocation MoveLoc = MovingCall->getExprLoc();
506
507 Check->diag(
508 UseLoc,
509 "'%0' used after it was %select{forwarded|moved|invalidated by %2}1")
510 << MoveArg->getDecl()->getName() << Type << MoveDecl;
511 Check->diag(MoveLoc, "%select{forward|move|invalidation}0 occurred here",
512 DiagnosticIDs::Note)
513 << Type;
514 if (Use.EvaluationOrderUndefined) {
515 Check->diag(
516 UseLoc,
517 "the use and %select{forward|move|invalidation}0 are unsequenced, i.e. "
518 "there is no guarantee about the order in which they are evaluated",
519 DiagnosticIDs::Note)
520 << Type;
521 } else if (Use.UseHappensInLaterLoopIteration) {
522 Check->diag(UseLoc,
523 "the use happens in a later loop iteration than the "
524 "%select{forward|move|invalidation}0",
525 DiagnosticIDs::Note)
526 << Type;
527 }
528}
529
531 : ClangTidyCheck(Name, Context),
532 InvalidationFunctions(utils::options::parseStringList(
533 Options.get("InvalidationFunctions", ""))),
534 ReinitializationFunctions(utils::options::parseStringList(
535 Options.get("ReinitializationFunctions", ""))) {}
536
538 Options.store(Opts, "InvalidationFunctions",
539 utils::options::serializeStringList(InvalidationFunctions));
540 Options.store(Opts, "ReinitializationFunctions",
541 utils::options::serializeStringList(ReinitializationFunctions));
542}
543
544void UseAfterMoveCheck::registerMatchers(MatchFinder *Finder) {
545 // try_emplace is a common maybe-moving function that returns a
546 // bool to tell callers whether it moved. Ignore std::move inside
547 // try_emplace to avoid false positives as we don't track uses of
548 // the bool.
549 auto TryEmplaceMatcher =
550 cxxMemberCallExpr(callee(cxxMethodDecl(hasName("try_emplace"))));
551 auto Arg = declRefExpr().bind("arg");
552 auto IsMemberCallee = callee(functionDecl(unless(isStaticStorageClass())));
553 auto CallMoveMatcher = callExpr(
554 callee(functionDecl(getNameMatcher(InvalidationFunctions))
555 .bind("move-decl")),
556 anyOf(cxxMemberCallExpr(IsMemberCallee, on(Arg)),
557 callExpr(unless(cxxMemberCallExpr(IsMemberCallee)),
558 hasArgument(0, Arg))),
559 unless(inDecltypeOrTemplateArg()), unless(hasParent(TryEmplaceMatcher)),
560 expr().bind("call-move"),
561 optionally(hasParent(implicitCastExpr(hasCastKind(CK_DerivedToBase))
562 .bind("optional-cast"))),
563 anyOf(hasAncestor(compoundStmt(
564 hasParent(lambdaExpr().bind("containing-lambda")))),
565 hasAncestor(functionDecl(
566 anyOf(cxxConstructorDecl(
567 hasAnyConstructorInitializer(withInitializer(
568 expr(anyOf(equalsBoundNode("call-move"),
569 hasDescendant(expr(
570 equalsBoundNode("call-move")))))
571 .bind("containing-ctor-init"))))
572 .bind("containing-ctor"),
573 functionDecl().bind("containing-func"))))));
574
575 Finder->addMatcher(
576 traverse(
577 TK_AsIs,
578 // To find the Stmt that we assume performs the actual move, we look
579 // for the direct ancestor of the std::move() that isn't one of the
580 // node types ignored by ignoringParenImpCasts().
581 stmt(
582 forEach(expr(ignoringParenImpCasts(CallMoveMatcher))),
583 // Don't allow an InitListExpr to be the moving call. An
584 // InitListExpr has both a syntactic and a semantic form, and the
585 // parent-child relationships are different between the two. This
586 // could cause an InitListExpr to be analyzed as the moving call
587 // in addition to the Expr that we actually want, resulting in two
588 // diagnostics with different code locations for the same move.
589 unless(initListExpr()),
590 unless(expr(ignoringParenImpCasts(equalsBoundNode("call-move")))))
591 .bind("moving-call")),
592 this);
593}
594
595void UseAfterMoveCheck::check(const MatchFinder::MatchResult &Result) {
596 const auto *ContainingCtor =
597 Result.Nodes.getNodeAs<CXXConstructorDecl>("containing-ctor");
598 const auto *ContainingCtorInit =
599 Result.Nodes.getNodeAs<Expr>("containing-ctor-init");
600 const auto *ContainingLambda =
601 Result.Nodes.getNodeAs<LambdaExpr>("containing-lambda");
602 const auto *ContainingFunc =
603 Result.Nodes.getNodeAs<FunctionDecl>("containing-func");
604 const auto *CallMove = Result.Nodes.getNodeAs<CallExpr>("call-move");
605 const auto *MovingCall = Result.Nodes.getNodeAs<Expr>("moving-call");
606 const auto *Arg = Result.Nodes.getNodeAs<DeclRefExpr>("arg");
607 const auto *MoveDecl = Result.Nodes.getNodeAs<FunctionDecl>("move-decl");
608 const auto *ParentCast =
609 Result.Nodes.getNodeAs<ImplicitCastExpr>("optional-cast");
610
611 if (!MovingCall || !MovingCall->getExprLoc().isValid())
612 MovingCall = CallMove;
613
614 // Ignore the std::move if the variable that was passed to it isn't a local
615 // variable.
616 if (!Arg->getDecl()->getDeclContext()->isFunctionOrMethod())
617 return;
618
619 // Collect all code blocks that could use the arg after move.
620 SmallVector<Stmt *> CodeBlocks{};
621 if (ContainingCtor) {
622 CodeBlocks.push_back(ContainingCtor->getBody());
623 if (ContainingCtorInit) {
624 // Collect the constructor initializer expressions.
625 bool BeforeMove{true};
626 for (const CXXCtorInitializer *Init : ContainingCtor->inits()) {
627 if (BeforeMove && Init->getInit()->IgnoreImplicit() ==
628 ContainingCtorInit->IgnoreImplicit())
629 BeforeMove = false;
630 if (!BeforeMove)
631 CodeBlocks.push_back(Init->getInit());
632 }
633 }
634 } else if (ContainingLambda) {
635 CodeBlocks.push_back(ContainingLambda->getBody());
636 } else if (ContainingFunc) {
637 CodeBlocks.push_back(ContainingFunc->getBody());
638 }
639
640 const CXXRecordDecl *MovedAs =
641 ParentCast ? ParentCast->getType()->getAsCXXRecordDecl() : nullptr;
642
643 for (Stmt *CodeBlock : CodeBlocks) {
644 UseAfterMoveFinder Finder(Result.Context, InvalidationFunctions,
645 ReinitializationFunctions, MovedAs);
646 if (auto Use = Finder.find(CodeBlock, MovingCall, Arg))
647 emitDiagnostic(MovingCall, Arg, *Use, this, Result.Context,
648 determineMoveType(MoveDecl), MoveDecl);
649 }
650}
651
652} // namespace clang::tidy::bugprone
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
UseAfterMoveCheck(StringRef Name, ClangTidyContext *Context)
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
std::vector< std::string > match(const SymbolIndex &I, const FuzzyFindRequest &Req, bool *Incomplete)
static StatementMatcher makeReinitMatcher(const ValueDecl *MovedVariable, llvm::ArrayRef< StringRef > InvalidationFunctions, llvm::ArrayRef< StringRef > ReinitializationFunctions)
static MoveType determineMoveType(const FunctionDecl *FuncDecl)
static bool isSpecifiedAfterMove(const ValueDecl *VD)
static std::optional< StringRef > getStringLiteral(const Expr *E)
static auto getNameMatcher(llvm::ArrayRef< StringRef > InvalidationFunctions)
static StatementMatcher inDecltypeOrTemplateArg()
static bool isNullAfterMoveAnnotate(const AnnotateAttr *Attr)
static void emitDiagnostic(const Expr *MovingCall, const DeclRefExpr *MoveArg, const UseAfterMove &Use, ClangTidyCheck *Check, ASTContext *Context, MoveType Type, const FunctionDecl *MoveDecl)
AST_MATCHER_P(Stmt, isStatementIdenticalToBoundNode, std::string, ID)
inline ::clang::ast_matchers::internal::Matcher< NamedDecl > matchesAnyListedRegexName(llvm::ArrayRef< StringRef > NameList)
std::string serializeStringList(ArrayRef< StringRef > Strings)
Serialize a sequence of names that can be parsed by parseStringList.
llvm::StringMap< ClangTidyValue > OptionMap
static constexpr const char FuncDecl[]