[clang] Fix a crash in handling this-pointer captured in nested lambdas in field initializater. (PR #245491)

Wontae Choi via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 23 21:28:32 PST 2026


https://github.com/wtchoi created https://github.com/llvm/llvm-project/pull/245491

Environment.initialize() currently crashes when handling a this-pointer captured
by a nested lambda expression appearing in a field initializer of a struct.
Consider the following example:

struct {
  int f = int f{[this]() { return [this]() { return 1; }(); }()};
}

When handling the this-pointer captured in the inner lambda,
Environment.initialize() tries to get the enclosing record by calling
getLambdaContext() on the lambda's Closure. However, getLambdaContext() only
works for the outermost lambda. For inner lambdas, it just returns nullptr,
which causes a null-dereference.

This PR fixes that issue by introducing a helper function that finds the
outermost lambda and get getLambdaContextDecl() from it.


>From bf474df53117296c9434d6e2ee6697eea39579c9 Mon Sep 17 00:00:00 2001
From: Wontae Choi <wtchoi at google.com>
Date: Tue, 24 Nov 2026 01:09:23 +0000
Subject: [PATCH] Environment::initialize now properly handles "this" pointer
 captured by a nested lambda expression, when the lambda expression was
 apeparing in the field initializer. Consider the following example:

struct {
  int f = int f{[this]() { return [this]() { return 1; }(); }()};
}

In the above code, "this" pointer captured by the inner lambda was not
properly handled, causing null-dereference.
---
 .../FlowSensitive/DataflowEnvironment.cpp     | 22 +++++-
 .../FlowSensitive/DataflowEnvironmentTest.cpp | 69 +++++++++++++++++++
 2 files changed, 90 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
index 33f2d4782db119..d6f69cf61d3f61 100644
--- a/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
+++ b/clang/lib/Analysis/FlowSensitive/DataflowEnvironment.cpp
@@ -1101,6 +1101,26 @@ Environment::Environment(const Environment &Other)
       ExprToLoc(Other.ExprToLoc), ExprToVal(Other.ExprToVal),
       LocToVal(Other.LocToVal), BoolState(Other.BoolState->clone()) {}
 
+// Returns the field whose default member initializer contains the lambda with
+// closure type `Closure`, or null if there is no such field.
+//
+// `Closure` may be nested inside other lambdas within the default member
+// initializer. In that case only the outermost closure has the `FieldDecl` as
+// its lambda context declaration. So walk out through the enclosing lambdas
+// until a context declaration is found.
+static const FieldDecl *getFieldBeingInitialized(const CXXRecordDecl *Closure) {
+  while (true) {
+    assert(Closure->isLambda());
+    if (const Decl *ContextDecl = Closure->getLambdaContextDecl())
+      return dyn_cast<FieldDecl>(ContextDecl);
+    const auto *EnclosingMethod =
+        dyn_cast<CXXMethodDecl>(Closure->getDeclContext());
+    if (EnclosingMethod == nullptr || !EnclosingMethod->getParent()->isLambda())
+      return nullptr;
+    Closure = EnclosingMethod->getParent();
+  }
+}
+
 void Environment::initialize() {
   if (InitialTargetStmt == nullptr)
     return;
@@ -1148,7 +1168,7 @@ void Environment::initialize() {
             setThisPointeeStorageLocation(
                 cast<RecordStorageLocation>(createObject(ThisPointeeType)));
           } else if (auto *FieldBeingInitialized =
-                         dyn_cast<FieldDecl>(Parent->getLambdaContextDecl())) {
+                         getFieldBeingInitialized(Parent)) {
             // This is in a field initializer, rather than a method.
             const RecordDecl *RD = FieldBeingInitialized->getParent();
             const ASTContext &Ctx = RD->getASTContext();
diff --git a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
index 6bab26d472e66a..b9a6d7bce0b4f2 100644
--- a/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/DataflowEnvironmentTest.cpp
@@ -552,6 +552,75 @@ TEST_F(EnvironmentTest, LambdaCapturingThisInFieldInitializer) {
   ASSERT_NE(nullptr, Env.getThisPointeeStorageLocation());
 }
 
+/*
+TEST_F(EnvironmentTest, NestedLambdaCapturingThisInFieldInitializer) {
+  using namespace ast_matchers;
+  std::string Code = R"cc(
+      struct S {
+      int f{[this]() { return [this]() { return 1; }(); }()};
+      };
+    )cc";
+
+  auto Unit =
+      tooling::buildASTFromCodeWithArgs(Code, {"-fsyntax-only", "-std=c++11"});
+  auto &Context = Unit->getASTContext();
+
+  ASSERT_EQ(Context.getDiagnostics().getClient()->getNumErrors(), 0U);
+
+  auto Results = match(cxxMethodDecl(hasName("operator()"), isDefinition(),
+                                     ofClass(cxxRecordDecl(isLambda())))
+                           .bind("method"),
+                       Context);
+
+  // Touch all methods and make sure initialization doesn't crash on any.
+  for (const auto& Node : Results) {
+    const auto *Method = Node.getNodeAs<CXXMethodDecl>("method");
+    if (Method->isDependentContext())
+      continue;
+    Environment Env(DAContext, *Method);
+    // Don't crash when initializing.
+    Env.initialize();
+    // And initialize the captured `this` pointee.
+    ASSERT_NE(nullptr, Env.getThisPointeeStorageLocation());
+  }
+}
+*/
+
+TEST_F(EnvironmentTest,
+       NestedLambdaCapturingClassTemplateThisInFieldInitializer) {
+  using namespace ast_matchers;
+  std::string Code = R"cc(
+      template <class T>
+      struct S {
+        int f{[this]() { return [this]() { return 1; }(); }()};
+      };
+      S<int> s;
+    )cc";
+
+  auto Unit =
+      tooling::buildASTFromCodeWithArgs(Code, {"-fsyntax-only", "-std=c++11"});
+  auto &Context = Unit->getASTContext();
+
+  ASSERT_EQ(Context.getDiagnostics().getClient()->getNumErrors(), 0U);
+
+  auto Results = match(cxxMethodDecl(hasName("operator()"), isDefinition(),
+                                     ofClass(cxxRecordDecl(isLambda())))
+                           .bind("method"),
+                       Context);
+
+  // Touch all methods and make sure initialization doesn't crash on any.
+  for (const auto &Node : Results) {
+    const auto *Method = Node.getNodeAs<CXXMethodDecl>("method");
+    if (Method->isDependentContext())
+      continue;
+    Environment Env(DAContext, *Method);
+    // Don't crash when initializing.
+    Env.initialize();
+    // And initialize the captured `this` pointee.
+    ASSERT_NE(nullptr, Env.getThisPointeeStorageLocation());
+  }
+}
+
 TEST_F(EnvironmentTest, ThisExprLocInNonMemberIsInitListLoc) {
   using namespace ast_matchers;
   std::string Code = R"cc(



More information about the cfe-commits mailing list