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(
"="),
136 hasLHS(ignoringParenImpCasts(DeclRefMatcher))),
139 declStmt(hasDescendant(equalsNode(MovedVariable))),
142 on(expr(DeclRefMatcher, StandardContainerTypeMatcher)),
148 callee(cxxMethodDecl(hasAnyName(
"clear",
"assign")))),
150 cxxMemberCallExpr(on(expr(DeclRefMatcher,
151 StandardResettableOwnerTypeMatcher)),
152 callee(cxxMethodDecl(hasName(
"reset")))),
156 callee(cxxMethodDecl(hasAttr(attr::Reinitializes)))),
161 ReinitializationFunctions))),
162 anyOf(cxxMemberCallExpr(on(DeclRefMatcher)),
163 callExpr(unless(cxxMemberCallExpr()),
164 hasArgument(0, DeclRefMatcher)))),
166 callExpr(forEachArgumentWithParam(
167 unaryOperator(hasOperatorName(
"&"),
168 hasUnaryOperand(DeclRefMatcher)),
170 parmVarDecl(hasType(pointsTo(isConstQualified())))))),
173 callExpr(forEachArgumentWithParam(
174 traverse(TK_AsIs, DeclRefMatcher),
175 unless(parmVarDecl(hasType(
176 references(qualType(isConstQualified())))))),
177 unless(callee(functionDecl(
190 return anyOf(hasAncestor(typeLoc()),
191 hasAncestor(declRefExpr(
192 to(functionDecl(ast_matchers::isTemplateInstantiation())))),
193 hasAncestor(expr(hasUnevaluatedContext())));
196UseAfterMoveFinder::UseAfterMoveFinder(
197 ASTContext *TheContext, llvm::ArrayRef<StringRef> InvalidationFunctions,
198 llvm::ArrayRef<StringRef> ReinitializationFunctions,
199 const CXXRecordDecl *MovedAs)
200 : Context(TheContext), InvalidationFunctions(InvalidationFunctions),
201 ReinitializationFunctions(ReinitializationFunctions), MovedAs(MovedAs) {}
203std::optional<UseAfterMove>
204UseAfterMoveFinder::find(Stmt *
CodeBlock,
const Expr *MovingCall,
205 const DeclRefExpr *MovedVariable) {
213 CFG::BuildOptions Options;
214 Options.AddImplicitDtors =
true;
215 Options.AddTemporaryDtors =
true;
216 std::unique_ptr<CFG> TheCFG =
217 CFG::buildCFG(
nullptr,
CodeBlock, Context, Options);
221 Sequence = std::make_unique<ExprSequence>(TheCFG.get(),
CodeBlock, Context);
222 BlockMap = std::make_unique<StmtToBlockMap>(TheCFG.get(), Context);
225 const CFGBlock *MoveBlock = BlockMap->blockContainingStmt(MovingCall);
230 MoveBlock = &TheCFG->getEntry();
233 auto TheUseAfterMove =
234 findInternal(MoveBlock, MovingCall, MovedVariable->getDecl());
236 if (TheUseAfterMove) {
237 if (
const CFGBlock *UseBlock =
238 BlockMap->blockContainingStmt(TheUseAfterMove->DeclRef)) {
244 CFGReverseBlockReachabilityAnalysis CFA(*TheCFG);
245 TheUseAfterMove->UseHappensInLaterLoopIteration =
246 UseBlock == MoveBlock ? Visited.contains(UseBlock)
247 : CFA.isReachable(UseBlock, MoveBlock);
250 return TheUseAfterMove;
253std::optional<UseAfterMove>
254UseAfterMoveFinder::findInternal(
const CFGBlock *Block,
const Expr *MovingCall,
255 const ValueDecl *MovedVariable) {
256 if (Visited.contains(Block))
262 Visited.insert(Block);
265 SmallVector<const DeclRefExpr *, 1> Uses;
266 llvm::SmallPtrSet<const Stmt *, 1> Reinits;
267 getUsesAndReinits(Block, MovedVariable, &Uses, &Reinits);
273 SmallVector<const Stmt *, 1> ReinitsToDelete;
274 for (
const Stmt *Reinit : Reinits)
275 if (MovingCall && Reinit != MovingCall &&
276 Sequence->potentiallyAfter(MovingCall, Reinit))
277 ReinitsToDelete.push_back(Reinit);
278 for (
const Stmt *Reinit : ReinitsToDelete)
279 Reinits.erase(Reinit);
282 for (
const DeclRefExpr *Use : Uses) {
283 if (!MovingCall || Sequence->potentiallyAfter(Use, MovingCall)) {
287 bool HaveSavingReinit =
false;
288 for (
const Stmt *Reinit : Reinits)
289 if (!Sequence->potentiallyAfter(Reinit, Use))
290 HaveSavingReinit =
true;
292 if (!HaveSavingReinit) {
293 UseAfterMove TheUseAfterMove;
294 TheUseAfterMove.DeclRef = Use;
300 TheUseAfterMove.EvaluationOrderUndefined =
301 MovingCall !=
nullptr &&
302 Sequence->potentiallyAfter(MovingCall, Use);
304 return TheUseAfterMove;
311 if (Reinits.empty()) {
312 for (
const auto &Succ : Block->succs()) {
314 if (
auto Found = findInternal(Succ,
nullptr, MovedVariable))
323void UseAfterMoveFinder::getUsesAndReinits(
324 const CFGBlock *Block,
const ValueDecl *MovedVariable,
325 SmallVectorImpl<const DeclRefExpr *> *Uses,
326 llvm::SmallPtrSetImpl<const Stmt *> *Reinits) {
327 llvm::SmallPtrSet<const DeclRefExpr *, 1> DeclRefs;
328 llvm::SmallPtrSet<const DeclRefExpr *, 1> ReinitDeclRefs;
330 getDeclRefs(Block, MovedVariable, &DeclRefs);
331 getReinits(Block, MovedVariable, Reinits, &ReinitDeclRefs);
335 for (
const DeclRefExpr *DeclRef : DeclRefs)
336 if (!ReinitDeclRefs.contains(DeclRef))
337 Uses->push_back(DeclRef);
340 llvm::sort(*Uses, [](
const DeclRefExpr *D1,
const DeclRefExpr *D2) {
341 return D1->getExprLoc() < D2->getExprLoc();
347 if (
const auto *SL = dyn_cast<StringLiteral>(E->IgnoreParenImpCasts()))
348 return SL->getString();
356 if (Attr->getAnnotation() !=
"clang-tidy")
359 if (Attr->args_size() != 2)
363 std::optional<StringRef> Annotation =
getStringLiteral(Attr->args_begin()[1]);
365 return Plugin && Annotation && *Plugin ==
"bugprone-use-after-move" &&
366 *Annotation ==
"null_after_move";
370 const Type *TheType = VD->getType().getNonReferenceType().getTypePtrOrNull();
374 const CXXRecordDecl *RecordDecl = TheType->getAsCXXRecordDecl();
380 if (
const CXXRecordDecl *DefinitionDecl = RecordDecl->getDefinition()) {
381 for (
const auto *Attr : DefinitionDecl->specific_attrs<AnnotateAttr>())
387 const IdentifierInfo *ID = RecordDecl->getIdentifier();
391 const StringRef Name = ID->getName();
392 if (Name !=
"unique_ptr" && Name !=
"shared_ptr" && Name !=
"weak_ptr")
395 return RecordDecl->getDeclContext()->isStdNamespace();
398void UseAfterMoveFinder::getDeclRefs(
399 const CFGBlock *
Block,
const Decl *MovedVariable,
400 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs) {
402 for (
const auto &Elem : *
Block) {
403 std::optional<CFGStmt> S = Elem.getAs<CFGStmt>();
407 auto AddDeclRefs = [
this,
Block,
408 DeclRefs](
const ArrayRef<BoundNodes> Matches) {
409 for (
const auto &Match : Matches) {
410 const auto *DeclRef = Match.getNodeAs<DeclRefExpr>(
"declref");
411 const auto *Member = Match.getNodeAs<MemberExpr>(
"member-expr");
412 const auto *Operator = Match.getNodeAs<CXXOperatorCallExpr>(
"operator");
414 if (Member && MovedAs && !isa<CXXMethodDecl>(Member->getMemberDecl()) &&
415 !MovedAs->hasMemberName(Member->getMemberDecl()->getIdentifier())) {
418 if (DeclRef && BlockMap->blockContainingStmt(DeclRef) ==
Block) {
422 if (Operator || !isSpecifiedAfterMove(DeclRef->getDecl()))
423 DeclRefs->insert(DeclRef);
428 auto DeclRefMatcher =
429 declRefExpr(hasDeclaration(equalsNode(MovedVariable)),
431 unless(hasParentIgnoringParenImpCasts(
432 memberExpr(hasDeclaration(cxxDestructorDecl())))),
433 optionally(hasParentIgnoringParenImpCasts(
434 memberExpr().bind(
"member-expr"))))
437 AddDeclRefs(
match(traverse(TK_AsIs, findAll(DeclRefMatcher)), *S->getStmt(),
439 AddDeclRefs(
match(findAll(cxxOperatorCallExpr(
440 hasAnyOverloadedOperatorName(
"*",
"->",
"[]"),
441 hasArgument(0, DeclRefMatcher))
443 *S->getStmt(), *Context));
447void UseAfterMoveFinder::getReinits(
448 const CFGBlock *Block,
const ValueDecl *MovedVariable,
449 llvm::SmallPtrSetImpl<const Stmt *> *Stmts,
450 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs) {
452 MovedVariable, InvalidationFunctions, ReinitializationFunctions);
456 for (
const auto &Elem : *Block) {
457 std::optional<CFGStmt> S = Elem.getAs<CFGStmt>();
461 const SmallVector<BoundNodes, 1> Matches =
462 match(findAll(ReinitMatcher), *S->getStmt(), *Context);
464 for (
const auto &Match : Matches) {
465 const auto *TheStmt = Match.getNodeAs<Stmt>(
"reinit");
466 const auto *TheDeclRef = Match.getNodeAs<DeclRefExpr>(
"declref");
467 if (TheStmt && BlockMap->blockContainingStmt(TheStmt) == Block) {
468 Stmts->insert(TheStmt);
474 DeclRefs->insert(TheDeclRef);
493 return MoveType::Move;
494 if (
FuncDecl->getName() ==
"forward")
495 return MoveType::Forward;
498 return MoveType::Invalidation;
503 ASTContext *Context, MoveType Type,
504 const FunctionDecl *MoveDecl) {
505 const SourceLocation UseLoc = Use.DeclRef->getExprLoc();
506 const SourceLocation MoveLoc = MovingCall->getExprLoc();
510 "'%0' used after it was %select{forwarded|moved|invalidated by %2}1")
511 << MoveArg->getDecl()->getName() << Type << MoveDecl;
512 Check->diag(MoveLoc,
"%select{forward|move|invalidation}0 occurred here",
515 if (Use.EvaluationOrderUndefined) {
518 "the use and %select{forward|move|invalidation}0 are unsequenced, i.e. "
519 "there is no guarantee about the order in which they are evaluated",
522 }
else if (Use.UseHappensInLaterLoopIteration) {
524 "the use happens in a later loop iteration than the "
525 "%select{forward|move|invalidation}0",
534 Options.get(
"InvalidationFunctions",
""))),
535 ReinitializationFunctions(
utils::
options::parseStringList(
536 Options.get(
"ReinitializationFunctions",
""))) {}
539 Options.store(Opts,
"InvalidationFunctions",
541 Options.store(Opts,
"ReinitializationFunctions",
550 auto TryEmplaceMatcher =
551 cxxMemberCallExpr(callee(cxxMethodDecl(hasName(
"try_emplace"))));
552 auto Arg = declRefExpr().bind(
"arg");
553 auto IsMemberCallee = callee(functionDecl(unless(isStaticStorageClass())));
554 auto CallMoveMatcher = callExpr(
557 anyOf(cxxMemberCallExpr(IsMemberCallee, on(Arg)),
558 callExpr(unless(cxxMemberCallExpr(IsMemberCallee)),
559 hasArgument(0, Arg))),
561 expr().bind(
"call-move"),
562 optionally(hasParent(implicitCastExpr(hasCastKind(CK_DerivedToBase))
563 .bind(
"optional-cast"))),
564 anyOf(hasAncestor(compoundStmt(
565 hasParent(lambdaExpr().bind(
"containing-lambda")))),
566 hasAncestor(functionDecl(
567 anyOf(cxxConstructorDecl(
568 hasAnyConstructorInitializer(withInitializer(
569 expr(anyOf(equalsBoundNode(
"call-move"),
571 equalsBoundNode(
"call-move")))))
572 .bind(
"containing-ctor-init"))))
573 .bind(
"containing-ctor"),
574 functionDecl().bind(
"containing-func"))))));
583 forEach(expr(ignoringParenImpCasts(CallMoveMatcher))),
590 unless(initListExpr()),
591 unless(expr(ignoringParenImpCasts(equalsBoundNode(
"call-move")))))
592 .bind(
"moving-call")),
597 const auto *ContainingCtor =
598 Result.Nodes.getNodeAs<CXXConstructorDecl>(
"containing-ctor");
599 const auto *ContainingCtorInit =
600 Result.Nodes.getNodeAs<Expr>(
"containing-ctor-init");
601 const auto *ContainingLambda =
602 Result.Nodes.getNodeAs<LambdaExpr>(
"containing-lambda");
603 const auto *ContainingFunc =
604 Result.Nodes.getNodeAs<FunctionDecl>(
"containing-func");
605 const auto *CallMove = Result.Nodes.getNodeAs<CallExpr>(
"call-move");
606 const auto *MovingCall = Result.Nodes.getNodeAs<Expr>(
"moving-call");
607 const auto *Arg = Result.Nodes.getNodeAs<DeclRefExpr>(
"arg");
608 const auto *MoveDecl = Result.Nodes.getNodeAs<FunctionDecl>(
"move-decl");
609 const auto *ParentCast =
610 Result.Nodes.getNodeAs<ImplicitCastExpr>(
"optional-cast");
612 if (!MovingCall || !MovingCall->getExprLoc().isValid())
613 MovingCall = CallMove;
617 if (!Arg->getDecl()->getDeclContext()->isFunctionOrMethod())
622 if (ContainingCtor) {
623 CodeBlocks.push_back(ContainingCtor->getBody());
624 if (ContainingCtorInit) {
626 bool BeforeMove{
true};
627 for (
const CXXCtorInitializer *Init : ContainingCtor->inits()) {
628 if (BeforeMove && Init->getInit()->IgnoreImplicit() ==
629 ContainingCtorInit->IgnoreImplicit())
632 CodeBlocks.push_back(Init->getInit());
635 }
else if (ContainingLambda) {
636 CodeBlocks.push_back(ContainingLambda->getBody());
637 }
else if (ContainingFunc) {
638 CodeBlocks.push_back(ContainingFunc->getBody());
641 const CXXRecordDecl *MovedAs =
642 ParentCast ? ParentCast->getType()->getAsCXXRecordDecl() :
nullptr;
645 UseAfterMoveFinder Finder(Result.Context, InvalidationFunctions,
646 ReinitializationFunctions, MovedAs);
647 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[]