[clang] [Sema] Fix crash in Sema::FindInstantiatedDecl (PR #96509)

Alejandro Álvarez Ayllón via cfe-commits cfe-commits at lists.llvm.org
Mon Jun 24 08:47:40 PDT 2024


https://github.com/alejandro-alvarez-sonarsource created https://github.com/llvm/llvm-project/pull/96509

When looking for a template instantiation with a non-type parameter of unknown type and with a default value.

This can happen when a template non-type parameter has a broken expression that gets replaced by a `RecoveryExpr`.

>From 96b0c2c18c197a1ce03d31b01c14d1b18348e9ee Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Alejandro=20=C3=81lvarez=20Ayll=C3=B3n?=
 <alejandro.alvarez at sonarsource.com>
Date: Thu, 1 Jun 2023 16:30:54 +0200
Subject: [PATCH] [Sema] Fix crash in Sema::FindInstantiatedDecl

when looking for a template instantiation with a non-type
parameter of unknown type and with a default value.

This can happen when a template non-type parameter has a broken
expression that gets replaced by a `RecoveryExpr`.
---
 clang/lib/Sema/SemaTemplateInstantiateDecl.cpp       |  2 +-
 .../instantiate-template-broken-nontype-default.cpp  | 12 ++++++++++++
 2 files changed, 13 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/SemaCXX/instantiate-template-broken-nontype-default.cpp

diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 0681520764d9a..999fec0ebb259 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -6300,7 +6300,7 @@ NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
                   getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
           }
           QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
-          if (T.isNull())
+          if (T.isNull() || T->containsErrors())
             return nullptr;
           CXXRecordDecl *SubstRecord = T->getAsCXXRecordDecl();
 
diff --git a/clang/test/SemaCXX/instantiate-template-broken-nontype-default.cpp b/clang/test/SemaCXX/instantiate-template-broken-nontype-default.cpp
new file mode 100644
index 0000000000000..a644cc3d057cb
--- /dev/null
+++ b/clang/test/SemaCXX/instantiate-template-broken-nontype-default.cpp
@@ -0,0 +1,12 @@
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s
+
+constexpr Missing a = 0; // expected-error {{unknown type name 'Missing'}}
+
+template < typename T, Missing b = a> // expected-error {{unknown type name 'Missing'}}
+class Klass { // expected-note {{candidate template ignored: could not match 'Klass<T, b>' against 'int'}}
+  Klass(T);   // expected-note {{candidate template ignored: substitution failure [with T = int, b = <recovery-expr>()]}}
+};
+
+Klass foo{5}; // no-crash \
+                 expected-error {{no viable constructor or deduction guide for deduction of template arguments of 'Klass'}}
+



More information about the cfe-commits mailing list