Skip to content

Commit 27e98b9

Browse files
committed
[Clang] enhance loop analysis to handle variable changes inside lambdas
1 parent a9827fb commit 27e98b9

File tree

3 files changed

+38
-2
lines changed

3 files changed

+38
-2
lines changed

clang/docs/ReleaseNotes.rst

+2
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

+21-2
Original file line numberDiff line numberDiff line change
@@ -2002,9 +2002,28 @@ 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+
Visit(E->getCallee());
2024+
2025+
for (auto *Arg : E->arguments())
2026+
Visit(Arg->IgnoreParenImpCasts());
20082027
}
20092028

20102029
void VisitPseudoObjectExpr(PseudoObjectExpr *POE) {
@@ -2021,7 +2040,7 @@ namespace {
20212040

20222041
bool FoundDeclInUse() { return FoundDecl; }
20232042

2024-
}; // end class DeclMatcher
2043+
}; // end class DeclMatcher
20252044

20262045
void CheckForLoopConditionalStatement(Sema &S, Expr *Second,
20272046
Expr *Third, Stmt *Body) {

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

+15
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)