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"
31using matchers::hasUnevaluatedContext;
35 ast_matchers::internal::Matcher<Expr>, InnerMatcher) {
36 const Expr *E = &Node;
38 const DynTypedNodeList
Parents = Finder->getASTContext().getParents(*E);
44 }
while (isa<ImplicitCastExpr, ParenExpr>(E));
46 return InnerMatcher.matches(*E, Finder, Builder);
52 const DeclRefExpr *DeclRef;
55 bool EvaluationOrderUndefined =
false;
60 bool UseHappensInLaterLoopIteration =
false;
65class UseAfterMoveFinder {
67 UseAfterMoveFinder(ASTContext *TheContext,
68 llvm::ArrayRef<StringRef> InvalidationFunctions,
69 llvm::ArrayRef<StringRef> ReinitializationFunctions,
70 const CXXRecordDecl *MovedAs);
76 std::optional<UseAfterMove> find(Stmt *CodeBlock,
const Expr *MovingCall,
77 const DeclRefExpr *MovedVariable);
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);
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;
104 return anyOf(hasAnyName(
"::std::move",
"::std::forward"),
108static StatementMatcher
110 llvm::ArrayRef<StringRef> InvalidationFunctions,
111 llvm::ArrayRef<StringRef> ReinitializationFunctions) {
112 const auto DeclRefMatcher =
113 declRefExpr(hasDeclaration(equalsNode(MovedVariable))).bind(
"declref");
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"))))));
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"))))));
135 binaryOperation(hasOperatorName(
"="), hasLHS(DeclRefMatcher)),
138 declStmt(hasDescendant(equalsNode(MovedVariable))),
141 on(expr(DeclRefMatcher, StandardContainerTypeMatcher)),
147 callee(cxxMethodDecl(hasAnyName(
"clear",
"assign")))),
149 cxxMemberCallExpr(on(expr(DeclRefMatcher,
150 StandardResettableOwnerTypeMatcher)),
151 callee(cxxMethodDecl(hasName(
"reset")))),
155 callee(cxxMethodDecl(hasAttr(attr::Reinitializes)))),
160 ReinitializationFunctions))),
161 anyOf(cxxMemberCallExpr(on(DeclRefMatcher)),
162 callExpr(unless(cxxMemberCallExpr()),
163 hasArgument(0, DeclRefMatcher)))),
165 callExpr(forEachArgumentWithParam(
166 unaryOperator(hasOperatorName(
"&"),
167 hasUnaryOperand(DeclRefMatcher)),
169 parmVarDecl(hasType(pointsTo(isConstQualified())))))),
172 callExpr(forEachArgumentWithParam(
173 traverse(TK_AsIs, DeclRefMatcher),
174 unless(parmVarDecl(hasType(
175 references(qualType(isConstQualified())))))),
176 unless(callee(functionDecl(
189 return anyOf(hasAncestor(typeLoc()),
190 hasAncestor(declRefExpr(
191 to(functionDecl(ast_matchers::isTemplateInstantiation())))),
192 hasAncestor(expr(hasUnevaluatedContext())));
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) {}
202std::optional<UseAfterMove>
203UseAfterMoveFinder::find(Stmt *
CodeBlock,
const Expr *MovingCall,
204 const DeclRefExpr *MovedVariable) {
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);
220 Sequence = std::make_unique<ExprSequence>(TheCFG.get(),
CodeBlock, Context);
221 BlockMap = std::make_unique<StmtToBlockMap>(TheCFG.get(), Context);
224 const CFGBlock *MoveBlock = BlockMap->blockContainingStmt(MovingCall);
229 MoveBlock = &TheCFG->getEntry();
232 auto TheUseAfterMove =
233 findInternal(MoveBlock, MovingCall, MovedVariable->getDecl());
235 if (TheUseAfterMove) {
236 if (
const CFGBlock *UseBlock =
237 BlockMap->blockContainingStmt(TheUseAfterMove->DeclRef)) {
243 CFGReverseBlockReachabilityAnalysis CFA(*TheCFG);
244 TheUseAfterMove->UseHappensInLaterLoopIteration =
245 UseBlock == MoveBlock ? Visited.contains(UseBlock)
246 : CFA.isReachable(UseBlock, MoveBlock);
249 return TheUseAfterMove;
252std::optional<UseAfterMove>
253UseAfterMoveFinder::findInternal(
const CFGBlock *Block,
const Expr *MovingCall,
254 const ValueDecl *MovedVariable) {
255 if (Visited.contains(Block))
261 Visited.insert(Block);
264 SmallVector<const DeclRefExpr *, 1> Uses;
265 llvm::SmallPtrSet<const Stmt *, 1> Reinits;
266 getUsesAndReinits(Block, MovedVariable, &Uses, &Reinits);
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);
281 for (
const DeclRefExpr *Use : Uses) {
282 if (!MovingCall || Sequence->potentiallyAfter(Use, MovingCall)) {
286 bool HaveSavingReinit =
false;
287 for (
const Stmt *Reinit : Reinits)
288 if (!Sequence->potentiallyAfter(Reinit, Use))
289 HaveSavingReinit =
true;
291 if (!HaveSavingReinit) {
292 UseAfterMove TheUseAfterMove;
293 TheUseAfterMove.DeclRef = Use;
299 TheUseAfterMove.EvaluationOrderUndefined =
300 MovingCall !=
nullptr &&
301 Sequence->potentiallyAfter(MovingCall, Use);
303 return TheUseAfterMove;
310 if (Reinits.empty()) {
311 for (
const auto &Succ : Block->succs()) {
313 if (
auto Found = findInternal(Succ,
nullptr, MovedVariable))
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;
329 getDeclRefs(Block, MovedVariable, &DeclRefs);
330 getReinits(Block, MovedVariable, Reinits, &ReinitDeclRefs);
334 for (
const DeclRefExpr *DeclRef : DeclRefs)
335 if (!ReinitDeclRefs.contains(DeclRef))
336 Uses->push_back(DeclRef);
339 llvm::sort(*Uses, [](
const DeclRefExpr *D1,
const DeclRefExpr *D2) {
340 return D1->getExprLoc() < D2->getExprLoc();
346 if (
const auto *SL = dyn_cast<StringLiteral>(E->IgnoreParenImpCasts()))
347 return SL->getString();
355 if (Attr->getAnnotation() !=
"clang-tidy")
358 if (Attr->args_size() != 2)
362 std::optional<StringRef> Annotation =
getStringLiteral(Attr->args_begin()[1]);
364 return Plugin && Annotation && *Plugin ==
"bugprone-use-after-move" &&
365 *Annotation ==
"null_after_move";
369 const Type *TheType = VD->getType().getNonReferenceType().getTypePtrOrNull();
373 const CXXRecordDecl *RecordDecl = TheType->getAsCXXRecordDecl();
379 if (
const CXXRecordDecl *DefinitionDecl = RecordDecl->getDefinition()) {
380 for (
const auto *Attr : DefinitionDecl->specific_attrs<AnnotateAttr>())
386 const IdentifierInfo *ID = RecordDecl->getIdentifier();
390 const StringRef Name = ID->getName();
391 if (Name !=
"unique_ptr" && Name !=
"shared_ptr" && Name !=
"weak_ptr")
394 return RecordDecl->getDeclContext()->isStdNamespace();
397void UseAfterMoveFinder::getDeclRefs(
398 const CFGBlock *
Block,
const Decl *MovedVariable,
399 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs) {
401 for (
const auto &Elem : *
Block) {
402 std::optional<CFGStmt> S = Elem.getAs<CFGStmt>();
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");
413 if (Member && MovedAs && !isa<CXXMethodDecl>(Member->getMemberDecl()) &&
414 !MovedAs->hasMemberName(Member->getMemberDecl()->getIdentifier())) {
417 if (DeclRef && BlockMap->blockContainingStmt(DeclRef) ==
Block) {
421 if (Operator || !isSpecifiedAfterMove(DeclRef->getDecl()))
422 DeclRefs->insert(DeclRef);
427 auto DeclRefMatcher =
428 declRefExpr(hasDeclaration(equalsNode(MovedVariable)),
430 unless(hasParentIgnoringParenImpCasts(
431 memberExpr(hasDeclaration(cxxDestructorDecl())))),
432 optionally(hasParentIgnoringParenImpCasts(
433 memberExpr().bind(
"member-expr"))))
436 AddDeclRefs(
match(traverse(TK_AsIs, findAll(DeclRefMatcher)), *S->getStmt(),
438 AddDeclRefs(
match(findAll(cxxOperatorCallExpr(
439 hasAnyOverloadedOperatorName(
"*",
"->",
"[]"),
440 hasArgument(0, DeclRefMatcher))
442 *S->getStmt(), *Context));
446void UseAfterMoveFinder::getReinits(
447 const CFGBlock *Block,
const ValueDecl *MovedVariable,
448 llvm::SmallPtrSetImpl<const Stmt *> *Stmts,
449 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs) {
451 MovedVariable, InvalidationFunctions, ReinitializationFunctions);
455 for (
const auto &Elem : *Block) {
456 std::optional<CFGStmt> S = Elem.getAs<CFGStmt>();
460 const SmallVector<BoundNodes, 1> Matches =
461 match(findAll(ReinitMatcher), *S->getStmt(), *Context);
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);
473 DeclRefs->insert(TheDeclRef);
492 return MoveType::Move;
493 if (
FuncDecl->getName() ==
"forward")
494 return MoveType::Forward;
497 return MoveType::Invalidation;
502 ASTContext *Context, MoveType Type,
503 const FunctionDecl *MoveDecl) {
504 const SourceLocation UseLoc = Use.DeclRef->getExprLoc();
505 const SourceLocation MoveLoc = MovingCall->getExprLoc();
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",
514 if (Use.EvaluationOrderUndefined) {
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",
521 }
else if (Use.UseHappensInLaterLoopIteration) {
523 "the use happens in a later loop iteration than the "
524 "%select{forward|move|invalidation}0",
533 Options.get(
"InvalidationFunctions",
""))),
534 ReinitializationFunctions(
utils::
options::parseStringList(
535 Options.get(
"ReinitializationFunctions",
""))) {}
538 Options.store(Opts,
"InvalidationFunctions",
540 Options.store(Opts,
"ReinitializationFunctions",
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(
556 anyOf(cxxMemberCallExpr(IsMemberCallee, on(Arg)),
557 callExpr(unless(cxxMemberCallExpr(IsMemberCallee)),
558 hasArgument(0, Arg))),
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"),
570 equalsBoundNode(
"call-move")))))
571 .bind(
"containing-ctor-init"))))
572 .bind(
"containing-ctor"),
573 functionDecl().bind(
"containing-func"))))));
582 forEach(expr(ignoringParenImpCasts(CallMoveMatcher))),
589 unless(initListExpr()),
590 unless(expr(ignoringParenImpCasts(equalsBoundNode(
"call-move")))))
591 .bind(
"moving-call")),
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");
611 if (!MovingCall || !MovingCall->getExprLoc().isValid())
612 MovingCall = CallMove;
616 if (!Arg->getDecl()->getDeclContext()->isFunctionOrMethod())
621 if (ContainingCtor) {
622 CodeBlocks.push_back(ContainingCtor->getBody());
623 if (ContainingCtorInit) {
625 bool BeforeMove{
true};
626 for (
const CXXCtorInitializer *Init : ContainingCtor->inits()) {
627 if (BeforeMove && Init->getInit()->IgnoreImplicit() ==
628 ContainingCtorInit->IgnoreImplicit())
631 CodeBlocks.push_back(Init->getInit());
634 }
else if (ContainingLambda) {
635 CodeBlocks.push_back(ContainingLambda->getBody());
636 }
else if (ContainingFunc) {
637 CodeBlocks.push_back(ContainingFunc->getBody());
640 const CXXRecordDecl *MovedAs =
641 ParentCast ? ParentCast->getType()->getAsCXXRecordDecl() :
nullptr;
644 UseAfterMoveFinder Finder(Result.Context, InvalidationFunctions,
645 ReinitializationFunctions, MovedAs);
646 if (
auto Use = Finder.find(
CodeBlock, MovingCall, Arg))
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[]