12 #include "clang/Analysis/CFG.h" 13 #include "clang/Lex/Lexer.h" 15 #include "../utils/ExprSequence.h" 38 class UseAfterMoveFinder {
40 UseAfterMoveFinder(ASTContext *TheContext);
46 bool find(Stmt *FunctionBody,
const Expr *MovingCall,
47 const ValueDecl *MovedVariable, UseAfterMove *TheUseAfterMove);
50 bool findInternal(
const CFGBlock *Block,
const Expr *MovingCall,
51 const ValueDecl *MovedVariable,
52 UseAfterMove *TheUseAfterMove);
53 void getUsesAndReinits(
const CFGBlock *Block,
const ValueDecl *MovedVariable,
54 llvm::SmallVectorImpl<const DeclRefExpr *> *Uses,
55 llvm::SmallPtrSetImpl<const Stmt *> *Reinits);
56 void getDeclRefs(
const CFGBlock *Block,
const Decl *MovedVariable,
57 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs);
58 void getReinits(
const CFGBlock *Block,
const ValueDecl *MovedVariable,
59 llvm::SmallPtrSetImpl<const Stmt *> *Stmts,
60 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs);
63 std::unique_ptr<ExprSequence> Sequence;
64 std::unique_ptr<StmtToBlockMap> BlockMap;
65 llvm::SmallPtrSet<const CFGBlock *, 8> Visited;
79 return anyOf(hasAncestor(typeLoc()),
80 hasAncestor(declRefExpr(
81 to(functionDecl(ast_matchers::isTemplateInstantiation())))));
84 UseAfterMoveFinder::UseAfterMoveFinder(ASTContext *TheContext)
85 : Context(TheContext) {}
87 bool UseAfterMoveFinder::find(Stmt *FunctionBody,
const Expr *MovingCall,
88 const ValueDecl *MovedVariable,
89 UseAfterMove *TheUseAfterMove) {
97 CFG::BuildOptions Options;
98 Options.AddImplicitDtors =
true;
99 Options.AddTemporaryDtors =
true;
100 std::unique_ptr<CFG> TheCFG =
101 CFG::buildCFG(
nullptr, FunctionBody, Context, Options);
105 Sequence.reset(
new ExprSequence(TheCFG.get(), Context));
109 const CFGBlock *Block = BlockMap->blockContainingStmt(MovingCall);
113 return findInternal(Block, MovingCall, MovedVariable, TheUseAfterMove);
116 bool UseAfterMoveFinder::findInternal(
const CFGBlock *Block,
117 const Expr *MovingCall,
118 const ValueDecl *MovedVariable,
119 UseAfterMove *TheUseAfterMove) {
120 if (Visited.count(Block))
126 Visited.insert(Block);
129 llvm::SmallVector<const DeclRefExpr *, 1> Uses;
130 llvm::SmallPtrSet<const Stmt *, 1> Reinits;
131 getUsesAndReinits(Block, MovedVariable, &Uses, &Reinits);
135 llvm::SmallVector<const Stmt *, 1> ReinitsToDelete;
136 for (
const Stmt *Reinit : Reinits) {
137 if (MovingCall && Sequence->potentiallyAfter(MovingCall, Reinit))
138 ReinitsToDelete.push_back(Reinit);
140 for (
const Stmt *Reinit : ReinitsToDelete) {
141 Reinits.erase(Reinit);
145 for (
const DeclRefExpr *Use : Uses) {
146 if (!MovingCall || Sequence->potentiallyAfter(Use, MovingCall)) {
150 bool HaveSavingReinit =
false;
151 for (
const Stmt *Reinit : Reinits) {
152 if (!Sequence->potentiallyAfter(Reinit, Use))
153 HaveSavingReinit =
true;
156 if (!HaveSavingReinit) {
157 TheUseAfterMove->DeclRef = Use;
163 TheUseAfterMove->EvaluationOrderUndefined =
164 MovingCall !=
nullptr &&
165 Sequence->potentiallyAfter(MovingCall, Use);
174 if (Reinits.empty()) {
175 for (
const auto &Succ : Block->succs()) {
176 if (Succ && findInternal(Succ,
nullptr, MovedVariable, TheUseAfterMove))
184 void UseAfterMoveFinder::getUsesAndReinits(
185 const CFGBlock *Block,
const ValueDecl *MovedVariable,
186 llvm::SmallVectorImpl<const DeclRefExpr *> *Uses,
187 llvm::SmallPtrSetImpl<const Stmt *> *Reinits) {
188 llvm::SmallPtrSet<const DeclRefExpr *, 1> DeclRefs;
189 llvm::SmallPtrSet<const DeclRefExpr *, 1> ReinitDeclRefs;
191 getDeclRefs(Block, MovedVariable, &DeclRefs);
192 getReinits(Block, MovedVariable, Reinits, &ReinitDeclRefs);
196 for (
const DeclRefExpr *
DeclRef : DeclRefs) {
197 if (!ReinitDeclRefs.count(
DeclRef))
202 std::sort(Uses->begin(), Uses->end(),
203 [](
const DeclRefExpr *D1,
const DeclRefExpr *D2) {
204 return D1->getExprLoc() < D2->getExprLoc();
209 const Type *TheType = VD->getType().getTypePtrOrNull();
213 const CXXRecordDecl *RecordDecl = TheType->getAsCXXRecordDecl();
217 const IdentifierInfo *ID = RecordDecl->getIdentifier();
221 StringRef
Name = ID->getName();
222 if (Name !=
"unique_ptr" && Name !=
"shared_ptr" && Name !=
"weak_ptr")
225 return RecordDecl->getDeclContext()->isStdNamespace();
228 void UseAfterMoveFinder::getDeclRefs(
229 const CFGBlock *Block,
const Decl *MovedVariable,
230 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs) {
232 for (
const auto &Elem : *Block) {
233 Optional<CFGStmt> S = Elem.getAs<CFGStmt>();
237 auto addDeclRefs = [
this, Block,
238 DeclRefs](
const ArrayRef<BoundNodes> Matches) {
239 for (
const auto &Match : Matches) {
240 const auto *
DeclRef = Match.getNodeAs<DeclRefExpr>(
"declref");
241 const auto *Operator = Match.getNodeAs<CXXOperatorCallExpr>(
"operator");
252 auto DeclRefMatcher = declRefExpr(hasDeclaration(equalsNode(MovedVariable)),
256 addDeclRefs(match(findAll(DeclRefMatcher), *S->getStmt(), *Context));
258 findAll(cxxOperatorCallExpr(anyOf(hasOverloadedOperatorName(
"*"),
259 hasOverloadedOperatorName(
"->"),
260 hasOverloadedOperatorName(
"[]")),
261 hasArgument(0, DeclRefMatcher))
263 *S->getStmt(), *Context));
267 void UseAfterMoveFinder::getReinits(
268 const CFGBlock *Block,
const ValueDecl *MovedVariable,
269 llvm::SmallPtrSetImpl<const Stmt *> *Stmts,
270 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs) {
271 auto DeclRefMatcher =
272 declRefExpr(hasDeclaration(equalsNode(MovedVariable))).bind(
"declref");
274 auto StandardContainerTypeMatcher = hasType(hasUnqualifiedDesugaredType(
275 recordType(hasDeclaration(cxxRecordDecl(hasAnyName(
276 "::std::basic_string",
"::std::vector",
"::std::deque",
277 "::std::forward_list",
"::std::list",
"::std::set",
"::std::map",
278 "::std::multiset",
"::std::multimap",
"::std::unordered_set",
279 "::std::unordered_map",
"::std::unordered_multiset",
280 "::std::unordered_multimap"))))));
282 auto StandardSmartPointerTypeMatcher = hasType(hasUnqualifiedDesugaredType(
283 recordType(hasDeclaration(cxxRecordDecl(hasAnyName(
284 "::std::unique_ptr",
"::std::shared_ptr",
"::std::weak_ptr"))))));
292 binaryOperator(hasOperatorName(
"="), hasLHS(DeclRefMatcher)),
293 cxxOperatorCallExpr(hasOverloadedOperatorName(
"="),
294 hasArgument(0, DeclRefMatcher)),
297 declStmt(hasDescendant(equalsNode(MovedVariable))),
300 on(allOf(DeclRefMatcher, StandardContainerTypeMatcher)),
306 callee(cxxMethodDecl(hasAnyName(
"clear",
"assign")))),
309 on(allOf(DeclRefMatcher, StandardSmartPointerTypeMatcher)),
310 callee(cxxMethodDecl(hasName(
"reset")))),
312 callExpr(forEachArgumentWithParam(
313 unaryOperator(hasOperatorName(
"&"),
314 hasUnaryOperand(DeclRefMatcher)),
315 unless(parmVarDecl(hasType(pointsTo(isConstQualified())))))),
318 callExpr(forEachArgumentWithParam(
320 unless(parmVarDecl(hasType(
321 references(qualType(isConstQualified())))))),
322 unless(callee(functionDecl(hasName(
"::std::move")))))))
327 for (
const auto &Elem : *Block) {
328 Optional<CFGStmt> S = Elem.getAs<CFGStmt>();
332 SmallVector<BoundNodes, 1> Matches =
333 match(findAll(ReinitMatcher), *S->getStmt(), *Context);
335 for (
const auto &Match : Matches) {
336 const auto *TheStmt = Match.getNodeAs<Stmt>(
"reinit");
337 const auto *TheDeclRef = Match.getNodeAs<DeclRefExpr>(
"declref");
338 if (TheStmt && BlockMap->blockContainingStmt(TheStmt) == Block) {
339 Stmts->insert(TheStmt);
345 DeclRefs->insert(TheDeclRef);
353 ASTContext *Context) {
354 SourceLocation UseLoc = Use.DeclRef->getExprLoc();
355 SourceLocation MoveLoc = MovingCall->getExprLoc();
357 Check->
diag(UseLoc,
"'%0' used after it was moved")
358 << MoveArg->getDecl()->getName();
359 Check->
diag(MoveLoc,
"move occurred here", DiagnosticIDs::Note);
360 if (Use.EvaluationOrderUndefined) {
362 "the use and move are unsequenced, i.e. there is no guarantee " 363 "about the order in which they are evaluated",
364 DiagnosticIDs::Note);
365 }
else if (UseLoc < MoveLoc || Use.DeclRef == MoveArg) {
367 "the use happens in a later loop iteration than the move",
368 DiagnosticIDs::Note);
372 void UseAfterMoveCheck::registerMatchers(MatchFinder *Finder) {
373 if (!getLangOpts().CPlusPlus11)
376 auto CallMoveMatcher =
377 callExpr(callee(functionDecl(hasName(
"::std::move"))), argumentCountIs(1),
378 hasArgument(0, declRefExpr().bind(
"arg")),
379 anyOf(hasAncestor(lambdaExpr().bind(
"containing-lambda")),
380 hasAncestor(functionDecl().bind(
"containing-func"))),
388 stmt(forEach(expr(ignoringParenImpCasts(CallMoveMatcher))),
395 unless(initListExpr()),
396 unless(expr(ignoringParenImpCasts(equalsBoundNode(
"call-move")))))
397 .bind(
"moving-call"),
401 void UseAfterMoveCheck::check(
const MatchFinder::MatchResult &Result) {
402 const auto *ContainingLambda =
403 Result.Nodes.getNodeAs<LambdaExpr>(
"containing-lambda");
404 const auto *ContainingFunc =
405 Result.Nodes.getNodeAs<FunctionDecl>(
"containing-func");
406 const auto *CallMove = Result.Nodes.getNodeAs<CallExpr>(
"call-move");
407 const auto *MovingCall = Result.Nodes.getNodeAs<Expr>(
"moving-call");
408 const auto *Arg = Result.Nodes.getNodeAs<DeclRefExpr>(
"arg");
410 if (!MovingCall || !MovingCall->getExprLoc().isValid())
411 MovingCall = CallMove;
413 Stmt *FunctionBody =
nullptr;
414 if (ContainingLambda)
415 FunctionBody = ContainingLambda->getBody();
416 else if (ContainingFunc)
417 FunctionBody = ContainingFunc->getBody();
423 if (!Arg->getDecl()->getDeclContext()->isFunctionOrMethod())
426 UseAfterMoveFinder finder(Result.Context);
428 if (finder.find(FunctionBody, MovingCall, Arg->getDecl(), &Use))
Maps Stmts to the CFGBlock that contains them.
Provides information about the evaluation order of (sub-)expressions within a CFGBlock.
Base class for all clang-tidy checks.
bool isStandardSmartPointer(const ValueDecl *VD)
static StatementMatcher inDecltypeOrTemplateArg()
bool EvaluationOrderUndefined
const DeclRefExpr * DeclRef
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
static void emitDiagnostic(const Expr *MovingCall, const DeclRefExpr *MoveArg, const UseAfterMove &Use, ClangTidyCheck *Check, ASTContext *Context)