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);
106 llvm::make_unique<ExprSequence>(TheCFG.get(), FunctionBody, Context);
107 BlockMap = llvm::make_unique<StmtToBlockMap>(TheCFG.get(), Context);
110 const CFGBlock *Block = BlockMap->blockContainingStmt(MovingCall);
114 return findInternal(Block, MovingCall, MovedVariable, TheUseAfterMove);
117 bool UseAfterMoveFinder::findInternal(
const CFGBlock *Block,
118 const Expr *MovingCall,
119 const ValueDecl *MovedVariable,
120 UseAfterMove *TheUseAfterMove) {
121 if (Visited.count(Block))
127 Visited.insert(Block);
130 llvm::SmallVector<const DeclRefExpr *, 1> Uses;
131 llvm::SmallPtrSet<const Stmt *, 1> Reinits;
132 getUsesAndReinits(Block, MovedVariable, &Uses, &Reinits);
136 llvm::SmallVector<const Stmt *, 1> ReinitsToDelete;
137 for (
const Stmt *Reinit : Reinits) {
138 if (MovingCall && Sequence->potentiallyAfter(MovingCall, Reinit))
139 ReinitsToDelete.push_back(Reinit);
141 for (
const Stmt *Reinit : ReinitsToDelete) {
142 Reinits.erase(Reinit);
146 for (
const DeclRefExpr *Use : Uses) {
147 if (!MovingCall || Sequence->potentiallyAfter(Use, MovingCall)) {
151 bool HaveSavingReinit =
false;
152 for (
const Stmt *Reinit : Reinits) {
153 if (!Sequence->potentiallyAfter(Reinit, Use))
154 HaveSavingReinit =
true;
157 if (!HaveSavingReinit) {
158 TheUseAfterMove->DeclRef = Use;
164 TheUseAfterMove->EvaluationOrderUndefined =
165 MovingCall !=
nullptr &&
166 Sequence->potentiallyAfter(MovingCall, Use);
175 if (Reinits.empty()) {
176 for (
const auto &Succ : Block->succs()) {
177 if (Succ && findInternal(Succ,
nullptr, MovedVariable, TheUseAfterMove))
185 void UseAfterMoveFinder::getUsesAndReinits(
186 const CFGBlock *Block,
const ValueDecl *MovedVariable,
187 llvm::SmallVectorImpl<const DeclRefExpr *> *Uses,
188 llvm::SmallPtrSetImpl<const Stmt *> *Reinits) {
189 llvm::SmallPtrSet<const DeclRefExpr *, 1> DeclRefs;
190 llvm::SmallPtrSet<const DeclRefExpr *, 1> ReinitDeclRefs;
192 getDeclRefs(Block, MovedVariable, &DeclRefs);
193 getReinits(Block, MovedVariable, Reinits, &ReinitDeclRefs);
197 for (
const DeclRefExpr *
DeclRef : DeclRefs) {
198 if (!ReinitDeclRefs.count(
DeclRef))
203 std::sort(Uses->begin(), Uses->end(),
204 [](
const DeclRefExpr *D1,
const DeclRefExpr *D2) {
205 return D1->getExprLoc() < D2->getExprLoc();
210 const Type *TheType = VD->getType().getNonReferenceType().getTypePtrOrNull();
214 const CXXRecordDecl *RecordDecl = TheType->getAsCXXRecordDecl();
218 const IdentifierInfo *ID = RecordDecl->getIdentifier();
222 StringRef
Name = ID->getName();
223 if (Name !=
"unique_ptr" && Name !=
"shared_ptr" && Name !=
"weak_ptr")
226 return RecordDecl->getDeclContext()->isStdNamespace();
229 void UseAfterMoveFinder::getDeclRefs(
230 const CFGBlock *Block,
const Decl *MovedVariable,
231 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs) {
233 for (
const auto &Elem : *Block) {
234 Optional<CFGStmt> S = Elem.getAs<CFGStmt>();
238 auto addDeclRefs = [
this, Block,
239 DeclRefs](
const ArrayRef<BoundNodes> Matches) {
240 for (
const auto &Match : Matches) {
241 const auto *
DeclRef = Match.getNodeAs<DeclRefExpr>(
"declref");
242 const auto *Operator = Match.getNodeAs<CXXOperatorCallExpr>(
"operator");
253 auto DeclRefMatcher = declRefExpr(hasDeclaration(equalsNode(MovedVariable)),
257 addDeclRefs(match(findAll(DeclRefMatcher), *S->getStmt(), *Context));
259 findAll(cxxOperatorCallExpr(anyOf(hasOverloadedOperatorName(
"*"),
260 hasOverloadedOperatorName(
"->"),
261 hasOverloadedOperatorName(
"[]")),
262 hasArgument(0, DeclRefMatcher))
264 *S->getStmt(), *Context));
268 void UseAfterMoveFinder::getReinits(
269 const CFGBlock *Block,
const ValueDecl *MovedVariable,
270 llvm::SmallPtrSetImpl<const Stmt *> *Stmts,
271 llvm::SmallPtrSetImpl<const DeclRefExpr *> *DeclRefs) {
272 auto DeclRefMatcher =
273 declRefExpr(hasDeclaration(equalsNode(MovedVariable))).bind(
"declref");
275 auto StandardContainerTypeMatcher = hasType(hasUnqualifiedDesugaredType(
276 recordType(hasDeclaration(cxxRecordDecl(hasAnyName(
277 "::std::basic_string",
"::std::vector",
"::std::deque",
278 "::std::forward_list",
"::std::list",
"::std::set",
"::std::map",
279 "::std::multiset",
"::std::multimap",
"::std::unordered_set",
280 "::std::unordered_map",
"::std::unordered_multiset",
281 "::std::unordered_multimap"))))));
283 auto StandardSmartPointerTypeMatcher = hasType(hasUnqualifiedDesugaredType(
284 recordType(hasDeclaration(cxxRecordDecl(hasAnyName(
285 "::std::unique_ptr",
"::std::shared_ptr",
"::std::weak_ptr"))))));
293 binaryOperator(hasOperatorName(
"="), hasLHS(DeclRefMatcher)),
294 cxxOperatorCallExpr(hasOverloadedOperatorName(
"="),
295 hasArgument(0, DeclRefMatcher)),
298 declStmt(hasDescendant(equalsNode(MovedVariable))),
301 on(expr(DeclRefMatcher, StandardContainerTypeMatcher)),
307 callee(cxxMethodDecl(hasAnyName(
"clear",
"assign")))),
310 on(expr(DeclRefMatcher, StandardSmartPointerTypeMatcher)),
311 callee(cxxMethodDecl(hasName(
"reset")))),
315 callee(cxxMethodDecl(hasAttr(clang::attr::Reinitializes)))),
317 callExpr(forEachArgumentWithParam(
318 unaryOperator(hasOperatorName(
"&"),
319 hasUnaryOperand(DeclRefMatcher)),
320 unless(parmVarDecl(hasType(pointsTo(isConstQualified())))))),
323 callExpr(forEachArgumentWithParam(
325 unless(parmVarDecl(hasType(
326 references(qualType(isConstQualified())))))),
327 unless(callee(functionDecl(hasName(
"::std::move")))))))
332 for (
const auto &Elem : *Block) {
333 Optional<CFGStmt> S = Elem.getAs<CFGStmt>();
337 SmallVector<BoundNodes, 1> Matches =
338 match(findAll(ReinitMatcher), *S->getStmt(), *Context);
340 for (
const auto &Match : Matches) {
341 const auto *TheStmt = Match.getNodeAs<Stmt>(
"reinit");
342 const auto *TheDeclRef = Match.getNodeAs<DeclRefExpr>(
"declref");
343 if (TheStmt && BlockMap->blockContainingStmt(TheStmt) == Block) {
344 Stmts->insert(TheStmt);
350 DeclRefs->insert(TheDeclRef);
358 ASTContext *Context) {
359 SourceLocation UseLoc = Use.DeclRef->getExprLoc();
360 SourceLocation MoveLoc = MovingCall->getExprLoc();
362 Check->
diag(UseLoc,
"'%0' used after it was moved")
363 << MoveArg->getDecl()->getName();
364 Check->
diag(MoveLoc,
"move occurred here", DiagnosticIDs::Note);
365 if (Use.EvaluationOrderUndefined) {
367 "the use and move are unsequenced, i.e. there is no guarantee " 368 "about the order in which they are evaluated",
369 DiagnosticIDs::Note);
370 }
else if (UseLoc < MoveLoc || Use.DeclRef == MoveArg) {
372 "the use happens in a later loop iteration than the move",
373 DiagnosticIDs::Note);
377 void UseAfterMoveCheck::registerMatchers(MatchFinder *Finder) {
378 if (!getLangOpts().CPlusPlus11)
381 auto CallMoveMatcher =
382 callExpr(callee(functionDecl(hasName(
"::std::move"))), argumentCountIs(1),
383 hasArgument(0, declRefExpr().bind(
"arg")),
384 anyOf(hasAncestor(lambdaExpr().bind(
"containing-lambda")),
385 hasAncestor(functionDecl().bind(
"containing-func"))),
393 stmt(forEach(expr(ignoringParenImpCasts(CallMoveMatcher))),
400 unless(initListExpr()),
401 unless(expr(ignoringParenImpCasts(equalsBoundNode(
"call-move")))))
402 .bind(
"moving-call"),
406 void UseAfterMoveCheck::check(
const MatchFinder::MatchResult &
Result) {
407 const auto *ContainingLambda =
408 Result.Nodes.getNodeAs<LambdaExpr>(
"containing-lambda");
409 const auto *ContainingFunc =
410 Result.Nodes.getNodeAs<FunctionDecl>(
"containing-func");
411 const auto *CallMove = Result.Nodes.getNodeAs<CallExpr>(
"call-move");
412 const auto *MovingCall = Result.Nodes.getNodeAs<Expr>(
"moving-call");
413 const auto *Arg = Result.Nodes.getNodeAs<DeclRefExpr>(
"arg");
415 if (!MovingCall || !MovingCall->getExprLoc().isValid())
416 MovingCall = CallMove;
418 Stmt *FunctionBody =
nullptr;
419 if (ContainingLambda)
420 FunctionBody = ContainingLambda->getBody();
421 else if (ContainingFunc)
422 FunctionBody = ContainingFunc->getBody();
428 if (!Arg->getDecl()->getDeclContext()->isFunctionOrMethod())
431 UseAfterMoveFinder finder(Result.Context);
433 if (finder.find(FunctionBody, MovingCall, Arg->getDecl(), &Use))
Base class for all clang-tidy checks.
static constexpr llvm::StringLiteral Name
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
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)