clang-tools 22.0.0git
InfiniteLoopCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "InfiniteLoopCheck.h"
10#include "../utils/Aliasing.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/Analysis/Analyses/ExprMutationAnalyzer.h"
14#include "clang/Analysis/CallGraph.h"
15#include "llvm/ADT/SCCIterator.h"
16
17using namespace clang::ast_matchers;
18using clang::ast_matchers::internal::Matcher;
20
21namespace clang::tidy::bugprone {
22
23namespace {
24/// matches a Decl if it has a "no return" attribute of any kind
25AST_MATCHER(Decl, declHasNoReturnAttr) {
26 return Node.hasAttr<NoReturnAttr>() || Node.hasAttr<CXX11NoReturnAttr>() ||
27 Node.hasAttr<C11NoReturnAttr>();
28}
29
30/// matches a FunctionType if the type includes the GNU no return attribute
31AST_MATCHER(FunctionType, typeHasNoReturnAttr) {
32 return Node.getNoReturnAttr();
33}
34} // namespace
35
36static Matcher<Stmt> loopEndingStmt(Matcher<Stmt> Internal) {
37 const Matcher<QualType> IsNoReturnFunType =
38 ignoringParens(functionType(typeHasNoReturnAttr()));
39 Matcher<Decl> IsNoReturnDecl =
40 anyOf(declHasNoReturnAttr(), functionDecl(hasType(IsNoReturnFunType)),
41 varDecl(hasType(blockPointerType(pointee(IsNoReturnFunType)))));
42
43 return stmt(anyOf(
44 mapAnyOf(breakStmt, returnStmt, gotoStmt, cxxThrowExpr).with(Internal),
45 callExpr(Internal,
46 callee(mapAnyOf(functionDecl, /* block callee */ varDecl)
47 .with(IsNoReturnDecl))),
48 objcMessageExpr(Internal, callee(IsNoReturnDecl))));
49}
50
51/// Return whether `Var` was changed in `LoopStmt`.
52static bool isChanged(const Stmt *LoopStmt, const ValueDecl *Var,
53 ASTContext *Context) {
54 if (const auto *ForLoop = dyn_cast<ForStmt>(LoopStmt))
55 return (ForLoop->getInc() &&
56 ExprMutationAnalyzer(*ForLoop->getInc(), *Context)
57 .isMutated(Var)) ||
58 (ForLoop->getBody() &&
59 ExprMutationAnalyzer(*ForLoop->getBody(), *Context)
60 .isMutated(Var)) ||
61 (ForLoop->getCond() &&
62 ExprMutationAnalyzer(*ForLoop->getCond(), *Context).isMutated(Var));
63
64 return ExprMutationAnalyzer(*LoopStmt, *Context).isMutated(Var);
65}
66
67static bool isVarPossiblyChanged(const Decl *Func, const Stmt *LoopStmt,
68 const ValueDecl *VD, ASTContext *Context) {
69 const VarDecl *Var = nullptr;
70 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
71 Var = VarD;
72 } else if (const auto *BD = dyn_cast<BindingDecl>(VD)) {
73 if (const auto *DD = dyn_cast<DecompositionDecl>(BD->getDecomposedDecl()))
74 Var = DD;
75 }
76
77 if (!Var)
78 return false;
79
80 if (!Var->isLocalVarDeclOrParm() || Var->getType().isVolatileQualified())
81 return true;
82
83 if (!VD->getType().getTypePtr()->isIntegerType())
84 return true;
85
86 return hasPtrOrReferenceInFunc(Func, VD) || isChanged(LoopStmt, VD, Context);
87 // FIXME: Track references.
88}
89
90/// Return whether `Cond` is a variable that is possibly changed in `LoopStmt`.
91static bool isVarThatIsPossiblyChanged(const Decl *Func, const Stmt *LoopStmt,
92 const Stmt *Cond, ASTContext *Context) {
93 if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
94 if (const auto *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
95 return isVarPossiblyChanged(Func, LoopStmt, VD, Context);
96 } else if (isa<MemberExpr, CallExpr, ObjCIvarRefExpr, ObjCPropertyRefExpr,
97 ObjCMessageExpr>(Cond)) {
98 // FIXME: Handle MemberExpr.
99 return true;
100 } else if (const auto *CE = dyn_cast<CastExpr>(Cond)) {
101 QualType T = CE->getType();
102 while (true) {
103 if (T.isVolatileQualified())
104 return true;
105
106 if (!T->isAnyPointerType() && !T->isReferenceType())
107 break;
108
109 T = T->getPointeeType();
110 }
111 }
112
113 return false;
114}
115
116/// Return whether at least one variable of `Cond` changed in `LoopStmt`.
117static bool isAtLeastOneCondVarChanged(const Decl *Func, const Stmt *LoopStmt,
118 const Stmt *Cond, ASTContext *Context) {
119 if (isVarThatIsPossiblyChanged(Func, LoopStmt, Cond, Context))
120 return true;
121
122 return llvm::any_of(Cond->children(), [&](const Stmt *Child) {
123 return Child && isAtLeastOneCondVarChanged(Func, LoopStmt, Child, Context);
124 });
125}
126
127/// Return the variable names in `Cond`.
128static std::string getCondVarNames(const Stmt *Cond) {
129 if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
130 if (const auto *Var = dyn_cast<VarDecl>(DRE->getDecl()))
131 return std::string(Var->getName());
132
133 if (const auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
134 return std::string(BD->getName());
135 }
136
137 std::string Result;
138 for (const Stmt *Child : Cond->children()) {
139 if (!Child)
140 continue;
141
142 const std::string NewNames = getCondVarNames(Child);
143 if (!Result.empty() && !NewNames.empty())
144 Result += ", ";
145 Result += NewNames;
146 }
147 return Result;
148}
149
150static bool isKnownToHaveValue(const Expr &Cond, const ASTContext &Ctx,
151 bool ExpectedValue) {
152 if (Cond.isValueDependent()) {
153 if (const auto *BinOp = dyn_cast<BinaryOperator>(&Cond)) {
154 // Conjunctions (disjunctions) can still be handled if at least one
155 // conjunct (disjunct) is known to be false (true).
156 if (!ExpectedValue && BinOp->getOpcode() == BO_LAnd)
157 return isKnownToHaveValue(*BinOp->getLHS(), Ctx, false) ||
158 isKnownToHaveValue(*BinOp->getRHS(), Ctx, false);
159 if (ExpectedValue && BinOp->getOpcode() == BO_LOr)
160 return isKnownToHaveValue(*BinOp->getLHS(), Ctx, true) ||
161 isKnownToHaveValue(*BinOp->getRHS(), Ctx, true);
162 if (BinOp->getOpcode() == BO_Comma)
163 return isKnownToHaveValue(*BinOp->getRHS(), Ctx, ExpectedValue);
164 } else if (const auto *UnOp = dyn_cast<UnaryOperator>(&Cond)) {
165 if (UnOp->getOpcode() == UO_LNot)
166 return isKnownToHaveValue(*UnOp->getSubExpr(), Ctx, !ExpectedValue);
167 } else if (const auto *Paren = dyn_cast<ParenExpr>(&Cond))
168 return isKnownToHaveValue(*Paren->getSubExpr(), Ctx, ExpectedValue);
169 else if (const auto *ImplCast = dyn_cast<ImplicitCastExpr>(&Cond))
170 return isKnownToHaveValue(*ImplCast->getSubExpr(), Ctx, ExpectedValue);
171 return false;
172 }
173 bool Result = false;
174 if (Cond.EvaluateAsBooleanCondition(Result, Ctx))
175 return Result == ExpectedValue;
176 return false;
177}
178
179/// populates the set `Callees` with all function (and objc method) declarations
180/// called in `StmtNode` if all visited call sites have resolved call targets.
181///
182/// \return true iff all `CallExprs` visited have callees; false otherwise
183/// indicating there is an unresolved indirect call.
184static bool populateCallees(const Stmt *StmtNode,
185 llvm::SmallPtrSet<const Decl *, 16> &Callees) {
186 if (const auto *Call = dyn_cast<CallExpr>(StmtNode)) {
187 const Decl *Callee = Call->getDirectCallee();
188
189 if (!Callee)
190 return false; // unresolved call
191 Callees.insert(Callee->getCanonicalDecl());
192 }
193 if (const auto *Call = dyn_cast<ObjCMessageExpr>(StmtNode)) {
194 const Decl *Callee = Call->getMethodDecl();
195
196 if (!Callee)
197 return false; // unresolved call
198 Callees.insert(Callee->getCanonicalDecl());
199 }
200 for (const Stmt *Child : StmtNode->children())
201 if (Child && !populateCallees(Child, Callees))
202 return false;
203 return true;
204}
205
206/// returns true iff `SCC` contains `Func` and its' function set overlaps with
207/// `Callees`
208static bool overlap(ArrayRef<CallGraphNode *> SCC,
209 const llvm::SmallPtrSet<const Decl *, 16> &Callees,
210 const Decl *Func) {
211 bool ContainsFunc = false, Overlap = false;
212
213 for (const CallGraphNode *GNode : SCC) {
214 const Decl *CanDecl = GNode->getDecl()->getCanonicalDecl();
215
216 ContainsFunc = ContainsFunc || (CanDecl == Func);
217 Overlap = Overlap || Callees.contains(CanDecl);
218 if (ContainsFunc && Overlap)
219 return true;
220 }
221 return false;
222}
223
224/// returns true iff `Cond` involves at least one static local variable.
225static bool hasStaticLocalVariable(const Stmt *Cond) {
226 if (const auto *DRE = dyn_cast<DeclRefExpr>(Cond)) {
227 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
228 if (VD->isStaticLocal())
229 return true;
230
231 if (const auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
232 if (const auto *DD = dyn_cast<DecompositionDecl>(BD->getDecomposedDecl()))
233 if (DD->isStaticLocal())
234 return true;
235 }
236
237 return llvm::any_of(Cond->children(), [](const Stmt *Child) {
238 return Child && hasStaticLocalVariable(Child);
239 });
240}
241
242/// Tests if the loop condition `Cond` involves static local variables and
243/// the enclosing function `Func` is recursive.
244///
245/// \code
246/// void f() {
247/// static int i = 10;
248/// i--;
249/// while (i >= 0) f();
250/// }
251/// \endcode
252/// The example above is NOT an infinite loop.
253static bool hasRecursionOverStaticLoopCondVariables(const Expr *Cond,
254 const Stmt *LoopStmt,
255 const Decl *Func,
256 const ASTContext *Ctx) {
257 if (!hasStaticLocalVariable(Cond))
258 return false;
259
260 llvm::SmallPtrSet<const Decl *, 16> CalleesInLoop;
261
262 if (!populateCallees(LoopStmt, CalleesInLoop)) {
263 // If there are unresolved indirect calls, we assume there could
264 // be recursion so to avoid false alarm.
265 return true;
266 }
267 if (CalleesInLoop.empty())
268 return false;
269
270 TranslationUnitDecl *TUDecl = Ctx->getTranslationUnitDecl();
271 CallGraph CG;
272
273 CG.addToCallGraph(TUDecl);
274 // For each `SCC` containing `Func`, if functions in the `SCC`
275 // overlap with `CalleesInLoop`, there is a recursive call in `LoopStmt`.
276 for (llvm::scc_iterator<CallGraph *> SCCI = llvm::scc_begin(&CG),
277 SCCE = llvm::scc_end(&CG);
278 SCCI != SCCE; ++SCCI) {
279 if (!SCCI.hasCycle()) // We only care about cycles, not standalone nodes.
280 continue;
281 // `SCC`s are mutually disjoint, so there will be no redundancy in
282 // comparing `SCC` with the callee set one by one.
283 if (overlap(*SCCI, CalleesInLoop, Func->getCanonicalDecl()))
284 return true;
285 }
286 return false;
287}
288
289void InfiniteLoopCheck::registerMatchers(MatchFinder *Finder) {
290 const auto LoopCondition = allOf(
291 hasCondition(expr(forCallable(decl().bind("func"))).bind("condition")),
292 unless(hasBody(hasDescendant(
293 loopEndingStmt(forCallable(equalsBoundNode("func")))))));
294
295 Finder->addMatcher(mapAnyOf(whileStmt, doStmt, forStmt)
296 .with(LoopCondition)
297 .bind("loop-stmt"),
298 this);
299}
300
301void InfiniteLoopCheck::check(const MatchFinder::MatchResult &Result) {
302 const auto *Cond = Result.Nodes.getNodeAs<Expr>("condition");
303 const auto *LoopStmt = Result.Nodes.getNodeAs<Stmt>("loop-stmt");
304 const auto *Func = Result.Nodes.getNodeAs<Decl>("func");
305
306 if (isKnownToHaveValue(*Cond, *Result.Context, false))
307 return;
308
309 bool ShouldHaveConditionVariables = true;
310 if (const auto *While = dyn_cast<WhileStmt>(LoopStmt)) {
311 if (const VarDecl *LoopVarDecl = While->getConditionVariable()) {
312 if (const Expr *Init = LoopVarDecl->getInit()) {
313 ShouldHaveConditionVariables = false;
314 Cond = Init;
315 }
316 }
317 }
318
319 if (ExprMutationAnalyzer::isUnevaluated(LoopStmt, *Result.Context))
320 return;
321
322 if (isAtLeastOneCondVarChanged(Func, LoopStmt, Cond, Result.Context))
323 return;
324 if (hasRecursionOverStaticLoopCondVariables(Cond, LoopStmt, Func,
325 Result.Context))
326 return;
327
328 const std::string CondVarNames = getCondVarNames(Cond);
329 if (ShouldHaveConditionVariables && CondVarNames.empty())
330 return;
331
332 if (CondVarNames.empty()) {
333 diag(LoopStmt->getBeginLoc(),
334 "this loop is infinite; it does not check any variables in the"
335 " condition");
336 } else {
337 diag(LoopStmt->getBeginLoc(),
338 "this loop is infinite; none of its condition variables (%0)"
339 " are updated in the loop body")
340 << CondVarNames;
341 }
342}
343
344} // namespace clang::tidy::bugprone
bool hasPtrOrReferenceInFunc(const Decl *Func, const ValueDecl *Var)
Returns whether Var has a pointer or reference in Func.
Definition Aliasing.cpp:86
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
static bool isChanged(const Stmt *LoopStmt, const ValueDecl *Var, ASTContext *Context)
Return whether Var was changed in LoopStmt.
static Matcher< Stmt > loopEndingStmt(Matcher< Stmt > Internal)
static bool isKnownToHaveValue(const Expr &Cond, const ASTContext &Ctx, bool ExpectedValue)
static bool hasStaticLocalVariable(const Stmt *Cond)
returns true iff Cond involves at least one static local variable.
static bool isVarThatIsPossiblyChanged(const Decl *Func, const Stmt *LoopStmt, const Stmt *Cond, ASTContext *Context)
Return whether Cond is a variable that is possibly changed in LoopStmt.
static bool hasRecursionOverStaticLoopCondVariables(const Expr *Cond, const Stmt *LoopStmt, const Decl *Func, const ASTContext *Ctx)
Tests if the loop condition Cond involves static local variables and the enclosing function Func is r...
static bool overlap(ArrayRef< CallGraphNode * > SCC, const llvm::SmallPtrSet< const Decl *, 16 > &Callees, const Decl *Func)
returns true iff SCC contains Func and its' function set overlaps with Callees
static std::string getCondVarNames(const Stmt *Cond)
Return the variable names in Cond.
static bool populateCallees(const Stmt *StmtNode, llvm::SmallPtrSet< const Decl *, 16 > &Callees)
populates the set Callees with all function (and objc method) declarations called in StmtNode if all ...
static bool isVarPossiblyChanged(const Decl *Func, const Stmt *LoopStmt, const ValueDecl *VD, ASTContext *Context)
static bool isAtLeastOneCondVarChanged(const Decl *Func, const Stmt *LoopStmt, const Stmt *Cond, ASTContext *Context)
Return whether at least one variable of Cond changed in LoopStmt.
AST_MATCHER(BinaryOperator, isRelationalOperator)
bool hasPtrOrReferenceInFunc(const Decl *Func, const ValueDecl *Var)
Returns whether Var has a pointer or reference in Func.
Definition Aliasing.cpp:86