[clang] [clang-repl] Re-emit implicitly instantiated templates on subsequent uses (PR #192588)

Caevan Lin via cfe-commits cfe-commits at lists.llvm.org
Fri Apr 17 02:15:14 PDT 2026


https://github.com/voyager-jhk updated https://github.com/llvm/llvm-project/pull/192588

>From 238aadfe174ed8218b38c77d527c8c3e69e20623 Mon Sep 17 00:00:00 2001
From: voyager-jhk <voyager.lpq at gmail.com>
Date: Fri, 17 Apr 2026 11:39:28 +0800
Subject: [PATCH] [clang-repl] Re-emit implicitly instantiated templates on
 subsequent uses

Parsing failures in incremental mode cause CodeGen to discard the current module. However, Sema retains implicitly instantiated function bodies. On subsequent valid references, Sema skips emission, leading to unresolved JIT symbols.

This patch forces re-emission of valid implicit instantiations in IncrementalExtensions mode. CodeGen's GlobalDeclMap naturally deduplicates redundant emissions.

Fixes #146770
---
 clang/lib/Sema/SemaExpr.cpp                  |  7 +++++++
 clang/test/Interpreter/template-recovery.cpp | 12 ++++++++++++
 2 files changed, 19 insertions(+)
 create mode 100644 clang/test/Interpreter/template-recovery.cpp

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 9fd8c6a0a5451..95625c765b266 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -19045,6 +19045,13 @@ void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
         }
       }
     });
+  } else if (NeedDefinition && getLangOpts().IncrementalExtensions) {
+    const FunctionDecl *Def = nullptr;
+    if (Func->getBody(Def) && 
+        Def->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
+        !Def->isInvalidDecl()) {
+      Consumer.HandleTopLevelDecl(DeclGroupRef(const_cast<FunctionDecl*>(Def)));
+    }
   }
 
   // If a constructor was defined in the context of a default parameter
diff --git a/clang/test/Interpreter/template-recovery.cpp b/clang/test/Interpreter/template-recovery.cpp
new file mode 100644
index 0000000000000..37256d1339a31
--- /dev/null
+++ b/clang/test/Interpreter/template-recovery.cpp
@@ -0,0 +1,12 @@
+// REQUIRES: host-supports-jit
+// RUN: clang-repl -Xcc -fno-color-diagnostics < %s 2>&1 | FileCheck %s
+
+#include <cmath>
+extern "C" int printf(const char *, ...);
+
+(10-)*std::pow(2,2);
+// CHECK: error: expected expression
+// CHECK: error: Parsing failed.
+
+printf("%d\n", (int)((10-1)*std::pow(2,2)));
+// CHECK: 36
\ No newline at end of file



More information about the cfe-commits mailing list