[clan-tidy] Fix false positive in bugprone-infinite-loop
The checker bugprone-infinite-loop does not track changes of
variables in the initialization expression of a variable
declared inside the condition of the while statement. This
leads to false positives, similarly to the one in the bug
report https://bugs.llvm.org/show_bug.cgi?id=44618. This
patch fixes this issue by enabling tracking of the variables
of this expression as well.
Differential Revision: https://reviews.llvm.org/D73270
diff --git a/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp
index 81ae45a..c771ba8 100644
--- a/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/InfiniteLoopCheck.cpp
@@ -170,17 +170,33 @@
const auto *LoopStmt = Result.Nodes.getNodeAs<Stmt>("loop-stmt");
const auto *Func = Result.Nodes.getNodeAs<FunctionDecl>("func");
+ bool ShouldHaveConditionVariables = true;
+ if (const auto *While = dyn_cast<WhileStmt>(LoopStmt)) {
+ if (const VarDecl *LoopVarDecl = While->getConditionVariable()) {
+ if (const Expr *Init = LoopVarDecl->getInit()) {
+ ShouldHaveConditionVariables = false;
+ Cond = Init;
+ }
+ }
+ }
+
if (isAtLeastOneCondVarChanged(Func, LoopStmt, Cond, Result.Context))
return;
std::string CondVarNames = getCondVarNames(Cond);
- if (CondVarNames.empty())
+ if (ShouldHaveConditionVariables && CondVarNames.empty())
return;
- diag(LoopStmt->getBeginLoc(),
- "this loop is infinite; none of its condition variables (%0)"
- " are updated in the loop body")
+ if (CondVarNames.empty()) {
+ diag(LoopStmt->getBeginLoc(),
+ "this loop is infinite; it does not check any variables in the"
+ " condition");
+ } else {
+ diag(LoopStmt->getBeginLoc(),
+ "this loop is infinite; none of its condition variables (%0)"
+ " are updated in the loop body")
<< CondVarNames;
+ }
}
} // namespace bugprone