[clang] [Clang] enhance loop analysis to handle variable changes inside lambdas (PR #135573)

Aaron Ballman via cfe-commits cfe-commits at lists.llvm.org
Fri Feb 13 04:44:47 PST 2026


================
@@ -1996,9 +1996,33 @@ namespace {
     }
 
     void VisitDeclRefExpr(DeclRefExpr *E) {
-      if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
+      if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
         if (Decls.count(VD))
           FoundDecl = true;
+      } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getDecl());
+                 MD && isLambdaCallOperator(MD)) {
+        // FIXME: This has limitations handling updates to the loop control
+        // variable that occur indirectly inside a lambda called from the loop
+        // body. For example:
+        //
+        //   int a = 0;
+        //   int *c = &a;
+        //   auto incr_c = [c]() { ++*c; };
+        //   for (a = 10; a <= 20; incr_c())
+        //     foo(a);
+        for (const auto &Capture : MD->getParent()->captures()) {
+          if (!Capture.capturesVariable())
+            continue;
+
+          LambdaCaptureKind CK = Capture.getCaptureKind();
+          if (CK != LCK_ByRef)
+            continue;
+
+          VarDecl *VD = dyn_cast<VarDecl>(Capture.getCapturedVar());
----------------
AaronBallman wrote:

```suggestion
          const auto *VD = dyn_cast<VarDecl>(Capture.getCapturedVar());
```

https://github.com/llvm/llvm-project/pull/135573


More information about the cfe-commits mailing list