Skip to content

Commit 6a4bfc4

Browse files
committed
[Clang] enhance loop analysis to handle variable changes inside lambdas
1 parent d3153ad commit 6a4bfc4

File tree

3 files changed

+40
-2
lines changed

3 files changed

+40
-2
lines changed

clang/docs/ReleaseNotes.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,8 @@ Improvements to Clang's diagnostics
379379

380380
Fixes #GH131127
381381

382+
- The ``-Wloop-analysis`` warning now handles variable modifications inside lambda expressions (#GH132038).
383+
382384
Improvements to Clang's time-trace
383385
----------------------------------
384386

clang/lib/Sema/SemaStmt.cpp

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2002,9 +2002,30 @@ namespace {
20022002
}
20032003

20042004
void VisitDeclRefExpr(DeclRefExpr *E) {
2005-
if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
2005+
if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
20062006
if (Decls.count(VD))
20072007
FoundDecl = true;
2008+
} else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getDecl());
2009+
MD && isLambdaCallOperator(MD)) {
2010+
for (const auto &Capture : MD->getParent()->captures()) {
2011+
if (!Capture.capturesVariable())
2012+
continue;
2013+
2014+
if (VarDecl *VD = dyn_cast<VarDecl>(Capture.getCapturedVar())) {
2015+
if (Decls.count(VD))
2016+
FoundDecl = true;
2017+
}
2018+
}
2019+
}
2020+
}
2021+
2022+
void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
2023+
Expr *Callee = E->getCallee();
2024+
if (Callee) {
2025+
Visit(E->getCallee());
2026+
for (auto *Arg : E->arguments())
2027+
Visit(Arg->IgnoreParenImpCasts());
2028+
}
20082029
}
20092030

20102031
void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
@@ -2021,7 +2042,7 @@ namespace {
20212042

20222043
bool FoundDeclInUse() { return FoundDecl; }
20232044

2024-
}; // end class DeclMatcher
2045+
}; // end class DeclMatcher
20252046

20262047
void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
20272048
Expr *Third, Stmt *Body) {

clang/test/SemaCXX/warn-loop-analysis.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,3 +299,18 @@ void test10() {
299299
for (auto[i, j, k] = arr; i < a; ++i) { }
300300
for (auto[i, j, k] = arr; i < a; ++arr[0]) { }
301301
};
302+
303+
extern void foo(int);
304+
void test11() {
305+
int a = 0;
306+
auto incr_a = [&a]() { ++a; };
307+
308+
for (int b = 10; a <= b; incr_a())
309+
foo(a);
310+
311+
for (int b = 10; a <= b;)
312+
incr_a();
313+
314+
for (int b = 10; a <= b; [&a]() { ++a; }()) { }
315+
for (int b = 10; a <= b; [&a]() { }()) { }
316+
}

0 commit comments

Comments
 (0)