https://github.com/hokein created 
https://github.com/llvm/llvm-project/pull/173546

Fix https://github.com/clangd/clangd/issues/2572.

>From f8e78cec607f16b0bf30a33b19b8e7a72bf7198f Mon Sep 17 00:00:00 2001
From: Haojian Wu <[email protected]>
Date: Thu, 25 Dec 2025 12:26:18 +0100
Subject: [PATCH] [clang] Preserve the initializer when the variable
 declaration fails to deduce the type.

---
 clang/lib/Sema/SemaDecl.cpp          | 9 ++++++++-
 clang/test/AST/ast-dump-recovery.cpp | 8 ++++++++
 2 files changed, 16 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 1a5e8c607a242..2cbb7b9fd3e17 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -13839,8 +13839,15 @@ void Sema::AddInitializerToDecl(Decl *RealDecl, Expr 
*Init, bool DirectInit) {
       return;
     }
 
-    if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
+    if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) {
+      assert(VDecl->isInvalidDecl() &&
+             "decl should be invalidated when deduce fails");
+      if (auto *RecoveryExpr =
+              CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), 
{Init})
+                  .get())
+        VDecl->setInit(RecoveryExpr);
       return;
+    }
   }
 
   this->CheckAttributesOnDeducedType(RealDecl);
diff --git a/clang/test/AST/ast-dump-recovery.cpp 
b/clang/test/AST/ast-dump-recovery.cpp
index 060ae3b62b6f8..80ec0a449d556 100644
--- a/clang/test/AST/ast-dump-recovery.cpp
+++ b/clang/test/AST/ast-dump-recovery.cpp
@@ -301,3 +301,11 @@ void foo() {
   U g{};
 }
 } // namespace GH112560
+
+// CHECK:     VarDecl {{.*}} invalid x 'auto *' cinit
+// CHECK-NEXT: `-RecoveryExpr {{.*}} '<dependent type>' contains-errors lvalue
+// CHECK-NEXT:   `-CallExpr {{.*}} 'int'
+// DISABLED-NOT: -RecoveryExpr {{.*}} contains-errors
+void brokenDeducedVarDecl() {
+   auto* x = some_func(nullptr);
+}

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to