clang 20.0.0git
SemaTemplate.cpp
Go to the documentation of this file.
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements semantic analysis for C++ templates.
9//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
14#include "clang/AST/Decl.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
27#include "clang/Basic/Stack.h"
29#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/SemaCUDA.h"
38#include "clang/Sema/Template.h"
40#include "llvm/ADT/BitVector.h"
41#include "llvm/ADT/SmallBitVector.h"
42#include "llvm/ADT/SmallString.h"
43#include "llvm/ADT/StringExtras.h"
44
45#include <iterator>
46#include <optional>
47using namespace clang;
48using namespace sema;
49
50// Exported for use by Parser.
53 unsigned N) {
54 if (!N) return SourceRange();
55 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
56}
57
58unsigned Sema::getTemplateDepth(Scope *S) const {
59 unsigned Depth = 0;
60
61 // Each template parameter scope represents one level of template parameter
62 // depth.
63 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
64 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
65 ++Depth;
66 }
67
68 // Note that there are template parameters with the given depth.
69 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
70
71 // Look for parameters of an enclosing generic lambda. We don't create a
72 // template parameter scope for these.
74 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
75 if (!LSI->TemplateParams.empty()) {
76 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
77 break;
78 }
79 if (LSI->GLTemplateParameterList) {
80 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
81 break;
82 }
83 }
84 }
85
86 // Look for parameters of an enclosing terse function template. We don't
87 // create a template parameter scope for these either.
88 for (const InventedTemplateParameterInfo &Info :
90 if (!Info.TemplateParams.empty()) {
91 ParamsAtDepth(Info.AutoTemplateParameterDepth);
92 break;
93 }
94 }
95
96 return Depth;
97}
98
99/// \brief Determine whether the declaration found is acceptable as the name
100/// of a template and, if so, return that template declaration. Otherwise,
101/// returns null.
102///
103/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
104/// is true. In all other cases it will return a TemplateDecl (or null).
106 bool AllowFunctionTemplates,
107 bool AllowDependent) {
108 D = D->getUnderlyingDecl();
109
110 if (isa<TemplateDecl>(D)) {
111 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
112 return nullptr;
113
114 return D;
115 }
116
117 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
118 // C++ [temp.local]p1:
119 // Like normal (non-template) classes, class templates have an
120 // injected-class-name (Clause 9). The injected-class-name
121 // can be used with or without a template-argument-list. When
122 // it is used without a template-argument-list, it is
123 // equivalent to the injected-class-name followed by the
124 // template-parameters of the class template enclosed in
125 // <>. When it is used with a template-argument-list, it
126 // refers to the specified class template specialization,
127 // which could be the current specialization or another
128 // specialization.
129 if (Record->isInjectedClassName()) {
130 Record = cast<CXXRecordDecl>(Record->getDeclContext());
131 if (Record->getDescribedClassTemplate())
132 return Record->getDescribedClassTemplate();
133
134 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
135 return Spec->getSpecializedTemplate();
136 }
137
138 return nullptr;
139 }
140
141 // 'using Dependent::foo;' can resolve to a template name.
142 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
143 // injected-class-name).
144 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
145 return D;
146
147 return nullptr;
148}
149
151 bool AllowFunctionTemplates,
152 bool AllowDependent) {
153 LookupResult::Filter filter = R.makeFilter();
154 while (filter.hasNext()) {
155 NamedDecl *Orig = filter.next();
156 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
157 filter.erase();
158 }
159 filter.done();
160}
161
163 bool AllowFunctionTemplates,
164 bool AllowDependent,
165 bool AllowNonTemplateFunctions) {
166 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
167 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
168 return true;
169 if (AllowNonTemplateFunctions &&
170 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
171 return true;
172 }
173
174 return false;
175}
176
178 CXXScopeSpec &SS,
179 bool hasTemplateKeyword,
180 const UnqualifiedId &Name,
181 ParsedType ObjectTypePtr,
182 bool EnteringContext,
183 TemplateTy &TemplateResult,
184 bool &MemberOfUnknownSpecialization,
185 bool Disambiguation) {
186 assert(getLangOpts().CPlusPlus && "No template names in C!");
187
188 DeclarationName TName;
189 MemberOfUnknownSpecialization = false;
190
191 switch (Name.getKind()) {
193 TName = DeclarationName(Name.Identifier);
194 break;
195
198 Name.OperatorFunctionId.Operator);
199 break;
200
202 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
203 break;
204
205 default:
206 return TNK_Non_template;
207 }
208
209 QualType ObjectType = ObjectTypePtr.get();
210
211 AssumedTemplateKind AssumedTemplate;
212 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
213 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
214 /*RequiredTemplate=*/SourceLocation(),
215 &AssumedTemplate,
216 /*AllowTypoCorrection=*/!Disambiguation))
217 return TNK_Non_template;
218 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
219
220 if (AssumedTemplate != AssumedTemplateKind::None) {
221 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
222 // Let the parser know whether we found nothing or found functions; if we
223 // found nothing, we want to more carefully check whether this is actually
224 // a function template name versus some other kind of undeclared identifier.
225 return AssumedTemplate == AssumedTemplateKind::FoundNothing
228 }
229
230 if (R.empty())
231 return TNK_Non_template;
232
233 NamedDecl *D = nullptr;
234 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
235 if (R.isAmbiguous()) {
236 // If we got an ambiguity involving a non-function template, treat this
237 // as a template name, and pick an arbitrary template for error recovery.
238 bool AnyFunctionTemplates = false;
239 for (NamedDecl *FoundD : R) {
240 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
241 if (isa<FunctionTemplateDecl>(FoundTemplate))
242 AnyFunctionTemplates = true;
243 else {
244 D = FoundTemplate;
245 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
246 break;
247 }
248 }
249 }
250
251 // If we didn't find any templates at all, this isn't a template name.
252 // Leave the ambiguity for a later lookup to diagnose.
253 if (!D && !AnyFunctionTemplates) {
254 R.suppressDiagnostics();
255 return TNK_Non_template;
256 }
257
258 // If the only templates were function templates, filter out the rest.
259 // We'll diagnose the ambiguity later.
260 if (!D)
262 }
263
264 // At this point, we have either picked a single template name declaration D
265 // or we have a non-empty set of results R containing either one template name
266 // declaration or a set of function templates.
267
268 TemplateName Template;
269 TemplateNameKind TemplateKind;
270
271 unsigned ResultCount = R.end() - R.begin();
272 if (!D && ResultCount > 1) {
273 // We assume that we'll preserve the qualifier from a function
274 // template name in other ways.
275 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
276 TemplateKind = TNK_Function_template;
277
278 // We'll do this lookup again later.
280 } else {
281 if (!D) {
283 assert(D && "unambiguous result is not a template name");
284 }
285
286 if (isa<UnresolvedUsingValueDecl>(D)) {
287 // We don't yet know whether this is a template-name or not.
288 MemberOfUnknownSpecialization = true;
289 return TNK_Non_template;
290 }
291
292 TemplateDecl *TD = cast<TemplateDecl>(D);
293 Template =
294 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
295 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
296 if (!SS.isInvalid()) {
297 NestedNameSpecifier *Qualifier = SS.getScopeRep();
298 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
299 Template);
300 }
301
302 if (isa<FunctionTemplateDecl>(TD)) {
303 TemplateKind = TNK_Function_template;
304
305 // We'll do this lookup again later.
307 } else {
308 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
309 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
310 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
311 TemplateKind =
312 isa<VarTemplateDecl>(TD) ? TNK_Var_template :
313 isa<ConceptDecl>(TD) ? TNK_Concept_template :
315 }
316 }
317
318 TemplateResult = TemplateTy::make(Template);
319 return TemplateKind;
320}
321
323 SourceLocation NameLoc, CXXScopeSpec &SS,
324 ParsedTemplateTy *Template /*=nullptr*/) {
325 // We could use redeclaration lookup here, but we don't need to: the
326 // syntactic form of a deduction guide is enough to identify it even
327 // if we can't look up the template name at all.
328 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
329 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
330 /*EnteringContext*/ false))
331 return false;
332
333 if (R.empty()) return false;
334 if (R.isAmbiguous()) {
335 // FIXME: Diagnose an ambiguity if we find at least one template.
337 return false;
338 }
339
340 // We only treat template-names that name type templates as valid deduction
341 // guide names.
343 if (!TD || !getAsTypeTemplateDecl(TD))
344 return false;
345
346 if (Template) {
348 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
349 *Template = TemplateTy::make(Name);
350 }
351 return true;
352}
353
355 SourceLocation IILoc,
356 Scope *S,
357 const CXXScopeSpec *SS,
358 TemplateTy &SuggestedTemplate,
359 TemplateNameKind &SuggestedKind) {
360 // We can't recover unless there's a dependent scope specifier preceding the
361 // template name.
362 // FIXME: Typo correction?
363 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
365 return false;
366
367 // The code is missing a 'template' keyword prior to the dependent template
368 // name.
370 Diag(IILoc, diag::err_template_kw_missing)
371 << Qualifier << II.getName()
372 << FixItHint::CreateInsertion(IILoc, "template ");
373 SuggestedTemplate
375 SuggestedKind = TNK_Dependent_template_name;
376 return true;
377}
378
380 QualType ObjectType, bool EnteringContext,
381 RequiredTemplateKind RequiredTemplate,
383 bool AllowTypoCorrection) {
384 if (ATK)
386
387 if (SS.isInvalid())
388 return true;
389
390 Found.setTemplateNameLookup(true);
391
392 // Determine where to perform name lookup
393 DeclContext *LookupCtx = nullptr;
394 bool IsDependent = false;
395 if (!ObjectType.isNull()) {
396 // This nested-name-specifier occurs in a member access expression, e.g.,
397 // x->B::f, and we are looking into the type of the object.
398 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
399 LookupCtx = computeDeclContext(ObjectType);
400 IsDependent = !LookupCtx && ObjectType->isDependentType();
401 assert((IsDependent || !ObjectType->isIncompleteType() ||
402 !ObjectType->getAs<TagType>() ||
403 ObjectType->castAs<TagType>()->isBeingDefined()) &&
404 "Caller should have completed object type");
405
406 // Template names cannot appear inside an Objective-C class or object type
407 // or a vector type.
408 //
409 // FIXME: This is wrong. For example:
410 //
411 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
412 // Vec<int> vi;
413 // vi.Vec<int>::~Vec<int>();
414 //
415 // ... should be accepted but we will not treat 'Vec' as a template name
416 // here. The right thing to do would be to check if the name is a valid
417 // vector component name, and look up a template name if not. And similarly
418 // for lookups into Objective-C class and object types, where the same
419 // problem can arise.
420 if (ObjectType->isObjCObjectOrInterfaceType() ||
421 ObjectType->isVectorType()) {
422 Found.clear();
423 return false;
424 }
425 } else if (SS.isNotEmpty()) {
426 // This nested-name-specifier occurs after another nested-name-specifier,
427 // so long into the context associated with the prior nested-name-specifier.
428 LookupCtx = computeDeclContext(SS, EnteringContext);
429 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
430
431 // The declaration context must be complete.
432 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
433 return true;
434 }
435
436 bool ObjectTypeSearchedInScope = false;
437 bool AllowFunctionTemplatesInLookup = true;
438 if (LookupCtx) {
439 // Perform "qualified" name lookup into the declaration context we
440 // computed, which is either the type of the base of a member access
441 // expression or the declaration context associated with a prior
442 // nested-name-specifier.
443 LookupQualifiedName(Found, LookupCtx);
444
445 // FIXME: The C++ standard does not clearly specify what happens in the
446 // case where the object type is dependent, and implementations vary. In
447 // Clang, we treat a name after a . or -> as a template-name if lookup
448 // finds a non-dependent member or member of the current instantiation that
449 // is a type template, or finds no such members and lookup in the context
450 // of the postfix-expression finds a type template. In the latter case, the
451 // name is nonetheless dependent, and we may resolve it to a member of an
452 // unknown specialization when we come to instantiate the template.
453 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
454 }
455
456 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
457 // C++ [basic.lookup.classref]p1:
458 // In a class member access expression (5.2.5), if the . or -> token is
459 // immediately followed by an identifier followed by a <, the
460 // identifier must be looked up to determine whether the < is the
461 // beginning of a template argument list (14.2) or a less-than operator.
462 // The identifier is first looked up in the class of the object
463 // expression. If the identifier is not found, it is then looked up in
464 // the context of the entire postfix-expression and shall name a class
465 // template.
466 if (S)
467 LookupName(Found, S);
468
469 if (!ObjectType.isNull()) {
470 // FIXME: We should filter out all non-type templates here, particularly
471 // variable templates and concepts. But the exclusion of alias templates
472 // and template template parameters is a wording defect.
473 AllowFunctionTemplatesInLookup = false;
474 ObjectTypeSearchedInScope = true;
475 }
476
477 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
478 }
479
480 if (Found.isAmbiguous())
481 return false;
482
483 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
484 !RequiredTemplate.hasTemplateKeyword()) {
485 // C++2a [temp.names]p2:
486 // A name is also considered to refer to a template if it is an
487 // unqualified-id followed by a < and name lookup finds either one or more
488 // functions or finds nothing.
489 //
490 // To keep our behavior consistent, we apply the "finds nothing" part in
491 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
492 // successfully form a call to an undeclared template-id.
493 bool AllFunctions =
494 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
495 return isa<FunctionDecl>(ND->getUnderlyingDecl());
496 });
497 if (AllFunctions || (Found.empty() && !IsDependent)) {
498 // If lookup found any functions, or if this is a name that can only be
499 // used for a function, then strongly assume this is a function
500 // template-id.
501 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
504 Found.clear();
505 return false;
506 }
507 }
508
509 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
510 // If we did not find any names, and this is not a disambiguation, attempt
511 // to correct any typos.
512 DeclarationName Name = Found.getLookupName();
513 Found.clear();
514 // Simple filter callback that, for keywords, only accepts the C++ *_cast
515 DefaultFilterCCC FilterCCC{};
516 FilterCCC.WantTypeSpecifiers = false;
517 FilterCCC.WantExpressionKeywords = false;
518 FilterCCC.WantRemainingKeywords = false;
519 FilterCCC.WantCXXNamedCasts = true;
520 if (TypoCorrection Corrected =
521 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
522 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
523 if (auto *ND = Corrected.getFoundDecl())
524 Found.addDecl(ND);
526 if (Found.isAmbiguous()) {
527 Found.clear();
528 } else if (!Found.empty()) {
529 Found.setLookupName(Corrected.getCorrection());
530 if (LookupCtx) {
531 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
532 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
533 Name.getAsString() == CorrectedStr;
534 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
535 << Name << LookupCtx << DroppedSpecifier
536 << SS.getRange());
537 } else {
538 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
539 }
540 }
541 }
542 }
543
544 NamedDecl *ExampleLookupResult =
545 Found.empty() ? nullptr : Found.getRepresentativeDecl();
546 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
547 if (Found.empty()) {
548 if (IsDependent) {
549 Found.setNotFoundInCurrentInstantiation();
550 return false;
551 }
552
553 // If a 'template' keyword was used, a lookup that finds only non-template
554 // names is an error.
555 if (ExampleLookupResult && RequiredTemplate) {
556 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
557 << Found.getLookupName() << SS.getRange()
558 << RequiredTemplate.hasTemplateKeyword()
559 << RequiredTemplate.getTemplateKeywordLoc();
560 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
561 diag::note_template_kw_refers_to_non_template)
562 << Found.getLookupName();
563 return true;
564 }
565
566 return false;
567 }
568
569 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
571 // C++03 [basic.lookup.classref]p1:
572 // [...] If the lookup in the class of the object expression finds a
573 // template, the name is also looked up in the context of the entire
574 // postfix-expression and [...]
575 //
576 // Note: C++11 does not perform this second lookup.
577 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
579 FoundOuter.setTemplateNameLookup(true);
580 LookupName(FoundOuter, S);
581 // FIXME: We silently accept an ambiguous lookup here, in violation of
582 // [basic.lookup]/1.
583 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
584
585 NamedDecl *OuterTemplate;
586 if (FoundOuter.empty()) {
587 // - if the name is not found, the name found in the class of the
588 // object expression is used, otherwise
589 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
590 !(OuterTemplate =
591 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
592 // - if the name is found in the context of the entire
593 // postfix-expression and does not name a class template, the name
594 // found in the class of the object expression is used, otherwise
595 FoundOuter.clear();
596 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
597 // - if the name found is a class template, it must refer to the same
598 // entity as the one found in the class of the object expression,
599 // otherwise the program is ill-formed.
600 if (!Found.isSingleResult() ||
601 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
602 OuterTemplate->getCanonicalDecl()) {
603 Diag(Found.getNameLoc(),
604 diag::ext_nested_name_member_ref_lookup_ambiguous)
605 << Found.getLookupName()
606 << ObjectType;
607 Diag(Found.getRepresentativeDecl()->getLocation(),
608 diag::note_ambig_member_ref_object_type)
609 << ObjectType;
610 Diag(FoundOuter.getFoundDecl()->getLocation(),
611 diag::note_ambig_member_ref_scope);
612
613 // Recover by taking the template that we found in the object
614 // expression's type.
615 }
616 }
617 }
618
619 return false;
620}
621
625 if (TemplateName.isInvalid())
626 return;
627
628 DeclarationNameInfo NameInfo;
629 CXXScopeSpec SS;
630 LookupNameKind LookupKind;
631
632 DeclContext *LookupCtx = nullptr;
633 NamedDecl *Found = nullptr;
634 bool MissingTemplateKeyword = false;
635
636 // Figure out what name we looked up.
637 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
638 NameInfo = DRE->getNameInfo();
639 SS.Adopt(DRE->getQualifierLoc());
640 LookupKind = LookupOrdinaryName;
641 Found = DRE->getFoundDecl();
642 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
643 NameInfo = ME->getMemberNameInfo();
644 SS.Adopt(ME->getQualifierLoc());
645 LookupKind = LookupMemberName;
646 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
647 Found = ME->getMemberDecl();
648 } else if (auto *DSDRE =
649 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
650 NameInfo = DSDRE->getNameInfo();
651 SS.Adopt(DSDRE->getQualifierLoc());
652 MissingTemplateKeyword = true;
653 } else if (auto *DSME =
654 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
655 NameInfo = DSME->getMemberNameInfo();
656 SS.Adopt(DSME->getQualifierLoc());
657 MissingTemplateKeyword = true;
658 } else {
659 llvm_unreachable("unexpected kind of potential template name");
660 }
661
662 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
663 // was missing.
664 if (MissingTemplateKeyword) {
665 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
666 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
667 return;
668 }
669
670 // Try to correct the name by looking for templates and C++ named casts.
671 struct TemplateCandidateFilter : CorrectionCandidateCallback {
672 Sema &S;
673 TemplateCandidateFilter(Sema &S) : S(S) {
674 WantTypeSpecifiers = false;
675 WantExpressionKeywords = false;
676 WantRemainingKeywords = false;
677 WantCXXNamedCasts = true;
678 };
679 bool ValidateCandidate(const TypoCorrection &Candidate) override {
680 if (auto *ND = Candidate.getCorrectionDecl())
681 return S.getAsTemplateNameDecl(ND);
682 return Candidate.isKeyword();
683 }
684
685 std::unique_ptr<CorrectionCandidateCallback> clone() override {
686 return std::make_unique<TemplateCandidateFilter>(*this);
687 }
688 };
689
690 DeclarationName Name = NameInfo.getName();
691 TemplateCandidateFilter CCC(*this);
692 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
693 CTK_ErrorRecovery, LookupCtx)) {
694 auto *ND = Corrected.getFoundDecl();
695 if (ND)
696 ND = getAsTemplateNameDecl(ND);
697 if (ND || Corrected.isKeyword()) {
698 if (LookupCtx) {
699 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
700 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
701 Name.getAsString() == CorrectedStr;
702 diagnoseTypo(Corrected,
703 PDiag(diag::err_non_template_in_member_template_id_suggest)
704 << Name << LookupCtx << DroppedSpecifier
705 << SS.getRange(), false);
706 } else {
707 diagnoseTypo(Corrected,
708 PDiag(diag::err_non_template_in_template_id_suggest)
709 << Name, false);
710 }
711 if (Found)
712 Diag(Found->getLocation(),
713 diag::note_non_template_in_template_id_found);
714 return;
715 }
716 }
717
718 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
719 << Name << SourceRange(Less, Greater);
720 if (Found)
721 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
722}
723
726 SourceLocation TemplateKWLoc,
727 const DeclarationNameInfo &NameInfo,
728 bool isAddressOfOperand,
729 const TemplateArgumentListInfo *TemplateArgs) {
730 if (SS.isEmpty()) {
731 // FIXME: This codepath is only used by dependent unqualified names
732 // (e.g. a dependent conversion-function-id, or operator= once we support
733 // it). It doesn't quite do the right thing, and it will silently fail if
734 // getCurrentThisType() returns null.
735 QualType ThisType = getCurrentThisType();
736 if (ThisType.isNull())
737 return ExprError();
738
740 Context, /*Base=*/nullptr, ThisType,
741 /*IsArrow=*/!Context.getLangOpts().HLSL,
742 /*OperatorLoc=*/SourceLocation(),
743 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
744 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
745 }
746 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
747}
748
751 SourceLocation TemplateKWLoc,
752 const DeclarationNameInfo &NameInfo,
753 const TemplateArgumentListInfo *TemplateArgs) {
754 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
755 if (!SS.isValid())
756 return CreateRecoveryExpr(
757 SS.getBeginLoc(),
758 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
759
761 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
762 TemplateArgs);
763}
764
766 NamedDecl *Instantiation,
767 bool InstantiatedFromMember,
768 const NamedDecl *Pattern,
769 const NamedDecl *PatternDef,
771 bool Complain /*= true*/) {
772 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
773 isa<VarDecl>(Instantiation));
774
775 bool IsEntityBeingDefined = false;
776 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
777 IsEntityBeingDefined = TD->isBeingDefined();
778
779 if (PatternDef && !IsEntityBeingDefined) {
780 NamedDecl *SuggestedDef = nullptr;
781 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
782 &SuggestedDef,
783 /*OnlyNeedComplete*/ false)) {
784 // If we're allowed to diagnose this and recover, do so.
785 bool Recover = Complain && !isSFINAEContext();
786 if (Complain)
787 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
789 return !Recover;
790 }
791 return false;
792 }
793
794 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
795 return true;
796
797 QualType InstantiationTy;
798 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
799 InstantiationTy = Context.getTypeDeclType(TD);
800 if (PatternDef) {
801 Diag(PointOfInstantiation,
802 diag::err_template_instantiate_within_definition)
803 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
804 << InstantiationTy;
805 // Not much point in noting the template declaration here, since
806 // we're lexically inside it.
807 Instantiation->setInvalidDecl();
808 } else if (InstantiatedFromMember) {
809 if (isa<FunctionDecl>(Instantiation)) {
810 Diag(PointOfInstantiation,
811 diag::err_explicit_instantiation_undefined_member)
812 << /*member function*/ 1 << Instantiation->getDeclName()
813 << Instantiation->getDeclContext();
814 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
815 } else {
816 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
817 Diag(PointOfInstantiation,
818 diag::err_implicit_instantiate_member_undefined)
819 << InstantiationTy;
820 Diag(Pattern->getLocation(), diag::note_member_declared_at);
821 }
822 } else {
823 if (isa<FunctionDecl>(Instantiation)) {
824 Diag(PointOfInstantiation,
825 diag::err_explicit_instantiation_undefined_func_template)
826 << Pattern;
827 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
828 } else if (isa<TagDecl>(Instantiation)) {
829 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
830 << (TSK != TSK_ImplicitInstantiation)
831 << InstantiationTy;
832 NoteTemplateLocation(*Pattern);
833 } else {
834 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
835 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
836 Diag(PointOfInstantiation,
837 diag::err_explicit_instantiation_undefined_var_template)
838 << Instantiation;
839 Instantiation->setInvalidDecl();
840 } else
841 Diag(PointOfInstantiation,
842 diag::err_explicit_instantiation_undefined_member)
843 << /*static data member*/ 2 << Instantiation->getDeclName()
844 << Instantiation->getDeclContext();
845 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
846 }
847 }
848
849 // In general, Instantiation isn't marked invalid to get more than one
850 // error for multiple undefined instantiations. But the code that does
851 // explicit declaration -> explicit definition conversion can't handle
852 // invalid declarations, so mark as invalid in that case.
854 Instantiation->setInvalidDecl();
855 return true;
856}
857
859 bool SupportedForCompatibility) {
860 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
861
862 // C++23 [temp.local]p6:
863 // The name of a template-parameter shall not be bound to any following.
864 // declaration whose locus is contained by the scope to which the
865 // template-parameter belongs.
866 //
867 // When MSVC compatibility is enabled, the diagnostic is always a warning
868 // by default. Otherwise, it an error unless SupportedForCompatibility is
869 // true, in which case it is a default-to-error warning.
870 unsigned DiagId =
871 getLangOpts().MSVCCompat
872 ? diag::ext_template_param_shadow
873 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
874 : diag::err_template_param_shadow);
875 const auto *ND = cast<NamedDecl>(PrevDecl);
876 Diag(Loc, DiagId) << ND->getDeclName();
878}
879
881 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
882 D = Temp->getTemplatedDecl();
883 return Temp;
884 }
885 return nullptr;
886}
887
889 SourceLocation EllipsisLoc) const {
890 assert(Kind == Template &&
891 "Only template template arguments can be pack expansions here");
892 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
893 "Template template argument pack expansion without packs");
895 Result.EllipsisLoc = EllipsisLoc;
896 return Result;
897}
898
900 const ParsedTemplateArgument &Arg) {
901
902 switch (Arg.getKind()) {
904 TypeSourceInfo *DI;
905 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
906 if (!DI)
907 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
909 }
910
912 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
914 }
915
917 TemplateName Template = Arg.getAsTemplate().get();
918 TemplateArgument TArg;
919 if (Arg.getEllipsisLoc().isValid())
920 TArg = TemplateArgument(Template, std::optional<unsigned int>());
921 else
922 TArg = Template;
923 return TemplateArgumentLoc(
924 SemaRef.Context, TArg,
926 Arg.getLocation(), Arg.getEllipsisLoc());
927 }
928 }
929
930 llvm_unreachable("Unhandled parsed template argument");
931}
932
934 TemplateArgumentListInfo &TemplateArgs) {
935 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
936 TemplateArgs.addArgument(translateTemplateArgument(*this,
937 TemplateArgsIn[I]));
938}
939
942 const IdentifierInfo *Name) {
943 NamedDecl *PrevDecl =
945 RedeclarationKind::ForVisibleRedeclaration);
946 if (PrevDecl && PrevDecl->isTemplateParameter())
947 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
948}
949
951 TypeSourceInfo *TInfo;
953 if (T.isNull())
954 return ParsedTemplateArgument();
955 assert(TInfo && "template argument with no location");
956
957 // If we might have formed a deduced template specialization type, convert
958 // it to a template template argument.
959 if (getLangOpts().CPlusPlus17) {
960 TypeLoc TL = TInfo->getTypeLoc();
961 SourceLocation EllipsisLoc;
962 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
963 EllipsisLoc = PET.getEllipsisLoc();
964 TL = PET.getPatternLoc();
965 }
966
967 CXXScopeSpec SS;
968 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
969 SS.Adopt(ET.getQualifierLoc());
970 TL = ET.getNamedTypeLoc();
971 }
972
973 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
974 TemplateName Name = DTST.getTypePtr()->getTemplateName();
976 DTST.getTemplateNameLoc());
977 if (EllipsisLoc.isValid())
978 Result = Result.getTemplatePackExpansion(EllipsisLoc);
979 return Result;
980 }
981 }
982
983 // This is a normal type template argument. Note, if the type template
984 // argument is an injected-class-name for a template, it has a dual nature
985 // and can be used as either a type or a template. We handle that in
986 // convertTypeTemplateArgumentToTemplate.
989 TInfo->getTypeLoc().getBeginLoc());
990}
991
993 SourceLocation EllipsisLoc,
994 SourceLocation KeyLoc,
995 IdentifierInfo *ParamName,
996 SourceLocation ParamNameLoc,
997 unsigned Depth, unsigned Position,
998 SourceLocation EqualLoc,
999 ParsedType DefaultArg,
1000 bool HasTypeConstraint) {
1001 assert(S->isTemplateParamScope() &&
1002 "Template type parameter not in template parameter scope!");
1003
1004 bool IsParameterPack = EllipsisLoc.isValid();
1007 KeyLoc, ParamNameLoc, Depth, Position,
1008 ParamName, Typename, IsParameterPack,
1009 HasTypeConstraint);
1010 Param->setAccess(AS_public);
1011
1012 if (Param->isParameterPack())
1013 if (auto *LSI = getEnclosingLambda())
1014 LSI->LocalPacks.push_back(Param);
1015
1016 if (ParamName) {
1017 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1018
1019 // Add the template parameter into the current scope.
1020 S->AddDecl(Param);
1021 IdResolver.AddDecl(Param);
1022 }
1023
1024 // C++0x [temp.param]p9:
1025 // A default template-argument may be specified for any kind of
1026 // template-parameter that is not a template parameter pack.
1027 if (DefaultArg && IsParameterPack) {
1028 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1029 DefaultArg = nullptr;
1030 }
1031
1032 // Handle the default argument, if provided.
1033 if (DefaultArg) {
1034 TypeSourceInfo *DefaultTInfo;
1035 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1036
1037 assert(DefaultTInfo && "expected source information for type");
1038
1039 // Check for unexpanded parameter packs.
1040 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1042 return Param;
1043
1044 // Check the template argument itself.
1045 if (CheckTemplateArgument(DefaultTInfo)) {
1046 Param->setInvalidDecl();
1047 return Param;
1048 }
1049
1050 Param->setDefaultArgument(
1051 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1052 }
1053
1054 return Param;
1055}
1056
1057/// Convert the parser's template argument list representation into our form.
1060 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1061 TemplateId.RAngleLoc);
1062 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1063 TemplateId.NumArgs);
1064 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1065 return TemplateArgs;
1066}
1067
1069
1070 TemplateName TN = TypeConstr->Template.get();
1071 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1072
1073 // C++2a [temp.param]p4:
1074 // [...] The concept designated by a type-constraint shall be a type
1075 // concept ([temp.concept]).
1076 if (!CD->isTypeConcept()) {
1077 Diag(TypeConstr->TemplateNameLoc,
1078 diag::err_type_constraint_non_type_concept);
1079 return true;
1080 }
1081
1082 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1083 return true;
1084
1085 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1086
1087 if (!WereArgsSpecified &&
1089 Diag(TypeConstr->TemplateNameLoc,
1090 diag::err_type_constraint_missing_arguments)
1091 << CD;
1092 return true;
1093 }
1094 return false;
1095}
1096
1098 TemplateIdAnnotation *TypeConstr,
1099 TemplateTypeParmDecl *ConstrainedParameter,
1100 SourceLocation EllipsisLoc) {
1101 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1102 false);
1103}
1104
1106 TemplateIdAnnotation *TypeConstr,
1107 TemplateTypeParmDecl *ConstrainedParameter,
1108 SourceLocation EllipsisLoc,
1109 bool AllowUnexpandedPack) {
1110
1111 if (CheckTypeConstraint(TypeConstr))
1112 return true;
1113
1114 TemplateName TN = TypeConstr->Template.get();
1115 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1117
1118 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1119 TypeConstr->TemplateNameLoc);
1120
1121 TemplateArgumentListInfo TemplateArgs;
1122 if (TypeConstr->LAngleLoc.isValid()) {
1123 TemplateArgs =
1124 makeTemplateArgumentListInfo(*this, *TypeConstr);
1125
1126 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1127 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1129 return true;
1130 }
1131 }
1132 }
1133 return AttachTypeConstraint(
1135 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1136 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1137 ConstrainedParameter, EllipsisLoc);
1138}
1139
1140template <typename ArgumentLocAppender>
1143 ConceptDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1144 SourceLocation RAngleLoc, QualType ConstrainedType,
1145 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1146 SourceLocation EllipsisLoc) {
1147
1148 TemplateArgumentListInfo ConstraintArgs;
1149 ConstraintArgs.addArgument(
1151 /*NTTPType=*/QualType(), ParamNameLoc));
1152
1153 ConstraintArgs.setRAngleLoc(RAngleLoc);
1154 ConstraintArgs.setLAngleLoc(LAngleLoc);
1155 Appender(ConstraintArgs);
1156
1157 // C++2a [temp.param]p4:
1158 // [...] This constraint-expression E is called the immediately-declared
1159 // constraint of T. [...]
1160 CXXScopeSpec SS;
1161 SS.Adopt(NS);
1162 ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1163 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1164 /*FoundDecl=*/FoundDecl ? FoundDecl : NamedConcept, NamedConcept,
1165 &ConstraintArgs);
1166 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1167 return ImmediatelyDeclaredConstraint;
1168
1169 // C++2a [temp.param]p4:
1170 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1171 //
1172 // We have the following case:
1173 //
1174 // template<typename T> concept C1 = true;
1175 // template<C1... T> struct s1;
1176 //
1177 // The constraint: (C1<T> && ...)
1178 //
1179 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1180 // any unqualified lookups for 'operator&&' here.
1181 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1182 /*LParenLoc=*/SourceLocation(),
1183 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1184 EllipsisLoc, /*RHS=*/nullptr,
1185 /*RParenLoc=*/SourceLocation(),
1186 /*NumExpansions=*/std::nullopt);
1187}
1188
1190 DeclarationNameInfo NameInfo,
1191 ConceptDecl *NamedConcept, NamedDecl *FoundDecl,
1192 const TemplateArgumentListInfo *TemplateArgs,
1193 TemplateTypeParmDecl *ConstrainedParameter,
1194 SourceLocation EllipsisLoc) {
1195 // C++2a [temp.param]p4:
1196 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1197 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1198 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1200 *TemplateArgs) : nullptr;
1201
1202 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1203
1204 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1205 *this, NS, NameInfo, NamedConcept, FoundDecl,
1206 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1207 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1208 ParamAsArgument, ConstrainedParameter->getLocation(),
1209 [&](TemplateArgumentListInfo &ConstraintArgs) {
1210 if (TemplateArgs)
1211 for (const auto &ArgLoc : TemplateArgs->arguments())
1212 ConstraintArgs.addArgument(ArgLoc);
1213 },
1214 EllipsisLoc);
1215 if (ImmediatelyDeclaredConstraint.isInvalid())
1216 return true;
1217
1218 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1219 /*TemplateKWLoc=*/SourceLocation{},
1220 /*ConceptNameInfo=*/NameInfo,
1221 /*FoundDecl=*/FoundDecl,
1222 /*NamedConcept=*/NamedConcept,
1223 /*ArgsWritten=*/ArgsAsWritten);
1224 ConstrainedParameter->setTypeConstraint(CL,
1225 ImmediatelyDeclaredConstraint.get());
1226 return false;
1227}
1228
1230 NonTypeTemplateParmDecl *NewConstrainedParm,
1231 NonTypeTemplateParmDecl *OrigConstrainedParm,
1232 SourceLocation EllipsisLoc) {
1233 if (NewConstrainedParm->getType() != TL.getType() ||
1235 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1236 diag::err_unsupported_placeholder_constraint)
1237 << NewConstrainedParm->getTypeSourceInfo()
1238 ->getTypeLoc()
1239 .getSourceRange();
1240 return true;
1241 }
1242 // FIXME: Concepts: This should be the type of the placeholder, but this is
1243 // unclear in the wording right now.
1244 DeclRefExpr *Ref =
1245 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1246 VK_PRValue, OrigConstrainedParm->getLocation());
1247 if (!Ref)
1248 return true;
1249 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1251 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1253 OrigConstrainedParm->getLocation(),
1254 [&](TemplateArgumentListInfo &ConstraintArgs) {
1255 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1256 ConstraintArgs.addArgument(TL.getArgLoc(I));
1257 },
1258 EllipsisLoc);
1259 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1260 !ImmediatelyDeclaredConstraint.isUsable())
1261 return true;
1262
1263 NewConstrainedParm->setPlaceholderTypeConstraint(
1264 ImmediatelyDeclaredConstraint.get());
1265 return false;
1266}
1267
1270 if (TSI->getType()->isUndeducedType()) {
1271 // C++17 [temp.dep.expr]p3:
1272 // An id-expression is type-dependent if it contains
1273 // - an identifier associated by name lookup with a non-type
1274 // template-parameter declared with a type that contains a
1275 // placeholder type (7.1.7.4),
1277 }
1278
1280}
1281
1283 if (T->isDependentType())
1284 return false;
1285
1286 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1287 return true;
1288
1289 if (T->isStructuralType())
1290 return false;
1291
1292 // Structural types are required to be object types or lvalue references.
1293 if (T->isRValueReferenceType()) {
1294 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1295 return true;
1296 }
1297
1298 // Don't mention structural types in our diagnostic prior to C++20. Also,
1299 // there's not much more we can say about non-scalar non-class types --
1300 // because we can't see functions or arrays here, those can only be language
1301 // extensions.
1302 if (!getLangOpts().CPlusPlus20 ||
1303 (!T->isScalarType() && !T->isRecordType())) {
1304 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1305 return true;
1306 }
1307
1308 // Structural types are required to be literal types.
1309 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1310 return true;
1311
1312 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1313
1314 // Drill down into the reason why the class is non-structural.
1315 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1316 // All members are required to be public and non-mutable, and can't be of
1317 // rvalue reference type. Check these conditions first to prefer a "local"
1318 // reason over a more distant one.
1319 for (const FieldDecl *FD : RD->fields()) {
1320 if (FD->getAccess() != AS_public) {
1321 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1322 return true;
1323 }
1324 if (FD->isMutable()) {
1325 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1326 return true;
1327 }
1328 if (FD->getType()->isRValueReferenceType()) {
1329 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1330 << T;
1331 return true;
1332 }
1333 }
1334
1335 // All bases are required to be public.
1336 for (const auto &BaseSpec : RD->bases()) {
1337 if (BaseSpec.getAccessSpecifier() != AS_public) {
1338 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1339 << T << 1;
1340 return true;
1341 }
1342 }
1343
1344 // All subobjects are required to be of structural types.
1345 SourceLocation SubLoc;
1346 QualType SubType;
1347 int Kind = -1;
1348
1349 for (const FieldDecl *FD : RD->fields()) {
1350 QualType T = Context.getBaseElementType(FD->getType());
1351 if (!T->isStructuralType()) {
1352 SubLoc = FD->getLocation();
1353 SubType = T;
1354 Kind = 0;
1355 break;
1356 }
1357 }
1358
1359 if (Kind == -1) {
1360 for (const auto &BaseSpec : RD->bases()) {
1361 QualType T = BaseSpec.getType();
1362 if (!T->isStructuralType()) {
1363 SubLoc = BaseSpec.getBaseTypeLoc();
1364 SubType = T;
1365 Kind = 1;
1366 break;
1367 }
1368 }
1369 }
1370
1371 assert(Kind != -1 && "couldn't find reason why type is not structural");
1372 Diag(SubLoc, diag::note_not_structural_subobject)
1373 << T << Kind << SubType;
1374 T = SubType;
1375 RD = T->getAsCXXRecordDecl();
1376 }
1377
1378 return true;
1379}
1380
1383 // We don't allow variably-modified types as the type of non-type template
1384 // parameters.
1385 if (T->isVariablyModifiedType()) {
1386 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1387 << T;
1388 return QualType();
1389 }
1390
1391 // C++ [temp.param]p4:
1392 //
1393 // A non-type template-parameter shall have one of the following
1394 // (optionally cv-qualified) types:
1395 //
1396 // -- integral or enumeration type,
1398 // -- pointer to object or pointer to function,
1399 T->isPointerType() ||
1400 // -- lvalue reference to object or lvalue reference to function,
1402 // -- pointer to member,
1404 // -- std::nullptr_t, or
1405 T->isNullPtrType() ||
1406 // -- a type that contains a placeholder type.
1407 T->isUndeducedType()) {
1408 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1409 // are ignored when determining its type.
1410 return T.getUnqualifiedType();
1411 }
1412
1413 // C++ [temp.param]p8:
1414 //
1415 // A non-type template-parameter of type "array of T" or
1416 // "function returning T" is adjusted to be of type "pointer to
1417 // T" or "pointer to function returning T", respectively.
1418 if (T->isArrayType() || T->isFunctionType())
1419 return Context.getDecayedType(T);
1420
1421 // If T is a dependent type, we can't do the check now, so we
1422 // assume that it is well-formed. Note that stripping off the
1423 // qualifiers here is not really correct if T turns out to be
1424 // an array type, but we'll recompute the type everywhere it's
1425 // used during instantiation, so that should be OK. (Using the
1426 // qualified type is equally wrong.)
1427 if (T->isDependentType())
1428 return T.getUnqualifiedType();
1429
1430 // C++20 [temp.param]p6:
1431 // -- a structural type
1433 return QualType();
1434
1435 if (!getLangOpts().CPlusPlus20) {
1436 // FIXME: Consider allowing structural types as an extension in C++17. (In
1437 // earlier language modes, the template argument evaluation rules are too
1438 // inflexible.)
1439 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1440 return QualType();
1441 }
1442
1443 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1444 return T.getUnqualifiedType();
1445}
1446
1448 unsigned Depth,
1449 unsigned Position,
1450 SourceLocation EqualLoc,
1451 Expr *Default) {
1453
1454 // Check that we have valid decl-specifiers specified.
1455 auto CheckValidDeclSpecifiers = [this, &D] {
1456 // C++ [temp.param]
1457 // p1
1458 // template-parameter:
1459 // ...
1460 // parameter-declaration
1461 // p2
1462 // ... A storage class shall not be specified in a template-parameter
1463 // declaration.
1464 // [dcl.typedef]p1:
1465 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1466 // of a parameter-declaration
1467 const DeclSpec &DS = D.getDeclSpec();
1468 auto EmitDiag = [this](SourceLocation Loc) {
1469 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1471 };
1473 EmitDiag(DS.getStorageClassSpecLoc());
1474
1476 EmitDiag(DS.getThreadStorageClassSpecLoc());
1477
1478 // [dcl.inline]p1:
1479 // The inline specifier can be applied only to the declaration or
1480 // definition of a variable or function.
1481
1482 if (DS.isInlineSpecified())
1483 EmitDiag(DS.getInlineSpecLoc());
1484
1485 // [dcl.constexpr]p1:
1486 // The constexpr specifier shall be applied only to the definition of a
1487 // variable or variable template or the declaration of a function or
1488 // function template.
1489
1490 if (DS.hasConstexprSpecifier())
1491 EmitDiag(DS.getConstexprSpecLoc());
1492
1493 // [dcl.fct.spec]p1:
1494 // Function-specifiers can be used only in function declarations.
1495
1496 if (DS.isVirtualSpecified())
1497 EmitDiag(DS.getVirtualSpecLoc());
1498
1499 if (DS.hasExplicitSpecifier())
1500 EmitDiag(DS.getExplicitSpecLoc());
1501
1502 if (DS.isNoreturnSpecified())
1503 EmitDiag(DS.getNoreturnSpecLoc());
1504 };
1505
1506 CheckValidDeclSpecifiers();
1507
1508 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1509 if (isa<AutoType>(T))
1510 Diag(D.getIdentifierLoc(),
1511 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1512 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1513
1514 assert(S->isTemplateParamScope() &&
1515 "Non-type template parameter not in template parameter scope!");
1516 bool Invalid = false;
1517
1518 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1519 if (T.isNull()) {
1520 T = Context.IntTy; // Recover with an 'int' type.
1521 Invalid = true;
1522 }
1523
1525
1526 const IdentifierInfo *ParamName = D.getIdentifier();
1527 bool IsParameterPack = D.hasEllipsis();
1530 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1531 TInfo);
1532 Param->setAccess(AS_public);
1533
1535 if (TL.isConstrained())
1536 if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1537 Invalid = true;
1538
1539 if (Invalid)
1540 Param->setInvalidDecl();
1541
1542 if (Param->isParameterPack())
1543 if (auto *LSI = getEnclosingLambda())
1544 LSI->LocalPacks.push_back(Param);
1545
1546 if (ParamName) {
1547 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1548 ParamName);
1549
1550 // Add the template parameter into the current scope.
1551 S->AddDecl(Param);
1552 IdResolver.AddDecl(Param);
1553 }
1554
1555 // C++0x [temp.param]p9:
1556 // A default template-argument may be specified for any kind of
1557 // template-parameter that is not a template parameter pack.
1558 if (Default && IsParameterPack) {
1559 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1560 Default = nullptr;
1561 }
1562
1563 // Check the well-formedness of the default template argument, if provided.
1564 if (Default) {
1565 // Check for unexpanded parameter packs.
1567 return Param;
1568
1569 Param->setDefaultArgument(
1571 QualType(), SourceLocation()));
1572 }
1573
1574 return Param;
1575}
1576
1578 Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params,
1579 bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *Name,
1580 SourceLocation NameLoc, unsigned Depth, unsigned Position,
1582 assert(S->isTemplateParamScope() &&
1583 "Template template parameter not in template parameter scope!");
1584
1585 // Construct the parameter object.
1586 bool IsParameterPack = EllipsisLoc.isValid();
1589 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1590 Name, Typename, Params);
1591 Param->setAccess(AS_public);
1592
1593 if (Param->isParameterPack())
1594 if (auto *LSI = getEnclosingLambda())
1595 LSI->LocalPacks.push_back(Param);
1596
1597 // If the template template parameter has a name, then link the identifier
1598 // into the scope and lookup mechanisms.
1599 if (Name) {
1600 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1601
1602 S->AddDecl(Param);
1603 IdResolver.AddDecl(Param);
1604 }
1605
1606 if (Params->size() == 0) {
1607 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1608 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1609 Param->setInvalidDecl();
1610 }
1611
1612 // C++0x [temp.param]p9:
1613 // A default template-argument may be specified for any kind of
1614 // template-parameter that is not a template parameter pack.
1615 if (IsParameterPack && !Default.isInvalid()) {
1616 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1618 }
1619
1620 if (!Default.isInvalid()) {
1621 // Check only that we have a template template argument. We don't want to
1622 // try to check well-formedness now, because our template template parameter
1623 // might have dependent types in its template parameters, which we wouldn't
1624 // be able to match now.
1625 //
1626 // If none of the template template parameter's template arguments mention
1627 // other template parameters, we could actually perform more checking here.
1628 // However, it isn't worth doing.
1630 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1631 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1632 << DefaultArg.getSourceRange();
1633 return Param;
1634 }
1635
1636 // Check for unexpanded parameter packs.
1638 DefaultArg.getArgument().getAsTemplate(),
1640 return Param;
1641
1642 Param->setDefaultArgument(Context, DefaultArg);
1643 }
1644
1645 return Param;
1646}
1647
1648namespace {
1649class ConstraintRefersToContainingTemplateChecker
1650 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1651 bool Result = false;
1652 const FunctionDecl *Friend = nullptr;
1653 unsigned TemplateDepth = 0;
1654
1655 // Check a record-decl that we've seen to see if it is a lexical parent of the
1656 // Friend, likely because it was referred to without its template arguments.
1657 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1658 CheckingRD = CheckingRD->getMostRecentDecl();
1659 if (!CheckingRD->isTemplated())
1660 return;
1661
1662 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1663 DC && !DC->isFileContext(); DC = DC->getParent())
1664 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1665 if (CheckingRD == RD->getMostRecentDecl())
1666 Result = true;
1667 }
1668
1669 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1670 assert(D->getDepth() <= TemplateDepth &&
1671 "Nothing should reference a value below the actual template depth, "
1672 "depth is likely wrong");
1673 if (D->getDepth() != TemplateDepth)
1674 Result = true;
1675
1676 // Necessary because the type of the NTTP might be what refers to the parent
1677 // constriant.
1678 TransformType(D->getType());
1679 }
1680
1681public:
1683
1684 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1685 const FunctionDecl *Friend,
1686 unsigned TemplateDepth)
1687 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1688 bool getResult() const { return Result; }
1689
1690 // This should be the only template parm type that we have to deal with.
1691 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1692 // FunctionParmPackExpr are all partially substituted, which cannot happen
1693 // with concepts at this point in translation.
1694 using inherited::TransformTemplateTypeParmType;
1695 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1696 TemplateTypeParmTypeLoc TL, bool) {
1697 assert(TL.getDecl()->getDepth() <= TemplateDepth &&
1698 "Nothing should reference a value below the actual template depth, "
1699 "depth is likely wrong");
1700 if (TL.getDecl()->getDepth() != TemplateDepth)
1701 Result = true;
1702 return inherited::TransformTemplateTypeParmType(
1703 TLB, TL,
1704 /*SuppressObjCLifetime=*/false);
1705 }
1706
1707 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1708 if (!D)
1709 return D;
1710 // FIXME : This is possibly an incomplete list, but it is unclear what other
1711 // Decl kinds could be used to refer to the template parameters. This is a
1712 // best guess so far based on examples currently available, but the
1713 // unreachable should catch future instances/cases.
1714 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1715 TransformType(TD->getUnderlyingType());
1716 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1717 CheckNonTypeTemplateParmDecl(NTTPD);
1718 else if (auto *VD = dyn_cast<ValueDecl>(D))
1719 TransformType(VD->getType());
1720 else if (auto *TD = dyn_cast<TemplateDecl>(D))
1721 TransformTemplateParameterList(TD->getTemplateParameters());
1722 else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1723 CheckIfContainingRecord(RD);
1724 else if (isa<NamedDecl>(D)) {
1725 // No direct types to visit here I believe.
1726 } else
1727 llvm_unreachable("Don't know how to handle this declaration type yet");
1728 return D;
1729 }
1730};
1731} // namespace
1732
1734 const FunctionDecl *Friend, unsigned TemplateDepth,
1735 const Expr *Constraint) {
1736 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1737 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1738 TemplateDepth);
1739 Checker.TransformExpr(const_cast<Expr *>(Constraint));
1740 return Checker.getResult();
1741}
1742
1745 SourceLocation ExportLoc,
1746 SourceLocation TemplateLoc,
1747 SourceLocation LAngleLoc,
1748 ArrayRef<NamedDecl *> Params,
1749 SourceLocation RAngleLoc,
1750 Expr *RequiresClause) {
1751 if (ExportLoc.isValid())
1752 Diag(ExportLoc, diag::warn_template_export_unsupported);
1753
1754 for (NamedDecl *P : Params)
1756
1758 Context, TemplateLoc, LAngleLoc,
1759 llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1760}
1761
1763 const CXXScopeSpec &SS) {
1764 if (SS.isSet())
1765 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1766}
1767
1768// Returns the template parameter list with all default template argument
1769// information.
1771 // Make sure we get the template parameter list from the most
1772 // recent declaration, since that is the only one that is guaranteed to
1773 // have all the default template argument information.
1774 Decl *D = TD->getMostRecentDecl();
1775 // C++11 N3337 [temp.param]p12:
1776 // A default template argument shall not be specified in a friend class
1777 // template declaration.
1778 //
1779 // Skip past friend *declarations* because they are not supposed to contain
1780 // default template arguments. Moreover, these declarations may introduce
1781 // template parameters living in different template depths than the
1782 // corresponding template parameters in TD, causing unmatched constraint
1783 // substitution.
1784 //
1785 // FIXME: Diagnose such cases within a class template:
1786 // template <class T>
1787 // struct S {
1788 // template <class = void> friend struct C;
1789 // };
1790 // template struct S<int>;
1792 D->getPreviousDecl())
1793 D = D->getPreviousDecl();
1794 return cast<TemplateDecl>(D)->getTemplateParameters();
1795}
1796
1798 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1799 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1800 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1801 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1802 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1803 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1804 assert(TemplateParams && TemplateParams->size() > 0 &&
1805 "No template parameters");
1806 assert(TUK != TagUseKind::Reference &&
1807 "Can only declare or define class templates");
1808 bool Invalid = false;
1809
1810 // Check that we can declare a template here.
1811 if (CheckTemplateDeclScope(S, TemplateParams))
1812 return true;
1813
1815 assert(Kind != TagTypeKind::Enum &&
1816 "can't build template of enumerated type");
1817
1818 // There is no such thing as an unnamed class template.
1819 if (!Name) {
1820 Diag(KWLoc, diag::err_template_unnamed_class);
1821 return true;
1822 }
1823
1824 // Find any previous declaration with this name. For a friend with no
1825 // scope explicitly specified, we only look for tag declarations (per
1826 // C++11 [basic.lookup.elab]p2).
1827 DeclContext *SemanticContext;
1828 LookupResult Previous(*this, Name, NameLoc,
1829 (SS.isEmpty() && TUK == TagUseKind::Friend)
1833 if (SS.isNotEmpty() && !SS.isInvalid()) {
1834 SemanticContext = computeDeclContext(SS, true);
1835 if (!SemanticContext) {
1836 // FIXME: Horrible, horrible hack! We can't currently represent this
1837 // in the AST, and historically we have just ignored such friend
1838 // class templates, so don't complain here.
1839 Diag(NameLoc, TUK == TagUseKind::Friend
1840 ? diag::warn_template_qualified_friend_ignored
1841 : diag::err_template_qualified_declarator_no_match)
1842 << SS.getScopeRep() << SS.getRange();
1843 return TUK != TagUseKind::Friend;
1844 }
1845
1846 if (RequireCompleteDeclContext(SS, SemanticContext))
1847 return true;
1848
1849 // If we're adding a template to a dependent context, we may need to
1850 // rebuilding some of the types used within the template parameter list,
1851 // now that we know what the current instantiation is.
1852 if (SemanticContext->isDependentContext()) {
1853 ContextRAII SavedContext(*this, SemanticContext);
1855 Invalid = true;
1856 }
1857
1858 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1859 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1860 /*TemplateId-*/ nullptr,
1861 /*IsMemberSpecialization*/ false);
1862
1863 LookupQualifiedName(Previous, SemanticContext);
1864 } else {
1865 SemanticContext = CurContext;
1866
1867 // C++14 [class.mem]p14:
1868 // If T is the name of a class, then each of the following shall have a
1869 // name different from T:
1870 // -- every member template of class T
1871 if (TUK != TagUseKind::Friend &&
1872 DiagnoseClassNameShadow(SemanticContext,
1873 DeclarationNameInfo(Name, NameLoc)))
1874 return true;
1875
1876 LookupName(Previous, S);
1877 }
1878
1879 if (Previous.isAmbiguous())
1880 return true;
1881
1882 NamedDecl *PrevDecl = nullptr;
1883 if (Previous.begin() != Previous.end())
1884 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1885
1886 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1887 // Maybe we will complain about the shadowed template parameter.
1888 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1889 // Just pretend that we didn't see the previous declaration.
1890 PrevDecl = nullptr;
1891 }
1892
1893 // If there is a previous declaration with the same name, check
1894 // whether this is a valid redeclaration.
1895 ClassTemplateDecl *PrevClassTemplate =
1896 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1897
1898 // We may have found the injected-class-name of a class template,
1899 // class template partial specialization, or class template specialization.
1900 // In these cases, grab the template that is being defined or specialized.
1901 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
1902 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1903 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1904 PrevClassTemplate
1905 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1906 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1907 PrevClassTemplate
1908 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1909 ->getSpecializedTemplate();
1910 }
1911 }
1912
1913 if (TUK == TagUseKind::Friend) {
1914 // C++ [namespace.memdef]p3:
1915 // [...] When looking for a prior declaration of a class or a function
1916 // declared as a friend, and when the name of the friend class or
1917 // function is neither a qualified name nor a template-id, scopes outside
1918 // the innermost enclosing namespace scope are not considered.
1919 if (!SS.isSet()) {
1920 DeclContext *OutermostContext = CurContext;
1921 while (!OutermostContext->isFileContext())
1922 OutermostContext = OutermostContext->getLookupParent();
1923
1924 if (PrevDecl &&
1925 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1926 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1927 SemanticContext = PrevDecl->getDeclContext();
1928 } else {
1929 // Declarations in outer scopes don't matter. However, the outermost
1930 // context we computed is the semantic context for our new
1931 // declaration.
1932 PrevDecl = PrevClassTemplate = nullptr;
1933 SemanticContext = OutermostContext;
1934
1935 // Check that the chosen semantic context doesn't already contain a
1936 // declaration of this name as a non-tag type.
1938 DeclContext *LookupContext = SemanticContext;
1939 while (LookupContext->isTransparentContext())
1940 LookupContext = LookupContext->getLookupParent();
1941 LookupQualifiedName(Previous, LookupContext);
1942
1943 if (Previous.isAmbiguous())
1944 return true;
1945
1946 if (Previous.begin() != Previous.end())
1947 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1948 }
1949 }
1950 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
1951 SemanticContext, S, SS.isValid()))
1952 PrevDecl = PrevClassTemplate = nullptr;
1953
1954 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1955 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1956 if (SS.isEmpty() &&
1957 !(PrevClassTemplate &&
1958 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1959 SemanticContext->getRedeclContext()))) {
1960 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1961 Diag(Shadow->getTargetDecl()->getLocation(),
1962 diag::note_using_decl_target);
1963 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
1964 // Recover by ignoring the old declaration.
1965 PrevDecl = PrevClassTemplate = nullptr;
1966 }
1967 }
1968
1969 if (PrevClassTemplate) {
1970 // Ensure that the template parameter lists are compatible. Skip this check
1971 // for a friend in a dependent context: the template parameter list itself
1972 // could be dependent.
1973 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
1975 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
1976 : CurContext,
1977 CurContext, KWLoc),
1978 TemplateParams, PrevClassTemplate,
1979 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
1981 return true;
1982
1983 // C++ [temp.class]p4:
1984 // In a redeclaration, partial specialization, explicit
1985 // specialization or explicit instantiation of a class template,
1986 // the class-key shall agree in kind with the original class
1987 // template declaration (7.1.5.3).
1988 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1990 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
1991 Diag(KWLoc, diag::err_use_with_wrong_tag)
1992 << Name
1993 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1994 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1995 Kind = PrevRecordDecl->getTagKind();
1996 }
1997
1998 // Check for redefinition of this class template.
1999 if (TUK == TagUseKind::Definition) {
2000 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2001 // If we have a prior definition that is not visible, treat this as
2002 // simply making that previous definition visible.
2003 NamedDecl *Hidden = nullptr;
2004 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2005 SkipBody->ShouldSkip = true;
2006 SkipBody->Previous = Def;
2007 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2008 assert(Tmpl && "original definition of a class template is not a "
2009 "class template?");
2012 } else {
2013 Diag(NameLoc, diag::err_redefinition) << Name;
2014 Diag(Def->getLocation(), diag::note_previous_definition);
2015 // FIXME: Would it make sense to try to "forget" the previous
2016 // definition, as part of error recovery?
2017 return true;
2018 }
2019 }
2020 }
2021 } else if (PrevDecl) {
2022 // C++ [temp]p5:
2023 // A class template shall not have the same name as any other
2024 // template, class, function, object, enumeration, enumerator,
2025 // namespace, or type in the same scope (3.3), except as specified
2026 // in (14.5.4).
2027 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2028 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2029 return true;
2030 }
2031
2032 // Check the template parameter list of this declaration, possibly
2033 // merging in the template parameter list from the previous class
2034 // template declaration. Skip this check for a friend in a dependent
2035 // context, because the template parameter list might be dependent.
2036 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2038 TemplateParams,
2039 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2040 : nullptr,
2041 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2042 SemanticContext->isDependentContext())
2046 SkipBody))
2047 Invalid = true;
2048
2049 if (SS.isSet()) {
2050 // If the name of the template was qualified, we must be defining the
2051 // template out-of-line.
2052 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2053 Diag(NameLoc, TUK == TagUseKind::Friend
2054 ? diag::err_friend_decl_does_not_match
2055 : diag::err_member_decl_does_not_match)
2056 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2057 Invalid = true;
2058 }
2059 }
2060
2061 // If this is a templated friend in a dependent context we should not put it
2062 // on the redecl chain. In some cases, the templated friend can be the most
2063 // recent declaration tricking the template instantiator to make substitutions
2064 // there.
2065 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2066 bool ShouldAddRedecl =
2068
2069 CXXRecordDecl *NewClass =
2070 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2071 PrevClassTemplate && ShouldAddRedecl ?
2072 PrevClassTemplate->getTemplatedDecl() : nullptr,
2073 /*DelayTypeCreation=*/true);
2074 SetNestedNameSpecifier(*this, NewClass, SS);
2075 if (NumOuterTemplateParamLists > 0)
2077 Context,
2078 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2079
2080 // Add alignment attributes if necessary; these attributes are checked when
2081 // the ASTContext lays out the structure.
2082 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2085 }
2086
2087 ClassTemplateDecl *NewTemplate
2088 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2089 DeclarationName(Name), TemplateParams,
2090 NewClass);
2091
2092 if (ShouldAddRedecl)
2093 NewTemplate->setPreviousDecl(PrevClassTemplate);
2094
2095 NewClass->setDescribedClassTemplate(NewTemplate);
2096
2097 if (ModulePrivateLoc.isValid())
2098 NewTemplate->setModulePrivate();
2099
2100 // Build the type for the class template declaration now.
2102 T = Context.getInjectedClassNameType(NewClass, T);
2103 assert(T->isDependentType() && "Class template type is not dependent?");
2104 (void)T;
2105
2106 // If we are providing an explicit specialization of a member that is a
2107 // class template, make a note of that.
2108 if (PrevClassTemplate &&
2109 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2110 PrevClassTemplate->setMemberSpecialization();
2111
2112 // Set the access specifier.
2113 if (!Invalid && TUK != TagUseKind::Friend &&
2114 NewTemplate->getDeclContext()->isRecord())
2115 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2116
2117 // Set the lexical context of these templates
2119 NewTemplate->setLexicalDeclContext(CurContext);
2120
2121 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2122 NewClass->startDefinition();
2123
2124 ProcessDeclAttributeList(S, NewClass, Attr);
2125 ProcessAPINotes(NewClass);
2126
2127 if (PrevClassTemplate)
2128 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2129
2133
2134 if (TUK != TagUseKind::Friend) {
2135 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2136 Scope *Outer = S;
2137 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2138 Outer = Outer->getParent();
2139 PushOnScopeChains(NewTemplate, Outer);
2140 } else {
2141 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2142 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2143 NewClass->setAccess(PrevClassTemplate->getAccess());
2144 }
2145
2146 NewTemplate->setObjectOfFriendDecl();
2147
2148 // Friend templates are visible in fairly strange ways.
2150 DeclContext *DC = SemanticContext->getRedeclContext();
2151 DC->makeDeclVisibleInContext(NewTemplate);
2152 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2153 PushOnScopeChains(NewTemplate, EnclosingScope,
2154 /* AddToContext = */ false);
2155 }
2156
2158 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2159 Friend->setAccess(AS_public);
2161 }
2162
2163 if (PrevClassTemplate)
2164 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2165
2166 if (Invalid) {
2167 NewTemplate->setInvalidDecl();
2168 NewClass->setInvalidDecl();
2169 }
2170
2171 ActOnDocumentableDecl(NewTemplate);
2172
2173 if (SkipBody && SkipBody->ShouldSkip)
2174 return SkipBody->Previous;
2175
2176 return NewTemplate;
2177}
2178
2179/// Diagnose the presence of a default template argument on a
2180/// template parameter, which is ill-formed in certain contexts.
2181///
2182/// \returns true if the default template argument should be dropped.
2185 SourceLocation ParamLoc,
2186 SourceRange DefArgRange) {
2187 switch (TPC) {
2191 return false;
2192
2195 // C++ [temp.param]p9:
2196 // A default template-argument shall not be specified in a
2197 // function template declaration or a function template
2198 // definition [...]
2199 // If a friend function template declaration specifies a default
2200 // template-argument, that declaration shall be a definition and shall be
2201 // the only declaration of the function template in the translation unit.
2202 // (C++98/03 doesn't have this wording; see DR226).
2203 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2204 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2205 : diag::ext_template_parameter_default_in_function_template)
2206 << DefArgRange;
2207 return false;
2208
2210 // C++0x [temp.param]p9:
2211 // A default template-argument shall not be specified in the
2212 // template-parameter-lists of the definition of a member of a
2213 // class template that appears outside of the member's class.
2214 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2215 << DefArgRange;
2216 return true;
2217
2220 // C++ [temp.param]p9:
2221 // A default template-argument shall not be specified in a
2222 // friend template declaration.
2223 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2224 << DefArgRange;
2225 return true;
2226
2227 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2228 // for friend function templates if there is only a single
2229 // declaration (and it is a definition). Strange!
2230 }
2231
2232 llvm_unreachable("Invalid TemplateParamListContext!");
2233}
2234
2235/// Check for unexpanded parameter packs within the template parameters
2236/// of a template template parameter, recursively.
2239 // A template template parameter which is a parameter pack is also a pack
2240 // expansion.
2241 if (TTP->isParameterPack())
2242 return false;
2243
2245 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2246 NamedDecl *P = Params->getParam(I);
2247 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2248 if (!TTP->isParameterPack())
2249 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2250 if (TC->hasExplicitTemplateArgs())
2251 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2254 return true;
2255 continue;
2256 }
2257
2258 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2259 if (!NTTP->isParameterPack() &&
2260 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2261 NTTP->getTypeSourceInfo(),
2263 return true;
2264
2265 continue;
2266 }
2267
2268 if (TemplateTemplateParmDecl *InnerTTP
2269 = dyn_cast<TemplateTemplateParmDecl>(P))
2270 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2271 return true;
2272 }
2273
2274 return false;
2275}
2276
2278 TemplateParameterList *OldParams,
2280 SkipBodyInfo *SkipBody) {
2281 bool Invalid = false;
2282
2283 // C++ [temp.param]p10:
2284 // The set of default template-arguments available for use with a
2285 // template declaration or definition is obtained by merging the
2286 // default arguments from the definition (if in scope) and all
2287 // declarations in scope in the same way default function
2288 // arguments are (8.3.6).
2289 bool SawDefaultArgument = false;
2290 SourceLocation PreviousDefaultArgLoc;
2291
2292 // Dummy initialization to avoid warnings.
2293 TemplateParameterList::iterator OldParam = NewParams->end();
2294 if (OldParams)
2295 OldParam = OldParams->begin();
2296
2297 bool RemoveDefaultArguments = false;
2298 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2299 NewParamEnd = NewParams->end();
2300 NewParam != NewParamEnd; ++NewParam) {
2301 // Whether we've seen a duplicate default argument in the same translation
2302 // unit.
2303 bool RedundantDefaultArg = false;
2304 // Whether we've found inconsis inconsitent default arguments in different
2305 // translation unit.
2306 bool InconsistentDefaultArg = false;
2307 // The name of the module which contains the inconsistent default argument.
2308 std::string PrevModuleName;
2309
2310 SourceLocation OldDefaultLoc;
2311 SourceLocation NewDefaultLoc;
2312
2313 // Variable used to diagnose missing default arguments
2314 bool MissingDefaultArg = false;
2315
2316 // Variable used to diagnose non-final parameter packs
2317 bool SawParameterPack = false;
2318
2319 if (TemplateTypeParmDecl *NewTypeParm
2320 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2321 // Check the presence of a default argument here.
2322 if (NewTypeParm->hasDefaultArgument() &&
2324 *this, TPC, NewTypeParm->getLocation(),
2325 NewTypeParm->getDefaultArgument().getSourceRange()))
2326 NewTypeParm->removeDefaultArgument();
2327
2328 // Merge default arguments for template type parameters.
2329 TemplateTypeParmDecl *OldTypeParm
2330 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2331 if (NewTypeParm->isParameterPack()) {
2332 assert(!NewTypeParm->hasDefaultArgument() &&
2333 "Parameter packs can't have a default argument!");
2334 SawParameterPack = true;
2335 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2336 NewTypeParm->hasDefaultArgument() &&
2337 (!SkipBody || !SkipBody->ShouldSkip)) {
2338 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2339 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2340 SawDefaultArgument = true;
2341
2342 if (!OldTypeParm->getOwningModule())
2343 RedundantDefaultArg = true;
2344 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2345 NewTypeParm)) {
2346 InconsistentDefaultArg = true;
2347 PrevModuleName =
2349 }
2350 PreviousDefaultArgLoc = NewDefaultLoc;
2351 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2352 // Merge the default argument from the old declaration to the
2353 // new declaration.
2354 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2355 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2356 } else if (NewTypeParm->hasDefaultArgument()) {
2357 SawDefaultArgument = true;
2358 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2359 } else if (SawDefaultArgument)
2360 MissingDefaultArg = true;
2361 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2362 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2363 // Check for unexpanded parameter packs.
2364 if (!NewNonTypeParm->isParameterPack() &&
2365 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2366 NewNonTypeParm->getTypeSourceInfo(),
2368 Invalid = true;
2369 continue;
2370 }
2371
2372 // Check the presence of a default argument here.
2373 if (NewNonTypeParm->hasDefaultArgument() &&
2375 *this, TPC, NewNonTypeParm->getLocation(),
2376 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2377 NewNonTypeParm->removeDefaultArgument();
2378 }
2379
2380 // Merge default arguments for non-type template parameters
2381 NonTypeTemplateParmDecl *OldNonTypeParm
2382 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2383 if (NewNonTypeParm->isParameterPack()) {
2384 assert(!NewNonTypeParm->hasDefaultArgument() &&
2385 "Parameter packs can't have a default argument!");
2386 if (!NewNonTypeParm->isPackExpansion())
2387 SawParameterPack = true;
2388 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2389 NewNonTypeParm->hasDefaultArgument() &&
2390 (!SkipBody || !SkipBody->ShouldSkip)) {
2391 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2392 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2393 SawDefaultArgument = true;
2394 if (!OldNonTypeParm->getOwningModule())
2395 RedundantDefaultArg = true;
2396 else if (!getASTContext().isSameDefaultTemplateArgument(
2397 OldNonTypeParm, NewNonTypeParm)) {
2398 InconsistentDefaultArg = true;
2399 PrevModuleName =
2400 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2401 }
2402 PreviousDefaultArgLoc = NewDefaultLoc;
2403 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2404 // Merge the default argument from the old declaration to the
2405 // new declaration.
2406 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2407 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2408 } else if (NewNonTypeParm->hasDefaultArgument()) {
2409 SawDefaultArgument = true;
2410 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2411 } else if (SawDefaultArgument)
2412 MissingDefaultArg = true;
2413 } else {
2414 TemplateTemplateParmDecl *NewTemplateParm
2415 = cast<TemplateTemplateParmDecl>(*NewParam);
2416
2417 // Check for unexpanded parameter packs, recursively.
2418 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2419 Invalid = true;
2420 continue;
2421 }
2422
2423 // Check the presence of a default argument here.
2424 if (NewTemplateParm->hasDefaultArgument() &&
2426 NewTemplateParm->getLocation(),
2427 NewTemplateParm->getDefaultArgument().getSourceRange()))
2428 NewTemplateParm->removeDefaultArgument();
2429
2430 // Merge default arguments for template template parameters
2431 TemplateTemplateParmDecl *OldTemplateParm
2432 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2433 if (NewTemplateParm->isParameterPack()) {
2434 assert(!NewTemplateParm->hasDefaultArgument() &&
2435 "Parameter packs can't have a default argument!");
2436 if (!NewTemplateParm->isPackExpansion())
2437 SawParameterPack = true;
2438 } else if (OldTemplateParm &&
2439 hasVisibleDefaultArgument(OldTemplateParm) &&
2440 NewTemplateParm->hasDefaultArgument() &&
2441 (!SkipBody || !SkipBody->ShouldSkip)) {
2442 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2443 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2444 SawDefaultArgument = true;
2445 if (!OldTemplateParm->getOwningModule())
2446 RedundantDefaultArg = true;
2447 else if (!getASTContext().isSameDefaultTemplateArgument(
2448 OldTemplateParm, NewTemplateParm)) {
2449 InconsistentDefaultArg = true;
2450 PrevModuleName =
2451 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2452 }
2453 PreviousDefaultArgLoc = NewDefaultLoc;
2454 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2455 // Merge the default argument from the old declaration to the
2456 // new declaration.
2457 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2458 PreviousDefaultArgLoc
2459 = OldTemplateParm->getDefaultArgument().getLocation();
2460 } else if (NewTemplateParm->hasDefaultArgument()) {
2461 SawDefaultArgument = true;
2462 PreviousDefaultArgLoc
2463 = NewTemplateParm->getDefaultArgument().getLocation();
2464 } else if (SawDefaultArgument)
2465 MissingDefaultArg = true;
2466 }
2467
2468 // C++11 [temp.param]p11:
2469 // If a template parameter of a primary class template or alias template
2470 // is a template parameter pack, it shall be the last template parameter.
2471 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2472 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2473 TPC == TPC_TypeAliasTemplate)) {
2474 Diag((*NewParam)->getLocation(),
2475 diag::err_template_param_pack_must_be_last_template_parameter);
2476 Invalid = true;
2477 }
2478
2479 // [basic.def.odr]/13:
2480 // There can be more than one definition of a
2481 // ...
2482 // default template argument
2483 // ...
2484 // in a program provided that each definition appears in a different
2485 // translation unit and the definitions satisfy the [same-meaning
2486 // criteria of the ODR].
2487 //
2488 // Simply, the design of modules allows the definition of template default
2489 // argument to be repeated across translation unit. Note that the ODR is
2490 // checked elsewhere. But it is still not allowed to repeat template default
2491 // argument in the same translation unit.
2492 if (RedundantDefaultArg) {
2493 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2494 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2495 Invalid = true;
2496 } else if (InconsistentDefaultArg) {
2497 // We could only diagnose about the case that the OldParam is imported.
2498 // The case NewParam is imported should be handled in ASTReader.
2499 Diag(NewDefaultLoc,
2500 diag::err_template_param_default_arg_inconsistent_redefinition);
2501 Diag(OldDefaultLoc,
2502 diag::note_template_param_prev_default_arg_in_other_module)
2503 << PrevModuleName;
2504 Invalid = true;
2505 } else if (MissingDefaultArg &&
2506 (TPC == TPC_ClassTemplate || TPC == TPC_FriendClassTemplate ||
2507 TPC == TPC_VarTemplate || TPC == TPC_TypeAliasTemplate)) {
2508 // C++ 23[temp.param]p14:
2509 // If a template-parameter of a class template, variable template, or
2510 // alias template has a default template argument, each subsequent
2511 // template-parameter shall either have a default template argument
2512 // supplied or be a template parameter pack.
2513 Diag((*NewParam)->getLocation(),
2514 diag::err_template_param_default_arg_missing);
2515 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2516 Invalid = true;
2517 RemoveDefaultArguments = true;
2518 }
2519
2520 // If we have an old template parameter list that we're merging
2521 // in, move on to the next parameter.
2522 if (OldParams)
2523 ++OldParam;
2524 }
2525
2526 // We were missing some default arguments at the end of the list, so remove
2527 // all of the default arguments.
2528 if (RemoveDefaultArguments) {
2529 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2530 NewParamEnd = NewParams->end();
2531 NewParam != NewParamEnd; ++NewParam) {
2532 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2533 TTP->removeDefaultArgument();
2534 else if (NonTypeTemplateParmDecl *NTTP
2535 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2536 NTTP->removeDefaultArgument();
2537 else
2538 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2539 }
2540 }
2541
2542 return Invalid;
2543}
2544
2545namespace {
2546
2547/// A class which looks for a use of a certain level of template
2548/// parameter.
2549struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2551
2552 unsigned Depth;
2553
2554 // Whether we're looking for a use of a template parameter that makes the
2555 // overall construct type-dependent / a dependent type. This is strictly
2556 // best-effort for now; we may fail to match at all for a dependent type
2557 // in some cases if this is set.
2558 bool IgnoreNonTypeDependent;
2559
2560 bool Match;
2561 SourceLocation MatchLoc;
2562
2563 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2564 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2565 Match(false) {}
2566
2567 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2568 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2569 NamedDecl *ND = Params->getParam(0);
2570 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2571 Depth = PD->getDepth();
2572 } else if (NonTypeTemplateParmDecl *PD =
2573 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2574 Depth = PD->getDepth();
2575 } else {
2576 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2577 }
2578 }
2579
2580 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2581 if (ParmDepth >= Depth) {
2582 Match = true;
2583 MatchLoc = Loc;
2584 return true;
2585 }
2586 return false;
2587 }
2588
2589 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2590 // Prune out non-type-dependent expressions if requested. This can
2591 // sometimes result in us failing to find a template parameter reference
2592 // (if a value-dependent expression creates a dependent type), but this
2593 // mode is best-effort only.
2594 if (auto *E = dyn_cast_or_null<Expr>(S))
2595 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2596 return true;
2597 return super::TraverseStmt(S, Q);
2598 }
2599
2600 bool TraverseTypeLoc(TypeLoc TL) {
2601 if (IgnoreNonTypeDependent && !TL.isNull() &&
2602 !TL.getType()->isDependentType())
2603 return true;
2604 return super::TraverseTypeLoc(TL);
2605 }
2606
2607 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2608 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2609 }
2610
2611 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2612 // For a best-effort search, keep looking until we find a location.
2613 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2614 }
2615
2616 bool TraverseTemplateName(TemplateName N) {
2617 if (TemplateTemplateParmDecl *PD =
2618 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2619 if (Matches(PD->getDepth()))
2620 return false;
2621 return super::TraverseTemplateName(N);
2622 }
2623
2624 bool VisitDeclRefExpr(DeclRefExpr *E) {
2625 if (NonTypeTemplateParmDecl *PD =
2626 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2627 if (Matches(PD->getDepth(), E->getExprLoc()))
2628 return false;
2629 return super::VisitDeclRefExpr(E);
2630 }
2631
2632 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2633 return TraverseType(T->getReplacementType());
2634 }
2635
2636 bool
2637 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2638 return TraverseTemplateArgument(T->getArgumentPack());
2639 }
2640
2641 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2642 return TraverseType(T->getInjectedSpecializationType());
2643 }
2644};
2645} // end anonymous namespace
2646
2647/// Determines whether a given type depends on the given parameter
2648/// list.
2649static bool
2651 if (!Params->size())
2652 return false;
2653
2654 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2655 Checker.TraverseType(T);
2656 return Checker.Match;
2657}
2658
2659// Find the source range corresponding to the named type in the given
2660// nested-name-specifier, if any.
2662 QualType T,
2663 const CXXScopeSpec &SS) {
2665 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2666 if (const Type *CurType = NNS->getAsType()) {
2667 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2668 return NNSLoc.getTypeLoc().getSourceRange();
2669 } else
2670 break;
2671
2672 NNSLoc = NNSLoc.getPrefix();
2673 }
2674
2675 return SourceRange();
2676}
2677
2679 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2680 TemplateIdAnnotation *TemplateId,
2681 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2682 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2683 IsMemberSpecialization = false;
2684 Invalid = false;
2685
2686 // The sequence of nested types to which we will match up the template
2687 // parameter lists. We first build this list by starting with the type named
2688 // by the nested-name-specifier and walking out until we run out of types.
2689 SmallVector<QualType, 4> NestedTypes;
2690 QualType T;
2691 if (SS.getScopeRep()) {
2693 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2695 else
2696 T = QualType(SS.getScopeRep()->getAsType(), 0);
2697 }
2698
2699 // If we found an explicit specialization that prevents us from needing
2700 // 'template<>' headers, this will be set to the location of that
2701 // explicit specialization.
2702 SourceLocation ExplicitSpecLoc;
2703
2704 while (!T.isNull()) {
2705 NestedTypes.push_back(T);
2706
2707 // Retrieve the parent of a record type.
2709 // If this type is an explicit specialization, we're done.
2711 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2712 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2713 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2714 ExplicitSpecLoc = Spec->getLocation();
2715 break;
2716 }
2717 } else if (Record->getTemplateSpecializationKind()
2719 ExplicitSpecLoc = Record->getLocation();
2720 break;
2721 }
2722
2723 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2725 else
2726 T = QualType();
2727 continue;
2728 }
2729
2730 if (const TemplateSpecializationType *TST
2732 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2733 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2735 else
2736 T = QualType();
2737 continue;
2738 }
2739 }
2740
2741 // Look one step prior in a dependent template specialization type.
2742 if (const DependentTemplateSpecializationType *DependentTST
2744 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2745 T = QualType(NNS->getAsType(), 0);
2746 else
2747 T = QualType();
2748 continue;
2749 }
2750
2751 // Look one step prior in a dependent name type.
2752 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2753 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2754 T = QualType(NNS->getAsType(), 0);
2755 else
2756 T = QualType();
2757 continue;
2758 }
2759
2760 // Retrieve the parent of an enumeration type.
2761 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2762 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2763 // check here.
2764 EnumDecl *Enum = EnumT->getDecl();
2765
2766 // Get to the parent type.
2767 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2769 else
2770 T = QualType();
2771 continue;
2772 }
2773
2774 T = QualType();
2775 }
2776 // Reverse the nested types list, since we want to traverse from the outermost
2777 // to the innermost while checking template-parameter-lists.
2778 std::reverse(NestedTypes.begin(), NestedTypes.end());
2779
2780 // C++0x [temp.expl.spec]p17:
2781 // A member or a member template may be nested within many
2782 // enclosing class templates. In an explicit specialization for
2783 // such a member, the member declaration shall be preceded by a
2784 // template<> for each enclosing class template that is
2785 // explicitly specialized.
2786 bool SawNonEmptyTemplateParameterList = false;
2787
2788 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2789 if (SawNonEmptyTemplateParameterList) {
2790 if (!SuppressDiagnostic)
2791 Diag(DeclLoc, diag::err_specialize_member_of_template)
2792 << !Recovery << Range;
2793 Invalid = true;
2794 IsMemberSpecialization = false;
2795 return true;
2796 }
2797
2798 return false;
2799 };
2800
2801 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2802 // Check that we can have an explicit specialization here.
2803 if (CheckExplicitSpecialization(Range, true))
2804 return true;
2805
2806 // We don't have a template header, but we should.
2807 SourceLocation ExpectedTemplateLoc;
2808 if (!ParamLists.empty())
2809 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2810 else
2811 ExpectedTemplateLoc = DeclStartLoc;
2812
2813 if (!SuppressDiagnostic)
2814 Diag(DeclLoc, diag::err_template_spec_needs_header)
2815 << Range
2816 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2817 return false;
2818 };
2819
2820 unsigned ParamIdx = 0;
2821 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2822 ++TypeIdx) {
2823 T = NestedTypes[TypeIdx];
2824
2825 // Whether we expect a 'template<>' header.
2826 bool NeedEmptyTemplateHeader = false;
2827
2828 // Whether we expect a template header with parameters.
2829 bool NeedNonemptyTemplateHeader = false;
2830
2831 // For a dependent type, the set of template parameters that we
2832 // expect to see.
2833 TemplateParameterList *ExpectedTemplateParams = nullptr;
2834
2835 // C++0x [temp.expl.spec]p15:
2836 // A member or a member template may be nested within many enclosing
2837 // class templates. In an explicit specialization for such a member, the
2838 // member declaration shall be preceded by a template<> for each
2839 // enclosing class template that is explicitly specialized.
2842 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2843 ExpectedTemplateParams = Partial->getTemplateParameters();
2844 NeedNonemptyTemplateHeader = true;
2845 } else if (Record->isDependentType()) {
2846 if (Record->getDescribedClassTemplate()) {
2847 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2848 ->getTemplateParameters();
2849 NeedNonemptyTemplateHeader = true;
2850 }
2851 } else if (ClassTemplateSpecializationDecl *Spec
2852 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2853 // C++0x [temp.expl.spec]p4:
2854 // Members of an explicitly specialized class template are defined
2855 // in the same manner as members of normal classes, and not using
2856 // the template<> syntax.
2857 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2858 NeedEmptyTemplateHeader = true;
2859 else
2860 continue;
2861 } else if (Record->getTemplateSpecializationKind()) {
2862 if (Record->getTemplateSpecializationKind()
2864 TypeIdx == NumTypes - 1)
2865 IsMemberSpecialization = true;
2866
2867 continue;
2868 }
2869 } else if (const TemplateSpecializationType *TST
2871 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2872 ExpectedTemplateParams = Template->getTemplateParameters();
2873 NeedNonemptyTemplateHeader = true;
2874 }
2876 // FIXME: We actually could/should check the template arguments here
2877 // against the corresponding template parameter list.
2878 NeedNonemptyTemplateHeader = false;
2879 }
2880
2881 // C++ [temp.expl.spec]p16:
2882 // In an explicit specialization declaration for a member of a class
2883 // template or a member template that appears in namespace scope, the
2884 // member template and some of its enclosing class templates may remain
2885 // unspecialized, except that the declaration shall not explicitly
2886 // specialize a class member template if its enclosing class templates
2887 // are not explicitly specialized as well.
2888 if (ParamIdx < ParamLists.size()) {
2889 if (ParamLists[ParamIdx]->size() == 0) {
2890 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2891 false))
2892 return nullptr;
2893 } else
2894 SawNonEmptyTemplateParameterList = true;
2895 }
2896
2897 if (NeedEmptyTemplateHeader) {
2898 // If we're on the last of the types, and we need a 'template<>' header
2899 // here, then it's a member specialization.
2900 if (TypeIdx == NumTypes - 1)
2901 IsMemberSpecialization = true;
2902
2903 if (ParamIdx < ParamLists.size()) {
2904 if (ParamLists[ParamIdx]->size() > 0) {
2905 // The header has template parameters when it shouldn't. Complain.
2906 if (!SuppressDiagnostic)
2907 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2908 diag::err_template_param_list_matches_nontemplate)
2909 << T
2910 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2911 ParamLists[ParamIdx]->getRAngleLoc())
2913 Invalid = true;
2914 return nullptr;
2915 }
2916
2917 // Consume this template header.
2918 ++ParamIdx;
2919 continue;
2920 }
2921
2922 if (!IsFriend)
2923 if (DiagnoseMissingExplicitSpecialization(
2925 return nullptr;
2926
2927 continue;
2928 }
2929
2930 if (NeedNonemptyTemplateHeader) {
2931 // In friend declarations we can have template-ids which don't
2932 // depend on the corresponding template parameter lists. But
2933 // assume that empty parameter lists are supposed to match this
2934 // template-id.
2935 if (IsFriend && T->isDependentType()) {
2936 if (ParamIdx < ParamLists.size() &&
2938 ExpectedTemplateParams = nullptr;
2939 else
2940 continue;
2941 }
2942
2943 if (ParamIdx < ParamLists.size()) {
2944 // Check the template parameter list, if we can.
2945 if (ExpectedTemplateParams &&
2947 ExpectedTemplateParams,
2948 !SuppressDiagnostic, TPL_TemplateMatch))
2949 Invalid = true;
2950
2951 if (!Invalid &&
2952 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2954 Invalid = true;
2955
2956 ++ParamIdx;
2957 continue;
2958 }
2959
2960 if (!SuppressDiagnostic)
2961 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2962 << T
2964 Invalid = true;
2965 continue;
2966 }
2967 }
2968
2969 // If there were at least as many template-ids as there were template
2970 // parameter lists, then there are no template parameter lists remaining for
2971 // the declaration itself.
2972 if (ParamIdx >= ParamLists.size()) {
2973 if (TemplateId && !IsFriend) {
2974 // We don't have a template header for the declaration itself, but we
2975 // should.
2976 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2977 TemplateId->RAngleLoc));
2978
2979 // Fabricate an empty template parameter list for the invented header.
2981 SourceLocation(), std::nullopt,
2982 SourceLocation(), nullptr);
2983 }
2984
2985 return nullptr;
2986 }
2987
2988 // If there were too many template parameter lists, complain about that now.
2989 if (ParamIdx < ParamLists.size() - 1) {
2990 bool HasAnyExplicitSpecHeader = false;
2991 bool AllExplicitSpecHeaders = true;
2992 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2993 if (ParamLists[I]->size() == 0)
2994 HasAnyExplicitSpecHeader = true;
2995 else
2996 AllExplicitSpecHeaders = false;
2997 }
2998
2999 if (!SuppressDiagnostic)
3000 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3001 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3002 : diag::err_template_spec_extra_headers)
3003 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3004 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3005
3006 // If there was a specialization somewhere, such that 'template<>' is
3007 // not required, and there were any 'template<>' headers, note where the
3008 // specialization occurred.
3009 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3010 !SuppressDiagnostic)
3011 Diag(ExplicitSpecLoc,
3012 diag::note_explicit_template_spec_does_not_need_header)
3013 << NestedTypes.back();
3014
3015 // We have a template parameter list with no corresponding scope, which
3016 // means that the resulting template declaration can't be instantiated
3017 // properly (we'll end up with dependent nodes when we shouldn't).
3018 if (!AllExplicitSpecHeaders)
3019 Invalid = true;
3020 }
3021
3022 // C++ [temp.expl.spec]p16:
3023 // In an explicit specialization declaration for a member of a class
3024 // template or a member template that ap- pears in namespace scope, the
3025 // member template and some of its enclosing class templates may remain
3026 // unspecialized, except that the declaration shall not explicitly
3027 // specialize a class member template if its en- closing class templates
3028 // are not explicitly specialized as well.
3029 if (ParamLists.back()->size() == 0 &&
3030 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3031 false))
3032 return nullptr;
3033
3034 // Return the last template parameter list, which corresponds to the
3035 // entity being declared.
3036 return ParamLists.back();
3037}
3038
3040 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3041 Diag(Template->getLocation(), diag::note_template_declared_here)
3042 << (isa<FunctionTemplateDecl>(Template)
3043 ? 0
3044 : isa<ClassTemplateDecl>(Template)
3045 ? 1
3046 : isa<VarTemplateDecl>(Template)
3047 ? 2
3048 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3049 << Template->getDeclName();
3050 return;
3051 }
3052
3053 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3054 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3055 IEnd = OST->end();
3056 I != IEnd; ++I)
3057 Diag((*I)->getLocation(), diag::note_template_declared_here)
3058 << 0 << (*I)->getDeclName();
3059
3060 return;
3061 }
3062}
3063
3064static QualType
3067 SourceLocation TemplateLoc,
3068 TemplateArgumentListInfo &TemplateArgs) {
3069 ASTContext &Context = SemaRef.getASTContext();
3070
3071 switch (BTD->getBuiltinTemplateKind()) {
3072 case BTK__make_integer_seq: {
3073 // Specializations of __make_integer_seq<S, T, N> are treated like
3074 // S<T, 0, ..., N-1>.
3075
3076 QualType OrigType = Converted[1].getAsType();
3077 // C++14 [inteseq.intseq]p1:
3078 // T shall be an integer type.
3079 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3080 SemaRef.Diag(TemplateArgs[1].getLocation(),
3081 diag::err_integer_sequence_integral_element_type);
3082 return QualType();
3083 }
3084
3085 TemplateArgument NumArgsArg = Converted[2];
3086 if (NumArgsArg.isDependent())
3088 Converted);
3089
3090 TemplateArgumentListInfo SyntheticTemplateArgs;
3091 // The type argument, wrapped in substitution sugar, gets reused as the
3092 // first template argument in the synthetic template argument list.
3093 SyntheticTemplateArgs.addArgument(
3096 OrigType, TemplateArgs[1].getLocation())));
3097
3098 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3099 // Expand N into 0 ... N-1.
3100 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3101 I < NumArgs; ++I) {
3102 TemplateArgument TA(Context, I, OrigType);
3103 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3104 TA, OrigType, TemplateArgs[2].getLocation()));
3105 }
3106 } else {
3107 // C++14 [inteseq.make]p1:
3108 // If N is negative the program is ill-formed.
3109 SemaRef.Diag(TemplateArgs[2].getLocation(),
3110 diag::err_integer_sequence_negative_length);
3111 return QualType();
3112 }
3113
3114 // The first template argument will be reused as the template decl that
3115 // our synthetic template arguments will be applied to.
3116 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3117 TemplateLoc, SyntheticTemplateArgs);
3118 }
3119
3121 // Specializations of
3122 // __type_pack_element<Index, T_1, ..., T_N>
3123 // are treated like T_Index.
3124 assert(Converted.size() == 2 &&
3125 "__type_pack_element should be given an index and a parameter pack");
3126
3127 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3128 if (IndexArg.isDependent() || Ts.isDependent())
3130 Converted);
3131
3132 llvm::APSInt Index = IndexArg.getAsIntegral();
3133 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3134 "type std::size_t, and hence be non-negative");
3135 // If the Index is out of bounds, the program is ill-formed.
3136 if (Index >= Ts.pack_size()) {
3137 SemaRef.Diag(TemplateArgs[0].getLocation(),
3138 diag::err_type_pack_element_out_of_bounds);
3139 return QualType();
3140 }
3141
3142 // We simply return the type at index `Index`.
3143 int64_t N = Index.getExtValue();
3144 return Ts.getPackAsArray()[N].getAsType();
3145 }
3146 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3147}
3148
3149/// Determine whether this alias template is "enable_if_t".
3150/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3152 return AliasTemplate->getName() == "enable_if_t" ||
3153 AliasTemplate->getName() == "__enable_if_t";
3154}
3155
3156/// Collect all of the separable terms in the given condition, which
3157/// might be a conjunction.
3158///
3159/// FIXME: The right answer is to convert the logical expression into
3160/// disjunctive normal form, so we can find the first failed term
3161/// within each possible clause.
3162static void collectConjunctionTerms(Expr *Clause,
3163 SmallVectorImpl<Expr *> &Terms) {
3164 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3165 if (BinOp->getOpcode() == BO_LAnd) {
3166 collectConjunctionTerms(BinOp->getLHS(), Terms);
3167 collectConjunctionTerms(BinOp->getRHS(), Terms);
3168 return;
3169 }
3170 }
3171
3172 Terms.push_back(Clause);
3173}
3174
3175// The ranges-v3 library uses an odd pattern of a top-level "||" with
3176// a left-hand side that is value-dependent but never true. Identify
3177// the idiom and ignore that term.
3179 // Top-level '||'.
3180 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3181 if (!BinOp) return Cond;
3182
3183 if (BinOp->getOpcode() != BO_LOr) return Cond;
3184
3185 // With an inner '==' that has a literal on the right-hand side.
3186 Expr *LHS = BinOp->getLHS();
3187 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3188 if (!InnerBinOp) return Cond;
3189
3190 if (InnerBinOp->getOpcode() != BO_EQ ||
3191 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3192 return Cond;
3193
3194 // If the inner binary operation came from a macro expansion named
3195 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3196 // of the '||', which is the real, user-provided condition.
3197 SourceLocation Loc = InnerBinOp->getExprLoc();
3198 if (!Loc.isMacroID()) return Cond;
3199
3200 StringRef MacroName = PP.getImmediateMacroName(Loc);
3201 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3202 return BinOp->getRHS();
3203
3204 return Cond;
3205}
3206
3207namespace {
3208
3209// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3210// within failing boolean expression, such as substituting template parameters
3211// for actual types.
3212class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3213public:
3214 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3215 : Policy(P) {}
3216
3217 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3218 const auto *DR = dyn_cast<DeclRefExpr>(E);
3219 if (DR && DR->getQualifier()) {
3220 // If this is a qualified name, expand the template arguments in nested
3221 // qualifiers.
3222 DR->getQualifier()->print(OS, Policy, true);
3223 // Then print the decl itself.
3224 const ValueDecl *VD = DR->getDecl();
3225 OS << VD->getName();
3226 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3227 // This is a template variable, print the expanded template arguments.
3229 OS, IV->getTemplateArgs().asArray(), Policy,
3230 IV->getSpecializedTemplate()->getTemplateParameters());
3231 }
3232 return true;
3233 }
3234 return false;
3235 }
3236
3237private:
3238 const PrintingPolicy Policy;
3239};
3240
3241} // end anonymous namespace
3242
3243std::pair<Expr *, std::string>
3245 Cond = lookThroughRangesV3Condition(PP, Cond);
3246
3247 // Separate out all of the terms in a conjunction.
3249 collectConjunctionTerms(Cond, Terms);
3250
3251 // Determine which term failed.
3252 Expr *FailedCond = nullptr;
3253 for (Expr *Term : Terms) {
3254 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3255
3256 // Literals are uninteresting.
3257 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3258 isa<IntegerLiteral>(TermAsWritten))
3259 continue;
3260
3261 // The initialization of the parameter from the argument is
3262 // a constant-evaluated context.
3265
3266 bool Succeeded;
3267 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3268 !Succeeded) {
3269 FailedCond = TermAsWritten;
3270 break;
3271 }
3272 }
3273 if (!FailedCond)
3274 FailedCond = Cond->IgnoreParenImpCasts();
3275
3276 std::string Description;
3277 {
3278 llvm::raw_string_ostream Out(Description);
3280 Policy.PrintCanonicalTypes = true;
3281 FailedBooleanConditionPrinterHelper Helper(Policy);
3282 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3283 }
3284 return { FailedCond, Description };
3285}
3286
3288 SourceLocation TemplateLoc,
3289 TemplateArgumentListInfo &TemplateArgs) {
3291 = Name.getUnderlying().getAsDependentTemplateName();
3292 if (DTN && DTN->isIdentifier())
3293 // When building a template-id where the template-name is dependent,
3294 // assume the template is a type template. Either our assumption is
3295 // correct, or the code is ill-formed and will be diagnosed when the
3296 // dependent name is substituted.
3299 TemplateArgs.arguments());
3300
3301 if (Name.getAsAssumedTemplateName() &&
3302 resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
3303 return QualType();
3304
3305 TemplateDecl *Template = Name.getAsTemplateDecl();
3306 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3307 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3308 // We might have a substituted template template parameter pack. If so,
3309 // build a template specialization type for it.
3310 if (Name.getAsSubstTemplateTemplateParmPack())
3312 TemplateArgs.arguments());
3313
3314 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3315 << Name;
3317 return QualType();
3318 }
3319
3320 // Check that the template argument list is well-formed for this
3321 // template.
3322 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3323 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false,
3324 SugaredConverted, CanonicalConverted,
3325 /*UpdateArgsWithConversions=*/true))
3326 return QualType();
3327
3328 QualType CanonType;
3329
3331 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3332
3333 // Find the canonical type for this type alias template specialization.
3334 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3335 if (Pattern->isInvalidDecl())
3336 return QualType();
3337
3338 // Only substitute for the innermost template argument list. NOTE: Some
3339 // external resugarers rely on leaving a Subst* node here. Make the
3340 // substitution non-final in that case. Note that these external resugarers
3341 // will still miss some information in this representation, because we don't
3342 // provide enough context in the Subst* nodes in order to tell different
3343 // template type alias specializations apart.
3344 MultiLevelTemplateArgumentList TemplateArgLists;
3345 TemplateArgLists.addOuterTemplateArguments(
3346 Template, SugaredConverted,
3347 /*Final=*/!getLangOpts().RetainSubstTemplateTypeParmTypeAstNodes);
3348 TemplateArgLists.addOuterRetainedLevels(
3349 AliasTemplate->getTemplateParameters()->getDepth());
3350
3353 *this, /*PointOfInstantiation=*/TemplateLoc,
3354 /*Entity=*/AliasTemplate,
3355 /*TemplateArgs=*/TemplateArgLists.getInnermost());
3356
3357 // Diagnose uses of this alias.
3358 (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3359
3360 if (Inst.isInvalid())
3361 return QualType();
3362
3363 std::optional<ContextRAII> SavedContext;
3364 if (!AliasTemplate->getDeclContext()->isFileContext())
3365 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3366
3367 CanonType =
3368 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3369 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3370 if (CanonType.isNull()) {
3371 // If this was enable_if and we failed to find the nested type
3372 // within enable_if in a SFINAE context, dig out the specific
3373 // enable_if condition that failed and present that instead.
3375 if (auto DeductionInfo = isSFINAEContext()) {
3376 if (*DeductionInfo &&
3377 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3378 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3379 diag::err_typename_nested_not_found_enable_if &&
3380 TemplateArgs[0].getArgument().getKind()
3382 Expr *FailedCond;
3383 std::string FailedDescription;
3384 std::tie(FailedCond, FailedDescription) =
3385 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3386
3387 // Remove the old SFINAE diagnostic.
3388 PartialDiagnosticAt OldDiag =
3390 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3391
3392 // Add a new SFINAE diagnostic specifying which condition
3393 // failed.
3394 (*DeductionInfo)->addSFINAEDiagnostic(
3395 OldDiag.first,
3396 PDiag(diag::err_typename_nested_not_found_requirement)
3397 << FailedDescription
3398 << FailedCond->getSourceRange());
3399 }
3400 }
3401 }
3402
3403 return QualType();
3404 }
3405 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3406 CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
3407 TemplateLoc, TemplateArgs);
3408 } else if (Name.isDependent() ||
3410 TemplateArgs, CanonicalConverted)) {
3411 // This class template specialization is a dependent
3412 // type. Therefore, its canonical type is another class template
3413 // specialization type that contains all of the converted
3414 // arguments in canonical form. This ensures that, e.g., A<T> and
3415 // A<T, T> have identical types when A is declared as:
3416 //
3417 // template<typename T, typename U = T> struct A;
3419 Name, CanonicalConverted);
3420
3421 // This might work out to be a current instantiation, in which
3422 // case the canonical type needs to be the InjectedClassNameType.
3423 //
3424 // TODO: in theory this could be a simple hashtable lookup; most
3425 // changes to CurContext don't change the set of current
3426 // instantiations.
3427 if (isa<ClassTemplateDecl>(Template)) {
3428 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3429 // If we get out to a namespace, we're done.
3430 if (Ctx->isFileContext()) break;
3431
3432 // If this isn't a record, keep looking.
3433 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3434 if (!Record) continue;
3435
3436 // Look for one of the two cases with InjectedClassNameTypes
3437 // and check whether it's the same template.
3438 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3439 !Record->getDescribedClassTemplate())
3440 continue;
3441
3442 // Fetch the injected class name type and check whether its
3443 // injected type is equal to the type we just built.
3445 QualType Injected = cast<InjectedClassNameType>(ICNT)
3446 ->getInjectedSpecializationType();
3447
3448 if (CanonType != Injected->getCanonicalTypeInternal())
3449 continue;
3450
3451 // If so, the canonical type of this TST is the injected
3452 // class name type of the record we just found.
3453 assert(ICNT.isCanonical());
3454 CanonType = ICNT;
3455 break;
3456 }
3457 }
3458 } else if (ClassTemplateDecl *ClassTemplate =
3459 dyn_cast<ClassTemplateDecl>(Template)) {
3460 // Find the class template specialization declaration that
3461 // corresponds to these arguments.
3462 void *InsertPos = nullptr;
3464 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3465 if (!Decl) {
3466 // This is the first time we have referenced this class template
3467 // specialization. Create the canonical declaration and add it to
3468 // the set of specializations.
3470 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3471 ClassTemplate->getDeclContext(),
3472 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3473 ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
3474 nullptr);
3475 ClassTemplate->AddSpecialization(Decl, InsertPos);
3476 if (ClassTemplate->isOutOfLine())
3477 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3478 }
3479
3480 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3481 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3482 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3483 if (!Inst.isInvalid()) {
3484 MultiLevelTemplateArgumentList TemplateArgLists(Template,
3485 CanonicalConverted,
3486 /*Final=*/false);
3487 InstantiateAttrsForDecl(TemplateArgLists,
3488 ClassTemplate->getTemplatedDecl(), Decl);
3489 }
3490 }
3491
3492 // Diagnose uses of this specialization.
3493 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3494
3495 CanonType = Context.getTypeDeclType(Decl);
3496 assert(isa<RecordType>(CanonType) &&
3497 "type of non-dependent specialization is not a RecordType");
3498 } else {
3499 llvm_unreachable("Unhandled template kind");
3500 }
3501
3502 // Build the fully-sugared type for this class template
3503 // specialization, which refers back to the class template
3504 // specialization we created or found.
3505 return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
3506 CanonType);
3507}
3508
3510 TemplateNameKind &TNK,
3511 SourceLocation NameLoc,
3512 IdentifierInfo *&II) {
3513 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3514
3515 TemplateName Name = ParsedName.get();
3516 auto *ATN = Name.getAsAssumedTemplateName();
3517 assert(ATN && "not an assumed template name");
3518 II = ATN->getDeclName().getAsIdentifierInfo();
3519
3520 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3521 // Resolved to a type template name.
3522 ParsedName = TemplateTy::make(Name);
3523 TNK = TNK_Type_template;
3524 }
3525}
3526
3528 SourceLocation NameLoc,
3529 bool Diagnose) {
3530 // We assumed this undeclared identifier to be an (ADL-only) function
3531 // template name, but it was used in a context where a type was required.
3532 // Try to typo-correct it now.
3533 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3534 assert(ATN && "not an assumed template name");
3535
3536 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3537 struct CandidateCallback : CorrectionCandidateCallback {
3538 bool ValidateCandidate(const TypoCorrection &TC) override {
3539 return TC.getCorrectionDecl() &&
3541 }
3542 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3543 return std::make_unique<CandidateCallback>(*this);
3544 }
3545 } FilterCCC;
3546
3547 TypoCorrection Corrected =
3548 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3549 FilterCCC, CTK_ErrorRecovery);
3550 if (Corrected && Corrected.getFoundDecl()) {
3551 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3552 << ATN->getDeclName());
3553 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3554 return false;
3555 }
3556
3557 if (Diagnose)
3558 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3559 return true;
3560}
3561
3563 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3564 TemplateTy TemplateD, const IdentifierInfo *TemplateII,
3565 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3566 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3567 bool IsCtorOrDtorName, bool IsClassName,
3568 ImplicitTypenameContext AllowImplicitTypename) {
3569 if (SS.isInvalid())
3570 return true;
3571
3572 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3573 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3574
3575 // C++ [temp.res]p3:
3576 // A qualified-id that refers to a type and in which the
3577 // nested-name-specifier depends on a template-parameter (14.6.2)
3578 // shall be prefixed by the keyword typename to indicate that the
3579 // qualified-id denotes a type, forming an
3580 // elaborated-type-specifier (7.1.5.3).
3581 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3582 // C++2a relaxes some of those restrictions in [temp.res]p5.
3583 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
3585 Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
3586 else
3587 Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
3588 << SS.getScopeRep() << TemplateII->getName()
3589 << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
3590 } else
3591 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3592 << SS.getScopeRep() << TemplateII->getName();
3593
3594 // FIXME: This is not quite correct recovery as we don't transform SS
3595 // into the corresponding dependent form (and we don't diagnose missing
3596 // 'template' keywords within SS as a result).
3597 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3598 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3599 TemplateArgsIn, RAngleLoc);
3600 }
3601
3602 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3603 // it's not actually allowed to be used as a type in most cases. Because
3604 // we annotate it before we know whether it's valid, we have to check for
3605 // this case here.
3606 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3607 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3608 Diag(TemplateIILoc,
3609 TemplateKWLoc.isInvalid()
3610 ? diag::err_out_of_line_qualified_id_type_names_constructor
3611 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3612 << TemplateII << 0 /*injected-class-name used as template name*/
3613 << 1 /*if any keyword was present, it was 'template'*/;
3614 }
3615 }
3616
3617 TemplateName Template = TemplateD.get();
3618 if (Template.getAsAssumedTemplateName() &&
3619 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3620 return true;
3621
3622 // Translate the parser's template argument list in our AST format.
3623 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3624 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3625
3626 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3627 assert(SS.getScopeRep() == DTN->getQualifier());
3629 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
3630 TemplateArgs.arguments());
3631 // Build type-source information.
3632 TypeLocBuilder TLB;
3637 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3638 SpecTL.setTemplateNameLoc(TemplateIILoc);
3639 SpecTL.setLAngleLoc(LAngleLoc);
3640 SpecTL.setRAngleLoc(RAngleLoc);
3641 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3642 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3644 }
3645
3646 QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3647 if (SpecTy.isNull())
3648 return true;
3649
3650 // Build type-source information.
3651 TypeLocBuilder TLB;
3654 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3655 SpecTL.setTemplateNameLoc(TemplateIILoc);
3656 SpecTL.setLAngleLoc(LAngleLoc);
3657 SpecTL.setRAngleLoc(RAngleLoc);
3658 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3659 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3660
3661 // Create an elaborated-type-specifier containing the nested-name-specifier.
3662 QualType ElTy =
3664 !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
3665 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
3667 if (!ElabTL.isEmpty())
3669 return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
3670}
3671
3673 TypeSpecifierType TagSpec,
3674 SourceLocation TagLoc,
3675 CXXScopeSpec &SS,
3676 SourceLocation TemplateKWLoc,
3677 TemplateTy TemplateD,
3678 SourceLocation TemplateLoc,
3679 SourceLocation LAngleLoc,
3680 ASTTemplateArgsPtr TemplateArgsIn,
3681 SourceLocation RAngleLoc) {
3682 if (SS.isInvalid())
3683 return TypeResult(true);
3684
3685 TemplateName Template = TemplateD.get();
3686
3687 // Translate the parser's template argument list in our AST format.
3688 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3689 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3690
3691 // Determine the tag kind
3693 ElaboratedTypeKeyword Keyword
3695
3696 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3697 assert(SS.getScopeRep() == DTN->getQualifier());
3699 Keyword, DTN->getQualifier(), DTN->getIdentifier(),
3700 TemplateArgs.arguments());
3701
3702 // Build type-source information.
3703 TypeLocBuilder TLB;
3706 SpecTL.setElaboratedKeywordLoc(TagLoc);
3708 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3709 SpecTL.setTemplateNameLoc(TemplateLoc);
3710 SpecTL.setLAngleLoc(LAngleLoc);
3711 SpecTL.setRAngleLoc(RAngleLoc);
3712 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3713 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3715 }
3716
3717 if (TypeAliasTemplateDecl *TAT =
3718 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3719 // C++0x [dcl.type.elab]p2:
3720 // If the identifier resolves to a typedef-name or the simple-template-id
3721 // resolves to an alias template specialization, the
3722 // elaborated-type-specifier is ill-formed.
3723 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3724 << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
3725 Diag(TAT->getLocation(), diag::note_declared_at);
3726 }
3727
3728 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3729 if (Result.isNull())
3730 return TypeResult(true);
3731
3732 // Check the tag kind
3733 if (const RecordType *RT = Result->getAs<RecordType>()) {
3734 RecordDecl *D = RT->getDecl();
3735
3736 IdentifierInfo *Id = D->getIdentifier();
3737 assert(Id && "templated class must have an identifier");
3738
3740 TagLoc, Id)) {
3741 Diag(TagLoc, diag::err_use_with_wrong_tag)
3742 << Result
3743 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3744 Diag(D->getLocation(), diag::note_previous_use);
3745 }
3746 }
3747
3748 // Provide source-location information for the template specialization.
3749 TypeLocBuilder TLB;
3752 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3753 SpecTL.setTemplateNameLoc(TemplateLoc);
3754 SpecTL.setLAngleLoc(LAngleLoc);
3755 SpecTL.setRAngleLoc(RAngleLoc);
3756 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3757 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3758
3759 // Construct an elaborated type containing the nested-name-specifier (if any)
3760 // and tag keyword.
3763 ElabTL.setElaboratedKeywordLoc(TagLoc);
3766}
3767
3768static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3769 NamedDecl *PrevDecl,
3772
3774
3776 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3777 switch (Arg.getKind()) {
3785 return false;
3786
3788 QualType Type = Arg.getAsType();
3789 const TemplateTypeParmType *TPT =
3791 return TPT && !Type.hasQualifiers() &&
3792 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3793 }
3794
3796 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3797 if (!DRE || !DRE->getDecl())
3798 return false;
3799 const NonTypeTemplateParmDecl *NTTP =
3800 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3801 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3802 }
3803
3805 const TemplateTemplateParmDecl *TTP =
3806 dyn_cast_or_null<TemplateTemplateParmDecl>(
3808 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3809 }
3810 llvm_unreachable("unexpected kind of template argument");
3811}
3812
3815 if (Params->size() != Args.size())
3816 return false;
3817
3818 unsigned Depth = Params->getDepth();
3819
3820 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3821 TemplateArgument Arg = Args[I];
3822
3823 // If the parameter is a pack expansion, the argument must be a pack
3824 // whose only element is a pack expansion.
3825 if (Params->getParam(I)->isParameterPack()) {
3826 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3827 !Arg.pack_begin()->isPackExpansion())
3828 return false;
3829 Arg = Arg.pack_begin()->getPackExpansionPattern();
3830 }
3831
3832 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3833 return false;
3834 }
3835
3836 return true;
3837}
3838
3839template<typename PartialSpecDecl>
3840static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3841 if (Partial->getDeclContext()->isDependentContext())
3842 return;
3843
3844 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3845 // for non-substitution-failure issues?
3846 TemplateDeductionInfo Info(Partial->getLocation());
3847 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3848 return;
3849
3850 auto *Template = Partial->getSpecializedTemplate();
3851 S.Diag(Partial->getLocation(),
3852 diag::ext_partial_spec_not_more_specialized_than_primary)
3853 << isa<VarTemplateDecl>(Template);
3854
3855 if (Info.hasSFINAEDiagnostic()) {
3859 SmallString<128> SFINAEArgString;
3860 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3861 S.Diag(Diag.first,
3862 diag::note_partial_spec_not_more_specialized_than_primary)
3863 << SFINAEArgString;
3864 }
3865
3866 S.NoteTemplateLocation(*Template);
3867 SmallVector<const Expr *, 3> PartialAC, TemplateAC;
3868 Template->getAssociatedConstraints(TemplateAC);
3869 Partial->getAssociatedConstraints(PartialAC);
3870 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
3871 TemplateAC);
3872}
3873
3874static void
3876 const llvm::SmallBitVector &DeducibleParams) {
3877 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3878 if (!DeducibleParams[I]) {
3879 NamedDecl *Param = TemplateParams->getParam(I);
3880 if (Param->getDeclName())
3881 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3882 << Param->getDeclName();
3883 else
3884 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3885 << "(anonymous)";
3886 }
3887 }
3888}
3889
3890
3891template<typename PartialSpecDecl>
3893 PartialSpecDecl *Partial) {
3894 // C++1z [temp.class.spec]p8: (DR1495)
3895 // - The specialization shall be more specialized than the primary
3896 // template (14.5.5.2).
3898
3899 // C++ [temp.class.spec]p8: (DR1315)
3900 // - Each template-parameter shall appear at least once in the
3901 // template-id outside a non-deduced context.
3902 // C++1z [temp.class.spec.match]p3 (P0127R2)
3903 // If the template arguments of a partial specialization cannot be
3904 // deduced because of the structure of its template-parameter-list
3905 // and the template-id, the program is ill-formed.
3906 auto *TemplateParams = Partial->getTemplateParameters();
3907 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3908 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3909 TemplateParams->getDepth(), DeducibleParams);
3910
3911 if (!DeducibleParams.all()) {
3912 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3913 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3914 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3915 << (NumNonDeducible > 1)
3916 << SourceRange(Partial->getLocation(),
3917 Partial->getTemplateArgsAsWritten()->RAngleLoc);
3918 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3919 }
3920}
3921
3924 checkTemplatePartialSpecialization(*this, Partial);
3925}
3926
3929 checkTemplatePartialSpecialization(*this, Partial);
3930}
3931
3933 // C++1z [temp.param]p11:
3934 // A template parameter of a deduction guide template that does not have a
3935 // default-argument shall be deducible from the parameter-type-list of the
3936 // deduction guide template.
3937 auto *TemplateParams = TD->getTemplateParameters();
3938 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3939 MarkDeducedTemplateParameters(TD, DeducibleParams);
3940 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3941 // A parameter pack is deducible (to an empty pack).
3942 auto *Param = TemplateParams->getParam(I);
3943 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3944 DeducibleParams[I] = true;
3945 }
3946
3947 if (!DeducibleParams.all()) {
3948 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3949 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3950 << (NumNonDeducible > 1);
3951 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3952 }
3953}
3954
3957 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
3959 // D must be variable template id.
3960 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
3961 "Variable template specialization is declared with a template id.");
3962
3963 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3964 TemplateArgumentListInfo TemplateArgs =
3965 makeTemplateArgumentListInfo(*this, *TemplateId);
3966 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3967 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3968 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3969
3970 TemplateName Name = TemplateId->Template.get();
3971
3972 // The template-id must name a variable template.
3974 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3975 if (!VarTemplate) {
3976 NamedDecl *FnTemplate;
3977 if (auto *OTS = Name.getAsOverloadedTemplate())
3978 FnTemplate = *OTS->begin();
3979 else
3980 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3981 if (FnTemplate)
3982 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3983 << FnTemplate->getDeclName();
3984 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3986 }
3987
3988 // Check for unexpanded parameter packs in any of the template arguments.
3989 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3990 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3994 return true;
3995
3996 // Check that the template argument list is well-formed for this
3997 // template.
3998 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3999 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4000 false, SugaredConverted, CanonicalConverted,
4001 /*UpdateArgsWithConversions=*/true))
4002 return true;
4003
4004 // Find the variable template (partial) specialization declaration that
4005 // corresponds to these arguments.
4008 TemplateArgs.size(),
4009 CanonicalConverted))
4010 return true;
4011
4012 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4013 // also do them during instantiation.
4014 if (!Name.isDependent() &&
4016 TemplateArgs, CanonicalConverted)) {
4017 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4018 << VarTemplate->getDeclName();
4020 }
4021
4022 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4023 CanonicalConverted) &&
4024 (!Context.getLangOpts().CPlusPlus20 ||
4025 !TemplateParams->hasAssociatedConstraints())) {
4026 // C++ [temp.class.spec]p9b3:
4027 //
4028 // -- The argument list of the specialization shall not be identical
4029 // to the implicit argument list of the primary template.
4030 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4031 << /*variable template*/ 1
4032 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4033 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4034 // FIXME: Recover from this by treating the declaration as a redeclaration
4035 // of the primary template.
4036 return true;
4037 }
4038 }
4039
4040 void *InsertPos = nullptr;
4041 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4042
4044 PrevDecl = VarTemplate->findPartialSpecialization(
4045 CanonicalConverted, TemplateParams, InsertPos);
4046 else
4047 PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4048
4050
4051 // Check whether we can declare a variable template specialization in
4052 // the current scope.
4053 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4054 TemplateNameLoc,
4056 return true;
4057
4058 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4059 // Since the only prior variable template specialization with these
4060 // arguments was referenced but not declared, reuse that
4061 // declaration node as our own, updating its source location and
4062 // the list of outer template parameters to reflect our new declaration.
4063 Specialization = PrevDecl;
4064 Specialization->setLocation(TemplateNameLoc);
4065 PrevDecl = nullptr;
4066 } else if (IsPartialSpecialization) {
4067 // Create a new class template partial specialization declaration node.
4069 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4072 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4073 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4074 CanonicalConverted);
4075 Partial->setTemplateArgsAsWritten(TemplateArgs);
4076
4077 if (!PrevPartial)
4078 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4079 Specialization = Partial;
4080
4081 // If we are providing an explicit specialization of a member variable
4082 // template specialization, make a note of that.
4083 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4084 PrevPartial->setMemberSpecialization();
4085
4087 } else {
4088 // Create a new class template specialization declaration node for
4089 // this explicit specialization or friend declaration.
4091 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4092 VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
4093 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4094
4095 if (!PrevDecl)
4096 VarTemplate->AddSpecialization(Specialization, InsertPos);
4097 }
4098
4099 // C++ [temp.expl.spec]p6:
4100 // If a template, a member template or the member of a class template is
4101 // explicitly specialized then that specialization shall be declared
4102 // before the first use of that specialization that would cause an implicit
4103 // instantiation to take place, in every translation unit in which such a
4104 // use occurs; no diagnostic is required.
4105 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4106 bool Okay = false;
4107 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4108 // Is there any previous explicit specialization declaration?
4110 Okay = true;
4111 break;
4112 }
4113 }
4114
4115 if (!Okay) {
4116 SourceRange Range(TemplateNameLoc, RAngleLoc);
4117 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4118 << Name << Range;
4119
4120 Diag(PrevDecl->getPointOfInstantiation(),
4121 diag::note_instantiation_required_here)
4122 << (PrevDecl->getTemplateSpecializationKind() !=
4124 return true;
4125 }
4126 }
4127
4128 Specialization->setLexicalDeclContext(CurContext);
4129
4130 // Add the specialization into its lexical context, so that it can
4131 // be seen when iterating through the list of declarations in that
4132 // context. However, specializations are not found by name lookup.
4134
4135 // Note that this is an explicit specialization.
4136 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4137
4138 Previous.clear();
4139 if (PrevDecl)
4140 Previous.addDecl(PrevDecl);
4141 else if (Specialization->isStaticDataMember() &&
4142 Specialization->isOutOfLine())
4143 Specialization->setAccess(VarTemplate->getAccess());
4144
4145 return Specialization;
4146}
4147
4148namespace {
4149/// A partial specialization whose template arguments have matched
4150/// a given template-id.
4151struct PartialSpecMatchResult {
4154};
4155} // end anonymous namespace
4156
4159 SourceLocation TemplateNameLoc,
4160 const TemplateArgumentListInfo &TemplateArgs) {
4161 assert(Template && "A variable template id without template?");
4162
4163 // Check that the template argument list is well-formed for this template.
4164 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4166 Template, TemplateNameLoc,
4167 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4168 SugaredConverted, CanonicalConverted,
4169 /*UpdateArgsWithConversions=*/true))
4170 return true;
4171
4172 // Produce a placeholder value if the specialization is dependent.
4173 if (Template->getDeclContext()->isDependentContext() ||
4175 TemplateArgs, CanonicalConverted))
4176 return DeclResult();
4177
4178 // Find the variable template specialization declaration that
4179 // corresponds to these arguments.
4180 void *InsertPos = nullptr;
4182 Template->findSpecialization(CanonicalConverted, InsertPos)) {
4183 checkSpecializationReachability(TemplateNameLoc, Spec);
4184 // If we already have a variable template specialization, return it.
4185 return Spec;
4186 }
4187
4188 // This is the first time we have referenced this variable template
4189 // specialization. Create the canonical declaration and add it to
4190 // the set of specializations, based on the closest partial specialization
4191 // that it represents. That is,
4192 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4193 const TemplateArgumentList *PartialSpecArgs = nullptr;
4194 bool AmbiguousPartialSpec = false;
4195 typedef PartialSpecMatchResult MatchResult;
4197 SourceLocation PointOfInstantiation = TemplateNameLoc;
4198 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4199 /*ForTakingAddress=*/false);
4200
4201 // 1. Attempt to find the closest partial specialization that this
4202 // specializes, if any.
4203 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4204 // Perhaps better after unification of DeduceTemplateArguments() and
4205 // getMoreSpecializedPartialSpecialization().
4207 Template->getPartialSpecializations(PartialSpecs);
4208
4209 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4210 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4211 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4212
4214 DeduceTemplateArguments(Partial, SugaredConverted, Info);
4216 // Store the failed-deduction information for use in diagnostics, later.
4217 // TODO: Actually use the failed-deduction info?
4218 FailedCandidates.addCandidate().set(
4219 DeclAccessPair::make(Template, AS_public), Partial,
4221 (void)Result;
4222 } else {
4223 Matched.push_back(PartialSpecMatchResult());
4224 Matched.back().Partial = Partial;
4225 Matched.back().Args = Info.takeSugared();
4226 }
4227 }
4228
4229 if (Matched.size() >= 1) {
4230 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4231 if (Matched.size() == 1) {
4232 // -- If exactly one matching specialization is found, the
4233 // instantiation is generated from that specialization.
4234 // We don't need to do anything for this.
4235 } else {
4236 // -- If more than one matching specialization is found, the
4237 // partial order rules (14.5.4.2) are used to determine
4238 // whether one of the specializations is more specialized
4239 // than the others. If none of the specializations is more
4240 // specialized than all of the other matching
4241 // specializations, then the use of the variable template is
4242 // ambiguous and the program is ill-formed.
4244 PEnd = Matched.end();
4245 P != PEnd; ++P) {
4246 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4247 PointOfInstantiation) ==
4248 P->Partial)
4249 Best = P;
4250 }
4251
4252 // Determine if the best partial specialization is more specialized than
4253 // the others.
4254 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4255 PEnd = Matched.end();
4256 P != PEnd; ++P) {
4258 P->Partial, Best->Partial,
4259 PointOfInstantiation) != Best->Partial) {
4260 AmbiguousPartialSpec = true;
4261 break;
4262 }
4263 }
4264 }
4265
4266 // Instantiate using the best variable template partial specialization.
4267 InstantiationPattern = Best->Partial;
4268 PartialSpecArgs = Best->Args;
4269 } else {
4270 // -- If no match is found, the instantiation is generated
4271 // from the primary template.
4272 // InstantiationPattern = Template->getTemplatedDecl();
4273 }
4274
4275 // 2. Create the canonical declaration.
4276 // Note that we do not instantiate a definition until we see an odr-use
4277 // in DoMarkVarDeclReferenced().
4278 // FIXME: LateAttrs et al.?
4280 Template, InstantiationPattern, PartialSpecArgs, TemplateArgs,
4281 CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4282 if (!Decl)
4283 return true;
4284
4285 if (AmbiguousPartialSpec) {
4286 // Partial ordering did not produce a clear winner. Complain.
4288 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4289 << Decl;
4290
4291 // Print the matching partial specializations.
4292 for (MatchResult P : Matched)
4293 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4294 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4295 *P.Args);
4296 return true;
4297 }
4298
4300 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4301 Decl->setInstantiationOf(D, PartialSpecArgs);
4302
4303 checkSpecializationReachability(TemplateNameLoc, Decl);
4304
4305 assert(Decl && "No variable template specialization?");
4306 return Decl;
4307}
4308
4310 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4311 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4312 const TemplateArgumentListInfo *TemplateArgs) {
4313
4314 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4315 *TemplateArgs);
4316 if (Decl.isInvalid())
4317 return ExprError();
4318
4319 if (!Decl.get())
4320 return ExprResult();
4321
4322 VarDecl *Var = cast<VarDecl>(Decl.get());
4325 NameInfo.getLoc());
4326
4327 // Build an ordinary singleton decl ref.
4328 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4329}
4330
4333 Diag(Loc, diag::err_template_missing_args)
4334 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4335 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4336 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4337 }
4338}
4339
4341 bool TemplateKeyword,
4342 TemplateDecl *TD,
4345 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4347}
4348
4351 SourceLocation TemplateKWLoc,
4352 const DeclarationNameInfo &ConceptNameInfo,
4353 NamedDecl *FoundDecl,
4354 ConceptDecl *NamedConcept,
4355 const TemplateArgumentListInfo *TemplateArgs) {
4356 assert(NamedConcept && "A concept template id without a template?");
4357
4358 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4360 NamedConcept, ConceptNameInfo.getLoc(),
4361 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4362 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
4363 /*UpdateArgsWithConversions=*/false))
4364 return ExprError();
4365
4366 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4367
4369 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4370 CanonicalConverted);
4371 ConstraintSatisfaction Satisfaction;
4372 bool AreArgsDependent =
4374 *TemplateArgs, CanonicalConverted);
4375 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
4376 /*Final=*/false);
4378
4381
4382 if (!AreArgsDependent &&
4384 NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
4385 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4386 TemplateArgs->getRAngleLoc()),
4387 Satisfaction))
4388 return ExprError();
4389 auto *CL = ConceptReference::Create(
4390 Context,
4392 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4395 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4396}
4397
4399 SourceLocation TemplateKWLoc,
4400 LookupResult &R,
4401 bool RequiresADL,
4402 const TemplateArgumentListInfo *TemplateArgs) {
4403 // FIXME: Can we do any checking at this point? I guess we could check the
4404 // template arguments that we have against the template name, if the template
4405 // name refers to a single template. That's not a terribly common case,
4406 // though.
4407 // foo<int> could identify a single function unambiguously
4408 // This approach does NOT work, since f<int>(1);
4409 // gets resolved prior to resorting to overload resolution
4410 // i.e., template<class T> void f(double);
4411 // vs template<class T, class U> void f(U);
4412
4413 // These should be filtered out by our callers.
4414 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4415
4416 // Non-function templates require a template argument list.
4417 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4418 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4420 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4421 return ExprError();
4422 }
4423 }
4424 bool KnownDependent = false;
4425 // In C++1y, check variable template ids.
4426 if (R.getAsSingle<VarTemplateDecl>()) {
4429 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4430 if (Res.isInvalid() || Res.isUsable())
4431 return Res;
4432 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4433 KnownDependent = true;
4434 }
4435
4436 if (R.getAsSingle<ConceptDecl>()) {
4437 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4439 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4440 }
4441
4442 // We don't want lookup warnings at this point.
4444
4447 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4448 R.begin(), R.end(), KnownDependent,
4449 /*KnownInstantiationDependent=*/false);
4450
4451 // Model the templates with UnresolvedTemplateTy. The expression should then
4452 // either be transformed in an instantiation or be diagnosed in
4453 // CheckPlaceholderExpr.
4454 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4457
4458 return ULE;
4459}
4460
4462 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4463 const DeclarationNameInfo &NameInfo,
4464 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4465 assert(TemplateArgs || TemplateKWLoc.isValid());
4466
4467 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4468 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
4469 /*EnteringContext=*/false, TemplateKWLoc))
4470 return ExprError();
4471
4472 if (R.isAmbiguous())
4473 return ExprError();
4474
4476 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4477
4478 if (R.empty()) {
4480 Diag(NameInfo.getLoc(), diag::err_no_member)
4481 << NameInfo.getName() << DC << SS.getRange();
4482 return ExprError();
4483 }
4484
4485 // If necessary, build an implicit class member access.
4486 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
4487 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
4488 /*S=*/nullptr);
4489
4490 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
4491}
4492
4494 CXXScopeSpec &SS,
4495 SourceLocation TemplateKWLoc,
4496 const UnqualifiedId &Name,
4497 ParsedType ObjectType,
4498 bool EnteringContext,
4500 bool AllowInjectedClassName) {
4501 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4502 Diag(TemplateKWLoc,
4504 diag::warn_cxx98_compat_template_outside_of_template :
4505 diag::ext_template_outside_of_template)
4506 << FixItHint::CreateRemoval(TemplateKWLoc);
4507
4508 if (SS.isInvalid())
4509 return TNK_Non_template;
4510
4511 // Figure out where isTemplateName is going to look.
4512 DeclContext *LookupCtx = nullptr;
4513 if (SS.isNotEmpty())
4514 LookupCtx = computeDeclContext(SS, EnteringContext);
4515 else if (ObjectType)
4516 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
4517
4518 // C++0x [temp.names]p5:
4519 // If a name prefixed by the keyword template is not the name of
4520 // a template, the program is ill-formed. [Note: the keyword
4521 // template may not be applied to non-template members of class
4522 // templates. -end note ] [ Note: as is the case with the
4523 // typename prefix, the template prefix is allowed in cases
4524 // where it is not strictly necessary; i.e., when the
4525 // nested-name-specifier or the expression on the left of the ->
4526 // or . is not dependent on a template-parameter, or the use
4527 // does not appear in the scope of a template. -end note]
4528 //
4529 // Note: C++03 was more strict here, because it banned the use of
4530 // the "template" keyword prior to a template-name that was not a
4531 // dependent name. C++ DR468 relaxed this requirement (the
4532 // "template" keyword is now permitted). We follow the C++0x
4533 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4534 bool MemberOfUnknownSpecialization;
4535 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4536 ObjectType, EnteringContext, Result,
4537 MemberOfUnknownSpecialization);
4538 if (TNK != TNK_Non_template) {
4539 // We resolved this to a (non-dependent) template name. Return it.
4540 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4541 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
4542 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4543 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4544 // C++14 [class.qual]p2:
4545 // In a lookup in which function names are not ignored and the
4546 // nested-name-specifier nominates a class C, if the name specified
4547 // [...] is the injected-class-name of C, [...] the name is instead
4548 // considered to name the constructor
4549 //
4550 // We don't get here if naming the constructor would be valid, so we
4551 // just reject immediately and recover by treating the
4552 // injected-class-name as naming the template.
4553 Diag(Name.getBeginLoc(),
4554 diag::ext_out_of_line_qualified_id_type_names_constructor)
4555 << Name.Identifier
4556 << 0 /*injected-class-name used as template name*/
4557 << TemplateKWLoc.isValid();
4558 }
4559 return TNK;
4560 }
4561
4562 if (!MemberOfUnknownSpecialization) {
4563 // Didn't find a template name, and the lookup wasn't dependent.
4564 // Do the lookup again to determine if this is a "nothing found" case or
4565 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4566 // need to do this.
4568 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4570 // Tell LookupTemplateName that we require a template so that it diagnoses
4571 // cases where it finds a non-template.
4572 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
4573 ? RequiredTemplateKind(TemplateKWLoc)
4575 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
4576 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
4577 !R.isAmbiguous()) {
4578 if (LookupCtx)
4579 Diag(Name.getBeginLoc(), diag::err_no_member)
4580 << DNI.getName() << LookupCtx << SS.getRange();
4581 else
4582 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
4583 << DNI.getName() << SS.getRange();
4584 }
4585 return TNK_Non_template;
4586 }
4587
4588 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4589
4590 switch (Name.getKind()) {
4593 Context.getDependentTemplateName(Qualifier, Name.Identifier));
4595
4598 Qualifier, Name.OperatorFunctionId.Operator));
4599 return TNK_Function_template;
4600
4602 // This is a kind of template name, but can never occur in a dependent
4603 // scope (literal operators can only be declared at namespace scope).
4604 break;
4605
4606 default:
4607 break;
4608 }
4609
4610 // This name cannot possibly name a dependent template. Diagnose this now
4611 // rather than building a dependent template name that can never be valid.
4612 Diag(Name.getBeginLoc(),
4613 diag::err_template_kw_refers_to_dependent_non_template)
4614 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4615 << TemplateKWLoc.isValid() << TemplateKWLoc;
4616 return TNK_Non_template;
4617}
4618
4621 SmallVectorImpl<TemplateArgument> &SugaredConverted,
4622 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
4623 const TemplateArgument &Arg = AL.getArgument();
4624 QualType ArgType;
4625 TypeSourceInfo *TSI = nullptr;
4626
4627 // Check template type parameter.
4628 switch(Arg.getKind()) {
4630 // C++ [temp.arg.type]p1:
4631 // A template-argument for a template-parameter which is a
4632 // type shall be a type-id.
4633 ArgType = Arg.getAsType();
4634 TSI = AL.getTypeSourceInfo();
4635 break;
4638 // We have a template type parameter but the template argument
4639 // is a template without any arguments.
4640 SourceRange SR = AL.getSourceRange();
4643 return true;
4644 }
4646 // We have a template type parameter but the template argument is an
4647 // expression; see if maybe it is missing the "typename" keyword.
4648 CXXScopeSpec SS;
4649 DeclarationNameInfo NameInfo;
4650
4651 if (DependentScopeDeclRefExpr *ArgExpr =
4652 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4653 SS.Adopt(ArgExpr->getQualifierLoc());
4654 NameInfo = ArgExpr->getNameInfo();
4655 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4656 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4657 if (ArgExpr->isImplicitAccess()) {
4658 SS.Adopt(ArgExpr->getQualifierLoc());
4659 NameInfo = ArgExpr->getMemberNameInfo();
4660 }
4661 }
4662
4663 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4664 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4665 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
4666
4667 if (Result.getAsSingle<TypeDecl>() ||
4668 Result.wasNotFoundInCurrentInstantiation()) {
4669 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
4670 // Suggest that the user add 'typename' before the NNS.
4672 Diag(Loc, getLangOpts().MSVCCompat
4673 ? diag::ext_ms_template_type_arg_missing_typename
4674 : diag::err_template_arg_must_be_type_suggest)
4675 << FixItHint::CreateInsertion(Loc, "typename ");
4677
4678 // Recover by synthesizing a type using the location information that we
4679 // already have.
4681 SS.getScopeRep(), II);
4682 TypeLocBuilder TLB;
4684 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4686 TL.setNameLoc(NameInfo.getLoc());
4687 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4688
4689 // Overwrite our input TemplateArgumentLoc so that we can recover
4690 // properly.
4693
4694 break;
4695 }
4696 }
4697 // fallthrough
4698 [[fallthrough]];
4699 }
4700 default: {
4701 // We allow instantiateing a template with template argument packs when
4702 // building deduction guides.
4703 if (Arg.getKind() == TemplateArgument::Pack &&
4704 CodeSynthesisContexts.back().Kind ==
4706 SugaredConverted.push_back(Arg);
4707 CanonicalConverted.push_back(Arg);
4708 return false;
4709 }
4710 // We have a template type parameter but the template argument
4711 // is not a type.
4712 SourceRange SR = AL.getSourceRange();
4713 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4715
4716 return true;
4717 }
4718 }
4719
4720 if (CheckTemplateArgument(TSI))
4721 return true;
4722
4723 // Objective-C ARC:
4724 // If an explicitly-specified template argument type is a lifetime type
4725 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4726 if (getLangOpts().ObjCAutoRefCount &&
4727 ArgType->isObjCLifetimeType() &&
4728 !ArgType.getObjCLifetime()) {
4729 Qualifiers Qs;
4731 ArgType = Context.getQualifiedType(ArgType, Qs);
4732 }
4733
4734 SugaredConverted.push_back(TemplateArgument(ArgType));
4735 CanonicalConverted.push_back(
4737 return false;
4738}
4739
4740/// Substitute template arguments into the default template argument for
4741/// the given template type parameter.
4742///
4743/// \param SemaRef the semantic analysis object for which we are performing
4744/// the substitution.
4745///
4746/// \param Template the template that we are synthesizing template arguments
4747/// for.
4748///
4749/// \param TemplateLoc the location of the template name that started the
4750/// template-id we are checking.
4751///
4752/// \param RAngleLoc the location of the right angle bracket ('>') that
4753/// terminates the template-id.
4754///
4755/// \param Param the template template parameter whose default we are
4756/// substituting into.
4757///
4758/// \param Converted the list of template arguments provided for template
4759/// parameters that precede \p Param in the template parameter list.
4760///
4761/// \param Output the resulting substituted template argument.
4762///
4763/// \returns true if an error occurred.
4765 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4766 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
4767 ArrayRef<TemplateArgument> SugaredConverted,
4768 ArrayRef<TemplateArgument> CanonicalConverted,
4769 TemplateArgumentLoc &Output) {
4770 Output = Param->getDefaultArgument();
4771
4772 // If the argument type is dependent, instantiate it now based
4773 // on the previously-computed template arguments.
4774 if (Output.getArgument().isInstantiationDependent()) {
4775 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
4776 SugaredConverted,
4777 SourceRange(TemplateLoc, RAngleLoc));
4778 if (Inst.isInvalid())
4779 return true;
4780
4781 // Only substitute for the innermost template argument list.
4782 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4783 /*Final=*/true);
4784 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4785 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4786
4787 bool ForLambdaCallOperator = false;
4788 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
4789 ForLambdaCallOperator = Rec->isLambda();
4790 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
4791 !ForLambdaCallOperator);
4792
4793 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
4794 Param->getDefaultArgumentLoc(),
4795 Param->getDeclName()))
4796 return true;
4797 }
4798
4799 return false;
4800}
4801
4802/// Substitute template arguments into the default template argument for
4803/// the given non-type template parameter.
4804///
4805/// \param SemaRef the semantic analysis object for which we are performing
4806/// the substitution.
4807///
4808/// \param Template the template that we are synthesizing template arguments
4809/// for.
4810///
4811/// \param TemplateLoc the location of the template name that started the
4812/// template-id we are checking.
4813///
4814/// \param RAngleLoc the location of the right angle bracket ('>') that
4815/// terminates the template-id.
4816///
4817/// \param Param the non-type template parameter whose default we are
4818/// substituting into.
4819///
4820/// \param Converted the list of template arguments provided for template
4821/// parameters that precede \p Param in the template parameter list.
4822///
4823/// \returns the substituted template argument, or NULL if an error occurred.
4825 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4826 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
4827 ArrayRef<TemplateArgument> SugaredConverted,
4828 ArrayRef<TemplateArgument> CanonicalConverted,
4829 TemplateArgumentLoc &Output) {
4830 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
4831 SugaredConverted,
4832 SourceRange(TemplateLoc, RAngleLoc));
4833 if (Inst.isInvalid())
4834 return true;
4835
4836 // Only substitute for the innermost template argument list.
4837 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4838 /*Final=*/true);
4839 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4840 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4841
4842 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4843 EnterExpressionEvaluationContext ConstantEvaluated(
4845 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
4846 TemplateArgLists, Output);
4847}
4848
4849/// Substitute template arguments into the default template argument for
4850/// the given template template parameter.
4851///
4852/// \param SemaRef the semantic analysis object for which we are performing
4853/// the substitution.
4854///
4855/// \param Template the template that we are synthesizing template arguments
4856/// for.
4857///
4858/// \param TemplateLoc the location of the template name that started the
4859/// template-id we are checking.
4860///
4861/// \param RAngleLoc the location of the right angle bracket ('>') that
4862/// terminates the template-id.
4863///
4864/// \param Param the template template parameter whose default we are
4865/// substituting into.
4866///
4867/// \param Converted the list of template arguments provided for template
4868/// parameters that precede \p Param in the template parameter list.
4869///
4870/// \param QualifierLoc Will be set to the nested-name-specifier (with
4871/// source-location information) that precedes the template name.
4872///
4873/// \returns the substituted template argument, or NULL if an error occurred.
4875 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4876 SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
4877 ArrayRef<TemplateArgument> SugaredConverted,
4878 ArrayRef<TemplateArgument> CanonicalConverted,
4879 NestedNameSpecifierLoc &QualifierLoc) {
4881 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
4882 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
4883 if (Inst.isInvalid())
4884 return TemplateName();
4885
4886 // Only substitute for the innermost template argument list.
4887 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4888 /*Final=*/true);
4889 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4890 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4891
4892 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4893 // Substitute into the nested-name-specifier first,
4894 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4895 if (QualifierLoc) {
4896 QualifierLoc =
4897 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4898 if (!QualifierLoc)
4899 return TemplateName();
4900 }
4901
4902 return SemaRef.SubstTemplateName(
4903 QualifierLoc,
4906 TemplateArgLists);
4907}
4908
4910 TemplateDecl *Template, SourceLocation TemplateLoc,
4911 SourceLocation RAngleLoc, Decl *Param,
4912 ArrayRef<TemplateArgument> SugaredConverted,
4913 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
4914 HasDefaultArg = false;
4915
4916 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4917 if (!hasReachableDefaultArgument(TypeParm))
4918 return TemplateArgumentLoc();
4919
4920 HasDefaultArg = true;
4921 TemplateArgumentLoc Output;
4922 if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
4923 TypeParm, SugaredConverted,
4924 CanonicalConverted, Output))
4925 return TemplateArgumentLoc();
4926 return Output;
4927 }
4928
4929 if (NonTypeTemplateParmDecl *NonTypeParm
4930 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4931 if (!hasReachableDefaultArgument(NonTypeParm))
4932 return TemplateArgumentLoc();
4933
4934 HasDefaultArg = true;
4935 TemplateArgumentLoc Output;
4936 if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
4937 NonTypeParm, SugaredConverted,
4938 CanonicalConverted, Output))
4939 return TemplateArgumentLoc();
4940 return Output;
4941 }
4942
4943 TemplateTemplateParmDecl *TempTempParm
4944 = cast<TemplateTemplateParmDecl>(Param);
4945 if (!hasReachableDefaultArgument(TempTempParm))
4946 return TemplateArgumentLoc();
4947
4948 HasDefaultArg = true;
4949 NestedNameSpecifierLoc QualifierLoc;
4951 *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
4952 CanonicalConverted, QualifierLoc);
4953 if (TName.isNull())
4954 return TemplateArgumentLoc();
4955
4956 return TemplateArgumentLoc(
4957 Context, TemplateArgument(TName),
4959 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4960}
4961
4962/// Convert a template-argument that we parsed as a type into a template, if
4963/// possible. C++ permits injected-class-names to perform dual service as
4964/// template template arguments and as template type arguments.