11#include "clang/AST/Expr.h"
12#include "clang/AST/ExprCXX.h"
13#include "clang/ASTMatchers/ASTMatchers.h"
14#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
15#include "clang/Analysis/CFG.h"
16#include "clang/Lex/Lexer.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallPtrSet.h"
30using matchers::hasUnevaluatedContext;
37 const DeclRefExpr *DeclRef;
40 bool EvaluationOrderUndefined =
false;
45 bool UseHappensInLaterLoopIteration =
false;
50class UseAfterMoveFinder {
52 UseAfterMoveFinder(ASTContext *TheContext,
53 llvm::ArrayRef<StringRef> InvalidationFunctions);
59 std::optional<UseAfterMove> find(Stmt *CodeBlock,
const Expr *MovingCall,
60 const DeclRefExpr *MovedVariable);
63 std::optional<UseAfterMove> findInternal(
const CFGBlock *Block,
64 const Expr *MovingCall,
65 const ValueDecl *MovedVariable);
66 void getUsesAndReinits(
const CFGBlock *Block,
const ValueDecl *MovedVariable,
67 llvm::SmallVectorImpl<const DeclRefExpr *> *Uses,
68 llvm::SmallPtrSetImpl<const Stmt *> *Reinits);
69 void getDeclRefs(
const CFGBlock *Block,
const Decl *MovedVariable,
70 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs);
71 void getReinits(
const CFGBlock *Block,
const ValueDecl *MovedVariable,
72 llvm::SmallPtrSetImpl<const Stmt *> *Stmts,
73 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs);
76 llvm::ArrayRef<StringRef> InvalidationFunctions;
77 std::unique_ptr<ExprSequence> Sequence;
78 std::unique_ptr<StmtToBlockMap> BlockMap;
79 llvm::SmallPtrSet<const CFGBlock *, 8> Visited;
85 return anyOf(hasAnyName(
"::std::move",
"::std::forward"),
97 return anyOf(hasAncestor(typeLoc()),
98 hasAncestor(declRefExpr(
99 to(functionDecl(ast_matchers::isTemplateInstantiation())))),
100 hasAncestor(expr(hasUnevaluatedContext())));
103UseAfterMoveFinder::UseAfterMoveFinder(
104 ASTContext *TheContext, llvm::ArrayRef<StringRef> InvalidationFunctions)
105 : Context(TheContext), InvalidationFunctions(InvalidationFunctions) {}
107std::optional<UseAfterMove>
108UseAfterMoveFinder::find(Stmt *
CodeBlock,
const Expr *MovingCall,
109 const DeclRefExpr *MovedVariable) {
117 CFG::BuildOptions Options;
118 Options.AddImplicitDtors =
true;
119 Options.AddTemporaryDtors =
true;
120 std::unique_ptr<CFG> TheCFG =
121 CFG::buildCFG(
nullptr,
CodeBlock, Context, Options);
125 Sequence = std::make_unique<ExprSequence>(TheCFG.get(),
CodeBlock, Context);
126 BlockMap = std::make_unique<StmtToBlockMap>(TheCFG.get(), Context);
129 const CFGBlock *MoveBlock = BlockMap->blockContainingStmt(MovingCall);
134 MoveBlock = &TheCFG->getEntry();
137 auto TheUseAfterMove =
138 findInternal(MoveBlock, MovingCall, MovedVariable->getDecl());
140 if (TheUseAfterMove) {
141 if (
const CFGBlock *UseBlock =
142 BlockMap->blockContainingStmt(TheUseAfterMove->DeclRef)) {
148 CFGReverseBlockReachabilityAnalysis CFA(*TheCFG);
149 TheUseAfterMove->UseHappensInLaterLoopIteration =
150 UseBlock == MoveBlock ? Visited.contains(UseBlock)
151 : CFA.isReachable(UseBlock, MoveBlock);
154 return TheUseAfterMove;
157std::optional<UseAfterMove>
158UseAfterMoveFinder::findInternal(
const CFGBlock *Block,
const Expr *MovingCall,
159 const ValueDecl *MovedVariable) {
160 if (Visited.contains(Block))
166 Visited.insert(Block);
169 llvm::SmallVector<const DeclRefExpr *, 1> Uses;
170 llvm::SmallPtrSet<const Stmt *, 1> Reinits;
171 getUsesAndReinits(Block, MovedVariable, &Uses, &Reinits);
177 llvm::SmallVector<const Stmt *, 1> ReinitsToDelete;
178 for (
const Stmt *Reinit : Reinits) {
179 if (MovingCall && Reinit != MovingCall &&
180 Sequence->potentiallyAfter(MovingCall, Reinit))
181 ReinitsToDelete.push_back(Reinit);
183 for (
const Stmt *Reinit : ReinitsToDelete) {
184 Reinits.erase(Reinit);
188 for (
const DeclRefExpr *Use : Uses) {
189 if (!MovingCall || Sequence->potentiallyAfter(Use, MovingCall)) {
193 bool HaveSavingReinit =
false;
194 for (
const Stmt *Reinit : Reinits) {
195 if (!Sequence->potentiallyAfter(Reinit, Use))
196 HaveSavingReinit =
true;
199 if (!HaveSavingReinit) {
200 UseAfterMove TheUseAfterMove;
201 TheUseAfterMove.DeclRef = Use;
207 TheUseAfterMove.EvaluationOrderUndefined =
208 MovingCall !=
nullptr &&
209 Sequence->potentiallyAfter(MovingCall, Use);
211 return TheUseAfterMove;
218 if (Reinits.empty()) {
219 for (
const auto &Succ : Block->succs()) {
221 if (
auto Found = findInternal(Succ,
nullptr, MovedVariable)) {
231void UseAfterMoveFinder::getUsesAndReinits(
232 const CFGBlock *Block,
const ValueDecl *MovedVariable,
233 llvm::SmallVectorImpl<const DeclRefExpr *> *Uses,
234 llvm::SmallPtrSetImpl<const Stmt *> *Reinits) {
235 llvm::SmallPtrSet<const DeclRefExpr *, 1> DeclRefs;
236 llvm::SmallPtrSet<const DeclRefExpr *, 1> ReinitDeclRefs;
238 getDeclRefs(Block, MovedVariable, &DeclRefs);
239 getReinits(Block, MovedVariable, Reinits, &ReinitDeclRefs);
243 for (
const DeclRefExpr *DeclRef : DeclRefs) {
244 if (!ReinitDeclRefs.contains(DeclRef))
245 Uses->push_back(DeclRef);
249 llvm::sort(*Uses, [](
const DeclRefExpr *D1,
const DeclRefExpr *D2) {
250 return D1->getExprLoc() < D2->getExprLoc();
255 const Type *TheType = VD->getType().getNonReferenceType().getTypePtrOrNull();
259 const CXXRecordDecl *RecordDecl = TheType->getAsCXXRecordDecl();
263 const IdentifierInfo *ID = RecordDecl->getIdentifier();
267 const StringRef Name = ID->getName();
268 if (Name !=
"unique_ptr" && Name !=
"shared_ptr" && Name !=
"weak_ptr")
271 return RecordDecl->getDeclContext()->isStdNamespace();
274void UseAfterMoveFinder::getDeclRefs(
275 const CFGBlock *
Block,
const Decl *MovedVariable,
276 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs) {
278 for (
const auto &Elem : *
Block) {
279 std::optional<CFGStmt> S = Elem.getAs<CFGStmt>();
283 auto AddDeclRefs = [
this,
Block,
284 DeclRefs](
const ArrayRef<BoundNodes> Matches) {
285 for (
const auto &Match : Matches) {
286 const auto *DeclRef = Match.getNodeAs<DeclRefExpr>(
"declref");
287 const auto *Operator = Match.getNodeAs<CXXOperatorCallExpr>(
"operator");
288 if (DeclRef && BlockMap->blockContainingStmt(DeclRef) ==
Block) {
291 if (Operator || !isStandardSmartPointer(DeclRef->getDecl())) {
292 DeclRefs->insert(DeclRef);
298 auto DeclRefMatcher = declRefExpr(hasDeclaration(equalsNode(MovedVariable)),
302 AddDeclRefs(
match(traverse(TK_AsIs, findAll(DeclRefMatcher)), *S->getStmt(),
304 AddDeclRefs(
match(findAll(cxxOperatorCallExpr(
305 hasAnyOverloadedOperatorName(
"*",
"->",
"[]"),
306 hasArgument(0, DeclRefMatcher))
308 *S->getStmt(), *Context));
312void UseAfterMoveFinder::getReinits(
313 const CFGBlock *Block,
const ValueDecl *MovedVariable,
314 llvm::SmallPtrSetImpl<const Stmt *> *Stmts,
315 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs) {
316 auto DeclRefMatcher =
317 declRefExpr(hasDeclaration(equalsNode(MovedVariable))).bind(
"declref");
319 auto StandardContainerTypeMatcher = hasType(hasUnqualifiedDesugaredType(
320 recordType(hasDeclaration(cxxRecordDecl(hasAnyName(
321 "::std::basic_string",
"::std::vector",
"::std::deque",
322 "::std::forward_list",
"::std::list",
"::std::set",
"::std::map",
323 "::std::multiset",
"::std::multimap",
"::std::unordered_set",
324 "::std::unordered_map",
"::std::unordered_multiset",
325 "::std::unordered_multimap"))))));
327 auto StandardResettableOwnerTypeMatcher = hasType(
328 hasUnqualifiedDesugaredType(recordType(hasDeclaration(cxxRecordDecl(
329 hasAnyName(
"::std::unique_ptr",
"::std::shared_ptr",
330 "::std::weak_ptr",
"::std::optional",
"::std::any"))))));
338 binaryOperation(hasOperatorName(
"="), hasLHS(DeclRefMatcher)),
341 declStmt(hasDescendant(equalsNode(MovedVariable))),
344 on(expr(DeclRefMatcher, StandardContainerTypeMatcher)),
350 callee(cxxMethodDecl(hasAnyName(
"clear",
"assign")))),
353 on(expr(DeclRefMatcher, StandardResettableOwnerTypeMatcher)),
354 callee(cxxMethodDecl(hasName(
"reset")))),
358 callee(cxxMethodDecl(hasAttr(clang::attr::Reinitializes)))),
360 callExpr(forEachArgumentWithParam(
361 unaryOperator(hasOperatorName(
"&"),
362 hasUnaryOperand(DeclRefMatcher)),
363 unless(parmVarDecl(hasType(pointsTo(isConstQualified())))))),
366 callExpr(forEachArgumentWithParam(
367 traverse(TK_AsIs, DeclRefMatcher),
368 unless(parmVarDecl(hasType(
369 references(qualType(isConstQualified())))))),
370 unless(callee(functionDecl(
376 for (
const auto &Elem : *Block) {
377 std::optional<CFGStmt> S = Elem.getAs<CFGStmt>();
381 const SmallVector<BoundNodes, 1> Matches =
382 match(findAll(ReinitMatcher), *S->getStmt(), *Context);
384 for (
const auto &Match : Matches) {
385 const auto *TheStmt = Match.getNodeAs<Stmt>(
"reinit");
386 const auto *TheDeclRef = Match.getNodeAs<DeclRefExpr>(
"declref");
387 if (TheStmt && BlockMap->blockContainingStmt(TheStmt) == Block) {
388 Stmts->insert(TheStmt);
394 DeclRefs->insert(TheDeclRef);
410 if (
FuncDecl->getName() ==
"forward")
419 ASTContext *Context,
MoveType Type) {
420 const SourceLocation UseLoc = Use.DeclRef->getExprLoc();
421 const SourceLocation MoveLoc = MovingCall->getExprLoc();
424 "'%0' used after it was %select{forwarded|moved|invalidated}1")
425 << MoveArg->getDecl()->getName() << Type;
426 Check->diag(MoveLoc,
"%select{forward|move|invalidation}0 occurred here",
429 if (Use.EvaluationOrderUndefined) {
432 "the use and %select{forward|move|invalidation}0 are unsequenced, i.e. "
433 "there is no guarantee about the order in which they are evaluated",
436 }
else if (Use.UseHappensInLaterLoopIteration) {
438 "the use happens in a later loop iteration than the "
439 "%select{forward|move|invalidation}0",
448 Options.get(
"InvalidationFunctions",
""))) {}
451 Options.store(Opts,
"InvalidationFunctions",
460 auto TryEmplaceMatcher =
461 cxxMemberCallExpr(callee(cxxMethodDecl(hasName(
"try_emplace"))));
462 auto Arg = declRefExpr().bind(
"arg");
463 auto IsMemberCallee = callee(functionDecl(unless(isStaticStorageClass())));
464 auto CallMoveMatcher =
465 callExpr(callee(functionDecl(
getNameMatcher(InvalidationFunctions))
467 anyOf(cxxMemberCallExpr(IsMemberCallee, on(Arg)),
468 callExpr(unless(cxxMemberCallExpr(IsMemberCallee)),
469 hasArgument(0, Arg))),
471 unless(hasParent(TryEmplaceMatcher)), expr().bind(
"call-move"),
472 anyOf(hasAncestor(compoundStmt(
473 hasParent(lambdaExpr().bind(
"containing-lambda")))),
474 hasAncestor(functionDecl(anyOf(
476 hasAnyConstructorInitializer(withInitializer(
477 expr(anyOf(equalsBoundNode(
"call-move"),
479 equalsBoundNode(
"call-move")))))
480 .bind(
"containing-ctor-init"))))
481 .bind(
"containing-ctor"),
482 functionDecl().bind(
"containing-func"))))));
491 forEach(expr(ignoringParenImpCasts(CallMoveMatcher))),
498 unless(initListExpr()),
499 unless(expr(ignoringParenImpCasts(equalsBoundNode(
"call-move")))))
500 .bind(
"moving-call")),
505 const auto *ContainingCtor =
506 Result.Nodes.getNodeAs<CXXConstructorDecl>(
"containing-ctor");
507 const auto *ContainingCtorInit =
508 Result.Nodes.getNodeAs<Expr>(
"containing-ctor-init");
509 const auto *ContainingLambda =
510 Result.Nodes.getNodeAs<LambdaExpr>(
"containing-lambda");
511 const auto *ContainingFunc =
512 Result.Nodes.getNodeAs<FunctionDecl>(
"containing-func");
513 const auto *CallMove = Result.Nodes.getNodeAs<CallExpr>(
"call-move");
514 const auto *MovingCall = Result.Nodes.getNodeAs<Expr>(
"moving-call");
515 const auto *Arg = Result.Nodes.getNodeAs<DeclRefExpr>(
"arg");
516 const auto *MoveDecl = Result.Nodes.getNodeAs<FunctionDecl>(
"move-decl");
518 if (!MovingCall || !MovingCall->getExprLoc().isValid())
519 MovingCall = CallMove;
523 if (!Arg->getDecl()->getDeclContext()->isFunctionOrMethod())
527 llvm::SmallVector<Stmt *> CodeBlocks{};
528 if (ContainingCtor) {
529 CodeBlocks.push_back(ContainingCtor->getBody());
530 if (ContainingCtorInit) {
532 bool BeforeMove{
true};
533 for (
const CXXCtorInitializer *Init : ContainingCtor->inits()) {
534 if (BeforeMove && Init->getInit()->IgnoreImplicit() ==
535 ContainingCtorInit->IgnoreImplicit())
538 CodeBlocks.push_back(Init->getInit());
541 }
else if (ContainingLambda) {
542 CodeBlocks.push_back(ContainingLambda->getBody());
543 }
else if (ContainingFunc) {
544 CodeBlocks.push_back(ContainingFunc->getBody());
548 UseAfterMoveFinder Finder(Result.Context, InvalidationFunctions);
549 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 void emitDiagnostic(const Expr *MovingCall, const DeclRefExpr *MoveArg, const UseAfterMove &Use, ClangTidyCheck *Check, ASTContext *Context, MoveType Type)
static bool isStandardSmartPointer(const ValueDecl *VD)
static MoveType determineMoveType(const FunctionDecl *FuncDecl)
static auto getNameMatcher(llvm::ArrayRef< StringRef > InvalidationFunctions)
static StatementMatcher inDecltypeOrTemplateArg()
inline ::clang::ast_matchers::internal::Matcher< NamedDecl > matchesAnyListedName(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[]