[clang] [clang] Don't use `VarDecl` of local variables as `ManglingContextDecl` for lambdas (PR #179035)

via cfe-commits cfe-commits at lists.llvm.org
Sat Jan 31 05:33:06 PST 2026


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-modules

Author: Jan Kokemüller (jiixyj)

<details>
<summary>Changes</summary>

A `VarDecl` can be the `ManglingContextDecl` for lambdas. But this is only relevant for global variables. For local variables, the `DeclContext` of the lambda is more appropriate I guess. Otherwise, it can happen that two separate lambdas in the same function mangle to the same name.

Fixes #<!-- -->178893 

---
Full diff: https://github.com/llvm/llvm-project/pull/179035.diff


2 Files Affected:

- (modified) clang/lib/Sema/SemaLambda.cpp (+8) 
- (added) clang/test/Modules/pr178893.cppm (+29) 


``````````diff
diff --git a/clang/lib/Sema/SemaLambda.cpp b/clang/lib/Sema/SemaLambda.cpp
index e74fe02bd0cf5..24426259bf01c 100644
--- a/clang/lib/Sema/SemaLambda.cpp
+++ b/clang/lib/Sema/SemaLambda.cpp
@@ -294,6 +294,14 @@ Sema::getCurrentMangleNumberContext(const DeclContext *DC) {
   bool IsInNonspecializedTemplate =
       inTemplateInstantiation() || CurContext->isDependentContext();
 
+  // If we must allocate mangling numbers but the `ManglingContextDecl`
+  // is a local variable, use the `DeclContext` containing the lambda expression
+  // instead.
+  if (ManglingContextDecl)
+    if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl);
+        Var && Var->isLocalVarDecl())
+      ManglingContextDecl = const_cast<Decl *>(cast<Decl>(DC));
+
   // Default arguments of member function parameters that appear in a class
   // definition, as well as the initializers of data members, receive special
   // treatment. Identify them.
diff --git a/clang/test/Modules/pr178893.cppm b/clang/test/Modules/pr178893.cppm
new file mode 100644
index 0000000000000..6d2a599588667
--- /dev/null
+++ b/clang/test/Modules/pr178893.cppm
@@ -0,0 +1,29 @@
+// RUN: %clang_cc1 -std=c++20 -triple x86_64-apple-macosx10.7.0 -fmodules -xc++ -emit-llvm -o - %s -w | FileCheck %s
+
+// CHECK-LABEL: define linkonce_odr noundef i32 @_ZZN8PR178893W3mod6format5parseEPiENKUlvE_clEv
+// CHECK-LABEL: define linkonce_odr noundef i32 @_ZZN8PR178893W3mod6format5parseEPiENKUlvE0_clEv
+
+export module mod;
+
+namespace PR178893 {
+  struct format {
+      static inline int parse(int* i)
+      {
+          int number;
+          number = [&]() -> int { return i[0]; }();
+
+          volatile bool b = true;
+          if (b) {
+              auto identifier = [&]() -> int { return i[1]; }();
+              return identifier;
+          }
+
+          return number;
+      }
+  };
+
+  int test_format() {
+      int n[2] = {1, 0};
+      return format::parse(n);
+  }
+}

``````````

</details>


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


More information about the cfe-commits mailing list