[clang] Add regression tests for GH214477 #217709
<!--LLVM NEW CONTRIBUTOR COMMENT-->
Hello @akash-manna-sky :wave:
Thank you for submitting a Pull Request (PR) to the LLVM Project. Since this is your first PR, here are a few useful links covering our main contribution policies and review practices.
All contributions to LLVM must follow our LLVM AI Tool Use Policy. In particular, if you used AI while working on this PR, remember to add a note to the PR description.
The LLVM Code-Review Policy and Practices document contains practical information about the PR process, including how patches are reviewed and accepted, and who can review a PR.
Please reply to this message to confirm that you have read these policies, especially the LLVM AI Tool Use Policy, and that any AI tool usage has been noted in the PR description.
---
Frequently asked questions
How do I add reviewers?
This PR will be automatically labeled, and the relevant teams will be notified. For some parts of the project, reviewers may also be added automatically.
You can also add reviewers manually using the Reviewers section on this page. If you cannot use that section, it is probably because you do not have write permissions for the repository. In that case, you can request a review by tagging reviewers in a comment using @ followed by their GitHub username.
What if there are no comments?
If you have not received any comments on your PR after a week, you can request a review by pinging the PR with a comment such as “Ping”. The common courtesy ping rate is once a week. Please remember that you are asking for volunteer time from other developers.
Are any special GitHub settings required to contribute to LLVM?
We only require contributors to have a public email address associated with their GitHub commits, see this section of LLVM Developer Policy for details.
---
If you have questions, feel free to leave a comment on this PR, or ask on LLVM Discord or LLVM Discourse.
Thank you,
The LLVM Community
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-clang
Author: Akash Manna (akash-manna-sky)
<details>
<summary>Changes</summary>
Fixes #<!-- -->214477
When a variable template specialization with a deduced type is first named in a context that doesn't require its definition (e.g. decltype(obj<0>)), Clang creates the specialization declaration, but for a member variable template of a class template the initializer still lives on the in-class pattern, so the type stays undeduced. Nothing completes it afterwards: the undeduced-type clause in DoMarkVarDeclReferenced skips variables usable in constant expressions, and the constant-evaluation path doesn't apply in unevaluated contexts. On the next reference, CheckVarTemplateId finds the existing specialization with an undeduced type and just assumes it is substituting the variable's own initializer, emitting "the type of variable template specialization declared with deduced type depends on itself" for perfectly valid code. As a side effect, decltype on such a specialization also yields the undeduced placeholder type instead of the deduced one.
CheckVarTemplateId now emits that error only when the specialization's initializer instantiation is actually in progress, checked against Sema::InstantiatingSpecializations. The eager initializer instantiation in BuildVariableInstantiation registers itself there with a RecursiveInstGuard, so genuine cycles (including indirect ones like a<0> = b<0>; b<0> = a<0>;) are still diagnosed. Finally, the !UsableInConstantExpr restriction in DoMarkVarDeclReferenced is dropped so that any reference to a specialization with a still-undeduced type instantiates its definition, meaning decltype deduces the type the same way GCC does.
LLM tools were used for this contribution. I've reviewed, built, and tested the change myself before pushing to GitHub.
---
Full diff: https://github.com/llvm/llvm-project/pull/217709.diff
5 Files Affected:
````````````diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 8c9467ca7b742..0ac80a68f46ef 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -528,6 +528,11 @@ features cannot lower the translation-unit ABI level;
parameter that follows a parameter pack (e.g.
`template <typename... T> S::S(T..., int = 10) {}`). (#GH216211)
+- Fixed a bogus "deduced type depends on itself" error when a variable template
+ specialization with a deduced type was first named in a context that did not
+ require its definition (such as ``decltype``) and then referenced again;
+ Clang now instantiates the definition to deduce the type instead. (#GH214477)
+
#### Bug Fixes to AST Handling
- Fixed a non-deterministic ordering of unused local typedefs that made
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index da76bbf3c35f0..a5a7398aee15f 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -20715,8 +20715,7 @@ static void DoMarkVarDeclReferenced(
bool NeedDefinition =
OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
- (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
- Var->getType()->isUndeducedType());
+ (TSK != clang::TSK_Undeclared && Var->getType()->isUndeducedType());
assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
"Can't instantiate a partial template specialization.");
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 1fde412749cc9..9b844a8da1403 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -4658,18 +4658,24 @@ Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {
checkSpecializationReachability(TemplateNameLoc, Spec);
if (Spec->getType()->isUndeducedType()) {
- if (ParsingInitForAutoVars.count(Spec))
+ if (ParsingInitForAutoVars.count(Spec)) {
Diag(TemplateNameLoc,
diag::err_auto_variable_cannot_appear_in_own_initializer)
<< diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
<< Spec->getType();
- else
+ return true;
+ }
+ if (InstantiatingSpecializations.contains(
+ {Spec->getCanonicalDecl(),
+ unsigned(RecursiveInstGuard::Kind::Template)})) {
// We are substituting the initializer of this variable template
// specialization.
Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)
<< Spec << Spec->getType();
-
- return true;
+ return true;
+ }
+ // Not yet deduced; the type is completed when the definition is
+ // instantiated.
}
// If we already have a variable template specialization, return it.
return Spec;
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index ff29ae27a3b66..fab93559a3f6c 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -6523,6 +6523,8 @@ void Sema::BuildVariableInstantiation(
// We're producing a template. Don't instantiate the initializer yet.
} else if (NewVar->getType()->isUndeducedType()) {
// We need the type to complete the declaration of the variable.
+ RecursiveInstGuard AlreadyInstantiating(*this, NewVar,
+ RecursiveInstGuard::Kind::Template);
InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
} else if (InstantiatingSpecFromTemplate ||
(OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
diff --git a/clang/test/SemaTemplate/GH214477.cpp b/clang/test/SemaTemplate/GH214477.cpp
new file mode 100644
index 0000000000000..76f8e9a2c51e8
--- /dev/null
+++ b/clang/test/SemaTemplate/GH214477.cpp
@@ -0,0 +1,76 @@
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -verify %s
+// RUN: %clang_cc1 -fsyntax-only -std=c++26 -verify %s
+
+namespace GH214477 {
+
+struct dummy {};
+template <typename A> struct real { A a; };
+
+template <typename V> struct Tests {
+ template <int> static constexpr dummy obj = {};
+
+ const int reg = [] {
+ using X = decltype(obj<0>);
+ static_assert(__is_same(X, const real<int>));
+ (void)&obj<0>;
+ return 0;
+ }();
+
+ template <int Tmp>
+ requires(Tmp == 0)
+ static constexpr real obj<Tmp> = {0};
+};
+
+void test() { (void)Tests<int>{}; }
+
+template <typename V> struct Tests2 {
+ template <int> static constexpr dummy obj = {};
+
+ void f() {
+ using X = decltype(obj<0>);
+ static_assert(__is_same(X, const real<int>));
+ (void)&obj<0>;
+ }
+
+ template <int Tmp>
+ requires(Tmp == 0)
+ static constexpr real obj<Tmp> = {0};
+};
+
+void test2() { Tests2<int>{}.f(); }
+
+template <typename V> struct Tests3 {
+ template <int> static constexpr dummy obj = {};
+
+ const int reg = [] {
+ (void)&obj<0>;
+ using X = decltype(obj<0>);
+ static_assert(__is_same(X, const real<int>));
+ return 0;
+ }();
+
+ template <int Tmp>
+ requires(Tmp == 0)
+ static constexpr real obj<Tmp> = {0};
+};
+
+void test3() { (void)Tests3<int>{}; }
+
+} // namespace GH214477
+
+namespace deduced_type_cycle {
+
+template <int> constexpr auto a = 0;
+template <int> constexpr auto b = 0;
+
+template <int N>
+ requires(N == 0)
+constexpr auto a<N> = b<N>; // expected-note {{in instantiation of variable template specialization 'deduced_type_cycle::b<N>' requested here}}
+
+template <int N>
+ requires(N == 0)
+constexpr auto b<N> = a<N>; // expected-error {{the type of variable template specialization 'a<0>' declared with deduced type 'const auto' depends on itself}}
+
+auto y = a<0>; // expected-note {{in instantiation of variable template specialization 'deduced_type_cycle::a<N>' requested here}}
+
+} // namespace deduced_type_cycle
</details>
Why is UsableInConstantExpr set for this issue?
Requested changes.
So I think here obj<0> is constexpr, and mightBeUsableInConstantExpressions() returns true for constexpr variables even while the type is still undeduced. The !UsableInConstantExpr guard assumed the NeededForConstantEvaluation branch would instantiate such variables, but that branch requires isPotentiallyConstantEvaluatedContext(), which is false in an unevaluated operand like decltype. So when the first reference is in decltype, neither branch requested the definition and the type never got deduced — that's the state the "depends on itself" diagnostic then misreads. Since the type of a deduced-type variable is needed at any reference, the undeduced case shouldn't be gated on constant-expression usability...
I don't think it makes much sense to allow instantiation within unevaluated context. I question if this should be IFNDR @cor3ntin
what do you think would be the right approach here? If you have a better way to address this issue, I'd be happy to give it a try. @zyn0217 @cor3ntin
Hi @zyn0217 and @cor3ntin, have you had a chance to take another look at this PR? It would be great to get your feedback so we can move forward with it. Thanks!
I wonder if you or your AI has ever read https://llvm.org/docs/Contributing.html#how-to-submit-a-patch
If you have received no comments on your patch for a week, you can request a review by ‘ping’ing the GitHub PR with “Ping” in a comment. The common courtesy ‘ping’ rate is once a week. Please remember that you are asking for valuable time from other professional developers.
Thanks.
I wonder if you or your AI has ever read https://llvm.org/docs/Contributing.html#how-to-submit-a-patch
> > If you have received no comments on your patch for a week, you can request a review by ‘ping’ing the GitHub PR with “Ping” in a comment. The common courtesy ‘ping’ rate is once a week. Please remember that you are asking for valuable time from other professional developers.
> Thanks.
Ping
@cor3ntin Please take a look.
Superseded by #237843.
Superseded by #237843.
Ok.. in that case I will add targeted tests and ask you for review .
Approved these changes.
<!--LLVM BUILDBOT INFORMATION COMMENT-->
@akash-manna-sky Congratulations on having your first Pull Request (PR) merged into the LLVM Project!
Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.
Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.
How to do this, and the rest of the post-merge process, is covered in detail here.
If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.
If you don't get any reports, no action is required from you. Your changes are working as expected, well done!
cor3ntin
akash-manna-sky
Fixes #214477
The bogus "deduced type depends on itself" error was fixed by #237843. I added the issue's reproducers tests for this.
LLM tools were used for this contribution.