[libc][docgen] simplify posix links (#119595)
[llvm-project.git] / clang / lib / Sema / SemaTemplate.cpp
blob5e7a3c8484c88f54515005800b53832263537834
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 //===----------------------------------------------------------------------===//
11 #include "TreeTransform.h"
12 #include "clang/AST/ASTConsumer.h"
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclFriend.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/DynamicRecursiveASTVisitor.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/TemplateName.h"
21 #include "clang/AST/TypeVisitor.h"
22 #include "clang/Basic/Builtins.h"
23 #include "clang/Basic/DiagnosticSema.h"
24 #include "clang/Basic/LangOptions.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/SourceLocation.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/EnterExpressionEvaluationContext.h"
30 #include "clang/Sema/Initialization.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Overload.h"
33 #include "clang/Sema/ParsedTemplate.h"
34 #include "clang/Sema/Scope.h"
35 #include "clang/Sema/SemaCUDA.h"
36 #include "clang/Sema/SemaInternal.h"
37 #include "clang/Sema/Template.h"
38 #include "clang/Sema/TemplateDeduction.h"
39 #include "llvm/ADT/SmallBitVector.h"
40 #include "llvm/ADT/StringExtras.h"
42 #include <optional>
43 using namespace clang;
44 using namespace sema;
46 // Exported for use by Parser.
47 SourceRange
48 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
49 unsigned N) {
50 if (!N) return SourceRange();
51 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
54 unsigned Sema::getTemplateDepth(Scope *S) const {
55 unsigned Depth = 0;
57 // Each template parameter scope represents one level of template parameter
58 // depth.
59 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
60 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
61 ++Depth;
64 // Note that there are template parameters with the given depth.
65 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
67 // Look for parameters of an enclosing generic lambda. We don't create a
68 // template parameter scope for these.
69 for (FunctionScopeInfo *FSI : getFunctionScopes()) {
70 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
71 if (!LSI->TemplateParams.empty()) {
72 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
73 break;
75 if (LSI->GLTemplateParameterList) {
76 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
77 break;
82 // Look for parameters of an enclosing terse function template. We don't
83 // create a template parameter scope for these either.
84 for (const InventedTemplateParameterInfo &Info :
85 getInventedParameterInfos()) {
86 if (!Info.TemplateParams.empty()) {
87 ParamsAtDepth(Info.AutoTemplateParameterDepth);
88 break;
92 return Depth;
95 /// \brief Determine whether the declaration found is acceptable as the name
96 /// of a template and, if so, return that template declaration. Otherwise,
97 /// returns null.
98 ///
99 /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
100 /// is true. In all other cases it will return a TemplateDecl (or null).
101 NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
102 bool AllowFunctionTemplates,
103 bool AllowDependent) {
104 D = D->getUnderlyingDecl();
106 if (isa<TemplateDecl>(D)) {
107 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
108 return nullptr;
110 return D;
113 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
114 // C++ [temp.local]p1:
115 // Like normal (non-template) classes, class templates have an
116 // injected-class-name (Clause 9). The injected-class-name
117 // can be used with or without a template-argument-list. When
118 // it is used without a template-argument-list, it is
119 // equivalent to the injected-class-name followed by the
120 // template-parameters of the class template enclosed in
121 // <>. When it is used with a template-argument-list, it
122 // refers to the specified class template specialization,
123 // which could be the current specialization or another
124 // specialization.
125 if (Record->isInjectedClassName()) {
126 Record = cast<CXXRecordDecl>(Record->getDeclContext());
127 if (Record->getDescribedClassTemplate())
128 return Record->getDescribedClassTemplate();
130 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
131 return Spec->getSpecializedTemplate();
134 return nullptr;
137 // 'using Dependent::foo;' can resolve to a template name.
138 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
139 // injected-class-name).
140 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
141 return D;
143 return nullptr;
146 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
147 bool AllowFunctionTemplates,
148 bool AllowDependent) {
149 LookupResult::Filter filter = R.makeFilter();
150 while (filter.hasNext()) {
151 NamedDecl *Orig = filter.next();
152 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
153 filter.erase();
155 filter.done();
158 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
159 bool AllowFunctionTemplates,
160 bool AllowDependent,
161 bool AllowNonTemplateFunctions) {
162 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
163 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
164 return true;
165 if (AllowNonTemplateFunctions &&
166 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
167 return true;
170 return false;
173 TemplateNameKind Sema::isTemplateName(Scope *S,
174 CXXScopeSpec &SS,
175 bool hasTemplateKeyword,
176 const UnqualifiedId &Name,
177 ParsedType ObjectTypePtr,
178 bool EnteringContext,
179 TemplateTy &TemplateResult,
180 bool &MemberOfUnknownSpecialization,
181 bool Disambiguation) {
182 assert(getLangOpts().CPlusPlus && "No template names in C!");
184 DeclarationName TName;
185 MemberOfUnknownSpecialization = false;
187 switch (Name.getKind()) {
188 case UnqualifiedIdKind::IK_Identifier:
189 TName = DeclarationName(Name.Identifier);
190 break;
192 case UnqualifiedIdKind::IK_OperatorFunctionId:
193 TName = Context.DeclarationNames.getCXXOperatorName(
194 Name.OperatorFunctionId.Operator);
195 break;
197 case UnqualifiedIdKind::IK_LiteralOperatorId:
198 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
199 break;
201 default:
202 return TNK_Non_template;
205 QualType ObjectType = ObjectTypePtr.get();
207 AssumedTemplateKind AssumedTemplate;
208 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
209 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
210 /*RequiredTemplate=*/SourceLocation(),
211 &AssumedTemplate,
212 /*AllowTypoCorrection=*/!Disambiguation))
213 return TNK_Non_template;
214 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
216 if (AssumedTemplate != AssumedTemplateKind::None) {
217 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
218 // Let the parser know whether we found nothing or found functions; if we
219 // found nothing, we want to more carefully check whether this is actually
220 // a function template name versus some other kind of undeclared identifier.
221 return AssumedTemplate == AssumedTemplateKind::FoundNothing
222 ? TNK_Undeclared_template
223 : TNK_Function_template;
226 if (R.empty())
227 return TNK_Non_template;
229 NamedDecl *D = nullptr;
230 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
231 if (R.isAmbiguous()) {
232 // If we got an ambiguity involving a non-function template, treat this
233 // as a template name, and pick an arbitrary template for error recovery.
234 bool AnyFunctionTemplates = false;
235 for (NamedDecl *FoundD : R) {
236 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
237 if (isa<FunctionTemplateDecl>(FoundTemplate))
238 AnyFunctionTemplates = true;
239 else {
240 D = FoundTemplate;
241 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
242 break;
247 // If we didn't find any templates at all, this isn't a template name.
248 // Leave the ambiguity for a later lookup to diagnose.
249 if (!D && !AnyFunctionTemplates) {
250 R.suppressDiagnostics();
251 return TNK_Non_template;
254 // If the only templates were function templates, filter out the rest.
255 // We'll diagnose the ambiguity later.
256 if (!D)
257 FilterAcceptableTemplateNames(R);
260 // At this point, we have either picked a single template name declaration D
261 // or we have a non-empty set of results R containing either one template name
262 // declaration or a set of function templates.
264 TemplateName Template;
265 TemplateNameKind TemplateKind;
267 unsigned ResultCount = R.end() - R.begin();
268 if (!D && ResultCount > 1) {
269 // We assume that we'll preserve the qualifier from a function
270 // template name in other ways.
271 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
272 TemplateKind = TNK_Function_template;
274 // We'll do this lookup again later.
275 R.suppressDiagnostics();
276 } else {
277 if (!D) {
278 D = getAsTemplateNameDecl(*R.begin());
279 assert(D && "unambiguous result is not a template name");
282 if (isa<UnresolvedUsingValueDecl>(D)) {
283 // We don't yet know whether this is a template-name or not.
284 MemberOfUnknownSpecialization = true;
285 return TNK_Non_template;
288 TemplateDecl *TD = cast<TemplateDecl>(D);
289 Template =
290 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
291 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
292 if (!SS.isInvalid()) {
293 NestedNameSpecifier *Qualifier = SS.getScopeRep();
294 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
295 Template);
298 if (isa<FunctionTemplateDecl>(TD)) {
299 TemplateKind = TNK_Function_template;
301 // We'll do this lookup again later.
302 R.suppressDiagnostics();
303 } else {
304 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
305 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
306 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
307 TemplateKind =
308 isa<VarTemplateDecl>(TD) ? TNK_Var_template :
309 isa<ConceptDecl>(TD) ? TNK_Concept_template :
310 TNK_Type_template;
314 TemplateResult = TemplateTy::make(Template);
315 return TemplateKind;
318 bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
319 SourceLocation NameLoc, CXXScopeSpec &SS,
320 ParsedTemplateTy *Template /*=nullptr*/) {
321 // We could use redeclaration lookup here, but we don't need to: the
322 // syntactic form of a deduction guide is enough to identify it even
323 // if we can't look up the template name at all.
324 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
325 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
326 /*EnteringContext*/ false))
327 return false;
329 if (R.empty()) return false;
330 if (R.isAmbiguous()) {
331 // FIXME: Diagnose an ambiguity if we find at least one template.
332 R.suppressDiagnostics();
333 return false;
336 // We only treat template-names that name type templates as valid deduction
337 // guide names.
338 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
339 if (!TD || !getAsTypeTemplateDecl(TD))
340 return false;
342 if (Template) {
343 TemplateName Name = Context.getQualifiedTemplateName(
344 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));
345 *Template = TemplateTy::make(Name);
347 return true;
350 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
351 SourceLocation IILoc,
352 Scope *S,
353 const CXXScopeSpec *SS,
354 TemplateTy &SuggestedTemplate,
355 TemplateNameKind &SuggestedKind) {
356 // We can't recover unless there's a dependent scope specifier preceding the
357 // template name.
358 // FIXME: Typo correction?
359 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
360 computeDeclContext(*SS))
361 return false;
363 // The code is missing a 'template' keyword prior to the dependent template
364 // name.
365 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
366 Diag(IILoc, diag::err_template_kw_missing)
367 << Qualifier << II.getName()
368 << FixItHint::CreateInsertion(IILoc, "template ");
369 SuggestedTemplate
370 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
371 SuggestedKind = TNK_Dependent_template_name;
372 return true;
375 bool Sema::LookupTemplateName(LookupResult &Found, Scope *S, CXXScopeSpec &SS,
376 QualType ObjectType, bool EnteringContext,
377 RequiredTemplateKind RequiredTemplate,
378 AssumedTemplateKind *ATK,
379 bool AllowTypoCorrection) {
380 if (ATK)
381 *ATK = AssumedTemplateKind::None;
383 if (SS.isInvalid())
384 return true;
386 Found.setTemplateNameLookup(true);
388 // Determine where to perform name lookup
389 DeclContext *LookupCtx = nullptr;
390 bool IsDependent = false;
391 if (!ObjectType.isNull()) {
392 // This nested-name-specifier occurs in a member access expression, e.g.,
393 // x->B::f, and we are looking into the type of the object.
394 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
395 LookupCtx = computeDeclContext(ObjectType);
396 IsDependent = !LookupCtx && ObjectType->isDependentType();
397 assert((IsDependent || !ObjectType->isIncompleteType() ||
398 !ObjectType->getAs<TagType>() ||
399 ObjectType->castAs<TagType>()->isBeingDefined()) &&
400 "Caller should have completed object type");
402 // Template names cannot appear inside an Objective-C class or object type
403 // or a vector type.
405 // FIXME: This is wrong. For example:
407 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
408 // Vec<int> vi;
409 // vi.Vec<int>::~Vec<int>();
411 // ... should be accepted but we will not treat 'Vec' as a template name
412 // here. The right thing to do would be to check if the name is a valid
413 // vector component name, and look up a template name if not. And similarly
414 // for lookups into Objective-C class and object types, where the same
415 // problem can arise.
416 if (ObjectType->isObjCObjectOrInterfaceType() ||
417 ObjectType->isVectorType()) {
418 Found.clear();
419 return false;
421 } else if (SS.isNotEmpty()) {
422 // This nested-name-specifier occurs after another nested-name-specifier,
423 // so long into the context associated with the prior nested-name-specifier.
424 LookupCtx = computeDeclContext(SS, EnteringContext);
425 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
427 // The declaration context must be complete.
428 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
429 return true;
432 bool ObjectTypeSearchedInScope = false;
433 bool AllowFunctionTemplatesInLookup = true;
434 if (LookupCtx) {
435 // Perform "qualified" name lookup into the declaration context we
436 // computed, which is either the type of the base of a member access
437 // expression or the declaration context associated with a prior
438 // nested-name-specifier.
439 LookupQualifiedName(Found, LookupCtx);
441 // FIXME: The C++ standard does not clearly specify what happens in the
442 // case where the object type is dependent, and implementations vary. In
443 // Clang, we treat a name after a . or -> as a template-name if lookup
444 // finds a non-dependent member or member of the current instantiation that
445 // is a type template, or finds no such members and lookup in the context
446 // of the postfix-expression finds a type template. In the latter case, the
447 // name is nonetheless dependent, and we may resolve it to a member of an
448 // unknown specialization when we come to instantiate the template.
449 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
452 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
453 // C++ [basic.lookup.classref]p1:
454 // In a class member access expression (5.2.5), if the . or -> token is
455 // immediately followed by an identifier followed by a <, the
456 // identifier must be looked up to determine whether the < is the
457 // beginning of a template argument list (14.2) or a less-than operator.
458 // The identifier is first looked up in the class of the object
459 // expression. If the identifier is not found, it is then looked up in
460 // the context of the entire postfix-expression and shall name a class
461 // template.
462 if (S)
463 LookupName(Found, S);
465 if (!ObjectType.isNull()) {
466 // FIXME: We should filter out all non-type templates here, particularly
467 // variable templates and concepts. But the exclusion of alias templates
468 // and template template parameters is a wording defect.
469 AllowFunctionTemplatesInLookup = false;
470 ObjectTypeSearchedInScope = true;
473 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
476 if (Found.isAmbiguous())
477 return false;
479 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
480 !RequiredTemplate.hasTemplateKeyword()) {
481 // C++2a [temp.names]p2:
482 // A name is also considered to refer to a template if it is an
483 // unqualified-id followed by a < and name lookup finds either one or more
484 // functions or finds nothing.
486 // To keep our behavior consistent, we apply the "finds nothing" part in
487 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
488 // successfully form a call to an undeclared template-id.
489 bool AllFunctions =
490 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
491 return isa<FunctionDecl>(ND->getUnderlyingDecl());
493 if (AllFunctions || (Found.empty() && !IsDependent)) {
494 // If lookup found any functions, or if this is a name that can only be
495 // used for a function, then strongly assume this is a function
496 // template-id.
497 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
498 ? AssumedTemplateKind::FoundNothing
499 : AssumedTemplateKind::FoundFunctions;
500 Found.clear();
501 return false;
505 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
506 // If we did not find any names, and this is not a disambiguation, attempt
507 // to correct any typos.
508 DeclarationName Name = Found.getLookupName();
509 Found.clear();
510 // Simple filter callback that, for keywords, only accepts the C++ *_cast
511 DefaultFilterCCC FilterCCC{};
512 FilterCCC.WantTypeSpecifiers = false;
513 FilterCCC.WantExpressionKeywords = false;
514 FilterCCC.WantRemainingKeywords = false;
515 FilterCCC.WantCXXNamedCasts = true;
516 if (TypoCorrection Corrected =
517 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
518 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
519 if (auto *ND = Corrected.getFoundDecl())
520 Found.addDecl(ND);
521 FilterAcceptableTemplateNames(Found);
522 if (Found.isAmbiguous()) {
523 Found.clear();
524 } else if (!Found.empty()) {
525 Found.setLookupName(Corrected.getCorrection());
526 if (LookupCtx) {
527 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
528 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
529 Name.getAsString() == CorrectedStr;
530 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
531 << Name << LookupCtx << DroppedSpecifier
532 << SS.getRange());
533 } else {
534 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
540 NamedDecl *ExampleLookupResult =
541 Found.empty() ? nullptr : Found.getRepresentativeDecl();
542 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
543 if (Found.empty()) {
544 if (IsDependent) {
545 Found.setNotFoundInCurrentInstantiation();
546 return false;
549 // If a 'template' keyword was used, a lookup that finds only non-template
550 // names is an error.
551 if (ExampleLookupResult && RequiredTemplate) {
552 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
553 << Found.getLookupName() << SS.getRange()
554 << RequiredTemplate.hasTemplateKeyword()
555 << RequiredTemplate.getTemplateKeywordLoc();
556 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
557 diag::note_template_kw_refers_to_non_template)
558 << Found.getLookupName();
559 return true;
562 return false;
565 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
566 !getLangOpts().CPlusPlus11) {
567 // C++03 [basic.lookup.classref]p1:
568 // [...] If the lookup in the class of the object expression finds a
569 // template, the name is also looked up in the context of the entire
570 // postfix-expression and [...]
572 // Note: C++11 does not perform this second lookup.
573 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
574 LookupOrdinaryName);
575 FoundOuter.setTemplateNameLookup(true);
576 LookupName(FoundOuter, S);
577 // FIXME: We silently accept an ambiguous lookup here, in violation of
578 // [basic.lookup]/1.
579 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
581 NamedDecl *OuterTemplate;
582 if (FoundOuter.empty()) {
583 // - if the name is not found, the name found in the class of the
584 // object expression is used, otherwise
585 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
586 !(OuterTemplate =
587 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
588 // - if the name is found in the context of the entire
589 // postfix-expression and does not name a class template, the name
590 // found in the class of the object expression is used, otherwise
591 FoundOuter.clear();
592 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
593 // - if the name found is a class template, it must refer to the same
594 // entity as the one found in the class of the object expression,
595 // otherwise the program is ill-formed.
596 if (!Found.isSingleResult() ||
597 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
598 OuterTemplate->getCanonicalDecl()) {
599 Diag(Found.getNameLoc(),
600 diag::ext_nested_name_member_ref_lookup_ambiguous)
601 << Found.getLookupName()
602 << ObjectType;
603 Diag(Found.getRepresentativeDecl()->getLocation(),
604 diag::note_ambig_member_ref_object_type)
605 << ObjectType;
606 Diag(FoundOuter.getFoundDecl()->getLocation(),
607 diag::note_ambig_member_ref_scope);
609 // Recover by taking the template that we found in the object
610 // expression's type.
615 return false;
618 void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
619 SourceLocation Less,
620 SourceLocation Greater) {
621 if (TemplateName.isInvalid())
622 return;
624 DeclarationNameInfo NameInfo;
625 CXXScopeSpec SS;
626 LookupNameKind LookupKind;
628 DeclContext *LookupCtx = nullptr;
629 NamedDecl *Found = nullptr;
630 bool MissingTemplateKeyword = false;
632 // Figure out what name we looked up.
633 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
634 NameInfo = DRE->getNameInfo();
635 SS.Adopt(DRE->getQualifierLoc());
636 LookupKind = LookupOrdinaryName;
637 Found = DRE->getFoundDecl();
638 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
639 NameInfo = ME->getMemberNameInfo();
640 SS.Adopt(ME->getQualifierLoc());
641 LookupKind = LookupMemberName;
642 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
643 Found = ME->getMemberDecl();
644 } else if (auto *DSDRE =
645 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
646 NameInfo = DSDRE->getNameInfo();
647 SS.Adopt(DSDRE->getQualifierLoc());
648 MissingTemplateKeyword = true;
649 } else if (auto *DSME =
650 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
651 NameInfo = DSME->getMemberNameInfo();
652 SS.Adopt(DSME->getQualifierLoc());
653 MissingTemplateKeyword = true;
654 } else {
655 llvm_unreachable("unexpected kind of potential template name");
658 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
659 // was missing.
660 if (MissingTemplateKeyword) {
661 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
662 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
663 return;
666 // Try to correct the name by looking for templates and C++ named casts.
667 struct TemplateCandidateFilter : CorrectionCandidateCallback {
668 Sema &S;
669 TemplateCandidateFilter(Sema &S) : S(S) {
670 WantTypeSpecifiers = false;
671 WantExpressionKeywords = false;
672 WantRemainingKeywords = false;
673 WantCXXNamedCasts = true;
675 bool ValidateCandidate(const TypoCorrection &Candidate) override {
676 if (auto *ND = Candidate.getCorrectionDecl())
677 return S.getAsTemplateNameDecl(ND);
678 return Candidate.isKeyword();
681 std::unique_ptr<CorrectionCandidateCallback> clone() override {
682 return std::make_unique<TemplateCandidateFilter>(*this);
686 DeclarationName Name = NameInfo.getName();
687 TemplateCandidateFilter CCC(*this);
688 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
689 CTK_ErrorRecovery, LookupCtx)) {
690 auto *ND = Corrected.getFoundDecl();
691 if (ND)
692 ND = getAsTemplateNameDecl(ND);
693 if (ND || Corrected.isKeyword()) {
694 if (LookupCtx) {
695 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
696 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
697 Name.getAsString() == CorrectedStr;
698 diagnoseTypo(Corrected,
699 PDiag(diag::err_non_template_in_member_template_id_suggest)
700 << Name << LookupCtx << DroppedSpecifier
701 << SS.getRange(), false);
702 } else {
703 diagnoseTypo(Corrected,
704 PDiag(diag::err_non_template_in_template_id_suggest)
705 << Name, false);
707 if (Found)
708 Diag(Found->getLocation(),
709 diag::note_non_template_in_template_id_found);
710 return;
714 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
715 << Name << SourceRange(Less, Greater);
716 if (Found)
717 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
720 ExprResult
721 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
722 SourceLocation TemplateKWLoc,
723 const DeclarationNameInfo &NameInfo,
724 bool isAddressOfOperand,
725 const TemplateArgumentListInfo *TemplateArgs) {
726 if (SS.isEmpty()) {
727 // FIXME: This codepath is only used by dependent unqualified names
728 // (e.g. a dependent conversion-function-id, or operator= once we support
729 // it). It doesn't quite do the right thing, and it will silently fail if
730 // getCurrentThisType() returns null.
731 QualType ThisType = getCurrentThisType();
732 if (ThisType.isNull())
733 return ExprError();
735 return CXXDependentScopeMemberExpr::Create(
736 Context, /*Base=*/nullptr, ThisType,
737 /*IsArrow=*/!Context.getLangOpts().HLSL,
738 /*OperatorLoc=*/SourceLocation(),
739 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
740 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
742 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
745 ExprResult
746 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
747 SourceLocation TemplateKWLoc,
748 const DeclarationNameInfo &NameInfo,
749 const TemplateArgumentListInfo *TemplateArgs) {
750 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
751 if (!SS.isValid())
752 return CreateRecoveryExpr(
753 SS.getBeginLoc(),
754 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});
756 return DependentScopeDeclRefExpr::Create(
757 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
758 TemplateArgs);
761 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
762 NamedDecl *Instantiation,
763 bool InstantiatedFromMember,
764 const NamedDecl *Pattern,
765 const NamedDecl *PatternDef,
766 TemplateSpecializationKind TSK,
767 bool Complain /*= true*/) {
768 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
769 isa<VarDecl>(Instantiation));
771 bool IsEntityBeingDefined = false;
772 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
773 IsEntityBeingDefined = TD->isBeingDefined();
775 if (PatternDef && !IsEntityBeingDefined) {
776 NamedDecl *SuggestedDef = nullptr;
777 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
778 &SuggestedDef,
779 /*OnlyNeedComplete*/ false)) {
780 // If we're allowed to diagnose this and recover, do so.
781 bool Recover = Complain && !isSFINAEContext();
782 if (Complain)
783 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
784 Sema::MissingImportKind::Definition, Recover);
785 return !Recover;
787 return false;
790 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
791 return true;
793 QualType InstantiationTy;
794 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
795 InstantiationTy = Context.getTypeDeclType(TD);
796 if (PatternDef) {
797 Diag(PointOfInstantiation,
798 diag::err_template_instantiate_within_definition)
799 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
800 << InstantiationTy;
801 // Not much point in noting the template declaration here, since
802 // we're lexically inside it.
803 Instantiation->setInvalidDecl();
804 } else if (InstantiatedFromMember) {
805 if (isa<FunctionDecl>(Instantiation)) {
806 Diag(PointOfInstantiation,
807 diag::err_explicit_instantiation_undefined_member)
808 << /*member function*/ 1 << Instantiation->getDeclName()
809 << Instantiation->getDeclContext();
810 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
811 } else {
812 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
813 Diag(PointOfInstantiation,
814 diag::err_implicit_instantiate_member_undefined)
815 << InstantiationTy;
816 Diag(Pattern->getLocation(), diag::note_member_declared_at);
818 } else {
819 if (isa<FunctionDecl>(Instantiation)) {
820 Diag(PointOfInstantiation,
821 diag::err_explicit_instantiation_undefined_func_template)
822 << Pattern;
823 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
824 } else if (isa<TagDecl>(Instantiation)) {
825 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
826 << (TSK != TSK_ImplicitInstantiation)
827 << InstantiationTy;
828 NoteTemplateLocation(*Pattern);
829 } else {
830 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
831 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
832 Diag(PointOfInstantiation,
833 diag::err_explicit_instantiation_undefined_var_template)
834 << Instantiation;
835 Instantiation->setInvalidDecl();
836 } else
837 Diag(PointOfInstantiation,
838 diag::err_explicit_instantiation_undefined_member)
839 << /*static data member*/ 2 << Instantiation->getDeclName()
840 << Instantiation->getDeclContext();
841 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
845 // In general, Instantiation isn't marked invalid to get more than one
846 // error for multiple undefined instantiations. But the code that does
847 // explicit declaration -> explicit definition conversion can't handle
848 // invalid declarations, so mark as invalid in that case.
849 if (TSK == TSK_ExplicitInstantiationDeclaration)
850 Instantiation->setInvalidDecl();
851 return true;
854 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
855 bool SupportedForCompatibility) {
856 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
858 // C++23 [temp.local]p6:
859 // The name of a template-parameter shall not be bound to any following.
860 // declaration whose locus is contained by the scope to which the
861 // template-parameter belongs.
863 // When MSVC compatibility is enabled, the diagnostic is always a warning
864 // by default. Otherwise, it an error unless SupportedForCompatibility is
865 // true, in which case it is a default-to-error warning.
866 unsigned DiagId =
867 getLangOpts().MSVCCompat
868 ? diag::ext_template_param_shadow
869 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
870 : diag::err_template_param_shadow);
871 const auto *ND = cast<NamedDecl>(PrevDecl);
872 Diag(Loc, DiagId) << ND->getDeclName();
873 NoteTemplateParameterLocation(*ND);
876 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
877 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
878 D = Temp->getTemplatedDecl();
879 return Temp;
881 return nullptr;
884 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
885 SourceLocation EllipsisLoc) const {
886 assert(Kind == Template &&
887 "Only template template arguments can be pack expansions here");
888 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
889 "Template template argument pack expansion without packs");
890 ParsedTemplateArgument Result(*this);
891 Result.EllipsisLoc = EllipsisLoc;
892 return Result;
895 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
896 const ParsedTemplateArgument &Arg) {
898 switch (Arg.getKind()) {
899 case ParsedTemplateArgument::Type: {
900 TypeSourceInfo *DI;
901 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
902 if (!DI)
903 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
904 return TemplateArgumentLoc(TemplateArgument(T), DI);
907 case ParsedTemplateArgument::NonType: {
908 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
909 return TemplateArgumentLoc(TemplateArgument(E), E);
912 case ParsedTemplateArgument::Template: {
913 TemplateName Template = Arg.getAsTemplate().get();
914 TemplateArgument TArg;
915 if (Arg.getEllipsisLoc().isValid())
916 TArg = TemplateArgument(Template, std::optional<unsigned int>());
917 else
918 TArg = Template;
919 return TemplateArgumentLoc(
920 SemaRef.Context, TArg,
921 Arg.getScopeSpec().getWithLocInContext(SemaRef.Context),
922 Arg.getLocation(), Arg.getEllipsisLoc());
926 llvm_unreachable("Unhandled parsed template argument");
929 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
930 TemplateArgumentListInfo &TemplateArgs) {
931 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
932 TemplateArgs.addArgument(translateTemplateArgument(*this,
933 TemplateArgsIn[I]));
936 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
937 SourceLocation Loc,
938 const IdentifierInfo *Name) {
939 NamedDecl *PrevDecl =
940 SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,
941 RedeclarationKind::ForVisibleRedeclaration);
942 if (PrevDecl && PrevDecl->isTemplateParameter())
943 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
946 ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
947 TypeSourceInfo *TInfo;
948 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
949 if (T.isNull())
950 return ParsedTemplateArgument();
951 assert(TInfo && "template argument with no location");
953 // If we might have formed a deduced template specialization type, convert
954 // it to a template template argument.
955 if (getLangOpts().CPlusPlus17) {
956 TypeLoc TL = TInfo->getTypeLoc();
957 SourceLocation EllipsisLoc;
958 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
959 EllipsisLoc = PET.getEllipsisLoc();
960 TL = PET.getPatternLoc();
963 CXXScopeSpec SS;
964 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
965 SS.Adopt(ET.getQualifierLoc());
966 TL = ET.getNamedTypeLoc();
969 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
970 TemplateName Name = DTST.getTypePtr()->getTemplateName();
971 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
972 DTST.getTemplateNameLoc());
973 if (EllipsisLoc.isValid())
974 Result = Result.getTemplatePackExpansion(EllipsisLoc);
975 return Result;
979 // This is a normal type template argument. Note, if the type template
980 // argument is an injected-class-name for a template, it has a dual nature
981 // and can be used as either a type or a template. We handle that in
982 // convertTypeTemplateArgumentToTemplate.
983 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
984 ParsedType.get().getAsOpaquePtr(),
985 TInfo->getTypeLoc().getBeginLoc());
988 NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
989 SourceLocation EllipsisLoc,
990 SourceLocation KeyLoc,
991 IdentifierInfo *ParamName,
992 SourceLocation ParamNameLoc,
993 unsigned Depth, unsigned Position,
994 SourceLocation EqualLoc,
995 ParsedType DefaultArg,
996 bool HasTypeConstraint) {
997 assert(S->isTemplateParamScope() &&
998 "Template type parameter not in template parameter scope!");
1000 bool IsParameterPack = EllipsisLoc.isValid();
1001 TemplateTypeParmDecl *Param
1002 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1003 KeyLoc, ParamNameLoc, Depth, Position,
1004 ParamName, Typename, IsParameterPack,
1005 HasTypeConstraint);
1006 Param->setAccess(AS_public);
1008 if (Param->isParameterPack())
1009 if (auto *CSI = getEnclosingLambdaOrBlock())
1010 CSI->LocalPacks.push_back(Param);
1012 if (ParamName) {
1013 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1015 // Add the template parameter into the current scope.
1016 S->AddDecl(Param);
1017 IdResolver.AddDecl(Param);
1020 // C++0x [temp.param]p9:
1021 // A default template-argument may be specified for any kind of
1022 // template-parameter that is not a template parameter pack.
1023 if (DefaultArg && IsParameterPack) {
1024 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1025 DefaultArg = nullptr;
1028 // Handle the default argument, if provided.
1029 if (DefaultArg) {
1030 TypeSourceInfo *DefaultTInfo;
1031 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1033 assert(DefaultTInfo && "expected source information for type");
1035 // Check for unexpanded parameter packs.
1036 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1037 UPPC_DefaultArgument))
1038 return Param;
1040 // Check the template argument itself.
1041 if (CheckTemplateArgument(DefaultTInfo)) {
1042 Param->setInvalidDecl();
1043 return Param;
1046 Param->setDefaultArgument(
1047 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1050 return Param;
1053 /// Convert the parser's template argument list representation into our form.
1054 static TemplateArgumentListInfo
1055 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1056 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1057 TemplateId.RAngleLoc);
1058 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1059 TemplateId.NumArgs);
1060 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1061 return TemplateArgs;
1064 bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {
1066 TemplateName TN = TypeConstr->Template.get();
1067 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1069 // C++2a [temp.param]p4:
1070 // [...] The concept designated by a type-constraint shall be a type
1071 // concept ([temp.concept]).
1072 if (!CD->isTypeConcept()) {
1073 Diag(TypeConstr->TemplateNameLoc,
1074 diag::err_type_constraint_non_type_concept);
1075 return true;
1078 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))
1079 return true;
1081 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1083 if (!WereArgsSpecified &&
1084 CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
1085 Diag(TypeConstr->TemplateNameLoc,
1086 diag::err_type_constraint_missing_arguments)
1087 << CD;
1088 return true;
1090 return false;
1093 bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1094 TemplateIdAnnotation *TypeConstr,
1095 TemplateTypeParmDecl *ConstrainedParameter,
1096 SourceLocation EllipsisLoc) {
1097 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1098 false);
1101 bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1102 TemplateIdAnnotation *TypeConstr,
1103 TemplateTypeParmDecl *ConstrainedParameter,
1104 SourceLocation EllipsisLoc,
1105 bool AllowUnexpandedPack) {
1107 if (CheckTypeConstraint(TypeConstr))
1108 return true;
1110 TemplateName TN = TypeConstr->Template.get();
1111 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1112 UsingShadowDecl *USD = TN.getAsUsingShadowDecl();
1114 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1115 TypeConstr->TemplateNameLoc);
1117 TemplateArgumentListInfo TemplateArgs;
1118 if (TypeConstr->LAngleLoc.isValid()) {
1119 TemplateArgs =
1120 makeTemplateArgumentListInfo(*this, *TypeConstr);
1122 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1123 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1124 if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint))
1125 return true;
1129 return AttachTypeConstraint(
1130 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1131 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
1132 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1133 ConstrainedParameter, Context.getTypeDeclType(ConstrainedParameter),
1134 EllipsisLoc);
1137 template <typename ArgumentLocAppender>
1138 static ExprResult formImmediatelyDeclaredConstraint(
1139 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1140 ConceptDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1141 SourceLocation RAngleLoc, QualType ConstrainedType,
1142 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1143 SourceLocation EllipsisLoc) {
1145 TemplateArgumentListInfo ConstraintArgs;
1146 ConstraintArgs.addArgument(
1147 S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
1148 /*NTTPType=*/QualType(), ParamNameLoc));
1150 ConstraintArgs.setRAngleLoc(RAngleLoc);
1151 ConstraintArgs.setLAngleLoc(LAngleLoc);
1152 Appender(ConstraintArgs);
1154 // C++2a [temp.param]p4:
1155 // [...] This constraint-expression E is called the immediately-declared
1156 // constraint of T. [...]
1157 CXXScopeSpec SS;
1158 SS.Adopt(NS);
1159 ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1160 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1161 /*FoundDecl=*/FoundDecl ? FoundDecl : NamedConcept, NamedConcept,
1162 &ConstraintArgs);
1163 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1164 return ImmediatelyDeclaredConstraint;
1166 // C++2a [temp.param]p4:
1167 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1169 // We have the following case:
1171 // template<typename T> concept C1 = true;
1172 // template<C1... T> struct s1;
1174 // The constraint: (C1<T> && ...)
1176 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1177 // any unqualified lookups for 'operator&&' here.
1178 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1179 /*LParenLoc=*/SourceLocation(),
1180 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1181 EllipsisLoc, /*RHS=*/nullptr,
1182 /*RParenLoc=*/SourceLocation(),
1183 /*NumExpansions=*/std::nullopt);
1186 bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1187 DeclarationNameInfo NameInfo,
1188 ConceptDecl *NamedConcept, NamedDecl *FoundDecl,
1189 const TemplateArgumentListInfo *TemplateArgs,
1190 TemplateTypeParmDecl *ConstrainedParameter,
1191 QualType ConstrainedType,
1192 SourceLocation EllipsisLoc) {
1193 // C++2a [temp.param]p4:
1194 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1195 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1196 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1197 TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
1198 *TemplateArgs) : nullptr;
1200 QualType ParamAsArgument = ConstrainedType;
1202 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1203 *this, NS, NameInfo, NamedConcept, FoundDecl,
1204 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1205 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1206 ParamAsArgument, ConstrainedParameter->getLocation(),
1207 [&](TemplateArgumentListInfo &ConstraintArgs) {
1208 if (TemplateArgs)
1209 for (const auto &ArgLoc : TemplateArgs->arguments())
1210 ConstraintArgs.addArgument(ArgLoc);
1212 EllipsisLoc);
1213 if (ImmediatelyDeclaredConstraint.isInvalid())
1214 return true;
1216 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1217 /*TemplateKWLoc=*/SourceLocation{},
1218 /*ConceptNameInfo=*/NameInfo,
1219 /*FoundDecl=*/FoundDecl,
1220 /*NamedConcept=*/NamedConcept,
1221 /*ArgsWritten=*/ArgsAsWritten);
1222 ConstrainedParameter->setTypeConstraint(CL,
1223 ImmediatelyDeclaredConstraint.get());
1224 return false;
1227 bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
1228 NonTypeTemplateParmDecl *NewConstrainedParm,
1229 NonTypeTemplateParmDecl *OrigConstrainedParm,
1230 SourceLocation EllipsisLoc) {
1231 if (NewConstrainedParm->getType() != TL.getType() ||
1232 TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1233 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1234 diag::err_unsupported_placeholder_constraint)
1235 << NewConstrainedParm->getTypeSourceInfo()
1236 ->getTypeLoc()
1237 .getSourceRange();
1238 return true;
1240 // FIXME: Concepts: This should be the type of the placeholder, but this is
1241 // unclear in the wording right now.
1242 DeclRefExpr *Ref =
1243 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1244 VK_PRValue, OrigConstrainedParm->getLocation());
1245 if (!Ref)
1246 return true;
1247 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1248 *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
1249 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1250 TL.getRAngleLoc(), BuildDecltypeType(Ref),
1251 OrigConstrainedParm->getLocation(),
1252 [&](TemplateArgumentListInfo &ConstraintArgs) {
1253 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1254 ConstraintArgs.addArgument(TL.getArgLoc(I));
1256 EllipsisLoc);
1257 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1258 !ImmediatelyDeclaredConstraint.isUsable())
1259 return true;
1261 NewConstrainedParm->setPlaceholderTypeConstraint(
1262 ImmediatelyDeclaredConstraint.get());
1263 return false;
1266 QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1267 SourceLocation Loc) {
1268 if (TSI->getType()->isUndeducedType()) {
1269 // C++17 [temp.dep.expr]p3:
1270 // An id-expression is type-dependent if it contains
1271 // - an identifier associated by name lookup with a non-type
1272 // template-parameter declared with a type that contains a
1273 // placeholder type (7.1.7.4),
1274 TSI = SubstAutoTypeSourceInfoDependent(TSI);
1277 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1280 bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1281 if (T->isDependentType())
1282 return false;
1284 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1285 return true;
1287 if (T->isStructuralType())
1288 return false;
1290 // Structural types are required to be object types or lvalue references.
1291 if (T->isRValueReferenceType()) {
1292 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1293 return true;
1296 // Don't mention structural types in our diagnostic prior to C++20. Also,
1297 // there's not much more we can say about non-scalar non-class types --
1298 // because we can't see functions or arrays here, those can only be language
1299 // extensions.
1300 if (!getLangOpts().CPlusPlus20 ||
1301 (!T->isScalarType() && !T->isRecordType())) {
1302 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1303 return true;
1306 // Structural types are required to be literal types.
1307 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1308 return true;
1310 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1312 // Drill down into the reason why the class is non-structural.
1313 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1314 // All members are required to be public and non-mutable, and can't be of
1315 // rvalue reference type. Check these conditions first to prefer a "local"
1316 // reason over a more distant one.
1317 for (const FieldDecl *FD : RD->fields()) {
1318 if (FD->getAccess() != AS_public) {
1319 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1320 return true;
1322 if (FD->isMutable()) {
1323 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1324 return true;
1326 if (FD->getType()->isRValueReferenceType()) {
1327 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1328 << T;
1329 return true;
1333 // All bases are required to be public.
1334 for (const auto &BaseSpec : RD->bases()) {
1335 if (BaseSpec.getAccessSpecifier() != AS_public) {
1336 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1337 << T << 1;
1338 return true;
1342 // All subobjects are required to be of structural types.
1343 SourceLocation SubLoc;
1344 QualType SubType;
1345 int Kind = -1;
1347 for (const FieldDecl *FD : RD->fields()) {
1348 QualType T = Context.getBaseElementType(FD->getType());
1349 if (!T->isStructuralType()) {
1350 SubLoc = FD->getLocation();
1351 SubType = T;
1352 Kind = 0;
1353 break;
1357 if (Kind == -1) {
1358 for (const auto &BaseSpec : RD->bases()) {
1359 QualType T = BaseSpec.getType();
1360 if (!T->isStructuralType()) {
1361 SubLoc = BaseSpec.getBaseTypeLoc();
1362 SubType = T;
1363 Kind = 1;
1364 break;
1369 assert(Kind != -1 && "couldn't find reason why type is not structural");
1370 Diag(SubLoc, diag::note_not_structural_subobject)
1371 << T << Kind << SubType;
1372 T = SubType;
1373 RD = T->getAsCXXRecordDecl();
1376 return true;
1379 QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1380 SourceLocation Loc) {
1381 // We don't allow variably-modified types as the type of non-type template
1382 // parameters.
1383 if (T->isVariablyModifiedType()) {
1384 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1385 << T;
1386 return QualType();
1389 // C++ [temp.param]p4:
1391 // A non-type template-parameter shall have one of the following
1392 // (optionally cv-qualified) types:
1394 // -- integral or enumeration type,
1395 if (T->isIntegralOrEnumerationType() ||
1396 // -- pointer to object or pointer to function,
1397 T->isPointerType() ||
1398 // -- lvalue reference to object or lvalue reference to function,
1399 T->isLValueReferenceType() ||
1400 // -- pointer to member,
1401 T->isMemberPointerType() ||
1402 // -- std::nullptr_t, or
1403 T->isNullPtrType() ||
1404 // -- a type that contains a placeholder type.
1405 T->isUndeducedType()) {
1406 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1407 // are ignored when determining its type.
1408 return T.getUnqualifiedType();
1411 // C++ [temp.param]p8:
1413 // A non-type template-parameter of type "array of T" or
1414 // "function returning T" is adjusted to be of type "pointer to
1415 // T" or "pointer to function returning T", respectively.
1416 if (T->isArrayType() || T->isFunctionType())
1417 return Context.getDecayedType(T);
1419 // If T is a dependent type, we can't do the check now, so we
1420 // assume that it is well-formed. Note that stripping off the
1421 // qualifiers here is not really correct if T turns out to be
1422 // an array type, but we'll recompute the type everywhere it's
1423 // used during instantiation, so that should be OK. (Using the
1424 // qualified type is equally wrong.)
1425 if (T->isDependentType())
1426 return T.getUnqualifiedType();
1428 // C++20 [temp.param]p6:
1429 // -- a structural type
1430 if (RequireStructuralType(T, Loc))
1431 return QualType();
1433 if (!getLangOpts().CPlusPlus20) {
1434 // FIXME: Consider allowing structural types as an extension in C++17. (In
1435 // earlier language modes, the template argument evaluation rules are too
1436 // inflexible.)
1437 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1438 return QualType();
1441 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1442 return T.getUnqualifiedType();
1445 NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1446 unsigned Depth,
1447 unsigned Position,
1448 SourceLocation EqualLoc,
1449 Expr *Default) {
1450 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
1452 // Check that we have valid decl-specifiers specified.
1453 auto CheckValidDeclSpecifiers = [this, &D] {
1454 // C++ [temp.param]
1455 // p1
1456 // template-parameter:
1457 // ...
1458 // parameter-declaration
1459 // p2
1460 // ... A storage class shall not be specified in a template-parameter
1461 // declaration.
1462 // [dcl.typedef]p1:
1463 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1464 // of a parameter-declaration
1465 const DeclSpec &DS = D.getDeclSpec();
1466 auto EmitDiag = [this](SourceLocation Loc) {
1467 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1468 << FixItHint::CreateRemoval(Loc);
1470 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1471 EmitDiag(DS.getStorageClassSpecLoc());
1473 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1474 EmitDiag(DS.getThreadStorageClassSpecLoc());
1476 // [dcl.inline]p1:
1477 // The inline specifier can be applied only to the declaration or
1478 // definition of a variable or function.
1480 if (DS.isInlineSpecified())
1481 EmitDiag(DS.getInlineSpecLoc());
1483 // [dcl.constexpr]p1:
1484 // The constexpr specifier shall be applied only to the definition of a
1485 // variable or variable template or the declaration of a function or
1486 // function template.
1488 if (DS.hasConstexprSpecifier())
1489 EmitDiag(DS.getConstexprSpecLoc());
1491 // [dcl.fct.spec]p1:
1492 // Function-specifiers can be used only in function declarations.
1494 if (DS.isVirtualSpecified())
1495 EmitDiag(DS.getVirtualSpecLoc());
1497 if (DS.hasExplicitSpecifier())
1498 EmitDiag(DS.getExplicitSpecLoc());
1500 if (DS.isNoreturnSpecified())
1501 EmitDiag(DS.getNoreturnSpecLoc());
1504 CheckValidDeclSpecifiers();
1506 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1507 if (isa<AutoType>(T))
1508 Diag(D.getIdentifierLoc(),
1509 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1510 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1512 assert(S->isTemplateParamScope() &&
1513 "Non-type template parameter not in template parameter scope!");
1514 bool Invalid = false;
1516 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1517 if (T.isNull()) {
1518 T = Context.IntTy; // Recover with an 'int' type.
1519 Invalid = true;
1522 CheckFunctionOrTemplateParamDeclarator(S, D);
1524 const IdentifierInfo *ParamName = D.getIdentifier();
1525 bool IsParameterPack = D.hasEllipsis();
1526 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1527 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1528 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1529 TInfo);
1530 Param->setAccess(AS_public);
1532 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1533 if (TL.isConstrained())
1534 if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1535 Invalid = true;
1537 if (Invalid)
1538 Param->setInvalidDecl();
1540 if (Param->isParameterPack())
1541 if (auto *CSI = getEnclosingLambdaOrBlock())
1542 CSI->LocalPacks.push_back(Param);
1544 if (ParamName) {
1545 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1546 ParamName);
1548 // Add the template parameter into the current scope.
1549 S->AddDecl(Param);
1550 IdResolver.AddDecl(Param);
1553 // C++0x [temp.param]p9:
1554 // A default template-argument may be specified for any kind of
1555 // template-parameter that is not a template parameter pack.
1556 if (Default && IsParameterPack) {
1557 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1558 Default = nullptr;
1561 // Check the well-formedness of the default template argument, if provided.
1562 if (Default) {
1563 // Check for unexpanded parameter packs.
1564 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1565 return Param;
1567 Param->setDefaultArgument(
1568 Context, getTrivialTemplateArgumentLoc(TemplateArgument(Default),
1569 QualType(), SourceLocation()));
1572 return Param;
1575 NamedDecl *Sema::ActOnTemplateTemplateParameter(
1576 Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params,
1577 bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *Name,
1578 SourceLocation NameLoc, unsigned Depth, unsigned Position,
1579 SourceLocation EqualLoc, ParsedTemplateArgument Default) {
1580 assert(S->isTemplateParamScope() &&
1581 "Template template parameter not in template parameter scope!");
1583 // Construct the parameter object.
1584 bool IsParameterPack = EllipsisLoc.isValid();
1585 TemplateTemplateParmDecl *Param = TemplateTemplateParmDecl::Create(
1586 Context, Context.getTranslationUnitDecl(),
1587 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1588 Name, Typename, Params);
1589 Param->setAccess(AS_public);
1591 if (Param->isParameterPack())
1592 if (auto *LSI = getEnclosingLambdaOrBlock())
1593 LSI->LocalPacks.push_back(Param);
1595 // If the template template parameter has a name, then link the identifier
1596 // into the scope and lookup mechanisms.
1597 if (Name) {
1598 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1600 S->AddDecl(Param);
1601 IdResolver.AddDecl(Param);
1604 if (Params->size() == 0) {
1605 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1606 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1607 Param->setInvalidDecl();
1610 // C++0x [temp.param]p9:
1611 // A default template-argument may be specified for any kind of
1612 // template-parameter that is not a template parameter pack.
1613 if (IsParameterPack && !Default.isInvalid()) {
1614 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1615 Default = ParsedTemplateArgument();
1618 if (!Default.isInvalid()) {
1619 // Check only that we have a template template argument. We don't want to
1620 // try to check well-formedness now, because our template template parameter
1621 // might have dependent types in its template parameters, which we wouldn't
1622 // be able to match now.
1624 // If none of the template template parameter's template arguments mention
1625 // other template parameters, we could actually perform more checking here.
1626 // However, it isn't worth doing.
1627 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1628 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1629 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1630 << DefaultArg.getSourceRange();
1631 return Param;
1634 // Check for unexpanded parameter packs.
1635 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1636 DefaultArg.getArgument().getAsTemplate(),
1637 UPPC_DefaultArgument))
1638 return Param;
1640 Param->setDefaultArgument(Context, DefaultArg);
1643 return Param;
1646 namespace {
1647 class ConstraintRefersToContainingTemplateChecker
1648 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1649 bool Result = false;
1650 const FunctionDecl *Friend = nullptr;
1651 unsigned TemplateDepth = 0;
1653 // Check a record-decl that we've seen to see if it is a lexical parent of the
1654 // Friend, likely because it was referred to without its template arguments.
1655 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1656 CheckingRD = CheckingRD->getMostRecentDecl();
1657 if (!CheckingRD->isTemplated())
1658 return;
1660 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1661 DC && !DC->isFileContext(); DC = DC->getParent())
1662 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1663 if (CheckingRD == RD->getMostRecentDecl())
1664 Result = true;
1667 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1668 if (D->getDepth() < TemplateDepth)
1669 Result = true;
1671 // Necessary because the type of the NTTP might be what refers to the parent
1672 // constriant.
1673 TransformType(D->getType());
1676 public:
1677 using inherited = TreeTransform<ConstraintRefersToContainingTemplateChecker>;
1679 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1680 const FunctionDecl *Friend,
1681 unsigned TemplateDepth)
1682 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1683 bool getResult() const { return Result; }
1685 // This should be the only template parm type that we have to deal with.
1686 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1687 // FunctionParmPackExpr are all partially substituted, which cannot happen
1688 // with concepts at this point in translation.
1689 using inherited::TransformTemplateTypeParmType;
1690 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1691 TemplateTypeParmTypeLoc TL, bool) {
1692 if (TL.getDecl()->getDepth() < TemplateDepth)
1693 Result = true;
1694 return inherited::TransformTemplateTypeParmType(
1695 TLB, TL,
1696 /*SuppressObjCLifetime=*/false);
1699 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1700 if (!D)
1701 return D;
1702 // FIXME : This is possibly an incomplete list, but it is unclear what other
1703 // Decl kinds could be used to refer to the template parameters. This is a
1704 // best guess so far based on examples currently available, but the
1705 // unreachable should catch future instances/cases.
1706 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1707 TransformType(TD->getUnderlyingType());
1708 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1709 CheckNonTypeTemplateParmDecl(NTTPD);
1710 else if (auto *VD = dyn_cast<ValueDecl>(D))
1711 TransformType(VD->getType());
1712 else if (auto *TD = dyn_cast<TemplateDecl>(D))
1713 TransformTemplateParameterList(TD->getTemplateParameters());
1714 else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1715 CheckIfContainingRecord(RD);
1716 else if (isa<NamedDecl>(D)) {
1717 // No direct types to visit here I believe.
1718 } else
1719 llvm_unreachable("Don't know how to handle this declaration type yet");
1720 return D;
1723 } // namespace
1725 bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1726 const FunctionDecl *Friend, unsigned TemplateDepth,
1727 const Expr *Constraint) {
1728 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1729 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1730 TemplateDepth);
1731 Checker.TransformExpr(const_cast<Expr *>(Constraint));
1732 return Checker.getResult();
1735 TemplateParameterList *
1736 Sema::ActOnTemplateParameterList(unsigned Depth,
1737 SourceLocation ExportLoc,
1738 SourceLocation TemplateLoc,
1739 SourceLocation LAngleLoc,
1740 ArrayRef<NamedDecl *> Params,
1741 SourceLocation RAngleLoc,
1742 Expr *RequiresClause) {
1743 if (ExportLoc.isValid())
1744 Diag(ExportLoc, diag::warn_template_export_unsupported);
1746 for (NamedDecl *P : Params)
1747 warnOnReservedIdentifier(P);
1749 return TemplateParameterList::Create(
1750 Context, TemplateLoc, LAngleLoc,
1751 llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1754 static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1755 const CXXScopeSpec &SS) {
1756 if (SS.isSet())
1757 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1760 // Returns the template parameter list with all default template argument
1761 // information.
1762 TemplateParameterList *Sema::GetTemplateParameterList(TemplateDecl *TD) {
1763 // Make sure we get the template parameter list from the most
1764 // recent declaration, since that is the only one that is guaranteed to
1765 // have all the default template argument information.
1766 Decl *D = TD->getMostRecentDecl();
1767 // C++11 N3337 [temp.param]p12:
1768 // A default template argument shall not be specified in a friend class
1769 // template declaration.
1771 // Skip past friend *declarations* because they are not supposed to contain
1772 // default template arguments. Moreover, these declarations may introduce
1773 // template parameters living in different template depths than the
1774 // corresponding template parameters in TD, causing unmatched constraint
1775 // substitution.
1777 // FIXME: Diagnose such cases within a class template:
1778 // template <class T>
1779 // struct S {
1780 // template <class = void> friend struct C;
1781 // };
1782 // template struct S<int>;
1783 while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
1784 D->getPreviousDecl())
1785 D = D->getPreviousDecl();
1786 return cast<TemplateDecl>(D)->getTemplateParameters();
1789 DeclResult Sema::CheckClassTemplate(
1790 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1791 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1792 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1793 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1794 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1795 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1796 assert(TemplateParams && TemplateParams->size() > 0 &&
1797 "No template parameters");
1798 assert(TUK != TagUseKind::Reference &&
1799 "Can only declare or define class templates");
1800 bool Invalid = false;
1802 // Check that we can declare a template here.
1803 if (CheckTemplateDeclScope(S, TemplateParams))
1804 return true;
1806 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1807 assert(Kind != TagTypeKind::Enum &&
1808 "can't build template of enumerated type");
1810 // There is no such thing as an unnamed class template.
1811 if (!Name) {
1812 Diag(KWLoc, diag::err_template_unnamed_class);
1813 return true;
1816 // Find any previous declaration with this name. For a friend with no
1817 // scope explicitly specified, we only look for tag declarations (per
1818 // C++11 [basic.lookup.elab]p2).
1819 DeclContext *SemanticContext;
1820 LookupResult Previous(*this, Name, NameLoc,
1821 (SS.isEmpty() && TUK == TagUseKind::Friend)
1822 ? LookupTagName
1823 : LookupOrdinaryName,
1824 forRedeclarationInCurContext());
1825 if (SS.isNotEmpty() && !SS.isInvalid()) {
1826 SemanticContext = computeDeclContext(SS, true);
1827 if (!SemanticContext) {
1828 // FIXME: Horrible, horrible hack! We can't currently represent this
1829 // in the AST, and historically we have just ignored such friend
1830 // class templates, so don't complain here.
1831 Diag(NameLoc, TUK == TagUseKind::Friend
1832 ? diag::warn_template_qualified_friend_ignored
1833 : diag::err_template_qualified_declarator_no_match)
1834 << SS.getScopeRep() << SS.getRange();
1835 return TUK != TagUseKind::Friend;
1838 if (RequireCompleteDeclContext(SS, SemanticContext))
1839 return true;
1841 // If we're adding a template to a dependent context, we may need to
1842 // rebuilding some of the types used within the template parameter list,
1843 // now that we know what the current instantiation is.
1844 if (SemanticContext->isDependentContext()) {
1845 ContextRAII SavedContext(*this, SemanticContext);
1846 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1847 Invalid = true;
1850 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1851 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1852 /*TemplateId-*/ nullptr,
1853 /*IsMemberSpecialization*/ false);
1855 LookupQualifiedName(Previous, SemanticContext);
1856 } else {
1857 SemanticContext = CurContext;
1859 // C++14 [class.mem]p14:
1860 // If T is the name of a class, then each of the following shall have a
1861 // name different from T:
1862 // -- every member template of class T
1863 if (TUK != TagUseKind::Friend &&
1864 DiagnoseClassNameShadow(SemanticContext,
1865 DeclarationNameInfo(Name, NameLoc)))
1866 return true;
1868 LookupName(Previous, S);
1871 if (Previous.isAmbiguous())
1872 return true;
1874 // Let the template parameter scope enter the lookup chain of the current
1875 // class template. For example, given
1877 // namespace ns {
1878 // template <class> bool Param = false;
1879 // template <class T> struct N;
1880 // }
1882 // template <class Param> struct ns::N { void foo(Param); };
1884 // When we reference Param inside the function parameter list, our name lookup
1885 // chain for it should be like:
1886 // FunctionScope foo
1887 // -> RecordScope N
1888 // -> TemplateParamScope (where we will find Param)
1889 // -> NamespaceScope ns
1891 // See also CppLookupName().
1892 if (S->isTemplateParamScope())
1893 EnterTemplatedContext(S, SemanticContext);
1895 NamedDecl *PrevDecl = nullptr;
1896 if (Previous.begin() != Previous.end())
1897 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1899 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1900 // Maybe we will complain about the shadowed template parameter.
1901 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1902 // Just pretend that we didn't see the previous declaration.
1903 PrevDecl = nullptr;
1906 // If there is a previous declaration with the same name, check
1907 // whether this is a valid redeclaration.
1908 ClassTemplateDecl *PrevClassTemplate =
1909 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1911 // We may have found the injected-class-name of a class template,
1912 // class template partial specialization, or class template specialization.
1913 // In these cases, grab the template that is being defined or specialized.
1914 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&
1915 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1916 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1917 PrevClassTemplate
1918 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1919 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1920 PrevClassTemplate
1921 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1922 ->getSpecializedTemplate();
1926 if (TUK == TagUseKind::Friend) {
1927 // C++ [namespace.memdef]p3:
1928 // [...] When looking for a prior declaration of a class or a function
1929 // declared as a friend, and when the name of the friend class or
1930 // function is neither a qualified name nor a template-id, scopes outside
1931 // the innermost enclosing namespace scope are not considered.
1932 if (!SS.isSet()) {
1933 DeclContext *OutermostContext = CurContext;
1934 while (!OutermostContext->isFileContext())
1935 OutermostContext = OutermostContext->getLookupParent();
1937 if (PrevDecl &&
1938 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1939 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1940 SemanticContext = PrevDecl->getDeclContext();
1941 } else {
1942 // Declarations in outer scopes don't matter. However, the outermost
1943 // context we computed is the semantic context for our new
1944 // declaration.
1945 PrevDecl = PrevClassTemplate = nullptr;
1946 SemanticContext = OutermostContext;
1948 // Check that the chosen semantic context doesn't already contain a
1949 // declaration of this name as a non-tag type.
1950 Previous.clear(LookupOrdinaryName);
1951 DeclContext *LookupContext = SemanticContext;
1952 while (LookupContext->isTransparentContext())
1953 LookupContext = LookupContext->getLookupParent();
1954 LookupQualifiedName(Previous, LookupContext);
1956 if (Previous.isAmbiguous())
1957 return true;
1959 if (Previous.begin() != Previous.end())
1960 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1963 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),
1964 SemanticContext, S, SS.isValid()))
1965 PrevDecl = PrevClassTemplate = nullptr;
1967 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1968 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1969 if (SS.isEmpty() &&
1970 !(PrevClassTemplate &&
1971 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1972 SemanticContext->getRedeclContext()))) {
1973 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1974 Diag(Shadow->getTargetDecl()->getLocation(),
1975 diag::note_using_decl_target);
1976 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
1977 // Recover by ignoring the old declaration.
1978 PrevDecl = PrevClassTemplate = nullptr;
1982 if (PrevClassTemplate) {
1983 // Ensure that the template parameter lists are compatible. Skip this check
1984 // for a friend in a dependent context: the template parameter list itself
1985 // could be dependent.
1986 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
1987 !TemplateParameterListsAreEqual(
1988 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
1989 : CurContext,
1990 CurContext, KWLoc),
1991 TemplateParams, PrevClassTemplate,
1992 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
1993 TPL_TemplateMatch))
1994 return true;
1996 // C++ [temp.class]p4:
1997 // In a redeclaration, partial specialization, explicit
1998 // specialization or explicit instantiation of a class template,
1999 // the class-key shall agree in kind with the original class
2000 // template declaration (7.1.5.3).
2001 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2002 if (!isAcceptableTagRedeclaration(
2003 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {
2004 Diag(KWLoc, diag::err_use_with_wrong_tag)
2005 << Name
2006 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2007 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2008 Kind = PrevRecordDecl->getTagKind();
2011 // Check for redefinition of this class template.
2012 if (TUK == TagUseKind::Definition) {
2013 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2014 // If we have a prior definition that is not visible, treat this as
2015 // simply making that previous definition visible.
2016 NamedDecl *Hidden = nullptr;
2017 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2018 SkipBody->ShouldSkip = true;
2019 SkipBody->Previous = Def;
2020 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2021 assert(Tmpl && "original definition of a class template is not a "
2022 "class template?");
2023 makeMergedDefinitionVisible(Hidden);
2024 makeMergedDefinitionVisible(Tmpl);
2025 } else {
2026 Diag(NameLoc, diag::err_redefinition) << Name;
2027 Diag(Def->getLocation(), diag::note_previous_definition);
2028 // FIXME: Would it make sense to try to "forget" the previous
2029 // definition, as part of error recovery?
2030 return true;
2034 } else if (PrevDecl) {
2035 // C++ [temp]p5:
2036 // A class template shall not have the same name as any other
2037 // template, class, function, object, enumeration, enumerator,
2038 // namespace, or type in the same scope (3.3), except as specified
2039 // in (14.5.4).
2040 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2041 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2042 return true;
2045 // Check the template parameter list of this declaration, possibly
2046 // merging in the template parameter list from the previous class
2047 // template declaration. Skip this check for a friend in a dependent
2048 // context, because the template parameter list might be dependent.
2049 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2050 CheckTemplateParameterList(
2051 TemplateParams,
2052 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2053 : nullptr,
2054 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2055 SemanticContext->isDependentContext())
2056 ? TPC_ClassTemplateMember
2057 : TUK == TagUseKind::Friend ? TPC_FriendClassTemplate
2058 : TPC_ClassTemplate,
2059 SkipBody))
2060 Invalid = true;
2062 if (SS.isSet()) {
2063 // If the name of the template was qualified, we must be defining the
2064 // template out-of-line.
2065 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2066 Diag(NameLoc, TUK == TagUseKind::Friend
2067 ? diag::err_friend_decl_does_not_match
2068 : diag::err_member_decl_does_not_match)
2069 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2070 Invalid = true;
2074 // If this is a templated friend in a dependent context we should not put it
2075 // on the redecl chain. In some cases, the templated friend can be the most
2076 // recent declaration tricking the template instantiator to make substitutions
2077 // there.
2078 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2079 bool ShouldAddRedecl =
2080 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2082 CXXRecordDecl *NewClass =
2083 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2084 PrevClassTemplate && ShouldAddRedecl ?
2085 PrevClassTemplate->getTemplatedDecl() : nullptr,
2086 /*DelayTypeCreation=*/true);
2087 SetNestedNameSpecifier(*this, NewClass, SS);
2088 if (NumOuterTemplateParamLists > 0)
2089 NewClass->setTemplateParameterListsInfo(
2090 Context,
2091 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2093 // Add alignment attributes if necessary; these attributes are checked when
2094 // the ASTContext lays out the structure.
2095 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2096 AddAlignmentAttributesForRecord(NewClass);
2097 AddMsStructLayoutForRecord(NewClass);
2100 ClassTemplateDecl *NewTemplate
2101 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2102 DeclarationName(Name), TemplateParams,
2103 NewClass);
2105 if (ShouldAddRedecl)
2106 NewTemplate->setPreviousDecl(PrevClassTemplate);
2108 NewClass->setDescribedClassTemplate(NewTemplate);
2110 if (ModulePrivateLoc.isValid())
2111 NewTemplate->setModulePrivate();
2113 // Build the type for the class template declaration now.
2114 QualType T = NewTemplate->getInjectedClassNameSpecialization();
2115 T = Context.getInjectedClassNameType(NewClass, T);
2116 assert(T->isDependentType() && "Class template type is not dependent?");
2117 (void)T;
2119 // If we are providing an explicit specialization of a member that is a
2120 // class template, make a note of that.
2121 if (PrevClassTemplate &&
2122 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2123 PrevClassTemplate->setMemberSpecialization();
2125 // Set the access specifier.
2126 if (!Invalid && TUK != TagUseKind::Friend &&
2127 NewTemplate->getDeclContext()->isRecord())
2128 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2130 // Set the lexical context of these templates
2131 NewClass->setLexicalDeclContext(CurContext);
2132 NewTemplate->setLexicalDeclContext(CurContext);
2134 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2135 NewClass->startDefinition();
2137 ProcessDeclAttributeList(S, NewClass, Attr);
2138 ProcessAPINotes(NewClass);
2140 if (PrevClassTemplate)
2141 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2143 AddPushedVisibilityAttribute(NewClass);
2144 inferGslOwnerPointerAttribute(NewClass);
2145 inferNullableClassAttribute(NewClass);
2147 if (TUK != TagUseKind::Friend) {
2148 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2149 Scope *Outer = S;
2150 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2151 Outer = Outer->getParent();
2152 PushOnScopeChains(NewTemplate, Outer);
2153 } else {
2154 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2155 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2156 NewClass->setAccess(PrevClassTemplate->getAccess());
2159 NewTemplate->setObjectOfFriendDecl();
2161 // Friend templates are visible in fairly strange ways.
2162 if (!CurContext->isDependentContext()) {
2163 DeclContext *DC = SemanticContext->getRedeclContext();
2164 DC->makeDeclVisibleInContext(NewTemplate);
2165 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2166 PushOnScopeChains(NewTemplate, EnclosingScope,
2167 /* AddToContext = */ false);
2170 FriendDecl *Friend = FriendDecl::Create(
2171 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2172 Friend->setAccess(AS_public);
2173 CurContext->addDecl(Friend);
2176 if (PrevClassTemplate)
2177 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2179 if (Invalid) {
2180 NewTemplate->setInvalidDecl();
2181 NewClass->setInvalidDecl();
2184 ActOnDocumentableDecl(NewTemplate);
2186 if (SkipBody && SkipBody->ShouldSkip)
2187 return SkipBody->Previous;
2189 return NewTemplate;
2192 /// Diagnose the presence of a default template argument on a
2193 /// template parameter, which is ill-formed in certain contexts.
2195 /// \returns true if the default template argument should be dropped.
2196 static bool DiagnoseDefaultTemplateArgument(Sema &S,
2197 Sema::TemplateParamListContext TPC,
2198 SourceLocation ParamLoc,
2199 SourceRange DefArgRange) {
2200 switch (TPC) {
2201 case Sema::TPC_ClassTemplate:
2202 case Sema::TPC_VarTemplate:
2203 case Sema::TPC_TypeAliasTemplate:
2204 return false;
2206 case Sema::TPC_FunctionTemplate:
2207 case Sema::TPC_FriendFunctionTemplateDefinition:
2208 // C++ [temp.param]p9:
2209 // A default template-argument shall not be specified in a
2210 // function template declaration or a function template
2211 // definition [...]
2212 // If a friend function template declaration specifies a default
2213 // template-argument, that declaration shall be a definition and shall be
2214 // the only declaration of the function template in the translation unit.
2215 // (C++98/03 doesn't have this wording; see DR226).
2216 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2217 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2218 : diag::ext_template_parameter_default_in_function_template)
2219 << DefArgRange;
2220 return false;
2222 case Sema::TPC_ClassTemplateMember:
2223 // C++0x [temp.param]p9:
2224 // A default template-argument shall not be specified in the
2225 // template-parameter-lists of the definition of a member of a
2226 // class template that appears outside of the member's class.
2227 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2228 << DefArgRange;
2229 return true;
2231 case Sema::TPC_FriendClassTemplate:
2232 case Sema::TPC_FriendFunctionTemplate:
2233 // C++ [temp.param]p9:
2234 // A default template-argument shall not be specified in a
2235 // friend template declaration.
2236 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2237 << DefArgRange;
2238 return true;
2240 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2241 // for friend function templates if there is only a single
2242 // declaration (and it is a definition). Strange!
2245 llvm_unreachable("Invalid TemplateParamListContext!");
2248 /// Check for unexpanded parameter packs within the template parameters
2249 /// of a template template parameter, recursively.
2250 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2251 TemplateTemplateParmDecl *TTP) {
2252 // A template template parameter which is a parameter pack is also a pack
2253 // expansion.
2254 if (TTP->isParameterPack())
2255 return false;
2257 TemplateParameterList *Params = TTP->getTemplateParameters();
2258 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2259 NamedDecl *P = Params->getParam(I);
2260 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2261 if (!TTP->isParameterPack())
2262 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2263 if (TC->hasExplicitTemplateArgs())
2264 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2265 if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
2266 Sema::UPPC_TypeConstraint))
2267 return true;
2268 continue;
2271 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2272 if (!NTTP->isParameterPack() &&
2273 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2274 NTTP->getTypeSourceInfo(),
2275 Sema::UPPC_NonTypeTemplateParameterType))
2276 return true;
2278 continue;
2281 if (TemplateTemplateParmDecl *InnerTTP
2282 = dyn_cast<TemplateTemplateParmDecl>(P))
2283 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2284 return true;
2287 return false;
2290 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2291 TemplateParameterList *OldParams,
2292 TemplateParamListContext TPC,
2293 SkipBodyInfo *SkipBody) {
2294 bool Invalid = false;
2296 // C++ [temp.param]p10:
2297 // The set of default template-arguments available for use with a
2298 // template declaration or definition is obtained by merging the
2299 // default arguments from the definition (if in scope) and all
2300 // declarations in scope in the same way default function
2301 // arguments are (8.3.6).
2302 bool SawDefaultArgument = false;
2303 SourceLocation PreviousDefaultArgLoc;
2305 // Dummy initialization to avoid warnings.
2306 TemplateParameterList::iterator OldParam = NewParams->end();
2307 if (OldParams)
2308 OldParam = OldParams->begin();
2310 bool RemoveDefaultArguments = false;
2311 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2312 NewParamEnd = NewParams->end();
2313 NewParam != NewParamEnd; ++NewParam) {
2314 // Whether we've seen a duplicate default argument in the same translation
2315 // unit.
2316 bool RedundantDefaultArg = false;
2317 // Whether we've found inconsis inconsitent default arguments in different
2318 // translation unit.
2319 bool InconsistentDefaultArg = false;
2320 // The name of the module which contains the inconsistent default argument.
2321 std::string PrevModuleName;
2323 SourceLocation OldDefaultLoc;
2324 SourceLocation NewDefaultLoc;
2326 // Variable used to diagnose missing default arguments
2327 bool MissingDefaultArg = false;
2329 // Variable used to diagnose non-final parameter packs
2330 bool SawParameterPack = false;
2332 if (TemplateTypeParmDecl *NewTypeParm
2333 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2334 // Check the presence of a default argument here.
2335 if (NewTypeParm->hasDefaultArgument() &&
2336 DiagnoseDefaultTemplateArgument(
2337 *this, TPC, NewTypeParm->getLocation(),
2338 NewTypeParm->getDefaultArgument().getSourceRange()))
2339 NewTypeParm->removeDefaultArgument();
2341 // Merge default arguments for template type parameters.
2342 TemplateTypeParmDecl *OldTypeParm
2343 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2344 if (NewTypeParm->isParameterPack()) {
2345 assert(!NewTypeParm->hasDefaultArgument() &&
2346 "Parameter packs can't have a default argument!");
2347 SawParameterPack = true;
2348 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2349 NewTypeParm->hasDefaultArgument() &&
2350 (!SkipBody || !SkipBody->ShouldSkip)) {
2351 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2352 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2353 SawDefaultArgument = true;
2355 if (!OldTypeParm->getOwningModule())
2356 RedundantDefaultArg = true;
2357 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2358 NewTypeParm)) {
2359 InconsistentDefaultArg = true;
2360 PrevModuleName =
2361 OldTypeParm->getImportedOwningModule()->getFullModuleName();
2363 PreviousDefaultArgLoc = NewDefaultLoc;
2364 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2365 // Merge the default argument from the old declaration to the
2366 // new declaration.
2367 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2368 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2369 } else if (NewTypeParm->hasDefaultArgument()) {
2370 SawDefaultArgument = true;
2371 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2372 } else if (SawDefaultArgument)
2373 MissingDefaultArg = true;
2374 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2375 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2376 // Check for unexpanded parameter packs.
2377 if (!NewNonTypeParm->isParameterPack() &&
2378 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2379 NewNonTypeParm->getTypeSourceInfo(),
2380 UPPC_NonTypeTemplateParameterType)) {
2381 Invalid = true;
2382 continue;
2385 // Check the presence of a default argument here.
2386 if (NewNonTypeParm->hasDefaultArgument() &&
2387 DiagnoseDefaultTemplateArgument(
2388 *this, TPC, NewNonTypeParm->getLocation(),
2389 NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2390 NewNonTypeParm->removeDefaultArgument();
2393 // Merge default arguments for non-type template parameters
2394 NonTypeTemplateParmDecl *OldNonTypeParm
2395 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2396 if (NewNonTypeParm->isParameterPack()) {
2397 assert(!NewNonTypeParm->hasDefaultArgument() &&
2398 "Parameter packs can't have a default argument!");
2399 if (!NewNonTypeParm->isPackExpansion())
2400 SawParameterPack = true;
2401 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2402 NewNonTypeParm->hasDefaultArgument() &&
2403 (!SkipBody || !SkipBody->ShouldSkip)) {
2404 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2405 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2406 SawDefaultArgument = true;
2407 if (!OldNonTypeParm->getOwningModule())
2408 RedundantDefaultArg = true;
2409 else if (!getASTContext().isSameDefaultTemplateArgument(
2410 OldNonTypeParm, NewNonTypeParm)) {
2411 InconsistentDefaultArg = true;
2412 PrevModuleName =
2413 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2415 PreviousDefaultArgLoc = NewDefaultLoc;
2416 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2417 // Merge the default argument from the old declaration to the
2418 // new declaration.
2419 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2420 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2421 } else if (NewNonTypeParm->hasDefaultArgument()) {
2422 SawDefaultArgument = true;
2423 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2424 } else if (SawDefaultArgument)
2425 MissingDefaultArg = true;
2426 } else {
2427 TemplateTemplateParmDecl *NewTemplateParm
2428 = cast<TemplateTemplateParmDecl>(*NewParam);
2430 // Check for unexpanded parameter packs, recursively.
2431 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2432 Invalid = true;
2433 continue;
2436 // Check the presence of a default argument here.
2437 if (NewTemplateParm->hasDefaultArgument() &&
2438 DiagnoseDefaultTemplateArgument(*this, TPC,
2439 NewTemplateParm->getLocation(),
2440 NewTemplateParm->getDefaultArgument().getSourceRange()))
2441 NewTemplateParm->removeDefaultArgument();
2443 // Merge default arguments for template template parameters
2444 TemplateTemplateParmDecl *OldTemplateParm
2445 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2446 if (NewTemplateParm->isParameterPack()) {
2447 assert(!NewTemplateParm->hasDefaultArgument() &&
2448 "Parameter packs can't have a default argument!");
2449 if (!NewTemplateParm->isPackExpansion())
2450 SawParameterPack = true;
2451 } else if (OldTemplateParm &&
2452 hasVisibleDefaultArgument(OldTemplateParm) &&
2453 NewTemplateParm->hasDefaultArgument() &&
2454 (!SkipBody || !SkipBody->ShouldSkip)) {
2455 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2456 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2457 SawDefaultArgument = true;
2458 if (!OldTemplateParm->getOwningModule())
2459 RedundantDefaultArg = true;
2460 else if (!getASTContext().isSameDefaultTemplateArgument(
2461 OldTemplateParm, NewTemplateParm)) {
2462 InconsistentDefaultArg = true;
2463 PrevModuleName =
2464 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2466 PreviousDefaultArgLoc = NewDefaultLoc;
2467 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2468 // Merge the default argument from the old declaration to the
2469 // new declaration.
2470 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2471 PreviousDefaultArgLoc
2472 = OldTemplateParm->getDefaultArgument().getLocation();
2473 } else if (NewTemplateParm->hasDefaultArgument()) {
2474 SawDefaultArgument = true;
2475 PreviousDefaultArgLoc
2476 = NewTemplateParm->getDefaultArgument().getLocation();
2477 } else if (SawDefaultArgument)
2478 MissingDefaultArg = true;
2481 // C++11 [temp.param]p11:
2482 // If a template parameter of a primary class template or alias template
2483 // is a template parameter pack, it shall be the last template parameter.
2484 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2485 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2486 TPC == TPC_TypeAliasTemplate)) {
2487 Diag((*NewParam)->getLocation(),
2488 diag::err_template_param_pack_must_be_last_template_parameter);
2489 Invalid = true;
2492 // [basic.def.odr]/13:
2493 // There can be more than one definition of a
2494 // ...
2495 // default template argument
2496 // ...
2497 // in a program provided that each definition appears in a different
2498 // translation unit and the definitions satisfy the [same-meaning
2499 // criteria of the ODR].
2501 // Simply, the design of modules allows the definition of template default
2502 // argument to be repeated across translation unit. Note that the ODR is
2503 // checked elsewhere. But it is still not allowed to repeat template default
2504 // argument in the same translation unit.
2505 if (RedundantDefaultArg) {
2506 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2507 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2508 Invalid = true;
2509 } else if (InconsistentDefaultArg) {
2510 // We could only diagnose about the case that the OldParam is imported.
2511 // The case NewParam is imported should be handled in ASTReader.
2512 Diag(NewDefaultLoc,
2513 diag::err_template_param_default_arg_inconsistent_redefinition);
2514 Diag(OldDefaultLoc,
2515 diag::note_template_param_prev_default_arg_in_other_module)
2516 << PrevModuleName;
2517 Invalid = true;
2518 } else if (MissingDefaultArg &&
2519 (TPC == TPC_ClassTemplate || TPC == TPC_FriendClassTemplate ||
2520 TPC == TPC_VarTemplate || TPC == TPC_TypeAliasTemplate)) {
2521 // C++ 23[temp.param]p14:
2522 // If a template-parameter of a class template, variable template, or
2523 // alias template has a default template argument, each subsequent
2524 // template-parameter shall either have a default template argument
2525 // supplied or be a template parameter pack.
2526 Diag((*NewParam)->getLocation(),
2527 diag::err_template_param_default_arg_missing);
2528 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2529 Invalid = true;
2530 RemoveDefaultArguments = true;
2533 // If we have an old template parameter list that we're merging
2534 // in, move on to the next parameter.
2535 if (OldParams)
2536 ++OldParam;
2539 // We were missing some default arguments at the end of the list, so remove
2540 // all of the default arguments.
2541 if (RemoveDefaultArguments) {
2542 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2543 NewParamEnd = NewParams->end();
2544 NewParam != NewParamEnd; ++NewParam) {
2545 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2546 TTP->removeDefaultArgument();
2547 else if (NonTypeTemplateParmDecl *NTTP
2548 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2549 NTTP->removeDefaultArgument();
2550 else
2551 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2555 return Invalid;
2558 namespace {
2560 /// A class which looks for a use of a certain level of template
2561 /// parameter.
2562 struct DependencyChecker : DynamicRecursiveASTVisitor {
2563 unsigned Depth;
2565 // Whether we're looking for a use of a template parameter that makes the
2566 // overall construct type-dependent / a dependent type. This is strictly
2567 // best-effort for now; we may fail to match at all for a dependent type
2568 // in some cases if this is set.
2569 bool IgnoreNonTypeDependent;
2571 bool Match;
2572 SourceLocation MatchLoc;
2574 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2575 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2576 Match(false) {}
2578 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2579 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2580 NamedDecl *ND = Params->getParam(0);
2581 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2582 Depth = PD->getDepth();
2583 } else if (NonTypeTemplateParmDecl *PD =
2584 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2585 Depth = PD->getDepth();
2586 } else {
2587 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2591 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2592 if (ParmDepth >= Depth) {
2593 Match = true;
2594 MatchLoc = Loc;
2595 return true;
2597 return false;
2600 bool TraverseStmt(Stmt *S) override {
2601 // Prune out non-type-dependent expressions if requested. This can
2602 // sometimes result in us failing to find a template parameter reference
2603 // (if a value-dependent expression creates a dependent type), but this
2604 // mode is best-effort only.
2605 if (auto *E = dyn_cast_or_null<Expr>(S))
2606 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2607 return true;
2608 return DynamicRecursiveASTVisitor::TraverseStmt(S);
2611 bool TraverseTypeLoc(TypeLoc TL) override {
2612 if (IgnoreNonTypeDependent && !TL.isNull() &&
2613 !TL.getType()->isDependentType())
2614 return true;
2615 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL);
2618 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2619 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2622 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2623 // For a best-effort search, keep looking until we find a location.
2624 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2627 bool TraverseTemplateName(TemplateName N) override {
2628 if (TemplateTemplateParmDecl *PD =
2629 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2630 if (Matches(PD->getDepth()))
2631 return false;
2632 return DynamicRecursiveASTVisitor::TraverseTemplateName(N);
2635 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2636 if (NonTypeTemplateParmDecl *PD =
2637 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2638 if (Matches(PD->getDepth(), E->getExprLoc()))
2639 return false;
2640 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);
2643 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2644 return TraverseType(T->getReplacementType());
2647 bool VisitSubstTemplateTypeParmPackType(
2648 SubstTemplateTypeParmPackType *T) override {
2649 return TraverseTemplateArgument(T->getArgumentPack());
2652 bool TraverseInjectedClassNameType(InjectedClassNameType *T) override {
2653 return TraverseType(T->getInjectedSpecializationType());
2656 } // end anonymous namespace
2658 /// Determines whether a given type depends on the given parameter
2659 /// list.
2660 static bool
2661 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2662 if (!Params->size())
2663 return false;
2665 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2666 Checker.TraverseType(T);
2667 return Checker.Match;
2670 // Find the source range corresponding to the named type in the given
2671 // nested-name-specifier, if any.
2672 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2673 QualType T,
2674 const CXXScopeSpec &SS) {
2675 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2676 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2677 if (const Type *CurType = NNS->getAsType()) {
2678 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2679 return NNSLoc.getTypeLoc().getSourceRange();
2680 } else
2681 break;
2683 NNSLoc = NNSLoc.getPrefix();
2686 return SourceRange();
2689 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2690 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2691 TemplateIdAnnotation *TemplateId,
2692 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2693 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2694 IsMemberSpecialization = false;
2695 Invalid = false;
2697 // The sequence of nested types to which we will match up the template
2698 // parameter lists. We first build this list by starting with the type named
2699 // by the nested-name-specifier and walking out until we run out of types.
2700 SmallVector<QualType, 4> NestedTypes;
2701 QualType T;
2702 if (SS.getScopeRep()) {
2703 if (CXXRecordDecl *Record
2704 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2705 T = Context.getTypeDeclType(Record);
2706 else
2707 T = QualType(SS.getScopeRep()->getAsType(), 0);
2710 // If we found an explicit specialization that prevents us from needing
2711 // 'template<>' headers, this will be set to the location of that
2712 // explicit specialization.
2713 SourceLocation ExplicitSpecLoc;
2715 while (!T.isNull()) {
2716 NestedTypes.push_back(T);
2718 // Retrieve the parent of a record type.
2719 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2720 // If this type is an explicit specialization, we're done.
2721 if (ClassTemplateSpecializationDecl *Spec
2722 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2723 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2724 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2725 ExplicitSpecLoc = Spec->getLocation();
2726 break;
2728 } else if (Record->getTemplateSpecializationKind()
2729 == TSK_ExplicitSpecialization) {
2730 ExplicitSpecLoc = Record->getLocation();
2731 break;
2734 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2735 T = Context.getTypeDeclType(Parent);
2736 else
2737 T = QualType();
2738 continue;
2741 if (const TemplateSpecializationType *TST
2742 = T->getAs<TemplateSpecializationType>()) {
2743 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2744 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2745 T = Context.getTypeDeclType(Parent);
2746 else
2747 T = QualType();
2748 continue;
2752 // Look one step prior in a dependent template specialization type.
2753 if (const DependentTemplateSpecializationType *DependentTST
2754 = T->getAs<DependentTemplateSpecializationType>()) {
2755 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2756 T = QualType(NNS->getAsType(), 0);
2757 else
2758 T = QualType();
2759 continue;
2762 // Look one step prior in a dependent name type.
2763 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2764 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2765 T = QualType(NNS->getAsType(), 0);
2766 else
2767 T = QualType();
2768 continue;
2771 // Retrieve the parent of an enumeration type.
2772 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2773 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2774 // check here.
2775 EnumDecl *Enum = EnumT->getDecl();
2777 // Get to the parent type.
2778 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2779 T = Context.getTypeDeclType(Parent);
2780 else
2781 T = QualType();
2782 continue;
2785 T = QualType();
2787 // Reverse the nested types list, since we want to traverse from the outermost
2788 // to the innermost while checking template-parameter-lists.
2789 std::reverse(NestedTypes.begin(), NestedTypes.end());
2791 // C++0x [temp.expl.spec]p17:
2792 // A member or a member template may be nested within many
2793 // enclosing class templates. In an explicit specialization for
2794 // such a member, the member declaration shall be preceded by a
2795 // template<> for each enclosing class template that is
2796 // explicitly specialized.
2797 bool SawNonEmptyTemplateParameterList = false;
2799 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2800 if (SawNonEmptyTemplateParameterList) {
2801 if (!SuppressDiagnostic)
2802 Diag(DeclLoc, diag::err_specialize_member_of_template)
2803 << !Recovery << Range;
2804 Invalid = true;
2805 IsMemberSpecialization = false;
2806 return true;
2809 return false;
2812 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2813 // Check that we can have an explicit specialization here.
2814 if (CheckExplicitSpecialization(Range, true))
2815 return true;
2817 // We don't have a template header, but we should.
2818 SourceLocation ExpectedTemplateLoc;
2819 if (!ParamLists.empty())
2820 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2821 else
2822 ExpectedTemplateLoc = DeclStartLoc;
2824 if (!SuppressDiagnostic)
2825 Diag(DeclLoc, diag::err_template_spec_needs_header)
2826 << Range
2827 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2828 return false;
2831 unsigned ParamIdx = 0;
2832 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2833 ++TypeIdx) {
2834 T = NestedTypes[TypeIdx];
2836 // Whether we expect a 'template<>' header.
2837 bool NeedEmptyTemplateHeader = false;
2839 // Whether we expect a template header with parameters.
2840 bool NeedNonemptyTemplateHeader = false;
2842 // For a dependent type, the set of template parameters that we
2843 // expect to see.
2844 TemplateParameterList *ExpectedTemplateParams = nullptr;
2846 // C++0x [temp.expl.spec]p15:
2847 // A member or a member template may be nested within many enclosing
2848 // class templates. In an explicit specialization for such a member, the
2849 // member declaration shall be preceded by a template<> for each
2850 // enclosing class template that is explicitly specialized.
2851 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2852 if (ClassTemplatePartialSpecializationDecl *Partial
2853 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2854 ExpectedTemplateParams = Partial->getTemplateParameters();
2855 NeedNonemptyTemplateHeader = true;
2856 } else if (Record->isDependentType()) {
2857 if (Record->getDescribedClassTemplate()) {
2858 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2859 ->getTemplateParameters();
2860 NeedNonemptyTemplateHeader = true;
2862 } else if (ClassTemplateSpecializationDecl *Spec
2863 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2864 // C++0x [temp.expl.spec]p4:
2865 // Members of an explicitly specialized class template are defined
2866 // in the same manner as members of normal classes, and not using
2867 // the template<> syntax.
2868 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2869 NeedEmptyTemplateHeader = true;
2870 else
2871 continue;
2872 } else if (Record->getTemplateSpecializationKind()) {
2873 if (Record->getTemplateSpecializationKind()
2874 != TSK_ExplicitSpecialization &&
2875 TypeIdx == NumTypes - 1)
2876 IsMemberSpecialization = true;
2878 continue;
2880 } else if (const TemplateSpecializationType *TST
2881 = T->getAs<TemplateSpecializationType>()) {
2882 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2883 ExpectedTemplateParams = Template->getTemplateParameters();
2884 NeedNonemptyTemplateHeader = true;
2886 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2887 // FIXME: We actually could/should check the template arguments here
2888 // against the corresponding template parameter list.
2889 NeedNonemptyTemplateHeader = false;
2892 // C++ [temp.expl.spec]p16:
2893 // In an explicit specialization declaration for a member of a class
2894 // template or a member template that appears in namespace scope, the
2895 // member template and some of its enclosing class templates may remain
2896 // unspecialized, except that the declaration shall not explicitly
2897 // specialize a class member template if its enclosing class templates
2898 // are not explicitly specialized as well.
2899 if (ParamIdx < ParamLists.size()) {
2900 if (ParamLists[ParamIdx]->size() == 0) {
2901 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2902 false))
2903 return nullptr;
2904 } else
2905 SawNonEmptyTemplateParameterList = true;
2908 if (NeedEmptyTemplateHeader) {
2909 // If we're on the last of the types, and we need a 'template<>' header
2910 // here, then it's a member specialization.
2911 if (TypeIdx == NumTypes - 1)
2912 IsMemberSpecialization = true;
2914 if (ParamIdx < ParamLists.size()) {
2915 if (ParamLists[ParamIdx]->size() > 0) {
2916 // The header has template parameters when it shouldn't. Complain.
2917 if (!SuppressDiagnostic)
2918 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2919 diag::err_template_param_list_matches_nontemplate)
2920 << T
2921 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2922 ParamLists[ParamIdx]->getRAngleLoc())
2923 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2924 Invalid = true;
2925 return nullptr;
2928 // Consume this template header.
2929 ++ParamIdx;
2930 continue;
2933 if (!IsFriend)
2934 if (DiagnoseMissingExplicitSpecialization(
2935 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2936 return nullptr;
2938 continue;
2941 if (NeedNonemptyTemplateHeader) {
2942 // In friend declarations we can have template-ids which don't
2943 // depend on the corresponding template parameter lists. But
2944 // assume that empty parameter lists are supposed to match this
2945 // template-id.
2946 if (IsFriend && T->isDependentType()) {
2947 if (ParamIdx < ParamLists.size() &&
2948 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2949 ExpectedTemplateParams = nullptr;
2950 else
2951 continue;
2954 if (ParamIdx < ParamLists.size()) {
2955 // Check the template parameter list, if we can.
2956 if (ExpectedTemplateParams &&
2957 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2958 ExpectedTemplateParams,
2959 !SuppressDiagnostic, TPL_TemplateMatch))
2960 Invalid = true;
2962 if (!Invalid &&
2963 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2964 TPC_ClassTemplateMember))
2965 Invalid = true;
2967 ++ParamIdx;
2968 continue;
2971 if (!SuppressDiagnostic)
2972 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2973 << T
2974 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2975 Invalid = true;
2976 continue;
2980 // If there were at least as many template-ids as there were template
2981 // parameter lists, then there are no template parameter lists remaining for
2982 // the declaration itself.
2983 if (ParamIdx >= ParamLists.size()) {
2984 if (TemplateId && !IsFriend) {
2985 // We don't have a template header for the declaration itself, but we
2986 // should.
2987 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2988 TemplateId->RAngleLoc));
2990 // Fabricate an empty template parameter list for the invented header.
2991 return TemplateParameterList::Create(Context, SourceLocation(),
2992 SourceLocation(), {},
2993 SourceLocation(), nullptr);
2996 return nullptr;
2999 // If there were too many template parameter lists, complain about that now.
3000 if (ParamIdx < ParamLists.size() - 1) {
3001 bool HasAnyExplicitSpecHeader = false;
3002 bool AllExplicitSpecHeaders = true;
3003 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3004 if (ParamLists[I]->size() == 0)
3005 HasAnyExplicitSpecHeader = true;
3006 else
3007 AllExplicitSpecHeaders = false;
3010 if (!SuppressDiagnostic)
3011 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3012 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3013 : diag::err_template_spec_extra_headers)
3014 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3015 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3017 // If there was a specialization somewhere, such that 'template<>' is
3018 // not required, and there were any 'template<>' headers, note where the
3019 // specialization occurred.
3020 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3021 !SuppressDiagnostic)
3022 Diag(ExplicitSpecLoc,
3023 diag::note_explicit_template_spec_does_not_need_header)
3024 << NestedTypes.back();
3026 // We have a template parameter list with no corresponding scope, which
3027 // means that the resulting template declaration can't be instantiated
3028 // properly (we'll end up with dependent nodes when we shouldn't).
3029 if (!AllExplicitSpecHeaders)
3030 Invalid = true;
3033 // C++ [temp.expl.spec]p16:
3034 // In an explicit specialization declaration for a member of a class
3035 // template or a member template that ap- pears in namespace scope, the
3036 // member template and some of its enclosing class templates may remain
3037 // unspecialized, except that the declaration shall not explicitly
3038 // specialize a class member template if its en- closing class templates
3039 // are not explicitly specialized as well.
3040 if (ParamLists.back()->size() == 0 &&
3041 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3042 false))
3043 return nullptr;
3045 // Return the last template parameter list, which corresponds to the
3046 // entity being declared.
3047 return ParamLists.back();
3050 void Sema::NoteAllFoundTemplates(TemplateName Name) {
3051 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3052 Diag(Template->getLocation(), diag::note_template_declared_here)
3053 << (isa<FunctionTemplateDecl>(Template)
3055 : isa<ClassTemplateDecl>(Template)
3057 : isa<VarTemplateDecl>(Template)
3059 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3060 << Template->getDeclName();
3061 return;
3064 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3065 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3066 IEnd = OST->end();
3067 I != IEnd; ++I)
3068 Diag((*I)->getLocation(), diag::note_template_declared_here)
3069 << 0 << (*I)->getDeclName();
3071 return;
3075 static QualType builtinCommonTypeImpl(Sema &S, TemplateName BaseTemplate,
3076 SourceLocation TemplateLoc,
3077 ArrayRef<TemplateArgument> Ts) {
3078 auto lookUpCommonType = [&](TemplateArgument T1,
3079 TemplateArgument T2) -> QualType {
3080 // Don't bother looking for other specializations if both types are
3081 // builtins - users aren't allowed to specialize for them
3082 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3083 return builtinCommonTypeImpl(S, BaseTemplate, TemplateLoc, {T1, T2});
3085 TemplateArgumentListInfo Args;
3086 Args.addArgument(TemplateArgumentLoc(
3087 T1, S.Context.getTrivialTypeSourceInfo(T1.getAsType())));
3088 Args.addArgument(TemplateArgumentLoc(
3089 T2, S.Context.getTrivialTypeSourceInfo(T2.getAsType())));
3091 EnterExpressionEvaluationContext UnevaluatedContext(
3092 S, Sema::ExpressionEvaluationContext::Unevaluated);
3093 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3094 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3096 QualType BaseTemplateInst =
3097 S.CheckTemplateIdType(BaseTemplate, TemplateLoc, Args);
3099 if (SFINAE.hasErrorOccurred())
3100 return QualType();
3102 return BaseTemplateInst;
3105 // Note A: For the common_type trait applied to a template parameter pack T of
3106 // types, the member type shall be either defined or not present as follows:
3107 switch (Ts.size()) {
3109 // If sizeof...(T) is zero, there shall be no member type.
3110 case 0:
3111 return QualType();
3113 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3114 // pack T. The member typedef-name type shall denote the same type, if any, as
3115 // common_type_t<T0, T0>; otherwise there shall be no member type.
3116 case 1:
3117 return lookUpCommonType(Ts[0], Ts[0]);
3119 // If sizeof...(T) is two, let the first and second types constituting T be
3120 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3121 // as decay_t<T1> and decay_t<T2>, respectively.
3122 case 2: {
3123 QualType T1 = Ts[0].getAsType();
3124 QualType T2 = Ts[1].getAsType();
3125 QualType D1 = S.BuiltinDecay(T1, {});
3126 QualType D2 = S.BuiltinDecay(T2, {});
3128 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3129 // the same type, if any, as common_type_t<D1, D2>.
3130 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))
3131 return lookUpCommonType(D1, D2);
3133 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3134 // denotes a valid type, let C denote that type.
3136 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3137 EnterExpressionEvaluationContext UnevaluatedContext(
3138 S, Sema::ExpressionEvaluationContext::Unevaluated);
3139 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3140 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3142 // false
3143 OpaqueValueExpr CondExpr(SourceLocation(), S.Context.BoolTy,
3144 VK_PRValue);
3145 ExprResult Cond = &CondExpr;
3147 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3148 if (ConstRefQual) {
3149 D1.addConst();
3150 D2.addConst();
3153 // declval<D1>()
3154 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3155 ExprResult LHS = &LHSExpr;
3157 // declval<D2>()
3158 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3159 ExprResult RHS = &RHSExpr;
3161 ExprValueKind VK = VK_PRValue;
3162 ExprObjectKind OK = OK_Ordinary;
3164 // decltype(false ? declval<D1>() : declval<D2>())
3165 QualType Result =
3166 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);
3168 if (Result.isNull() || SFINAE.hasErrorOccurred())
3169 return QualType();
3171 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3172 return S.BuiltinDecay(Result, TemplateLoc);
3175 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3176 return Res;
3178 // Let:
3179 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3180 // COND-RES(X, Y) be
3181 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3183 // C++20 only
3184 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3185 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3186 if (!S.Context.getLangOpts().CPlusPlus20)
3187 return QualType();
3188 return CheckConditionalOperands(true);
3192 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3193 // denote the first, second, and (pack of) remaining types constituting T. Let
3194 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3195 // a type C, the member typedef-name type shall denote the same type, if any,
3196 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3197 default: {
3198 QualType Result = Ts.front().getAsType();
3199 for (auto T : llvm::drop_begin(Ts)) {
3200 Result = lookUpCommonType(Result, T.getAsType());
3201 if (Result.isNull())
3202 return QualType();
3204 return Result;
3209 static QualType
3210 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3211 ArrayRef<TemplateArgument> Converted,
3212 SourceLocation TemplateLoc,
3213 TemplateArgumentListInfo &TemplateArgs) {
3214 ASTContext &Context = SemaRef.getASTContext();
3216 switch (BTD->getBuiltinTemplateKind()) {
3217 case BTK__make_integer_seq: {
3218 // Specializations of __make_integer_seq<S, T, N> are treated like
3219 // S<T, 0, ..., N-1>.
3221 QualType OrigType = Converted[1].getAsType();
3222 // C++14 [inteseq.intseq]p1:
3223 // T shall be an integer type.
3224 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3225 SemaRef.Diag(TemplateArgs[1].getLocation(),
3226 diag::err_integer_sequence_integral_element_type);
3227 return QualType();
3230 TemplateArgument NumArgsArg = Converted[2];
3231 if (NumArgsArg.isDependent())
3232 return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
3233 Converted);
3235 TemplateArgumentListInfo SyntheticTemplateArgs;
3236 // The type argument, wrapped in substitution sugar, gets reused as the
3237 // first template argument in the synthetic template argument list.
3238 SyntheticTemplateArgs.addArgument(
3239 TemplateArgumentLoc(TemplateArgument(OrigType),
3240 SemaRef.Context.getTrivialTypeSourceInfo(
3241 OrigType, TemplateArgs[1].getLocation())));
3243 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3244 // Expand N into 0 ... N-1.
3245 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3246 I < NumArgs; ++I) {
3247 TemplateArgument TA(Context, I, OrigType);
3248 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3249 TA, OrigType, TemplateArgs[2].getLocation()));
3251 } else {
3252 // C++14 [inteseq.make]p1:
3253 // If N is negative the program is ill-formed.
3254 SemaRef.Diag(TemplateArgs[2].getLocation(),
3255 diag::err_integer_sequence_negative_length);
3256 return QualType();
3259 // The first template argument will be reused as the template decl that
3260 // our synthetic template arguments will be applied to.
3261 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3262 TemplateLoc, SyntheticTemplateArgs);
3265 case BTK__type_pack_element: {
3266 // Specializations of
3267 // __type_pack_element<Index, T_1, ..., T_N>
3268 // are treated like T_Index.
3269 assert(Converted.size() == 2 &&
3270 "__type_pack_element should be given an index and a parameter pack");
3272 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3273 if (IndexArg.isDependent() || Ts.isDependent())
3274 return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
3275 Converted);
3277 llvm::APSInt Index = IndexArg.getAsIntegral();
3278 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3279 "type std::size_t, and hence be non-negative");
3280 // If the Index is out of bounds, the program is ill-formed.
3281 if (Index >= Ts.pack_size()) {
3282 SemaRef.Diag(TemplateArgs[0].getLocation(),
3283 diag::err_type_pack_element_out_of_bounds);
3284 return QualType();
3287 // We simply return the type at index `Index`.
3288 int64_t N = Index.getExtValue();
3289 return Ts.getPackAsArray()[N].getAsType();
3292 case BTK__builtin_common_type: {
3293 assert(Converted.size() == 4);
3294 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))
3295 return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD),
3296 Converted);
3298 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3299 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3300 QualType HasNoTypeMember = Converted[2].getAsType();
3301 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3302 if (auto CT = builtinCommonTypeImpl(SemaRef, BaseTemplate, TemplateLoc, Ts);
3303 !CT.isNull()) {
3304 TemplateArgumentListInfo TAs;
3305 TAs.addArgument(TemplateArgumentLoc(
3306 TemplateArgument(CT), SemaRef.Context.getTrivialTypeSourceInfo(
3307 CT, TemplateArgs[1].getLocation())));
3309 return SemaRef.CheckTemplateIdType(HasTypeMember, TemplateLoc, TAs);
3311 return HasNoTypeMember;
3314 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3317 /// Determine whether this alias template is "enable_if_t".
3318 /// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3319 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3320 return AliasTemplate->getName() == "enable_if_t" ||
3321 AliasTemplate->getName() == "__enable_if_t";
3324 /// Collect all of the separable terms in the given condition, which
3325 /// might be a conjunction.
3327 /// FIXME: The right answer is to convert the logical expression into
3328 /// disjunctive normal form, so we can find the first failed term
3329 /// within each possible clause.
3330 static void collectConjunctionTerms(Expr *Clause,
3331 SmallVectorImpl<Expr *> &Terms) {
3332 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3333 if (BinOp->getOpcode() == BO_LAnd) {
3334 collectConjunctionTerms(BinOp->getLHS(), Terms);
3335 collectConjunctionTerms(BinOp->getRHS(), Terms);
3336 return;
3340 Terms.push_back(Clause);
3343 // The ranges-v3 library uses an odd pattern of a top-level "||" with
3344 // a left-hand side that is value-dependent but never true. Identify
3345 // the idiom and ignore that term.
3346 static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3347 // Top-level '||'.
3348 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3349 if (!BinOp) return Cond;
3351 if (BinOp->getOpcode() != BO_LOr) return Cond;
3353 // With an inner '==' that has a literal on the right-hand side.
3354 Expr *LHS = BinOp->getLHS();
3355 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3356 if (!InnerBinOp) return Cond;
3358 if (InnerBinOp->getOpcode() != BO_EQ ||
3359 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3360 return Cond;
3362 // If the inner binary operation came from a macro expansion named
3363 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3364 // of the '||', which is the real, user-provided condition.
3365 SourceLocation Loc = InnerBinOp->getExprLoc();
3366 if (!Loc.isMacroID()) return Cond;
3368 StringRef MacroName = PP.getImmediateMacroName(Loc);
3369 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3370 return BinOp->getRHS();
3372 return Cond;
3375 namespace {
3377 // A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3378 // within failing boolean expression, such as substituting template parameters
3379 // for actual types.
3380 class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3381 public:
3382 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3383 : Policy(P) {}
3385 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3386 const auto *DR = dyn_cast<DeclRefExpr>(E);
3387 if (DR && DR->getQualifier()) {
3388 // If this is a qualified name, expand the template arguments in nested
3389 // qualifiers.
3390 DR->getQualifier()->print(OS, Policy, true);
3391 // Then print the decl itself.
3392 const ValueDecl *VD = DR->getDecl();
3393 OS << VD->getName();
3394 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3395 // This is a template variable, print the expanded template arguments.
3396 printTemplateArgumentList(
3397 OS, IV->getTemplateArgs().asArray(), Policy,
3398 IV->getSpecializedTemplate()->getTemplateParameters());
3400 return true;
3402 return false;
3405 private:
3406 const PrintingPolicy Policy;
3409 } // end anonymous namespace
3411 std::pair<Expr *, std::string>
3412 Sema::findFailedBooleanCondition(Expr *Cond) {
3413 Cond = lookThroughRangesV3Condition(PP, Cond);
3415 // Separate out all of the terms in a conjunction.
3416 SmallVector<Expr *, 4> Terms;
3417 collectConjunctionTerms(Cond, Terms);
3419 // Determine which term failed.
3420 Expr *FailedCond = nullptr;
3421 for (Expr *Term : Terms) {
3422 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3424 // Literals are uninteresting.
3425 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3426 isa<IntegerLiteral>(TermAsWritten))
3427 continue;
3429 // The initialization of the parameter from the argument is
3430 // a constant-evaluated context.
3431 EnterExpressionEvaluationContext ConstantEvaluated(
3432 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3434 bool Succeeded;
3435 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3436 !Succeeded) {
3437 FailedCond = TermAsWritten;
3438 break;
3441 if (!FailedCond)
3442 FailedCond = Cond->IgnoreParenImpCasts();
3444 std::string Description;
3446 llvm::raw_string_ostream Out(Description);
3447 PrintingPolicy Policy = getPrintingPolicy();
3448 Policy.PrintCanonicalTypes = true;
3449 FailedBooleanConditionPrinterHelper Helper(Policy);
3450 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3452 return { FailedCond, Description };
3455 QualType Sema::CheckTemplateIdType(TemplateName Name,
3456 SourceLocation TemplateLoc,
3457 TemplateArgumentListInfo &TemplateArgs) {
3458 DependentTemplateName *DTN =
3459 Name.getUnderlying().getAsDependentTemplateName();
3460 if (DTN && DTN->isIdentifier())
3461 // When building a template-id where the template-name is dependent,
3462 // assume the template is a type template. Either our assumption is
3463 // correct, or the code is ill-formed and will be diagnosed when the
3464 // dependent name is substituted.
3465 return Context.getDependentTemplateSpecializationType(
3466 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
3467 TemplateArgs.arguments());
3469 if (Name.getAsAssumedTemplateName() &&
3470 resolveAssumedTemplateNameAsType(/*Scope=*/nullptr, Name, TemplateLoc))
3471 return QualType();
3473 auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3475 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3476 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3477 // We might have a substituted template template parameter pack. If so,
3478 // build a template specialization type for it.
3479 if (Name.getAsSubstTemplateTemplateParmPack())
3480 return Context.getTemplateSpecializationType(Name,
3481 TemplateArgs.arguments());
3483 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3484 << Name;
3485 NoteAllFoundTemplates(Name);
3486 return QualType();
3489 // Check that the template argument list is well-formed for this
3490 // template.
3491 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3492 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3493 DefaultArgs, false, SugaredConverted,
3494 CanonicalConverted,
3495 /*UpdateArgsWithConversions=*/true))
3496 return QualType();
3498 QualType CanonType;
3500 if (TypeAliasTemplateDecl *AliasTemplate =
3501 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3503 // Find the canonical type for this type alias template specialization.
3504 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3505 if (Pattern->isInvalidDecl())
3506 return QualType();
3508 // Only substitute for the innermost template argument list. NOTE: Some
3509 // external resugarers rely on leaving a Subst* node here. Make the
3510 // substitution non-final in that case. Note that these external resugarers
3511 // will still miss some information in this representation, because we don't
3512 // provide enough context in the Subst* nodes in order to tell different
3513 // template type alias specializations apart.
3514 MultiLevelTemplateArgumentList TemplateArgLists;
3515 TemplateArgLists.addOuterTemplateArguments(
3516 Template, SugaredConverted,
3517 /*Final=*/!getLangOpts().RetainSubstTemplateTypeParmTypeAstNodes);
3518 TemplateArgLists.addOuterRetainedLevels(
3519 AliasTemplate->getTemplateParameters()->getDepth());
3521 LocalInstantiationScope Scope(*this);
3522 InstantiatingTemplate Inst(
3523 *this, /*PointOfInstantiation=*/TemplateLoc,
3524 /*Entity=*/AliasTemplate,
3525 /*TemplateArgs=*/TemplateArgLists.getInnermost());
3527 // Diagnose uses of this alias.
3528 (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);
3530 if (Inst.isInvalid())
3531 return QualType();
3533 std::optional<ContextRAII> SavedContext;
3534 if (!AliasTemplate->getDeclContext()->isFileContext())
3535 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
3537 CanonType =
3538 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
3539 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
3540 if (CanonType.isNull()) {
3541 // If this was enable_if and we failed to find the nested type
3542 // within enable_if in a SFINAE context, dig out the specific
3543 // enable_if condition that failed and present that instead.
3544 if (isEnableIfAliasTemplate(AliasTemplate)) {
3545 if (auto DeductionInfo = isSFINAEContext()) {
3546 if (*DeductionInfo &&
3547 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3548 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3549 diag::err_typename_nested_not_found_enable_if &&
3550 TemplateArgs[0].getArgument().getKind()
3551 == TemplateArgument::Expression) {
3552 Expr *FailedCond;
3553 std::string FailedDescription;
3554 std::tie(FailedCond, FailedDescription) =
3555 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3557 // Remove the old SFINAE diagnostic.
3558 PartialDiagnosticAt OldDiag =
3559 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3560 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3562 // Add a new SFINAE diagnostic specifying which condition
3563 // failed.
3564 (*DeductionInfo)->addSFINAEDiagnostic(
3565 OldDiag.first,
3566 PDiag(diag::err_typename_nested_not_found_requirement)
3567 << FailedDescription
3568 << FailedCond->getSourceRange());
3573 return QualType();
3575 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3576 CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
3577 TemplateLoc, TemplateArgs);
3578 } else if (Name.isDependent() ||
3579 TemplateSpecializationType::anyDependentTemplateArguments(
3580 TemplateArgs, CanonicalConverted)) {
3581 // This class template specialization is a dependent
3582 // type. Therefore, its canonical type is another class template
3583 // specialization type that contains all of the converted
3584 // arguments in canonical form. This ensures that, e.g., A<T> and
3585 // A<T, T> have identical types when A is declared as:
3587 // template<typename T, typename U = T> struct A;
3588 CanonType = Context.getCanonicalTemplateSpecializationType(
3589 Name, CanonicalConverted);
3591 // This might work out to be a current instantiation, in which
3592 // case the canonical type needs to be the InjectedClassNameType.
3594 // TODO: in theory this could be a simple hashtable lookup; most
3595 // changes to CurContext don't change the set of current
3596 // instantiations.
3597 if (isa<ClassTemplateDecl>(Template)) {
3598 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3599 // If we get out to a namespace, we're done.
3600 if (Ctx->isFileContext()) break;
3602 // If this isn't a record, keep looking.
3603 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3604 if (!Record) continue;
3606 // Look for one of the two cases with InjectedClassNameTypes
3607 // and check whether it's the same template.
3608 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3609 !Record->getDescribedClassTemplate())
3610 continue;
3612 // Fetch the injected class name type and check whether its
3613 // injected type is equal to the type we just built.
3614 QualType ICNT = Context.getTypeDeclType(Record);
3615 QualType Injected = cast<InjectedClassNameType>(ICNT)
3616 ->getInjectedSpecializationType();
3618 if (CanonType != Injected->getCanonicalTypeInternal())
3619 continue;
3621 // If so, the canonical type of this TST is the injected
3622 // class name type of the record we just found.
3623 assert(ICNT.isCanonical());
3624 CanonType = ICNT;
3625 break;
3628 } else if (ClassTemplateDecl *ClassTemplate =
3629 dyn_cast<ClassTemplateDecl>(Template)) {
3630 // Find the class template specialization declaration that
3631 // corresponds to these arguments.
3632 void *InsertPos = nullptr;
3633 ClassTemplateSpecializationDecl *Decl =
3634 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3635 if (!Decl) {
3636 // This is the first time we have referenced this class template
3637 // specialization. Create the canonical declaration and add it to
3638 // the set of specializations.
3639 Decl = ClassTemplateSpecializationDecl::Create(
3640 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3641 ClassTemplate->getDeclContext(),
3642 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3643 ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
3644 nullptr);
3645 ClassTemplate->AddSpecialization(Decl, InsertPos);
3646 if (ClassTemplate->isOutOfLine())
3647 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3650 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3651 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3652 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3653 if (!Inst.isInvalid()) {
3654 MultiLevelTemplateArgumentList TemplateArgLists(Template,
3655 CanonicalConverted,
3656 /*Final=*/false);
3657 InstantiateAttrsForDecl(TemplateArgLists,
3658 ClassTemplate->getTemplatedDecl(), Decl);
3662 // Diagnose uses of this specialization.
3663 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3665 CanonType = Context.getTypeDeclType(Decl);
3666 assert(isa<RecordType>(CanonType) &&
3667 "type of non-dependent specialization is not a RecordType");
3668 } else {
3669 llvm_unreachable("Unhandled template kind");
3672 // Build the fully-sugared type for this class template
3673 // specialization, which refers back to the class template
3674 // specialization we created or found.
3675 return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
3676 CanonType);
3679 void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3680 TemplateNameKind &TNK,
3681 SourceLocation NameLoc,
3682 IdentifierInfo *&II) {
3683 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3685 TemplateName Name = ParsedName.get();
3686 auto *ATN = Name.getAsAssumedTemplateName();
3687 assert(ATN && "not an assumed template name");
3688 II = ATN->getDeclName().getAsIdentifierInfo();
3690 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3691 // Resolved to a type template name.
3692 ParsedName = TemplateTy::make(Name);
3693 TNK = TNK_Type_template;
3697 bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3698 SourceLocation NameLoc,
3699 bool Diagnose) {
3700 // We assumed this undeclared identifier to be an (ADL-only) function
3701 // template name, but it was used in a context where a type was required.
3702 // Try to typo-correct it now.
3703 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3704 assert(ATN && "not an assumed template name");
3706 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3707 struct CandidateCallback : CorrectionCandidateCallback {
3708 bool ValidateCandidate(const TypoCorrection &TC) override {
3709 return TC.getCorrectionDecl() &&
3710 getAsTypeTemplateDecl(TC.getCorrectionDecl());
3712 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3713 return std::make_unique<CandidateCallback>(*this);
3715 } FilterCCC;
3717 TypoCorrection Corrected =
3718 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3719 FilterCCC, CTK_ErrorRecovery);
3720 if (Corrected && Corrected.getFoundDecl()) {
3721 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3722 << ATN->getDeclName());
3723 Name = Context.getQualifiedTemplateName(
3724 /*NNS=*/nullptr, /*TemplateKeyword=*/false,
3725 TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()));
3726 return false;
3729 if (Diagnose)
3730 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3731 return true;
3734 TypeResult Sema::ActOnTemplateIdType(
3735 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3736 TemplateTy TemplateD, const IdentifierInfo *TemplateII,
3737 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3738 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3739 bool IsCtorOrDtorName, bool IsClassName,
3740 ImplicitTypenameContext AllowImplicitTypename) {
3741 if (SS.isInvalid())
3742 return true;
3744 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3745 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3747 // C++ [temp.res]p3:
3748 // A qualified-id that refers to a type and in which the
3749 // nested-name-specifier depends on a template-parameter (14.6.2)
3750 // shall be prefixed by the keyword typename to indicate that the
3751 // qualified-id denotes a type, forming an
3752 // elaborated-type-specifier (7.1.5.3).
3753 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3754 // C++2a relaxes some of those restrictions in [temp.res]p5.
3755 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
3756 if (getLangOpts().CPlusPlus20)
3757 Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
3758 else
3759 Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
3760 << SS.getScopeRep() << TemplateII->getName()
3761 << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
3762 } else
3763 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3764 << SS.getScopeRep() << TemplateII->getName();
3766 // FIXME: This is not quite correct recovery as we don't transform SS
3767 // into the corresponding dependent form (and we don't diagnose missing
3768 // 'template' keywords within SS as a result).
3769 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3770 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3771 TemplateArgsIn, RAngleLoc);
3774 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3775 // it's not actually allowed to be used as a type in most cases. Because
3776 // we annotate it before we know whether it's valid, we have to check for
3777 // this case here.
3778 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3779 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3780 Diag(TemplateIILoc,
3781 TemplateKWLoc.isInvalid()
3782 ? diag::err_out_of_line_qualified_id_type_names_constructor
3783 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3784 << TemplateII << 0 /*injected-class-name used as template name*/
3785 << 1 /*if any keyword was present, it was 'template'*/;
3789 TemplateName Template = TemplateD.get();
3790 if (Template.getAsAssumedTemplateName() &&
3791 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
3792 return true;
3794 // Translate the parser's template argument list in our AST format.
3795 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3796 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3798 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3799 assert(SS.getScopeRep() == DTN->getQualifier());
3800 QualType T = Context.getDependentTemplateSpecializationType(
3801 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
3802 TemplateArgs.arguments());
3803 // Build type-source information.
3804 TypeLocBuilder TLB;
3805 DependentTemplateSpecializationTypeLoc SpecTL
3806 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3807 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3808 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3809 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3810 SpecTL.setTemplateNameLoc(TemplateIILoc);
3811 SpecTL.setLAngleLoc(LAngleLoc);
3812 SpecTL.setRAngleLoc(RAngleLoc);
3813 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3814 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3815 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3818 QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3819 if (SpecTy.isNull())
3820 return true;
3822 // Build type-source information.
3823 TypeLocBuilder TLB;
3824 TemplateSpecializationTypeLoc SpecTL =
3825 TLB.push<TemplateSpecializationTypeLoc>(SpecTy);
3826 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3827 SpecTL.setTemplateNameLoc(TemplateIILoc);
3828 SpecTL.setLAngleLoc(LAngleLoc);
3829 SpecTL.setRAngleLoc(RAngleLoc);
3830 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3831 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3833 // Create an elaborated-type-specifier containing the nested-name-specifier.
3834 QualType ElTy =
3835 getElaboratedType(ElaboratedTypeKeyword::None,
3836 !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
3837 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
3838 ElabTL.setElaboratedKeywordLoc(SourceLocation());
3839 if (!ElabTL.isEmpty())
3840 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3841 return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
3844 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3845 TypeSpecifierType TagSpec,
3846 SourceLocation TagLoc,
3847 CXXScopeSpec &SS,
3848 SourceLocation TemplateKWLoc,
3849 TemplateTy TemplateD,
3850 SourceLocation TemplateLoc,
3851 SourceLocation LAngleLoc,
3852 ASTTemplateArgsPtr TemplateArgsIn,
3853 SourceLocation RAngleLoc) {
3854 if (SS.isInvalid())
3855 return TypeResult(true);
3857 TemplateName Template = TemplateD.get();
3859 // Translate the parser's template argument list in our AST format.
3860 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3861 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3863 // Determine the tag kind
3864 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3865 ElaboratedTypeKeyword Keyword
3866 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3868 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3869 assert(SS.getScopeRep() == DTN->getQualifier());
3870 QualType T = Context.getDependentTemplateSpecializationType(
3871 Keyword, DTN->getQualifier(), DTN->getIdentifier(),
3872 TemplateArgs.arguments());
3874 // Build type-source information.
3875 TypeLocBuilder TLB;
3876 DependentTemplateSpecializationTypeLoc SpecTL
3877 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3878 SpecTL.setElaboratedKeywordLoc(TagLoc);
3879 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3880 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3881 SpecTL.setTemplateNameLoc(TemplateLoc);
3882 SpecTL.setLAngleLoc(LAngleLoc);
3883 SpecTL.setRAngleLoc(RAngleLoc);
3884 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3885 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3886 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3889 if (TypeAliasTemplateDecl *TAT =
3890 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3891 // C++0x [dcl.type.elab]p2:
3892 // If the identifier resolves to a typedef-name or the simple-template-id
3893 // resolves to an alias template specialization, the
3894 // elaborated-type-specifier is ill-formed.
3895 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3896 << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
3897 Diag(TAT->getLocation(), diag::note_declared_at);
3900 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3901 if (Result.isNull())
3902 return TypeResult(true);
3904 // Check the tag kind
3905 if (const RecordType *RT = Result->getAs<RecordType>()) {
3906 RecordDecl *D = RT->getDecl();
3908 IdentifierInfo *Id = D->getIdentifier();
3909 assert(Id && "templated class must have an identifier");
3911 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TagUseKind::Definition,
3912 TagLoc, Id)) {
3913 Diag(TagLoc, diag::err_use_with_wrong_tag)
3914 << Result
3915 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3916 Diag(D->getLocation(), diag::note_previous_use);
3920 // Provide source-location information for the template specialization.
3921 TypeLocBuilder TLB;
3922 TemplateSpecializationTypeLoc SpecTL
3923 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3924 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3925 SpecTL.setTemplateNameLoc(TemplateLoc);
3926 SpecTL.setLAngleLoc(LAngleLoc);
3927 SpecTL.setRAngleLoc(RAngleLoc);
3928 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3929 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3931 // Construct an elaborated type containing the nested-name-specifier (if any)
3932 // and tag keyword.
3933 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3934 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3935 ElabTL.setElaboratedKeywordLoc(TagLoc);
3936 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3937 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3940 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3941 NamedDecl *PrevDecl,
3942 SourceLocation Loc,
3943 bool IsPartialSpecialization);
3945 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
3947 static bool isTemplateArgumentTemplateParameter(
3948 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3949 switch (Arg.getKind()) {
3950 case TemplateArgument::Null:
3951 case TemplateArgument::NullPtr:
3952 case TemplateArgument::Integral:
3953 case TemplateArgument::Declaration:
3954 case TemplateArgument::StructuralValue:
3955 case TemplateArgument::Pack:
3956 case TemplateArgument::TemplateExpansion:
3957 return false;
3959 case TemplateArgument::Type: {
3960 QualType Type = Arg.getAsType();
3961 const TemplateTypeParmType *TPT =
3962 Arg.getAsType()->getAs<TemplateTypeParmType>();
3963 return TPT && !Type.hasQualifiers() &&
3964 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3967 case TemplateArgument::Expression: {
3968 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3969 if (!DRE || !DRE->getDecl())
3970 return false;
3971 const NonTypeTemplateParmDecl *NTTP =
3972 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3973 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3976 case TemplateArgument::Template:
3977 const TemplateTemplateParmDecl *TTP =
3978 dyn_cast_or_null<TemplateTemplateParmDecl>(
3979 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3980 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3982 llvm_unreachable("unexpected kind of template argument");
3985 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3986 ArrayRef<TemplateArgument> Args) {
3987 if (Params->size() != Args.size())
3988 return false;
3990 unsigned Depth = Params->getDepth();
3992 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3993 TemplateArgument Arg = Args[I];
3995 // If the parameter is a pack expansion, the argument must be a pack
3996 // whose only element is a pack expansion.
3997 if (Params->getParam(I)->isParameterPack()) {
3998 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3999 !Arg.pack_begin()->isPackExpansion())
4000 return false;
4001 Arg = Arg.pack_begin()->getPackExpansionPattern();
4004 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4005 return false;
4008 return true;
4011 template<typename PartialSpecDecl>
4012 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4013 if (Partial->getDeclContext()->isDependentContext())
4014 return;
4016 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4017 // for non-substitution-failure issues?
4018 TemplateDeductionInfo Info(Partial->getLocation());
4019 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4020 return;
4022 auto *Template = Partial->getSpecializedTemplate();
4023 S.Diag(Partial->getLocation(),
4024 diag::ext_partial_spec_not_more_specialized_than_primary)
4025 << isa<VarTemplateDecl>(Template);
4027 if (Info.hasSFINAEDiagnostic()) {
4028 PartialDiagnosticAt Diag = {SourceLocation(),
4029 PartialDiagnostic::NullDiagnostic()};
4030 Info.takeSFINAEDiagnostic(Diag);
4031 SmallString<128> SFINAEArgString;
4032 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4033 S.Diag(Diag.first,
4034 diag::note_partial_spec_not_more_specialized_than_primary)
4035 << SFINAEArgString;
4038 S.NoteTemplateLocation(*Template);
4039 SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4040 Template->getAssociatedConstraints(TemplateAC);
4041 Partial->getAssociatedConstraints(PartialAC);
4042 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4043 TemplateAC);
4046 static void
4047 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4048 const llvm::SmallBitVector &DeducibleParams) {
4049 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4050 if (!DeducibleParams[I]) {
4051 NamedDecl *Param = TemplateParams->getParam(I);
4052 if (Param->getDeclName())
4053 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4054 << Param->getDeclName();
4055 else
4056 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4057 << "(anonymous)";
4063 template<typename PartialSpecDecl>
4064 static void checkTemplatePartialSpecialization(Sema &S,
4065 PartialSpecDecl *Partial) {
4066 // C++1z [temp.class.spec]p8: (DR1495)
4067 // - The specialization shall be more specialized than the primary
4068 // template (14.5.5.2).
4069 checkMoreSpecializedThanPrimary(S, Partial);
4071 // C++ [temp.class.spec]p8: (DR1315)
4072 // - Each template-parameter shall appear at least once in the
4073 // template-id outside a non-deduced context.
4074 // C++1z [temp.class.spec.match]p3 (P0127R2)
4075 // If the template arguments of a partial specialization cannot be
4076 // deduced because of the structure of its template-parameter-list
4077 // and the template-id, the program is ill-formed.
4078 auto *TemplateParams = Partial->getTemplateParameters();
4079 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4080 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4081 TemplateParams->getDepth(), DeducibleParams);
4083 if (!DeducibleParams.all()) {
4084 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4085 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4086 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4087 << (NumNonDeducible > 1)
4088 << SourceRange(Partial->getLocation(),
4089 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4090 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4094 void Sema::CheckTemplatePartialSpecialization(
4095 ClassTemplatePartialSpecializationDecl *Partial) {
4096 checkTemplatePartialSpecialization(*this, Partial);
4099 void Sema::CheckTemplatePartialSpecialization(
4100 VarTemplatePartialSpecializationDecl *Partial) {
4101 checkTemplatePartialSpecialization(*this, Partial);
4104 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4105 // C++1z [temp.param]p11:
4106 // A template parameter of a deduction guide template that does not have a
4107 // default-argument shall be deducible from the parameter-type-list of the
4108 // deduction guide template.
4109 auto *TemplateParams = TD->getTemplateParameters();
4110 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4111 MarkDeducedTemplateParameters(TD, DeducibleParams);
4112 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4113 // A parameter pack is deducible (to an empty pack).
4114 auto *Param = TemplateParams->getParam(I);
4115 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4116 DeducibleParams[I] = true;
4119 if (!DeducibleParams.all()) {
4120 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4121 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4122 << (NumNonDeducible > 1);
4123 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4127 DeclResult Sema::ActOnVarTemplateSpecialization(
4128 Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous,
4129 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4130 StorageClass SC, bool IsPartialSpecialization) {
4131 // D must be variable template id.
4132 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4133 "Variable template specialization is declared with a template id.");
4135 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4136 TemplateArgumentListInfo TemplateArgs =
4137 makeTemplateArgumentListInfo(*this, *TemplateId);
4138 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4139 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4140 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4142 TemplateName Name = TemplateId->Template.get();
4144 // The template-id must name a variable template.
4145 VarTemplateDecl *VarTemplate =
4146 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4147 if (!VarTemplate) {
4148 NamedDecl *FnTemplate;
4149 if (auto *OTS = Name.getAsOverloadedTemplate())
4150 FnTemplate = *OTS->begin();
4151 else
4152 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4153 if (FnTemplate)
4154 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4155 << FnTemplate->getDeclName();
4156 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4157 << IsPartialSpecialization;
4160 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4161 auto Message = DSA->getMessage();
4162 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
4163 << VarTemplate << !Message.empty() << Message;
4164 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
4167 // Check for unexpanded parameter packs in any of the template arguments.
4168 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4169 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4170 IsPartialSpecialization
4171 ? UPPC_PartialSpecialization
4172 : UPPC_ExplicitSpecialization))
4173 return true;
4175 // Check that the template argument list is well-formed for this
4176 // template.
4177 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4178 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4179 /*DefaultArgs=*/{}, false, SugaredConverted,
4180 CanonicalConverted,
4181 /*UpdateArgsWithConversions=*/true))
4182 return true;
4184 // Find the variable template (partial) specialization declaration that
4185 // corresponds to these arguments.
4186 if (IsPartialSpecialization) {
4187 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
4188 TemplateArgs.size(),
4189 CanonicalConverted))
4190 return true;
4192 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4193 // also do them during instantiation.
4194 if (!Name.isDependent() &&
4195 !TemplateSpecializationType::anyDependentTemplateArguments(
4196 TemplateArgs, CanonicalConverted)) {
4197 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4198 << VarTemplate->getDeclName();
4199 IsPartialSpecialization = false;
4202 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4203 CanonicalConverted) &&
4204 (!Context.getLangOpts().CPlusPlus20 ||
4205 !TemplateParams->hasAssociatedConstraints())) {
4206 // C++ [temp.class.spec]p9b3:
4208 // -- The argument list of the specialization shall not be identical
4209 // to the implicit argument list of the primary template.
4210 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4211 << /*variable template*/ 1
4212 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4213 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4214 // FIXME: Recover from this by treating the declaration as a redeclaration
4215 // of the primary template.
4216 return true;
4220 void *InsertPos = nullptr;
4221 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4223 if (IsPartialSpecialization)
4224 PrevDecl = VarTemplate->findPartialSpecialization(
4225 CanonicalConverted, TemplateParams, InsertPos);
4226 else
4227 PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4229 VarTemplateSpecializationDecl *Specialization = nullptr;
4231 // Check whether we can declare a variable template specialization in
4232 // the current scope.
4233 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4234 TemplateNameLoc,
4235 IsPartialSpecialization))
4236 return true;
4238 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4239 // Since the only prior variable template specialization with these
4240 // arguments was referenced but not declared, reuse that
4241 // declaration node as our own, updating its source location and
4242 // the list of outer template parameters to reflect our new declaration.
4243 Specialization = PrevDecl;
4244 Specialization->setLocation(TemplateNameLoc);
4245 PrevDecl = nullptr;
4246 } else if (IsPartialSpecialization) {
4247 // Create a new class template partial specialization declaration node.
4248 VarTemplatePartialSpecializationDecl *PrevPartial =
4249 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4250 VarTemplatePartialSpecializationDecl *Partial =
4251 VarTemplatePartialSpecializationDecl::Create(
4252 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4253 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4254 CanonicalConverted);
4255 Partial->setTemplateArgsAsWritten(TemplateArgs);
4257 if (!PrevPartial)
4258 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4259 Specialization = Partial;
4261 // If we are providing an explicit specialization of a member variable
4262 // template specialization, make a note of that.
4263 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4264 PrevPartial->setMemberSpecialization();
4266 CheckTemplatePartialSpecialization(Partial);
4267 } else {
4268 // Create a new class template specialization declaration node for
4269 // this explicit specialization or friend declaration.
4270 Specialization = VarTemplateSpecializationDecl::Create(
4271 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4272 VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
4273 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4275 if (!PrevDecl)
4276 VarTemplate->AddSpecialization(Specialization, InsertPos);
4279 // C++ [temp.expl.spec]p6:
4280 // If a template, a member template or the member of a class template is
4281 // explicitly specialized then that specialization shall be declared
4282 // before the first use of that specialization that would cause an implicit
4283 // instantiation to take place, in every translation unit in which such a
4284 // use occurs; no diagnostic is required.
4285 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4286 bool Okay = false;
4287 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4288 // Is there any previous explicit specialization declaration?
4289 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4290 Okay = true;
4291 break;
4295 if (!Okay) {
4296 SourceRange Range(TemplateNameLoc, RAngleLoc);
4297 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4298 << Name << Range;
4300 Diag(PrevDecl->getPointOfInstantiation(),
4301 diag::note_instantiation_required_here)
4302 << (PrevDecl->getTemplateSpecializationKind() !=
4303 TSK_ImplicitInstantiation);
4304 return true;
4308 Specialization->setLexicalDeclContext(CurContext);
4310 // Add the specialization into its lexical context, so that it can
4311 // be seen when iterating through the list of declarations in that
4312 // context. However, specializations are not found by name lookup.
4313 CurContext->addDecl(Specialization);
4315 // Note that this is an explicit specialization.
4316 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4318 Previous.clear();
4319 if (PrevDecl)
4320 Previous.addDecl(PrevDecl);
4321 else if (Specialization->isStaticDataMember() &&
4322 Specialization->isOutOfLine())
4323 Specialization->setAccess(VarTemplate->getAccess());
4325 return Specialization;
4328 namespace {
4329 /// A partial specialization whose template arguments have matched
4330 /// a given template-id.
4331 struct PartialSpecMatchResult {
4332 VarTemplatePartialSpecializationDecl *Partial;
4333 TemplateArgumentList *Args;
4335 } // end anonymous namespace
4337 DeclResult
4338 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4339 SourceLocation TemplateNameLoc,
4340 const TemplateArgumentListInfo &TemplateArgs) {
4341 assert(Template && "A variable template id without template?");
4343 // Check that the template argument list is well-formed for this template.
4344 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4345 if (CheckTemplateArgumentList(
4346 Template, TemplateNameLoc,
4347 const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4348 /*DefaultArgs=*/{}, false, SugaredConverted, CanonicalConverted,
4349 /*UpdateArgsWithConversions=*/true))
4350 return true;
4352 // Produce a placeholder value if the specialization is dependent.
4353 if (Template->getDeclContext()->isDependentContext() ||
4354 TemplateSpecializationType::anyDependentTemplateArguments(
4355 TemplateArgs, CanonicalConverted))
4356 return DeclResult();
4358 // Find the variable template specialization declaration that
4359 // corresponds to these arguments.
4360 void *InsertPos = nullptr;
4361 if (VarTemplateSpecializationDecl *Spec =
4362 Template->findSpecialization(CanonicalConverted, InsertPos)) {
4363 checkSpecializationReachability(TemplateNameLoc, Spec);
4364 // If we already have a variable template specialization, return it.
4365 return Spec;
4368 // This is the first time we have referenced this variable template
4369 // specialization. Create the canonical declaration and add it to
4370 // the set of specializations, based on the closest partial specialization
4371 // that it represents. That is,
4372 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4373 const TemplateArgumentList *PartialSpecArgs = nullptr;
4374 bool AmbiguousPartialSpec = false;
4375 typedef PartialSpecMatchResult MatchResult;
4376 SmallVector<MatchResult, 4> Matched;
4377 SourceLocation PointOfInstantiation = TemplateNameLoc;
4378 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4379 /*ForTakingAddress=*/false);
4381 // 1. Attempt to find the closest partial specialization that this
4382 // specializes, if any.
4383 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4384 // Perhaps better after unification of DeduceTemplateArguments() and
4385 // getMoreSpecializedPartialSpecialization().
4386 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4387 Template->getPartialSpecializations(PartialSpecs);
4389 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4390 // C++ [temp.spec.partial.member]p2:
4391 // If the primary member template is explicitly specialized for a given
4392 // (implicit) specialization of the enclosing class template, the partial
4393 // specializations of the member template are ignored for this
4394 // specialization of the enclosing class template. If a partial
4395 // specialization of the member template is explicitly specialized for a
4396 // given (implicit) specialization of the enclosing class template, the
4397 // primary member template and its other partial specializations are still
4398 // considered for this specialization of the enclosing class template.
4399 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4400 !Partial->getMostRecentDecl()->isMemberSpecialization())
4401 continue;
4403 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4405 if (TemplateDeductionResult Result =
4406 DeduceTemplateArguments(Partial, SugaredConverted, Info);
4407 Result != TemplateDeductionResult::Success) {
4408 // Store the failed-deduction information for use in diagnostics, later.
4409 // TODO: Actually use the failed-deduction info?
4410 FailedCandidates.addCandidate().set(
4411 DeclAccessPair::make(Template, AS_public), Partial,
4412 MakeDeductionFailureInfo(Context, Result, Info));
4413 (void)Result;
4414 } else {
4415 Matched.push_back(PartialSpecMatchResult());
4416 Matched.back().Partial = Partial;
4417 Matched.back().Args = Info.takeSugared();
4421 if (Matched.size() >= 1) {
4422 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4423 if (Matched.size() == 1) {
4424 // -- If exactly one matching specialization is found, the
4425 // instantiation is generated from that specialization.
4426 // We don't need to do anything for this.
4427 } else {
4428 // -- If more than one matching specialization is found, the
4429 // partial order rules (14.5.4.2) are used to determine
4430 // whether one of the specializations is more specialized
4431 // than the others. If none of the specializations is more
4432 // specialized than all of the other matching
4433 // specializations, then the use of the variable template is
4434 // ambiguous and the program is ill-formed.
4435 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4436 PEnd = Matched.end();
4437 P != PEnd; ++P) {
4438 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4439 PointOfInstantiation) ==
4440 P->Partial)
4441 Best = P;
4444 // Determine if the best partial specialization is more specialized than
4445 // the others.
4446 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4447 PEnd = Matched.end();
4448 P != PEnd; ++P) {
4449 if (P != Best && getMoreSpecializedPartialSpecialization(
4450 P->Partial, Best->Partial,
4451 PointOfInstantiation) != Best->Partial) {
4452 AmbiguousPartialSpec = true;
4453 break;
4458 // Instantiate using the best variable template partial specialization.
4459 InstantiationPattern = Best->Partial;
4460 PartialSpecArgs = Best->Args;
4461 } else {
4462 // -- If no match is found, the instantiation is generated
4463 // from the primary template.
4464 // InstantiationPattern = Template->getTemplatedDecl();
4467 // 2. Create the canonical declaration.
4468 // Note that we do not instantiate a definition until we see an odr-use
4469 // in DoMarkVarDeclReferenced().
4470 // FIXME: LateAttrs et al.?
4471 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4472 Template, InstantiationPattern, PartialSpecArgs, TemplateArgs,
4473 CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4474 if (!Decl)
4475 return true;
4477 if (AmbiguousPartialSpec) {
4478 // Partial ordering did not produce a clear winner. Complain.
4479 Decl->setInvalidDecl();
4480 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4481 << Decl;
4483 // Print the matching partial specializations.
4484 for (MatchResult P : Matched)
4485 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4486 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4487 *P.Args);
4488 return true;
4491 if (VarTemplatePartialSpecializationDecl *D =
4492 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4493 Decl->setInstantiationOf(D, PartialSpecArgs);
4495 checkSpecializationReachability(TemplateNameLoc, Decl);
4497 assert(Decl && "No variable template specialization?");
4498 return Decl;
4501 ExprResult Sema::CheckVarTemplateId(
4502 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4503 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4504 const TemplateArgumentListInfo *TemplateArgs) {
4506 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4507 *TemplateArgs);
4508 if (Decl.isInvalid())
4509 return ExprError();
4511 if (!Decl.get())
4512 return ExprResult();
4514 VarDecl *Var = cast<VarDecl>(Decl.get());
4515 if (!Var->getTemplateSpecializationKind())
4516 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4517 NameInfo.getLoc());
4519 // Build an ordinary singleton decl ref.
4520 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4523 void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4524 SourceLocation Loc) {
4525 Diag(Loc, diag::err_template_missing_args)
4526 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4527 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4528 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4532 void Sema::diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
4533 bool TemplateKeyword,
4534 TemplateDecl *TD,
4535 SourceLocation Loc) {
4536 TemplateName Name = Context.getQualifiedTemplateName(
4537 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));
4538 diagnoseMissingTemplateArguments(Name, Loc);
4541 ExprResult
4542 Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
4543 SourceLocation TemplateKWLoc,
4544 const DeclarationNameInfo &ConceptNameInfo,
4545 NamedDecl *FoundDecl,
4546 ConceptDecl *NamedConcept,
4547 const TemplateArgumentListInfo *TemplateArgs) {
4548 assert(NamedConcept && "A concept template id without a template?");
4550 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4551 if (CheckTemplateArgumentList(
4552 NamedConcept, ConceptNameInfo.getLoc(),
4553 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4554 /*DefaultArgs=*/{},
4555 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
4556 /*UpdateArgsWithConversions=*/false))
4557 return ExprError();
4559 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());
4561 auto *CSD = ImplicitConceptSpecializationDecl::Create(
4562 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
4563 CanonicalConverted);
4564 ConstraintSatisfaction Satisfaction;
4565 bool AreArgsDependent =
4566 TemplateSpecializationType::anyDependentTemplateArguments(
4567 *TemplateArgs, CanonicalConverted);
4568 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
4569 /*Final=*/false);
4570 LocalInstantiationScope Scope(*this);
4572 EnterExpressionEvaluationContext EECtx{
4573 *this, ExpressionEvaluationContext::Unevaluated, CSD};
4575 if (!AreArgsDependent &&
4576 CheckConstraintSatisfaction(
4577 NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
4578 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4579 TemplateArgs->getRAngleLoc()),
4580 Satisfaction))
4581 return ExprError();
4582 auto *CL = ConceptReference::Create(
4583 Context,
4584 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4585 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4586 ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs));
4587 return ConceptSpecializationExpr::Create(
4588 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
4591 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4592 SourceLocation TemplateKWLoc,
4593 LookupResult &R,
4594 bool RequiresADL,
4595 const TemplateArgumentListInfo *TemplateArgs) {
4596 // FIXME: Can we do any checking at this point? I guess we could check the
4597 // template arguments that we have against the template name, if the template
4598 // name refers to a single template. That's not a terribly common case,
4599 // though.
4600 // foo<int> could identify a single function unambiguously
4601 // This approach does NOT work, since f<int>(1);
4602 // gets resolved prior to resorting to overload resolution
4603 // i.e., template<class T> void f(double);
4604 // vs template<class T, class U> void f(U);
4606 // These should be filtered out by our callers.
4607 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4609 // Non-function templates require a template argument list.
4610 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4611 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4612 diagnoseMissingTemplateArguments(
4613 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());
4614 return ExprError();
4617 bool KnownDependent = false;
4618 // In C++1y, check variable template ids.
4619 if (R.getAsSingle<VarTemplateDecl>()) {
4620 ExprResult Res = CheckVarTemplateId(
4621 SS, R.getLookupNameInfo(), R.getAsSingle<VarTemplateDecl>(),
4622 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
4623 if (Res.isInvalid() || Res.isUsable())
4624 return Res;
4625 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4626 KnownDependent = true;
4629 if (R.getAsSingle<ConceptDecl>()) {
4630 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4631 R.getRepresentativeDecl(),
4632 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4635 // We don't want lookup warnings at this point.
4636 R.suppressDiagnostics();
4638 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
4639 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
4640 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
4641 R.begin(), R.end(), KnownDependent,
4642 /*KnownInstantiationDependent=*/false);
4644 // Model the templates with UnresolvedTemplateTy. The expression should then
4645 // either be transformed in an instantiation or be diagnosed in
4646 // CheckPlaceholderExpr.
4647 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4648 !R.getFoundDecl()->getAsFunction())
4649 ULE->setType(Context.UnresolvedTemplateTy);
4651 return ULE;
4654 ExprResult Sema::BuildQualifiedTemplateIdExpr(
4655 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4656 const DeclarationNameInfo &NameInfo,
4657 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4658 assert(TemplateArgs || TemplateKWLoc.isValid());
4660 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4661 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
4662 /*EnteringContext=*/false, TemplateKWLoc))
4663 return ExprError();
4665 if (R.isAmbiguous())
4666 return ExprError();
4668 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
4669 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4671 if (R.empty()) {
4672 DeclContext *DC = computeDeclContext(SS);
4673 Diag(NameInfo.getLoc(), diag::err_no_member)
4674 << NameInfo.getName() << DC << SS.getRange();
4675 return ExprError();
4678 // If necessary, build an implicit class member access.
4679 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
4680 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
4681 /*S=*/nullptr);
4683 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);
4686 TemplateNameKind Sema::ActOnTemplateName(Scope *S,
4687 CXXScopeSpec &SS,
4688 SourceLocation TemplateKWLoc,
4689 const UnqualifiedId &Name,
4690 ParsedType ObjectType,
4691 bool EnteringContext,
4692 TemplateTy &Result,
4693 bool AllowInjectedClassName) {
4694 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4695 Diag(TemplateKWLoc,
4696 getLangOpts().CPlusPlus11 ?
4697 diag::warn_cxx98_compat_template_outside_of_template :
4698 diag::ext_template_outside_of_template)
4699 << FixItHint::CreateRemoval(TemplateKWLoc);
4701 if (SS.isInvalid())
4702 return TNK_Non_template;
4704 // Figure out where isTemplateName is going to look.
4705 DeclContext *LookupCtx = nullptr;
4706 if (SS.isNotEmpty())
4707 LookupCtx = computeDeclContext(SS, EnteringContext);
4708 else if (ObjectType)
4709 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
4711 // C++0x [temp.names]p5:
4712 // If a name prefixed by the keyword template is not the name of
4713 // a template, the program is ill-formed. [Note: the keyword
4714 // template may not be applied to non-template members of class
4715 // templates. -end note ] [ Note: as is the case with the
4716 // typename prefix, the template prefix is allowed in cases
4717 // where it is not strictly necessary; i.e., when the
4718 // nested-name-specifier or the expression on the left of the ->
4719 // or . is not dependent on a template-parameter, or the use
4720 // does not appear in the scope of a template. -end note]
4722 // Note: C++03 was more strict here, because it banned the use of
4723 // the "template" keyword prior to a template-name that was not a
4724 // dependent name. C++ DR468 relaxed this requirement (the
4725 // "template" keyword is now permitted). We follow the C++0x
4726 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4727 bool MemberOfUnknownSpecialization;
4728 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4729 ObjectType, EnteringContext, Result,
4730 MemberOfUnknownSpecialization);
4731 if (TNK != TNK_Non_template) {
4732 // We resolved this to a (non-dependent) template name. Return it.
4733 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4734 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
4735 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4736 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4737 // C++14 [class.qual]p2:
4738 // In a lookup in which function names are not ignored and the
4739 // nested-name-specifier nominates a class C, if the name specified
4740 // [...] is the injected-class-name of C, [...] the name is instead
4741 // considered to name the constructor
4743 // We don't get here if naming the constructor would be valid, so we
4744 // just reject immediately and recover by treating the
4745 // injected-class-name as naming the template.
4746 Diag(Name.getBeginLoc(),
4747 diag::ext_out_of_line_qualified_id_type_names_constructor)
4748 << Name.Identifier
4749 << 0 /*injected-class-name used as template name*/
4750 << TemplateKWLoc.isValid();
4752 return TNK;
4755 if (!MemberOfUnknownSpecialization) {
4756 // Didn't find a template name, and the lookup wasn't dependent.
4757 // Do the lookup again to determine if this is a "nothing found" case or
4758 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4759 // need to do this.
4760 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4761 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4762 LookupOrdinaryName);
4763 // Tell LookupTemplateName that we require a template so that it diagnoses
4764 // cases where it finds a non-template.
4765 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
4766 ? RequiredTemplateKind(TemplateKWLoc)
4767 : TemplateNameIsRequired;
4768 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,
4769 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
4770 !R.isAmbiguous()) {
4771 if (LookupCtx)
4772 Diag(Name.getBeginLoc(), diag::err_no_member)
4773 << DNI.getName() << LookupCtx << SS.getRange();
4774 else
4775 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
4776 << DNI.getName() << SS.getRange();
4778 return TNK_Non_template;
4781 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4783 switch (Name.getKind()) {
4784 case UnqualifiedIdKind::IK_Identifier:
4785 Result = TemplateTy::make(
4786 Context.getDependentTemplateName(Qualifier, Name.Identifier));
4787 return TNK_Dependent_template_name;
4789 case UnqualifiedIdKind::IK_OperatorFunctionId:
4790 Result = TemplateTy::make(Context.getDependentTemplateName(
4791 Qualifier, Name.OperatorFunctionId.Operator));
4792 return TNK_Function_template;
4794 case UnqualifiedIdKind::IK_LiteralOperatorId:
4795 // This is a kind of template name, but can never occur in a dependent
4796 // scope (literal operators can only be declared at namespace scope).
4797 break;
4799 default:
4800 break;
4803 // This name cannot possibly name a dependent template. Diagnose this now
4804 // rather than building a dependent template name that can never be valid.
4805 Diag(Name.getBeginLoc(),
4806 diag::err_template_kw_refers_to_dependent_non_template)
4807 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4808 << TemplateKWLoc.isValid() << TemplateKWLoc;
4809 return TNK_Non_template;
4812 bool Sema::CheckTemplateTypeArgument(
4813 TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
4814 SmallVectorImpl<TemplateArgument> &SugaredConverted,
4815 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
4816 const TemplateArgument &Arg = AL.getArgument();
4817 QualType ArgType;
4818 TypeSourceInfo *TSI = nullptr;
4820 // Check template type parameter.
4821 switch(Arg.getKind()) {
4822 case TemplateArgument::Type:
4823 // C++ [temp.arg.type]p1:
4824 // A template-argument for a template-parameter which is a
4825 // type shall be a type-id.
4826 ArgType = Arg.getAsType();
4827 TSI = AL.getTypeSourceInfo();
4828 break;
4829 case TemplateArgument::Template:
4830 case TemplateArgument::TemplateExpansion: {
4831 // We have a template type parameter but the template argument
4832 // is a template without any arguments.
4833 SourceRange SR = AL.getSourceRange();
4834 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
4835 diagnoseMissingTemplateArguments(Name, SR.getEnd());
4836 return true;
4838 case TemplateArgument::Expression: {
4839 // We have a template type parameter but the template argument is an
4840 // expression; see if maybe it is missing the "typename" keyword.
4841 CXXScopeSpec SS;
4842 DeclarationNameInfo NameInfo;
4844 if (DependentScopeDeclRefExpr *ArgExpr =
4845 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4846 SS.Adopt(ArgExpr->getQualifierLoc());
4847 NameInfo = ArgExpr->getNameInfo();
4848 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4849 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4850 if (ArgExpr->isImplicitAccess()) {
4851 SS.Adopt(ArgExpr->getQualifierLoc());
4852 NameInfo = ArgExpr->getMemberNameInfo();
4856 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4857 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4858 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());
4860 if (Result.getAsSingle<TypeDecl>() ||
4861 Result.wasNotFoundInCurrentInstantiation()) {
4862 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
4863 // Suggest that the user add 'typename' before the NNS.
4864 SourceLocation Loc = AL.getSourceRange().getBegin();
4865 Diag(Loc, getLangOpts().MSVCCompat
4866 ? diag::ext_ms_template_type_arg_missing_typename
4867 : diag::err_template_arg_must_be_type_suggest)
4868 << FixItHint::CreateInsertion(Loc, "typename ");
4869 NoteTemplateParameterLocation(*Param);
4871 // Recover by synthesizing a type using the location information that we
4872 // already have.
4873 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::Typename,
4874 SS.getScopeRep(), II);
4875 TypeLocBuilder TLB;
4876 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4877 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4878 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4879 TL.setNameLoc(NameInfo.getLoc());
4880 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4882 // Overwrite our input TemplateArgumentLoc so that we can recover
4883 // properly.
4884 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4885 TemplateArgumentLocInfo(TSI));
4887 break;
4890 // fallthrough
4891 [[fallthrough]];
4893 default: {
4894 // We allow instantiateing a template with template argument packs when
4895 // building deduction guides.
4896 if (Arg.getKind() == TemplateArgument::Pack &&
4897 CodeSynthesisContexts.back().Kind ==
4898 Sema::CodeSynthesisContext::BuildingDeductionGuides) {
4899 SugaredConverted.push_back(Arg);
4900 CanonicalConverted.push_back(Arg);
4901 return false;
4903 // We have a template type parameter but the template argument
4904 // is not a type.
4905 SourceRange SR = AL.getSourceRange();
4906 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4907 NoteTemplateParameterLocation(*Param);
4909 return true;
4913 if (CheckTemplateArgument(TSI))
4914 return true;
4916 // Objective-C ARC:
4917 // If an explicitly-specified template argument type is a lifetime type
4918 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4919 if (getLangOpts().ObjCAutoRefCount &&
4920 ArgType->isObjCLifetimeType() &&
4921 !ArgType.getObjCLifetime()) {
4922 Qualifiers Qs;
4923 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4924 ArgType = Context.getQualifiedType(ArgType, Qs);
4927 SugaredConverted.push_back(TemplateArgument(ArgType));
4928 CanonicalConverted.push_back(
4929 TemplateArgument(Context.getCanonicalType(ArgType)));
4930 return false;
4933 /// Substitute template arguments into the default template argument for
4934 /// the given template type parameter.
4936 /// \param SemaRef the semantic analysis object for which we are performing
4937 /// the substitution.
4939 /// \param Template the template that we are synthesizing template arguments
4940 /// for.
4942 /// \param TemplateLoc the location of the template name that started the
4943 /// template-id we are checking.
4945 /// \param RAngleLoc the location of the right angle bracket ('>') that
4946 /// terminates the template-id.
4948 /// \param Param the template template parameter whose default we are
4949 /// substituting into.
4951 /// \param Converted the list of template arguments provided for template
4952 /// parameters that precede \p Param in the template parameter list.
4954 /// \param Output the resulting substituted template argument.
4956 /// \returns true if an error occurred.
4957 static bool SubstDefaultTemplateArgument(
4958 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
4959 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
4960 ArrayRef<TemplateArgument> SugaredConverted,
4961 ArrayRef<TemplateArgument> CanonicalConverted,
4962 TemplateArgumentLoc &Output) {
4963 Output = Param->getDefaultArgument();
4965 // If the argument type is dependent, instantiate it now based
4966 // on the previously-computed template arguments.
4967 if (Output.getArgument().isInstantiationDependent()) {
4968 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
4969 SugaredConverted,
4970 SourceRange(TemplateLoc, RAngleLoc));
4971 if (Inst.isInvalid())
4972 return true;
4974 // Only substitute for the innermost template argument list.
4975 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
4976 /*Final=*/true);
4977 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4978 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
4980 bool ForLambdaCallOperator = false;
4981 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
4982 ForLambdaCallOperator = Rec->isLambda();
4983 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
4984 !ForLambdaCallOperator);
4986 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,
4987 Param->getDefaultArgumentLoc(),
4988 Param->getDeclName()))
4989 return true;
4992 return false;
4995 /// Substitute template arguments into the default template argument for
4996 /// the given non-type template parameter.
4998 /// \param SemaRef the semantic analysis object for which we are performing
4999 /// the substitution.
5001 /// \param Template the template that we are synthesizing template arguments
5002 /// for.
5004 /// \param TemplateLoc the location of the template name that started the
5005 /// template-id we are checking.
5007 /// \param RAngleLoc the location of the right angle bracket ('>') that
5008 /// terminates the template-id.
5010 /// \param Param the non-type template parameter whose default we are
5011 /// substituting into.
5013 /// \param Converted the list of template arguments provided for template
5014 /// parameters that precede \p Param in the template parameter list.
5016 /// \returns the substituted template argument, or NULL if an error occurred.
5017 static bool SubstDefaultTemplateArgument(
5018 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5019 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5020 ArrayRef<TemplateArgument> SugaredConverted,
5021 ArrayRef<TemplateArgument> CanonicalConverted,
5022 TemplateArgumentLoc &Output) {
5023 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5024 SugaredConverted,
5025 SourceRange(TemplateLoc, RAngleLoc));
5026 if (Inst.isInvalid())
5027 return true;
5029 // Only substitute for the innermost template argument list.
5030 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5031 /*Final=*/true);
5032 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5033 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5035 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5036 EnterExpressionEvaluationContext ConstantEvaluated(
5037 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5038 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),
5039 TemplateArgLists, Output);
5042 /// Substitute template arguments into the default template argument for
5043 /// the given template template parameter.
5045 /// \param SemaRef the semantic analysis object for which we are performing
5046 /// the substitution.
5048 /// \param Template the template that we are synthesizing template arguments
5049 /// for.
5051 /// \param TemplateLoc the location of the template name that started the
5052 /// template-id we are checking.
5054 /// \param RAngleLoc the location of the right angle bracket ('>') that
5055 /// terminates the template-id.
5057 /// \param Param the template template parameter whose default we are
5058 /// substituting into.
5060 /// \param Converted the list of template arguments provided for template
5061 /// parameters that precede \p Param in the template parameter list.
5063 /// \param QualifierLoc Will be set to the nested-name-specifier (with
5064 /// source-location information) that precedes the template name.
5066 /// \returns the substituted template argument, or NULL if an error occurred.
5067 static TemplateName SubstDefaultTemplateArgument(
5068 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5069 SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
5070 ArrayRef<TemplateArgument> SugaredConverted,
5071 ArrayRef<TemplateArgument> CanonicalConverted,
5072 NestedNameSpecifierLoc &QualifierLoc) {
5073 Sema::InstantiatingTemplate Inst(
5074 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5075 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5076 if (Inst.isInvalid())
5077 return TemplateName();
5079 // Only substitute for the innermost template argument list.
5080 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5081 /*Final=*/true);
5082 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5083 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5085 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5086 // Substitute into the nested-name-specifier first,
5087 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
5088 if (QualifierLoc) {
5089 QualifierLoc =
5090 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
5091 if (!QualifierLoc)
5092 return TemplateName();
5095 return SemaRef.SubstTemplateName(
5096 QualifierLoc,
5097 Param->getDefaultArgument().getArgument().getAsTemplate(),
5098 Param->getDefaultArgument().getTemplateNameLoc(),
5099 TemplateArgLists);
5102 TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
5103 TemplateDecl *Template, SourceLocation TemplateLoc,
5104 SourceLocation RAngleLoc, Decl *Param,
5105 ArrayRef<TemplateArgument> SugaredConverted,
5106 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5107 HasDefaultArg = false;
5109 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5110 if (!hasReachableDefaultArgument(TypeParm))
5111 return TemplateArgumentLoc();
5113 HasDefaultArg = true;
5114 TemplateArgumentLoc Output;
5115 if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5116 TypeParm, SugaredConverted,
5117 CanonicalConverted, Output))
5118 return TemplateArgumentLoc();
5119 return Output;
5122 if (NonTypeTemplateParmDecl *NonTypeParm
5123 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5124 if (!hasReachableDefaultArgument(NonTypeParm))
5125 return TemplateArgumentLoc();
5127 HasDefaultArg = true;
5128 TemplateArgumentLoc Output;
5129 if (SubstDefaultTemplateArgument(*this, Template, TemplateLoc, RAngleLoc,
5130 NonTypeParm, SugaredConverted,
5131 CanonicalConverted, Output))
5132 return TemplateArgumentLoc();
5133 return Output;
5136 TemplateTemplateParmDecl *TempTempParm
5137 = cast<TemplateTemplateParmDecl>(Param);
5138 if (!hasReachableDefaultArgument(TempTempParm))
5139 return TemplateArgumentLoc();
5141 HasDefaultArg = true;
5142 NestedNameSpecifierLoc QualifierLoc;
5143 TemplateName TName = SubstDefaultTemplateArgument(
5144 *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted,
5145 CanonicalConverted, QualifierLoc);
5146 if (TName.isNull())
5147 return TemplateArgumentLoc();
5149 return TemplateArgumentLoc(
5150 Context, TemplateArgument(TName),
5151 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
5152 TempTempParm->getDefaultArgument().getTemplateNameLoc());
5155 /// Convert a template-argument that we parsed as a type into a template, if
5156 /// possible. C++ permits injected-class-names to perform dual service as
5157 /// template template arguments and as template type arguments.
5158 static TemplateArgumentLoc
5159 convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5160 // Extract and step over any surrounding nested-name-specifier.
5161 NestedNameSpecifierLoc QualLoc;
5162 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
5163 if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
5164 return TemplateArgumentLoc();
5166 QualLoc = ETLoc.getQualifierLoc();
5167 TLoc = ETLoc.getNamedTypeLoc();
5169 // If this type was written as an injected-class-name, it can be used as a
5170 // template template argument.
5171 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
5172 return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
5173 QualLoc, InjLoc.getNameLoc());
5175 // If this type was written as an injected-class-name, it may have been
5176 // converted to a RecordType during instantiation. If the RecordType is
5177 // *not* wrapped in a TemplateSpecializationType and denotes a class
5178 // template specialization, it must have come from an injected-class-name.
5179 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5180 if (auto *CTSD =
5181 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
5182 return TemplateArgumentLoc(Context,
5183 TemplateName(CTSD->getSpecializedTemplate()),
5184 QualLoc, RecLoc.getNameLoc());
5186 return TemplateArgumentLoc();
5189 bool Sema::CheckTemplateArgument(
5190 NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
5191 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5192 unsigned ArgumentPackIndex,
5193 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5194 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5195 CheckTemplateArgumentKind CTAK) {
5196 // Check template type parameters.
5197 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5198 return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted,
5199 CanonicalConverted);
5201 // Check non-type template parameters.
5202 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5203 // Do substitution on the type of the non-type template parameter
5204 // with the template arguments we've seen thus far. But if the
5205 // template has a dependent context then we cannot substitute yet.
5206 QualType NTTPType = NTTP->getType();
5207 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5208 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5210 if (NTTPType->isInstantiationDependentType() &&
5211 !isa<TemplateTemplateParmDecl>(Template) &&
5212 !Template->getDeclContext()->isDependentContext()) {
5213 // Do substitution on the type of the non-type template parameter.
5214 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5215 SugaredConverted,
5216 SourceRange(TemplateLoc, RAngleLoc));
5217 if (Inst.isInvalid())
5218 return true;
5220 MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
5221 /*Final=*/true);
5222 // If the parameter is a pack expansion, expand this slice of the pack.
5223 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5224 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
5225 ArgumentPackIndex);
5226 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
5227 NTTP->getDeclName());
5228 } else {
5229 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
5230 NTTP->getDeclName());
5233 // If that worked, check the non-type template parameter type
5234 // for validity.
5235 if (!NTTPType.isNull())
5236 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5237 NTTP->getLocation());
5238 if (NTTPType.isNull())
5239 return true;
5242 switch (Arg.getArgument().getKind()) {
5243 case TemplateArgument::Null:
5244 llvm_unreachable("Should never see a NULL template argument here");
5246 case TemplateArgument::Expression: {
5247 Expr *E = Arg.getArgument().getAsExpr();
5248 TemplateArgument SugaredResult, CanonicalResult;
5249 unsigned CurSFINAEErrors = NumSFINAEErrors;
5250 ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult,
5251 CanonicalResult, CTAK);
5252 if (Res.isInvalid())
5253 return true;
5254 // If the current template argument causes an error, give up now.
5255 if (CurSFINAEErrors < NumSFINAEErrors)
5256 return true;
5258 // If the resulting expression is new, then use it in place of the
5259 // old expression in the template argument.
5260 if (Res.get() != E) {
5261 TemplateArgument TA(Res.get());
5262 Arg = TemplateArgumentLoc(TA, Res.get());
5265 SugaredConverted.push_back(SugaredResult);
5266 CanonicalConverted.push_back(CanonicalResult);
5267 break;
5270 case TemplateArgument::Declaration:
5271 case TemplateArgument::Integral:
5272 case TemplateArgument::StructuralValue:
5273 case TemplateArgument::NullPtr:
5274 // We've already checked this template argument, so just copy
5275 // it to the list of converted arguments.
5276 SugaredConverted.push_back(Arg.getArgument());
5277 CanonicalConverted.push_back(
5278 Context.getCanonicalTemplateArgument(Arg.getArgument()));
5279 break;
5281 case TemplateArgument::Template:
5282 case TemplateArgument::TemplateExpansion:
5283 // We were given a template template argument. It may not be ill-formed;
5284 // see below.
5285 if (DependentTemplateName *DTN
5286 = Arg.getArgument().getAsTemplateOrTemplatePattern()
5287 .getAsDependentTemplateName()) {
5288 // We have a template argument such as \c T::template X, which we
5289 // parsed as a template template argument. However, since we now
5290 // know that we need a non-type template argument, convert this
5291 // template name into an expression.
5293 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5294 Arg.getTemplateNameLoc());
5296 CXXScopeSpec SS;
5297 SS.Adopt(Arg.getTemplateQualifierLoc());
5298 // FIXME: the template-template arg was a DependentTemplateName,
5299 // so it was provided with a template keyword. However, its source
5300 // location is not stored in the template argument structure.
5301 SourceLocation TemplateKWLoc;
5302 ExprResult E = DependentScopeDeclRefExpr::Create(
5303 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5304 nullptr);
5306 // If we parsed the template argument as a pack expansion, create a
5307 // pack expansion expression.
5308 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
5309 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
5310 if (E.isInvalid())
5311 return true;
5314 TemplateArgument SugaredResult, CanonicalResult;
5315 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult,
5316 CanonicalResult, CTAK_Specified);
5317 if (E.isInvalid())
5318 return true;
5320 SugaredConverted.push_back(SugaredResult);
5321 CanonicalConverted.push_back(CanonicalResult);
5322 break;
5325 // We have a template argument that actually does refer to a class
5326 // template, alias template, or template template parameter, and
5327 // therefore cannot be a non-type template argument.
5328 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5329 << Arg.getSourceRange();
5330 NoteTemplateParameterLocation(*Param);
5332 return true;
5334 case TemplateArgument::Type: {
5335 // We have a non-type template parameter but the template
5336 // argument is a type.
5338 // C++ [temp.arg]p2:
5339 // In a template-argument, an ambiguity between a type-id and
5340 // an expression is resolved to a type-id, regardless of the
5341 // form of the corresponding template-parameter.
5343 // We warn specifically about this case, since it can be rather
5344 // confusing for users.
5345 QualType T = Arg.getArgument().getAsType();
5346 SourceRange SR = Arg.getSourceRange();
5347 if (T->isFunctionType())
5348 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5349 else
5350 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5351 NoteTemplateParameterLocation(*Param);
5352 return true;
5355 case TemplateArgument::Pack:
5356 llvm_unreachable("Caller must expand template argument packs");
5359 return false;
5363 // Check template template parameters.
5364 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5366 TemplateParameterList *Params = TempParm->getTemplateParameters();
5367 if (TempParm->isExpandedParameterPack())
5368 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5370 // Substitute into the template parameter list of the template
5371 // template parameter, since previously-supplied template arguments
5372 // may appear within the template template parameter.
5374 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5376 // Set up a template instantiation context.
5377 LocalInstantiationScope Scope(*this);
5378 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5379 SugaredConverted,
5380 SourceRange(TemplateLoc, RAngleLoc));
5381 if (Inst.isInvalid())
5382 return true;
5384 Params =
5385 SubstTemplateParams(Params, CurContext,
5386 MultiLevelTemplateArgumentList(
5387 Template, SugaredConverted, /*Final=*/true),
5388 /*EvaluateConstraints=*/false);
5389 if (!Params)
5390 return true;
5393 // C++1z [temp.local]p1: (DR1004)
5394 // When [the injected-class-name] is used [...] as a template-argument for
5395 // a template template-parameter [...] it refers to the class template
5396 // itself.
5397 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5398 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5399 Context, Arg.getTypeSourceInfo()->getTypeLoc());
5400 if (!ConvertedArg.getArgument().isNull())
5401 Arg = ConvertedArg;
5404 switch (Arg.getArgument().getKind()) {
5405 case TemplateArgument::Null:
5406 llvm_unreachable("Should never see a NULL template argument here");
5408 case TemplateArgument::Template:
5409 case TemplateArgument::TemplateExpansion:
5410 if (CheckTemplateTemplateArgument(TempParm, Params, Arg,
5411 /*IsDeduced=*/CTAK != CTAK_Specified))
5412 return true;
5414 SugaredConverted.push_back(Arg.getArgument());
5415 CanonicalConverted.push_back(
5416 Context.getCanonicalTemplateArgument(Arg.getArgument()));
5417 break;
5419 case TemplateArgument::Expression:
5420 case TemplateArgument::Type:
5421 // We have a template template parameter but the template
5422 // argument does not refer to a template.
5423 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5424 << getLangOpts().CPlusPlus11;
5425 return true;
5427 case TemplateArgument::Declaration:
5428 case TemplateArgument::Integral:
5429 case TemplateArgument::StructuralValue:
5430 case TemplateArgument::NullPtr:
5431 llvm_unreachable("non-type argument with template template parameter");
5433 case TemplateArgument::Pack:
5434 llvm_unreachable("Caller must expand template argument packs");
5437 return false;
5440 /// Diagnose a missing template argument.
5441 template<typename TemplateParmDecl>
5442 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5443 TemplateDecl *TD,
5444 const TemplateParmDecl *D,
5445 TemplateArgumentListInfo &Args) {
5446 // Dig out the most recent declaration of the template parameter; there may be
5447 // declarations of the template that are more recent than TD.
5448 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5449 ->getTemplateParameters()
5450 ->getParam(D->getIndex()));
5452 // If there's a default argument that's not reachable, diagnose that we're
5453 // missing a module import.
5454 llvm::SmallVector<Module*, 8> Modules;
5455 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5456 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5457 D->getDefaultArgumentLoc(), Modules,
5458 Sema::MissingImportKind::DefaultArgument,
5459 /*Recover*/true);
5460 return true;
5463 // FIXME: If there's a more recent default argument that *is* visible,
5464 // diagnose that it was declared too late.
5466 TemplateParameterList *Params = TD->getTemplateParameters();
5468 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5469 << /*not enough args*/0
5470 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5471 << TD;
5472 S.NoteTemplateLocation(*TD, Params->getSourceRange());
5473 return true;
5476 /// Check that the given template argument list is well-formed
5477 /// for specializing the given template.
5478 bool Sema::CheckTemplateArgumentList(
5479 TemplateDecl *Template, SourceLocation TemplateLoc,
5480 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5481 bool PartialTemplateArgs,
5482 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5483 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
5484 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied,
5485 bool PartialOrderingTTP) {
5487 if (ConstraintsNotSatisfied)
5488 *ConstraintsNotSatisfied = false;
5490 // Make a copy of the template arguments for processing. Only make the
5491 // changes at the end when successful in matching the arguments to the
5492 // template.
5493 TemplateArgumentListInfo NewArgs = TemplateArgs;
5495 TemplateParameterList *Params = GetTemplateParameterList(Template);
5497 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5499 // C++ [temp.arg]p1:
5500 // [...] The type and form of each template-argument specified in
5501 // a template-id shall match the type and form specified for the
5502 // corresponding parameter declared by the template in its
5503 // template-parameter-list.
5504 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5505 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5506 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5507 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5508 LocalInstantiationScope InstScope(*this, true);
5509 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5510 ParamEnd = Params->end(),
5511 Param = ParamBegin;
5512 Param != ParamEnd;
5513 /* increment in loop */) {
5514 if (size_t ParamIdx = Param - ParamBegin;
5515 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5516 // All written arguments should have been consumed by this point.
5517 assert(ArgIdx == NumArgs && "bad default argument deduction");
5518 // FIXME: Don't ignore parameter packs.
5519 if (ParamIdx == DefaultArgs.StartPos && !(*Param)->isParameterPack()) {
5520 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5521 // Default arguments from a DeducedTemplateName are already converted.
5522 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5523 SugaredConverted.push_back(DefArg);
5524 CanonicalConverted.push_back(
5525 Context.getCanonicalTemplateArgument(DefArg));
5526 ++Param;
5528 continue;
5532 // If we have an expanded parameter pack, make sure we don't have too
5533 // many arguments.
5534 if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5535 if (*Expansions == SugaredArgumentPack.size()) {
5536 // We're done with this parameter pack. Pack up its arguments and add
5537 // them to the list.
5538 SugaredConverted.push_back(
5539 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5540 SugaredArgumentPack.clear();
5542 CanonicalConverted.push_back(
5543 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5544 CanonicalArgumentPack.clear();
5546 // This argument is assigned to the next parameter.
5547 ++Param;
5548 continue;
5549 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5550 // Not enough arguments for this parameter pack.
5551 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5552 << /*not enough args*/0
5553 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5554 << Template;
5555 NoteTemplateLocation(*Template, Params->getSourceRange());
5556 return true;
5560 if (ArgIdx < NumArgs) {
5561 // Check the template argument we were given.
5562 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
5563 RAngleLoc, SugaredArgumentPack.size(),
5564 SugaredConverted, CanonicalConverted,
5565 CTAK_Specified))
5566 return true;
5568 CanonicalConverted.back().setIsDefaulted(
5569 clang::isSubstitutedDefaultArgument(
5570 Context, NewArgs[ArgIdx].getArgument(), *Param,
5571 CanonicalConverted, Params->getDepth()));
5573 bool PackExpansionIntoNonPack =
5574 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5575 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5576 // CWG1430: Don't diagnose this pack expansion when partial
5577 // ordering template template parameters. Some uses of the template could
5578 // be valid, and invalid uses will be diagnosed later during
5579 // instantiation.
5580 if (PackExpansionIntoNonPack && !PartialOrderingTTP &&
5581 (isa<TypeAliasTemplateDecl>(Template) ||
5582 isa<ConceptDecl>(Template))) {
5583 // CWG1430: we have a pack expansion as an argument to an
5584 // alias template, and it's not part of a parameter pack. This
5585 // can't be canonicalized, so reject it now.
5586 // As for concepts - we cannot normalize constraints where this
5587 // situation exists.
5588 Diag(NewArgs[ArgIdx].getLocation(),
5589 diag::err_template_expansion_into_fixed_list)
5590 << (isa<ConceptDecl>(Template) ? 1 : 0)
5591 << NewArgs[ArgIdx].getSourceRange();
5592 NoteTemplateParameterLocation(**Param);
5593 return true;
5596 // We're now done with this argument.
5597 ++ArgIdx;
5599 if ((*Param)->isTemplateParameterPack()) {
5600 // The template parameter was a template parameter pack, so take the
5601 // deduced argument and place it on the argument pack. Note that we
5602 // stay on the same template parameter so that we can deduce more
5603 // arguments.
5604 SugaredArgumentPack.push_back(SugaredConverted.pop_back_val());
5605 CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val());
5606 } else {
5607 // Move to the next template parameter.
5608 ++Param;
5611 // If we just saw a pack expansion into a non-pack, then directly convert
5612 // the remaining arguments, because we don't know what parameters they'll
5613 // match up with.
5614 if (PackExpansionIntoNonPack) {
5615 if (!SugaredArgumentPack.empty()) {
5616 // If we were part way through filling in an expanded parameter pack,
5617 // fall back to just producing individual arguments.
5618 SugaredConverted.insert(SugaredConverted.end(),
5619 SugaredArgumentPack.begin(),
5620 SugaredArgumentPack.end());
5621 SugaredArgumentPack.clear();
5623 CanonicalConverted.insert(CanonicalConverted.end(),
5624 CanonicalArgumentPack.begin(),
5625 CanonicalArgumentPack.end());
5626 CanonicalArgumentPack.clear();
5629 while (ArgIdx < NumArgs) {
5630 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
5631 SugaredConverted.push_back(Arg);
5632 CanonicalConverted.push_back(
5633 Context.getCanonicalTemplateArgument(Arg));
5634 ++ArgIdx;
5637 return false;
5640 continue;
5643 // If we're checking a partial template argument list, we're done.
5644 if (PartialTemplateArgs) {
5645 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
5646 SugaredConverted.push_back(
5647 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5648 CanonicalConverted.push_back(
5649 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5651 return false;
5654 // If we have a template parameter pack with no more corresponding
5655 // arguments, just break out now and we'll fill in the argument pack below.
5656 if ((*Param)->isTemplateParameterPack()) {
5657 assert(!getExpandedPackSize(*Param) &&
5658 "Should have dealt with this already");
5660 // A non-expanded parameter pack before the end of the parameter list
5661 // only occurs for an ill-formed template parameter list, unless we've
5662 // got a partial argument list for a function template, so just bail out.
5663 if (Param + 1 != ParamEnd) {
5664 assert(
5665 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
5666 "Concept templates must have parameter packs at the end.");
5667 return true;
5670 SugaredConverted.push_back(
5671 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));
5672 SugaredArgumentPack.clear();
5674 CanonicalConverted.push_back(
5675 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));
5676 CanonicalArgumentPack.clear();
5678 ++Param;
5679 continue;
5682 // Check whether we have a default argument.
5683 bool HasDefaultArg;
5685 // Retrieve the default template argument from the template
5686 // parameter. For each kind of template parameter, we substitute the
5687 // template arguments provided thus far and any "outer" template arguments
5688 // (when the template parameter was part of a nested template) into
5689 // the default argument.
5690 TemplateArgumentLoc Arg = SubstDefaultTemplateArgumentIfAvailable(
5691 Template, TemplateLoc, RAngleLoc, *Param, SugaredConverted,
5692 CanonicalConverted, HasDefaultArg);
5694 if (Arg.getArgument().isNull()) {
5695 if (!HasDefaultArg) {
5696 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))
5697 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5698 NewArgs);
5699 if (NonTypeTemplateParmDecl *NTTP =
5700 dyn_cast<NonTypeTemplateParmDecl>(*Param))
5701 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5702 NewArgs);
5703 return diagnoseMissingArgument(*this, TemplateLoc, Template,
5704 cast<TemplateTemplateParmDecl>(*Param),
5705 NewArgs);
5707 return true;
5710 // Introduce an instantiation record that describes where we are using
5711 // the default template argument. We're not actually instantiating a
5712 // template here, we just create this object to put a note into the
5713 // context stack.
5714 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
5715 SugaredConverted,
5716 SourceRange(TemplateLoc, RAngleLoc));
5717 if (Inst.isInvalid())
5718 return true;
5720 // Check the default template argument.
5721 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
5722 SugaredConverted, CanonicalConverted,
5723 CTAK_Specified))
5724 return true;
5726 SugaredConverted.back().setIsDefaulted(true);
5727 CanonicalConverted.back().setIsDefaulted(true);
5729 // Core issue 150 (assumed resolution): if this is a template template
5730 // parameter, keep track of the default template arguments from the
5731 // template definition.
5732 if (isTemplateTemplateParameter)
5733 NewArgs.addArgument(Arg);
5735 // Move to the next template parameter and argument.
5736 ++Param;
5737 ++ArgIdx;
5740 // If we're performing a partial argument substitution, allow any trailing
5741 // pack expansions; they might be empty. This can happen even if
5742 // PartialTemplateArgs is false (the list of arguments is complete but
5743 // still dependent).
5744 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5745 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5746 while (ArgIdx < NumArgs &&
5747 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
5748 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
5749 SugaredConverted.push_back(Arg);
5750 CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg));
5754 // If we have any leftover arguments, then there were too many arguments.
5755 // Complain and fail.
5756 if (ArgIdx < NumArgs) {
5757 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5758 << /*too many args*/1
5759 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5760 << Template
5761 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5762 NoteTemplateLocation(*Template, Params->getSourceRange());
5763 return true;
5766 // No problems found with the new argument list, propagate changes back
5767 // to caller.
5768 if (UpdateArgsWithConversions)
5769 TemplateArgs = std::move(NewArgs);
5771 if (!PartialTemplateArgs) {
5772 // Setup the context/ThisScope for the case where we are needing to
5773 // re-instantiate constraints outside of normal instantiation.
5774 DeclContext *NewContext = Template->getDeclContext();
5776 // If this template is in a template, make sure we extract the templated
5777 // decl.
5778 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
5779 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
5780 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);
5782 Qualifiers ThisQuals;
5783 if (const auto *Method =
5784 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))
5785 ThisQuals = Method->getMethodQualifiers();
5787 ContextRAII Context(*this, NewContext);
5788 CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
5790 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
5791 Template, NewContext, /*Final=*/false, CanonicalConverted,
5792 /*RelativeToPrimary=*/true,
5793 /*Pattern=*/nullptr,
5794 /*ForConceptInstantiation=*/true);
5795 if (EnsureTemplateArgumentListConstraints(
5796 Template, MLTAL,
5797 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
5798 if (ConstraintsNotSatisfied)
5799 *ConstraintsNotSatisfied = true;
5800 return true;
5804 return false;
5807 namespace {
5808 class UnnamedLocalNoLinkageFinder
5809 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5811 Sema &S;
5812 SourceRange SR;
5814 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
5816 public:
5817 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5819 bool Visit(QualType T) {
5820 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5823 #define TYPE(Class, Parent) \
5824 bool Visit##Class##Type(const Class##Type *);
5825 #define ABSTRACT_TYPE(Class, Parent) \
5826 bool Visit##Class##Type(const Class##Type *) { return false; }
5827 #define NON_CANONICAL_TYPE(Class, Parent) \
5828 bool Visit##Class##Type(const Class##Type *) { return false; }
5829 #include "clang/AST/TypeNodes.inc"
5831 bool VisitTagDecl(const TagDecl *Tag);
5832 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5834 } // end anonymous namespace
5836 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5837 return false;
5840 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5841 return Visit(T->getElementType());
5844 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5845 return Visit(T->getPointeeType());
5848 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5849 const BlockPointerType* T) {
5850 return Visit(T->getPointeeType());
5853 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5854 const LValueReferenceType* T) {
5855 return Visit(T->getPointeeType());
5858 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5859 const RValueReferenceType* T) {
5860 return Visit(T->getPointeeType());
5863 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5864 const MemberPointerType* T) {
5865 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5868 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5869 const ConstantArrayType* T) {
5870 return Visit(T->getElementType());
5873 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5874 const IncompleteArrayType* T) {
5875 return Visit(T->getElementType());
5878 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5879 const VariableArrayType* T) {
5880 return Visit(T->getElementType());
5883 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5884 const DependentSizedArrayType* T) {
5885 return Visit(T->getElementType());
5888 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5889 const DependentSizedExtVectorType* T) {
5890 return Visit(T->getElementType());
5893 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
5894 const DependentSizedMatrixType *T) {
5895 return Visit(T->getElementType());
5898 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5899 const DependentAddressSpaceType *T) {
5900 return Visit(T->getPointeeType());
5903 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5904 return Visit(T->getElementType());
5907 bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
5908 const DependentVectorType *T) {
5909 return Visit(T->getElementType());
5912 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5913 return Visit(T->getElementType());
5916 bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
5917 const ConstantMatrixType *T) {
5918 return Visit(T->getElementType());
5921 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5922 const FunctionProtoType* T) {
5923 for (const auto &A : T->param_types()) {
5924 if (Visit(A))
5925 return true;
5928 return Visit(T->getReturnType());
5931 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5932 const FunctionNoProtoType* T) {
5933 return Visit(T->getReturnType());
5936 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5937 const UnresolvedUsingType*) {
5938 return false;
5941 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5942 return false;
5945 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5946 return Visit(T->getUnmodifiedType());
5949 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5950 return false;
5953 bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
5954 const PackIndexingType *) {
5955 return false;
5958 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5959 const UnaryTransformType*) {
5960 return false;
5963 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5964 return Visit(T->getDeducedType());
5967 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5968 const DeducedTemplateSpecializationType *T) {
5969 return Visit(T->getDeducedType());
5972 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5973 return VisitTagDecl(T->getDecl());
5976 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5977 return VisitTagDecl(T->getDecl());
5980 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5981 const TemplateTypeParmType*) {
5982 return false;
5985 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5986 const SubstTemplateTypeParmPackType *) {
5987 return false;
5990 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5991 const TemplateSpecializationType*) {
5992 return false;
5995 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5996 const InjectedClassNameType* T) {
5997 return VisitTagDecl(T->getDecl());
6000 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6001 const DependentNameType* T) {
6002 return VisitNestedNameSpecifier(T->getQualifier());
6005 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6006 const DependentTemplateSpecializationType* T) {
6007 if (auto *Q = T->getQualifier())
6008 return VisitNestedNameSpecifier(Q);
6009 return false;
6012 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6013 const PackExpansionType* T) {
6014 return Visit(T->getPattern());
6017 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6018 return false;
6021 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6022 const ObjCInterfaceType *) {
6023 return false;
6026 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6027 const ObjCObjectPointerType *) {
6028 return false;
6031 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6032 return Visit(T->getValueType());
6035 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6036 return false;
6039 bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6040 return false;
6043 bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6044 const ArrayParameterType *T) {
6045 return VisitConstantArrayType(T);
6048 bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6049 const DependentBitIntType *T) {
6050 return false;
6053 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6054 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6055 S.Diag(SR.getBegin(),
6056 S.getLangOpts().CPlusPlus11 ?
6057 diag::warn_cxx98_compat_template_arg_local_type :
6058 diag::ext_template_arg_local_type)
6059 << S.Context.getTypeDeclType(Tag) << SR;
6060 return true;
6063 if (!Tag->hasNameForLinkage()) {
6064 S.Diag(SR.getBegin(),
6065 S.getLangOpts().CPlusPlus11 ?
6066 diag::warn_cxx98_compat_template_arg_unnamed_type :
6067 diag::ext_template_arg_unnamed_type) << SR;
6068 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
6069 return true;
6072 return false;
6075 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6076 NestedNameSpecifier *NNS) {
6077 assert(NNS);
6078 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
6079 return true;
6081 switch (NNS->getKind()) {
6082 case NestedNameSpecifier::Identifier:
6083 case NestedNameSpecifier::Namespace:
6084 case NestedNameSpecifier::NamespaceAlias:
6085 case NestedNameSpecifier::Global:
6086 case NestedNameSpecifier::Super:
6087 return false;
6089 case NestedNameSpecifier::TypeSpec:
6090 case NestedNameSpecifier::TypeSpecWithTemplate:
6091 return Visit(QualType(NNS->getAsType(), 0));
6093 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6096 bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6097 const HLSLAttributedResourceType *T) {
6098 if (T->hasContainedType() && Visit(T->getContainedType()))
6099 return true;
6100 return Visit(T->getWrappedType());
6103 bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6104 assert(ArgInfo && "invalid TypeSourceInfo");
6105 QualType Arg = ArgInfo->getType();
6106 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6107 QualType CanonArg = Context.getCanonicalType(Arg);
6109 if (CanonArg->isVariablyModifiedType()) {
6110 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
6111 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
6112 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
6115 // C++03 [temp.arg.type]p2:
6116 // A local type, a type with no linkage, an unnamed type or a type
6117 // compounded from any of these types shall not be used as a
6118 // template-argument for a template type-parameter.
6120 // C++11 allows these, and even in C++03 we allow them as an extension with
6121 // a warning.
6122 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6123 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6124 (void)Finder.Visit(CanonArg);
6127 return false;
6130 enum NullPointerValueKind {
6131 NPV_NotNullPointer,
6132 NPV_NullPointer,
6133 NPV_Error
6136 /// Determine whether the given template argument is a null pointer
6137 /// value of the appropriate type.
6138 static NullPointerValueKind
6139 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
6140 QualType ParamType, Expr *Arg,
6141 Decl *Entity = nullptr) {
6142 if (Arg->isValueDependent() || Arg->isTypeDependent())
6143 return NPV_NotNullPointer;
6145 // dllimport'd entities aren't constant but are available inside of template
6146 // arguments.
6147 if (Entity && Entity->hasAttr<DLLImportAttr>())
6148 return NPV_NotNullPointer;
6150 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
6151 llvm_unreachable(
6152 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6154 if (!S.getLangOpts().CPlusPlus11)
6155 return NPV_NotNullPointer;
6157 // Determine whether we have a constant expression.
6158 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
6159 if (ArgRV.isInvalid())
6160 return NPV_Error;
6161 Arg = ArgRV.get();
6163 Expr::EvalResult EvalResult;
6164 SmallVector<PartialDiagnosticAt, 8> Notes;
6165 EvalResult.Diag = &Notes;
6166 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
6167 EvalResult.HasSideEffects) {
6168 SourceLocation DiagLoc = Arg->getExprLoc();
6170 // If our only note is the usual "invalid subexpression" note, just point
6171 // the caret at its location rather than producing an essentially
6172 // redundant note.
6173 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6174 diag::note_invalid_subexpr_in_const_expr) {
6175 DiagLoc = Notes[0].first;
6176 Notes.clear();
6179 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
6180 << Arg->getType() << Arg->getSourceRange();
6181 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6182 S.Diag(Notes[I].first, Notes[I].second);
6184 S.NoteTemplateParameterLocation(*Param);
6185 return NPV_Error;
6188 // C++11 [temp.arg.nontype]p1:
6189 // - an address constant expression of type std::nullptr_t
6190 if (Arg->getType()->isNullPtrType())
6191 return NPV_NullPointer;
6193 // - a constant expression that evaluates to a null pointer value (4.10); or
6194 // - a constant expression that evaluates to a null member pointer value
6195 // (4.11); or
6196 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6197 (EvalResult.Val.isMemberPointer() &&
6198 !EvalResult.Val.getMemberPointerDecl())) {
6199 // If our expression has an appropriate type, we've succeeded.
6200 bool ObjCLifetimeConversion;
6201 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
6202 S.IsQualificationConversion(Arg->getType(), ParamType, false,
6203 ObjCLifetimeConversion))
6204 return NPV_NullPointer;
6206 // The types didn't match, but we know we got a null pointer; complain,
6207 // then recover as if the types were correct.
6208 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
6209 << Arg->getType() << ParamType << Arg->getSourceRange();
6210 S.NoteTemplateParameterLocation(*Param);
6211 return NPV_NullPointer;
6214 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6215 // We found a pointer that isn't null, but doesn't refer to an object.
6216 // We could just return NPV_NotNullPointer, but we can print a better
6217 // message with the information we have here.
6218 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
6219 << EvalResult.Val.getAsString(S.Context, ParamType);
6220 S.NoteTemplateParameterLocation(*Param);
6221 return NPV_Error;
6224 // If we don't have a null pointer value, but we do have a NULL pointer
6225 // constant, suggest a cast to the appropriate type.
6226 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
6227 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6228 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
6229 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
6230 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
6231 ")");
6232 S.NoteTemplateParameterLocation(*Param);
6233 return NPV_NullPointer;
6236 // FIXME: If we ever want to support general, address-constant expressions
6237 // as non-type template arguments, we should return the ExprResult here to
6238 // be interpreted by the caller.
6239 return NPV_NotNullPointer;
6242 /// Checks whether the given template argument is compatible with its
6243 /// template parameter.
6244 static bool CheckTemplateArgumentIsCompatibleWithParameter(
6245 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6246 Expr *Arg, QualType ArgType) {
6247 bool ObjCLifetimeConversion;
6248 if (ParamType->isPointerType() &&
6249 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6250 S.IsQualificationConversion(ArgType, ParamType, false,
6251 ObjCLifetimeConversion)) {
6252 // For pointer-to-object types, qualification conversions are
6253 // permitted.
6254 } else {
6255 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6256 if (!ParamRef->getPointeeType()->isFunctionType()) {
6257 // C++ [temp.arg.nontype]p5b3:
6258 // For a non-type template-parameter of type reference to
6259 // object, no conversions apply. The type referred to by the
6260 // reference may be more cv-qualified than the (otherwise
6261 // identical) type of the template- argument. The
6262 // template-parameter is bound directly to the
6263 // template-argument, which shall be an lvalue.
6265 // FIXME: Other qualifiers?
6266 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6267 unsigned ArgQuals = ArgType.getCVRQualifiers();
6269 if ((ParamQuals | ArgQuals) != ParamQuals) {
6270 S.Diag(Arg->getBeginLoc(),
6271 diag::err_template_arg_ref_bind_ignores_quals)
6272 << ParamType << Arg->getType() << Arg->getSourceRange();
6273 S.NoteTemplateParameterLocation(*Param);
6274 return true;
6279 // At this point, the template argument refers to an object or
6280 // function with external linkage. We now need to check whether the
6281 // argument and parameter types are compatible.
6282 if (!S.Context.hasSameUnqualifiedType(ArgType,
6283 ParamType.getNonReferenceType())) {
6284 // We can't perform this conversion or binding.
6285 if (ParamType->isReferenceType())
6286 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
6287 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6288 else
6289 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
6290 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6291 S.NoteTemplateParameterLocation(*Param);
6292 return true;
6296 return false;
6299 /// Checks whether the given template argument is the address
6300 /// of an object or function according to C++ [temp.arg.nontype]p1.
6301 static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6302 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6303 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6304 bool Invalid = false;
6305 Expr *Arg = ArgIn;
6306 QualType ArgType = Arg->getType();
6308 bool AddressTaken = false;
6309 SourceLocation AddrOpLoc;
6310 if (S.getLangOpts().MicrosoftExt) {
6311 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6312 // dereference and address-of operators.
6313 Arg = Arg->IgnoreParenCasts();
6315 bool ExtWarnMSTemplateArg = false;
6316 UnaryOperatorKind FirstOpKind;
6317 SourceLocation FirstOpLoc;
6318 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6319 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6320 if (UnOpKind == UO_Deref)
6321 ExtWarnMSTemplateArg = true;
6322 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6323 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6324 if (!AddrOpLoc.isValid()) {
6325 FirstOpKind = UnOpKind;
6326 FirstOpLoc = UnOp->getOperatorLoc();
6328 } else
6329 break;
6331 if (FirstOpLoc.isValid()) {
6332 if (ExtWarnMSTemplateArg)
6333 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
6334 << ArgIn->getSourceRange();
6336 if (FirstOpKind == UO_AddrOf)
6337 AddressTaken = true;
6338 else if (Arg->getType()->isPointerType()) {
6339 // We cannot let pointers get dereferenced here, that is obviously not a
6340 // constant expression.
6341 assert(FirstOpKind == UO_Deref);
6342 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6343 << Arg->getSourceRange();
6346 } else {
6347 // See through any implicit casts we added to fix the type.
6348 Arg = Arg->IgnoreImpCasts();
6350 // C++ [temp.arg.nontype]p1:
6352 // A template-argument for a non-type, non-template
6353 // template-parameter shall be one of: [...]
6355 // -- the address of an object or function with external
6356 // linkage, including function templates and function
6357 // template-ids but excluding non-static class members,
6358 // expressed as & id-expression where the & is optional if
6359 // the name refers to a function or array, or if the
6360 // corresponding template-parameter is a reference; or
6362 // In C++98/03 mode, give an extension warning on any extra parentheses.
6363 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6364 bool ExtraParens = false;
6365 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6366 if (!Invalid && !ExtraParens) {
6367 S.Diag(Arg->getBeginLoc(),
6368 S.getLangOpts().CPlusPlus11
6369 ? diag::warn_cxx98_compat_template_arg_extra_parens
6370 : diag::ext_template_arg_extra_parens)
6371 << Arg->getSourceRange();
6372 ExtraParens = true;
6375 Arg = Parens->getSubExpr();
6378 while (SubstNonTypeTemplateParmExpr *subst =
6379 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6380 Arg = subst->getReplacement()->IgnoreImpCasts();
6382 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6383 if (UnOp->getOpcode() == UO_AddrOf) {
6384 Arg = UnOp->getSubExpr();
6385 AddressTaken = true;
6386 AddrOpLoc = UnOp->getOperatorLoc();
6390 while (SubstNonTypeTemplateParmExpr *subst =
6391 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6392 Arg = subst->getReplacement()->IgnoreImpCasts();
6395 ValueDecl *Entity = nullptr;
6396 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))
6397 Entity = DRE->getDecl();
6398 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))
6399 Entity = CUE->getGuidDecl();
6401 // If our parameter has pointer type, check for a null template value.
6402 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6403 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
6404 Entity)) {
6405 case NPV_NullPointer:
6406 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6407 SugaredConverted = TemplateArgument(ParamType,
6408 /*isNullPtr=*/true);
6409 CanonicalConverted =
6410 TemplateArgument(S.Context.getCanonicalType(ParamType),
6411 /*isNullPtr=*/true);
6412 return false;
6414 case NPV_Error:
6415 return true;
6417 case NPV_NotNullPointer:
6418 break;
6422 // Stop checking the precise nature of the argument if it is value dependent,
6423 // it should be checked when instantiated.
6424 if (Arg->isValueDependent()) {
6425 SugaredConverted = TemplateArgument(ArgIn);
6426 CanonicalConverted =
6427 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6428 return false;
6431 if (!Entity) {
6432 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6433 << Arg->getSourceRange();
6434 S.NoteTemplateParameterLocation(*Param);
6435 return true;
6438 // Cannot refer to non-static data members
6439 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
6440 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
6441 << Entity << Arg->getSourceRange();
6442 S.NoteTemplateParameterLocation(*Param);
6443 return true;
6446 // Cannot refer to non-static member functions
6447 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
6448 if (!Method->isStatic()) {
6449 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
6450 << Method << Arg->getSourceRange();
6451 S.NoteTemplateParameterLocation(*Param);
6452 return true;
6456 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
6457 VarDecl *Var = dyn_cast<VarDecl>(Entity);
6458 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);
6460 // A non-type template argument must refer to an object or function.
6461 if (!Func && !Var && !Guid) {
6462 // We found something, but we don't know specifically what it is.
6463 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
6464 << Arg->getSourceRange();
6465 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
6466 return true;
6469 // Address / reference template args must have external linkage in C++98.
6470 if (Entity->getFormalLinkage() == Linkage::Internal) {
6471 S.Diag(Arg->getBeginLoc(),
6472 S.getLangOpts().CPlusPlus11
6473 ? diag::warn_cxx98_compat_template_arg_object_internal
6474 : diag::ext_template_arg_object_internal)
6475 << !Func << Entity << Arg->getSourceRange();
6476 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6477 << !Func;
6478 } else if (!Entity->hasLinkage()) {
6479 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
6480 << !Func << Entity << Arg->getSourceRange();
6481 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
6482 << !Func;
6483 return true;
6486 if (Var) {
6487 // A value of reference type is not an object.
6488 if (Var->getType()->isReferenceType()) {
6489 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
6490 << Var->getType() << Arg->getSourceRange();
6491 S.NoteTemplateParameterLocation(*Param);
6492 return true;
6495 // A template argument must have static storage duration.
6496 if (Var->getTLSKind()) {
6497 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
6498 << Arg->getSourceRange();
6499 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
6500 return true;
6504 if (AddressTaken && ParamType->isReferenceType()) {
6505 // If we originally had an address-of operator, but the
6506 // parameter has reference type, complain and (if things look
6507 // like they will work) drop the address-of operator.
6508 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),
6509 ParamType.getNonReferenceType())) {
6510 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6511 << ParamType;
6512 S.NoteTemplateParameterLocation(*Param);
6513 return true;
6516 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
6517 << ParamType
6518 << FixItHint::CreateRemoval(AddrOpLoc);
6519 S.NoteTemplateParameterLocation(*Param);
6521 ArgType = Entity->getType();
6524 // If the template parameter has pointer type, either we must have taken the
6525 // address or the argument must decay to a pointer.
6526 if (!AddressTaken && ParamType->isPointerType()) {
6527 if (Func) {
6528 // Function-to-pointer decay.
6529 ArgType = S.Context.getPointerType(Func->getType());
6530 } else if (Entity->getType()->isArrayType()) {
6531 // Array-to-pointer decay.
6532 ArgType = S.Context.getArrayDecayedType(Entity->getType());
6533 } else {
6534 // If the template parameter has pointer type but the address of
6535 // this object was not taken, complain and (possibly) recover by
6536 // taking the address of the entity.
6537 ArgType = S.Context.getPointerType(Entity->getType());
6538 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
6539 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6540 << ParamType;
6541 S.NoteTemplateParameterLocation(*Param);
6542 return true;
6545 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
6546 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
6548 S.NoteTemplateParameterLocation(*Param);
6552 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6553 Arg, ArgType))
6554 return true;
6556 // Create the template argument.
6557 SugaredConverted = TemplateArgument(Entity, ParamType);
6558 CanonicalConverted =
6559 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
6560 S.Context.getCanonicalType(ParamType));
6561 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);
6562 return false;
6565 /// Checks whether the given template argument is a pointer to
6566 /// member constant according to C++ [temp.arg.nontype]p1.
6567 static bool
6568 CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param,
6569 QualType ParamType, Expr *&ResultArg,
6570 TemplateArgument &SugaredConverted,
6571 TemplateArgument &CanonicalConverted) {
6572 bool Invalid = false;
6574 Expr *Arg = ResultArg;
6575 bool ObjCLifetimeConversion;
6577 // C++ [temp.arg.nontype]p1:
6579 // A template-argument for a non-type, non-template
6580 // template-parameter shall be one of: [...]
6582 // -- a pointer to member expressed as described in 5.3.1.
6583 DeclRefExpr *DRE = nullptr;
6585 // In C++98/03 mode, give an extension warning on any extra parentheses.
6586 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6587 bool ExtraParens = false;
6588 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
6589 if (!Invalid && !ExtraParens) {
6590 S.Diag(Arg->getBeginLoc(),
6591 S.getLangOpts().CPlusPlus11
6592 ? diag::warn_cxx98_compat_template_arg_extra_parens
6593 : diag::ext_template_arg_extra_parens)
6594 << Arg->getSourceRange();
6595 ExtraParens = true;
6598 Arg = Parens->getSubExpr();
6601 while (SubstNonTypeTemplateParmExpr *subst =
6602 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
6603 Arg = subst->getReplacement()->IgnoreImpCasts();
6605 // A pointer-to-member constant written &Class::member.
6606 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
6607 if (UnOp->getOpcode() == UO_AddrOf) {
6608 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
6609 if (DRE && !DRE->getQualifier())
6610 DRE = nullptr;
6613 // A constant of pointer-to-member type.
6614 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
6615 ValueDecl *VD = DRE->getDecl();
6616 if (VD->getType()->isMemberPointerType()) {
6617 if (isa<NonTypeTemplateParmDecl>(VD)) {
6618 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6619 SugaredConverted = TemplateArgument(Arg);
6620 CanonicalConverted =
6621 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6622 } else {
6623 SugaredConverted = TemplateArgument(VD, ParamType);
6624 CanonicalConverted =
6625 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
6626 S.Context.getCanonicalType(ParamType));
6628 return Invalid;
6632 DRE = nullptr;
6635 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6637 // Check for a null pointer value.
6638 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
6639 Entity)) {
6640 case NPV_Error:
6641 return true;
6642 case NPV_NullPointer:
6643 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6644 SugaredConverted = TemplateArgument(ParamType,
6645 /*isNullPtr*/ true);
6646 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),
6647 /*isNullPtr*/ true);
6648 return false;
6649 case NPV_NotNullPointer:
6650 break;
6653 if (S.IsQualificationConversion(ResultArg->getType(),
6654 ParamType.getNonReferenceType(), false,
6655 ObjCLifetimeConversion)) {
6656 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
6657 ResultArg->getValueKind())
6658 .get();
6659 } else if (!S.Context.hasSameUnqualifiedType(
6660 ResultArg->getType(), ParamType.getNonReferenceType())) {
6661 // We can't perform this conversion.
6662 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
6663 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6664 S.NoteTemplateParameterLocation(*Param);
6665 return true;
6668 if (!DRE)
6669 return S.Diag(Arg->getBeginLoc(),
6670 diag::err_template_arg_not_pointer_to_member_form)
6671 << Arg->getSourceRange();
6673 if (isa<FieldDecl>(DRE->getDecl()) ||
6674 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6675 isa<CXXMethodDecl>(DRE->getDecl())) {
6676 assert((isa<FieldDecl>(DRE->getDecl()) ||
6677 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6678 cast<CXXMethodDecl>(DRE->getDecl())
6679 ->isImplicitObjectMemberFunction()) &&
6680 "Only non-static member pointers can make it here");
6682 // Okay: this is the address of a non-static member, and therefore
6683 // a member pointer constant.
6684 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6685 SugaredConverted = TemplateArgument(Arg);
6686 CanonicalConverted =
6687 S.Context.getCanonicalTemplateArgument(SugaredConverted);
6688 } else {
6689 ValueDecl *D = DRE->getDecl();
6690 SugaredConverted = TemplateArgument(D, ParamType);
6691 CanonicalConverted =
6692 TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
6693 S.Context.getCanonicalType(ParamType));
6695 return Invalid;
6698 // We found something else, but we don't know specifically what it is.
6699 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
6700 << Arg->getSourceRange();
6701 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
6702 return true;
6705 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6706 QualType ParamType, Expr *Arg,
6707 TemplateArgument &SugaredConverted,
6708 TemplateArgument &CanonicalConverted,
6709 CheckTemplateArgumentKind CTAK) {
6710 SourceLocation StartLoc = Arg->getBeginLoc();
6712 // If the parameter type somehow involves auto, deduce the type now.
6713 DeducedType *DeducedT = ParamType->getContainedDeducedType();
6714 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
6715 // During template argument deduction, we allow 'decltype(auto)' to
6716 // match an arbitrary dependent argument.
6717 // FIXME: The language rules don't say what happens in this case.
6718 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6719 // expression is merely instantiation-dependent; is this enough?
6720 if (Arg->isTypeDependent()) {
6721 auto *AT = dyn_cast<AutoType>(DeducedT);
6722 if (AT && AT->isDecltypeAuto()) {
6723 SugaredConverted = TemplateArgument(Arg);
6724 CanonicalConverted = TemplateArgument(
6725 Context.getCanonicalTemplateArgument(SugaredConverted));
6726 return Arg;
6730 // When checking a deduced template argument, deduce from its type even if
6731 // the type is dependent, in order to check the types of non-type template
6732 // arguments line up properly in partial ordering.
6733 Expr *DeductionArg = Arg;
6734 if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg))
6735 DeductionArg = PE->getPattern();
6736 TypeSourceInfo *TSI =
6737 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());
6738 if (isa<DeducedTemplateSpecializationType>(DeducedT)) {
6739 InitializedEntity Entity =
6740 InitializedEntity::InitializeTemplateParameter(ParamType, Param);
6741 InitializationKind Kind = InitializationKind::CreateForInit(
6742 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);
6743 Expr *Inits[1] = {DeductionArg};
6744 ParamType =
6745 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);
6746 if (ParamType.isNull())
6747 return ExprError();
6748 } else {
6749 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
6750 Param->getDepth() + 1);
6751 ParamType = QualType();
6752 TemplateDeductionResult Result =
6753 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,
6754 /*DependentDeduction=*/true,
6755 // We do not check constraints right now because the
6756 // immediately-declared constraint of the auto type is
6757 // also an associated constraint, and will be checked
6758 // along with the other associated constraints after
6759 // checking the template argument list.
6760 /*IgnoreConstraints=*/true);
6761 if (Result == TemplateDeductionResult::AlreadyDiagnosed) {
6762 if (ParamType.isNull())
6763 return ExprError();
6764 } else if (Result != TemplateDeductionResult::Success) {
6765 Diag(Arg->getExprLoc(),
6766 diag::err_non_type_template_parm_type_deduction_failure)
6767 << Param->getDeclName() << Param->getType() << Arg->getType()
6768 << Arg->getSourceRange();
6769 NoteTemplateParameterLocation(*Param);
6770 return ExprError();
6773 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6774 // an error. The error message normally references the parameter
6775 // declaration, but here we'll pass the argument location because that's
6776 // where the parameter type is deduced.
6777 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6778 if (ParamType.isNull()) {
6779 NoteTemplateParameterLocation(*Param);
6780 return ExprError();
6784 // We should have already dropped all cv-qualifiers by now.
6785 assert(!ParamType.hasQualifiers() &&
6786 "non-type template parameter type cannot be qualified");
6788 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
6789 if (CTAK == CTAK_Deduced &&
6790 (ParamType->isReferenceType()
6791 ? !Context.hasSameType(ParamType.getNonReferenceType(),
6792 Arg->getType())
6793 : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) {
6794 // FIXME: If either type is dependent, we skip the check. This isn't
6795 // correct, since during deduction we're supposed to have replaced each
6796 // template parameter with some unique (non-dependent) placeholder.
6797 // FIXME: If the argument type contains 'auto', we carry on and fail the
6798 // type check in order to force specific types to be more specialized than
6799 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6800 // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
6801 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6802 !Arg->getType()->getContainedDeducedType()) {
6803 SugaredConverted = TemplateArgument(Arg);
6804 CanonicalConverted = TemplateArgument(
6805 Context.getCanonicalTemplateArgument(SugaredConverted));
6806 return Arg;
6808 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6809 // we should actually be checking the type of the template argument in P,
6810 // not the type of the template argument deduced from A, against the
6811 // template parameter type.
6812 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6813 << Arg->getType()
6814 << ParamType.getUnqualifiedType();
6815 NoteTemplateParameterLocation(*Param);
6816 return ExprError();
6819 // If either the parameter has a dependent type or the argument is
6820 // type-dependent, there's nothing we can check now.
6821 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6822 // Force the argument to the type of the parameter to maintain invariants.
6823 auto *PE = dyn_cast<PackExpansionExpr>(Arg);
6824 if (PE)
6825 Arg = PE->getPattern();
6826 ExprResult E = ImpCastExprToType(
6827 Arg, ParamType.getNonLValueExprType(Context), CK_Dependent,
6828 ParamType->isLValueReferenceType() ? VK_LValue
6829 : ParamType->isRValueReferenceType() ? VK_XValue
6830 : VK_PRValue);
6831 if (E.isInvalid())
6832 return ExprError();
6833 if (PE) {
6834 // Recreate a pack expansion if we unwrapped one.
6835 E = new (Context)
6836 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
6837 PE->getNumExpansions());
6839 SugaredConverted = TemplateArgument(E.get());
6840 CanonicalConverted = TemplateArgument(
6841 Context.getCanonicalTemplateArgument(SugaredConverted));
6842 return E;
6845 QualType CanonParamType = Context.getCanonicalType(ParamType);
6846 // Avoid making a copy when initializing a template parameter of class type
6847 // from a template parameter object of the same type. This is going beyond
6848 // the standard, but is required for soundness: in
6849 // template<A a> struct X { X *p; X<a> *q; };
6850 // ... we need p and q to have the same type.
6852 // Similarly, don't inject a call to a copy constructor when initializing
6853 // from a template parameter of the same type.
6854 Expr *InnerArg = Arg->IgnoreParenImpCasts();
6855 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&
6856 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {
6857 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();
6858 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
6860 SugaredConverted = TemplateArgument(TPO, ParamType);
6861 CanonicalConverted =
6862 TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
6863 return Arg;
6865 if (isa<NonTypeTemplateParmDecl>(ND)) {
6866 SugaredConverted = TemplateArgument(Arg);
6867 CanonicalConverted =
6868 Context.getCanonicalTemplateArgument(SugaredConverted);
6869 return Arg;
6873 // The initialization of the parameter from the argument is
6874 // a constant-evaluated context.
6875 EnterExpressionEvaluationContext ConstantEvaluated(
6876 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6878 bool IsConvertedConstantExpression = true;
6879 if (isa<InitListExpr>(Arg) || ParamType->isRecordType()) {
6880 InitializationKind Kind = InitializationKind::CreateForInit(
6881 Arg->getBeginLoc(), /*DirectInit=*/false, Arg);
6882 Expr *Inits[1] = {Arg};
6883 InitializedEntity Entity =
6884 InitializedEntity::InitializeTemplateParameter(ParamType, Param);
6885 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
6886 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);
6887 if (Result.isInvalid() || !Result.get())
6888 return ExprError();
6889 Result = ActOnConstantExpression(Result.get());
6890 if (Result.isInvalid() || !Result.get())
6891 return ExprError();
6892 Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
6893 /*DiscardedValue=*/false,
6894 /*IsConstexpr=*/true, /*IsTemplateArgument=*/true)
6895 .get();
6896 IsConvertedConstantExpression = false;
6899 if (getLangOpts().CPlusPlus17) {
6900 // C++17 [temp.arg.nontype]p1:
6901 // A template-argument for a non-type template parameter shall be
6902 // a converted constant expression of the type of the template-parameter.
6903 APValue Value;
6904 ExprResult ArgResult;
6905 if (IsConvertedConstantExpression) {
6906 ArgResult = BuildConvertedConstantExpression(Arg, ParamType,
6907 CCEK_TemplateArg, Param);
6908 if (ArgResult.isInvalid())
6909 return ExprError();
6910 } else {
6911 ArgResult = Arg;
6914 // For a value-dependent argument, CheckConvertedConstantExpression is
6915 // permitted (and expected) to be unable to determine a value.
6916 if (ArgResult.get()->isValueDependent()) {
6917 SugaredConverted = TemplateArgument(ArgResult.get());
6918 CanonicalConverted =
6919 Context.getCanonicalTemplateArgument(SugaredConverted);
6920 return ArgResult;
6923 APValue PreNarrowingValue;
6924 ArgResult = EvaluateConvertedConstantExpression(
6925 ArgResult.get(), ParamType, Value, CCEK_TemplateArg, /*RequireInt=*/
6926 false, PreNarrowingValue);
6927 if (ArgResult.isInvalid())
6928 return ExprError();
6930 if (Value.isLValue()) {
6931 APValue::LValueBase Base = Value.getLValueBase();
6932 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
6933 // For a non-type template-parameter of pointer or reference type,
6934 // the value of the constant expression shall not refer to
6935 assert(ParamType->isPointerOrReferenceType() ||
6936 ParamType->isNullPtrType());
6937 // -- a temporary object
6938 // -- a string literal
6939 // -- the result of a typeid expression, or
6940 // -- a predefined __func__ variable
6941 if (Base &&
6942 (!VD ||
6943 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {
6944 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
6945 << Arg->getSourceRange();
6946 return ExprError();
6949 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
6950 VD->getType()->isArrayType() &&
6951 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
6952 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6953 SugaredConverted = TemplateArgument(VD, ParamType);
6954 CanonicalConverted = TemplateArgument(
6955 cast<ValueDecl>(VD->getCanonicalDecl()), CanonParamType);
6956 return ArgResult.get();
6959 // -- a subobject [until C++20]
6960 if (!getLangOpts().CPlusPlus20) {
6961 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6962 Value.isLValueOnePastTheEnd()) {
6963 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6964 << Value.getAsString(Context, ParamType);
6965 return ExprError();
6967 assert((VD || !ParamType->isReferenceType()) &&
6968 "null reference should not be a constant expression");
6969 assert((!VD || !ParamType->isNullPtrType()) &&
6970 "non-null value of type nullptr_t?");
6974 if (Value.isAddrLabelDiff())
6975 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6977 SugaredConverted = TemplateArgument(Context, ParamType, Value);
6978 CanonicalConverted = TemplateArgument(Context, CanonParamType, Value);
6979 return ArgResult.get();
6982 // C++ [temp.arg.nontype]p5:
6983 // The following conversions are performed on each expression used
6984 // as a non-type template-argument. If a non-type
6985 // template-argument cannot be converted to the type of the
6986 // corresponding template-parameter then the program is
6987 // ill-formed.
6988 if (ParamType->isIntegralOrEnumerationType()) {
6989 // C++11:
6990 // -- for a non-type template-parameter of integral or
6991 // enumeration type, conversions permitted in a converted
6992 // constant expression are applied.
6994 // C++98:
6995 // -- for a non-type template-parameter of integral or
6996 // enumeration type, integral promotions (4.5) and integral
6997 // conversions (4.7) are applied.
6999 if (getLangOpts().CPlusPlus11) {
7000 // C++ [temp.arg.nontype]p1:
7001 // A template-argument for a non-type, non-template template-parameter
7002 // shall be one of:
7004 // -- for a non-type template-parameter of integral or enumeration
7005 // type, a converted constant expression of the type of the
7006 // template-parameter; or
7007 llvm::APSInt Value;
7008 ExprResult ArgResult =
7009 CheckConvertedConstantExpression(Arg, ParamType, Value,
7010 CCEK_TemplateArg);
7011 if (ArgResult.isInvalid())
7012 return ExprError();
7014 // We can't check arbitrary value-dependent arguments.
7015 if (ArgResult.get()->isValueDependent()) {
7016 SugaredConverted = TemplateArgument(ArgResult.get());
7017 CanonicalConverted =
7018 Context.getCanonicalTemplateArgument(SugaredConverted);
7019 return ArgResult;
7022 // Widen the argument value to sizeof(parameter type). This is almost
7023 // always a no-op, except when the parameter type is bool. In
7024 // that case, this may extend the argument from 1 bit to 8 bits.
7025 QualType IntegerType = ParamType;
7026 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
7027 IntegerType = Enum->getDecl()->getIntegerType();
7028 Value = Value.extOrTrunc(IntegerType->isBitIntType()
7029 ? Context.getIntWidth(IntegerType)
7030 : Context.getTypeSize(IntegerType));
7032 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7033 CanonicalConverted =
7034 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));
7035 return ArgResult;
7038 ExprResult ArgResult = DefaultLvalueConversion(Arg);
7039 if (ArgResult.isInvalid())
7040 return ExprError();
7041 Arg = ArgResult.get();
7043 QualType ArgType = Arg->getType();
7045 // C++ [temp.arg.nontype]p1:
7046 // A template-argument for a non-type, non-template
7047 // template-parameter shall be one of:
7049 // -- an integral constant-expression of integral or enumeration
7050 // type; or
7051 // -- the name of a non-type template-parameter; or
7052 llvm::APSInt Value;
7053 if (!ArgType->isIntegralOrEnumerationType()) {
7054 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
7055 << ArgType << Arg->getSourceRange();
7056 NoteTemplateParameterLocation(*Param);
7057 return ExprError();
7058 } else if (!Arg->isValueDependent()) {
7059 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7060 QualType T;
7062 public:
7063 TmplArgICEDiagnoser(QualType T) : T(T) { }
7065 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7066 SourceLocation Loc) override {
7067 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
7069 } Diagnoser(ArgType);
7071 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
7072 if (!Arg)
7073 return ExprError();
7076 // From here on out, all we care about is the unqualified form
7077 // of the argument type.
7078 ArgType = ArgType.getUnqualifiedType();
7080 // Try to convert the argument to the parameter's type.
7081 if (Context.hasSameType(ParamType, ArgType)) {
7082 // Okay: no conversion necessary
7083 } else if (ParamType->isBooleanType()) {
7084 // This is an integral-to-boolean conversion.
7085 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
7086 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
7087 !ParamType->isEnumeralType()) {
7088 // This is an integral promotion or conversion.
7089 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
7090 } else {
7091 // We can't perform this conversion.
7092 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
7093 << Arg->getType() << ParamType << Arg->getSourceRange();
7094 NoteTemplateParameterLocation(*Param);
7095 return ExprError();
7098 // Add the value of this argument to the list of converted
7099 // arguments. We use the bitwidth and signedness of the template
7100 // parameter.
7101 if (Arg->isValueDependent()) {
7102 // The argument is value-dependent. Create a new
7103 // TemplateArgument with the converted expression.
7104 SugaredConverted = TemplateArgument(Arg);
7105 CanonicalConverted =
7106 Context.getCanonicalTemplateArgument(SugaredConverted);
7107 return Arg;
7110 QualType IntegerType = ParamType;
7111 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
7112 IntegerType = Enum->getDecl()->getIntegerType();
7115 if (ParamType->isBooleanType()) {
7116 // Value must be zero or one.
7117 Value = Value != 0;
7118 unsigned AllowedBits = Context.getTypeSize(IntegerType);
7119 if (Value.getBitWidth() != AllowedBits)
7120 Value = Value.extOrTrunc(AllowedBits);
7121 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7122 } else {
7123 llvm::APSInt OldValue = Value;
7125 // Coerce the template argument's value to the value it will have
7126 // based on the template parameter's type.
7127 unsigned AllowedBits = IntegerType->isBitIntType()
7128 ? Context.getIntWidth(IntegerType)
7129 : Context.getTypeSize(IntegerType);
7130 if (Value.getBitWidth() != AllowedBits)
7131 Value = Value.extOrTrunc(AllowedBits);
7132 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7134 // Complain if an unsigned parameter received a negative value.
7135 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7136 (OldValue.isSigned() && OldValue.isNegative())) {
7137 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
7138 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7139 << Arg->getSourceRange();
7140 NoteTemplateParameterLocation(*Param);
7143 // Complain if we overflowed the template parameter's type.
7144 unsigned RequiredBits;
7145 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7146 RequiredBits = OldValue.getActiveBits();
7147 else if (OldValue.isUnsigned())
7148 RequiredBits = OldValue.getActiveBits() + 1;
7149 else
7150 RequiredBits = OldValue.getSignificantBits();
7151 if (RequiredBits > AllowedBits) {
7152 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
7153 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
7154 << Arg->getSourceRange();
7155 NoteTemplateParameterLocation(*Param);
7159 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7160 SugaredConverted = TemplateArgument(Context, Value, T);
7161 CanonicalConverted =
7162 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7163 return Arg;
7166 QualType ArgType = Arg->getType();
7167 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7169 // Handle pointer-to-function, reference-to-function, and
7170 // pointer-to-member-function all in (roughly) the same way.
7171 if (// -- For a non-type template-parameter of type pointer to
7172 // function, only the function-to-pointer conversion (4.3) is
7173 // applied. If the template-argument represents a set of
7174 // overloaded functions (or a pointer to such), the matching
7175 // function is selected from the set (13.4).
7176 (ParamType->isPointerType() &&
7177 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7178 // -- For a non-type template-parameter of type reference to
7179 // function, no conversions apply. If the template-argument
7180 // represents a set of overloaded functions, the matching
7181 // function is selected from the set (13.4).
7182 (ParamType->isReferenceType() &&
7183 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7184 // -- For a non-type template-parameter of type pointer to
7185 // member function, no conversions apply. If the
7186 // template-argument represents a set of overloaded member
7187 // functions, the matching member function is selected from
7188 // the set (13.4).
7189 (ParamType->isMemberPointerType() &&
7190 ParamType->castAs<MemberPointerType>()->getPointeeType()
7191 ->isFunctionType())) {
7193 if (Arg->getType() == Context.OverloadTy) {
7194 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
7195 true,
7196 FoundResult)) {
7197 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7198 return ExprError();
7200 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7201 if (Res.isInvalid())
7202 return ExprError();
7203 Arg = Res.get();
7204 ArgType = Arg->getType();
7205 } else
7206 return ExprError();
7209 if (!ParamType->isMemberPointerType()) {
7210 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7211 *this, Param, ParamType, Arg, SugaredConverted,
7212 CanonicalConverted))
7213 return ExprError();
7214 return Arg;
7217 if (CheckTemplateArgumentPointerToMember(
7218 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7219 return ExprError();
7220 return Arg;
7223 if (ParamType->isPointerType()) {
7224 // -- for a non-type template-parameter of type pointer to
7225 // object, qualification conversions (4.4) and the
7226 // array-to-pointer conversion (4.2) are applied.
7227 // C++0x also allows a value of std::nullptr_t.
7228 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7229 "Only object pointers allowed here");
7231 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7232 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7233 return ExprError();
7234 return Arg;
7237 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7238 // -- For a non-type template-parameter of type reference to
7239 // object, no conversions apply. The type referred to by the
7240 // reference may be more cv-qualified than the (otherwise
7241 // identical) type of the template-argument. The
7242 // template-parameter is bound directly to the
7243 // template-argument, which must be an lvalue.
7244 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7245 "Only object references allowed here");
7247 if (Arg->getType() == Context.OverloadTy) {
7248 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
7249 ParamRefType->getPointeeType(),
7250 true,
7251 FoundResult)) {
7252 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))
7253 return ExprError();
7254 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
7255 if (Res.isInvalid())
7256 return ExprError();
7257 Arg = Res.get();
7258 ArgType = Arg->getType();
7259 } else
7260 return ExprError();
7263 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7264 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7265 return ExprError();
7266 return Arg;
7269 // Deal with parameters of type std::nullptr_t.
7270 if (ParamType->isNullPtrType()) {
7271 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7272 SugaredConverted = TemplateArgument(Arg);
7273 CanonicalConverted =
7274 Context.getCanonicalTemplateArgument(SugaredConverted);
7275 return Arg;
7278 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
7279 case NPV_NotNullPointer:
7280 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
7281 << Arg->getType() << ParamType;
7282 NoteTemplateParameterLocation(*Param);
7283 return ExprError();
7285 case NPV_Error:
7286 return ExprError();
7288 case NPV_NullPointer:
7289 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7290 SugaredConverted = TemplateArgument(ParamType,
7291 /*isNullPtr=*/true);
7292 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),
7293 /*isNullPtr=*/true);
7294 return Arg;
7298 // -- For a non-type template-parameter of type pointer to data
7299 // member, qualification conversions (4.4) are applied.
7300 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7302 if (CheckTemplateArgumentPointerToMember(
7303 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))
7304 return ExprError();
7305 return Arg;
7308 static void DiagnoseTemplateParameterListArityMismatch(
7309 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7310 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7312 bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7313 TemplateParameterList *Params,
7314 TemplateArgumentLoc &Arg,
7315 bool IsDeduced) {
7316 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7317 auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7318 if (!Template) {
7319 // Any dependent template name is fine.
7320 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7321 return false;
7324 if (Template->isInvalidDecl())
7325 return true;
7327 // C++0x [temp.arg.template]p1:
7328 // A template-argument for a template template-parameter shall be
7329 // the name of a class template or an alias template, expressed as an
7330 // id-expression. When the template-argument names a class template, only
7331 // primary class templates are considered when matching the
7332 // template template argument with the corresponding parameter;
7333 // partial specializations are not considered even if their
7334 // parameter lists match that of the template template parameter.
7336 // Note that we also allow template template parameters here, which
7337 // will happen when we are dealing with, e.g., class template
7338 // partial specializations.
7339 if (!isa<ClassTemplateDecl>(Template) &&
7340 !isa<TemplateTemplateParmDecl>(Template) &&
7341 !isa<TypeAliasTemplateDecl>(Template) &&
7342 !isa<BuiltinTemplateDecl>(Template)) {
7343 assert(isa<FunctionTemplateDecl>(Template) &&
7344 "Only function templates are possible here");
7345 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
7346 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
7347 << Template;
7350 // C++1z [temp.arg.template]p3: (DR 150)
7351 // A template-argument matches a template template-parameter P when P
7352 // is at least as specialized as the template-argument A.
7353 if (getLangOpts().RelaxedTemplateTemplateArgs) {
7354 // Quick check for the common case:
7355 // If P contains a parameter pack, then A [...] matches P if each of A's
7356 // template parameters matches the corresponding template parameter in
7357 // the template-parameter-list of P.
7358 if (TemplateParameterListsAreEqual(
7359 Template->getTemplateParameters(), Params, false,
7360 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()) &&
7361 // If the argument has no associated constraints, then the parameter is
7362 // definitely at least as specialized as the argument.
7363 // Otherwise - we need a more thorough check.
7364 !Template->hasAssociatedConstraints())
7365 return false;
7367 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(
7368 Params, Template, DefaultArgs, Arg.getLocation(), IsDeduced)) {
7369 // P2113
7370 // C++20[temp.func.order]p2
7371 // [...] If both deductions succeed, the partial ordering selects the
7372 // more constrained template (if one exists) as determined below.
7373 SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
7374 Params->getAssociatedConstraints(ParamsAC);
7375 // C++2a[temp.arg.template]p3
7376 // [...] In this comparison, if P is unconstrained, the constraints on A
7377 // are not considered.
7378 if (ParamsAC.empty())
7379 return false;
7381 Template->getAssociatedConstraints(TemplateAC);
7383 bool IsParamAtLeastAsConstrained;
7384 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
7385 IsParamAtLeastAsConstrained))
7386 return true;
7387 if (!IsParamAtLeastAsConstrained) {
7388 Diag(Arg.getLocation(),
7389 diag::err_template_template_parameter_not_at_least_as_constrained)
7390 << Template << Param << Arg.getSourceRange();
7391 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
7392 Diag(Template->getLocation(), diag::note_entity_declared_at)
7393 << Template;
7394 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
7395 TemplateAC);
7396 return true;
7398 return false;
7400 // FIXME: Produce better diagnostics for deduction failures.
7403 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
7404 Params,
7405 true,
7406 TPL_TemplateTemplateArgumentMatch,
7407 Arg.getLocation());
7410 static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7411 unsigned HereDiagID,
7412 unsigned ExternalDiagID) {
7413 if (Decl.getLocation().isValid())
7414 return S.Diag(Decl.getLocation(), HereDiagID);
7416 SmallString<128> Str;
7417 llvm::raw_svector_ostream Out(Str);
7418 PrintingPolicy PP = S.getPrintingPolicy();
7419 PP.TerseOutput = 1;
7420 Decl.print(Out, PP);
7421 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
7424 void Sema::NoteTemplateLocation(const NamedDecl &Decl,
7425 std::optional<SourceRange> ParamRange) {
7426 SemaDiagnosticBuilder DB =
7427 noteLocation(*this, Decl, diag::note_template_decl_here,
7428 diag::note_template_decl_external);
7429 if (ParamRange && ParamRange->isValid()) {
7430 assert(Decl.getLocation().isValid() &&
7431 "Parameter range has location when Decl does not");
7432 DB << *ParamRange;
7436 void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
7437 noteLocation(*this, Decl, diag::note_template_param_here,
7438 diag::note_template_param_external);
7441 ExprResult Sema::BuildExpressionFromDeclTemplateArgument(
7442 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7443 NamedDecl *TemplateParam) {
7444 // C++ [temp.param]p8:
7446 // A non-type template-parameter of type "array of T" or
7447 // "function returning T" is adjusted to be of type "pointer to
7448 // T" or "pointer to function returning T", respectively.
7449 if (ParamType->isArrayType())
7450 ParamType = Context.getArrayDecayedType(ParamType);
7451 else if (ParamType->isFunctionType())
7452 ParamType = Context.getPointerType(ParamType);
7454 // For a NULL non-type template argument, return nullptr casted to the
7455 // parameter's type.
7456 if (Arg.getKind() == TemplateArgument::NullPtr) {
7457 return ImpCastExprToType(
7458 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7459 ParamType,
7460 ParamType->getAs<MemberPointerType>()
7461 ? CK_NullToMemberPointer
7462 : CK_NullToPointer);
7464 assert(Arg.getKind() == TemplateArgument::Declaration &&
7465 "Only declaration template arguments permitted here");
7467 ValueDecl *VD = Arg.getAsDecl();
7469 CXXScopeSpec SS;
7470 if (ParamType->isMemberPointerType()) {
7471 // If this is a pointer to member, we need to use a qualified name to
7472 // form a suitable pointer-to-member constant.
7473 assert(VD->getDeclContext()->isRecord() &&
7474 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7475 isa<IndirectFieldDecl>(VD)));
7476 QualType ClassType
7477 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
7478 NestedNameSpecifier *Qualifier
7479 = NestedNameSpecifier::Create(Context, nullptr, false,
7480 ClassType.getTypePtr());
7481 SS.MakeTrivial(Context, Qualifier, Loc);
7484 ExprResult RefExpr = BuildDeclarationNameExpr(
7485 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
7486 if (RefExpr.isInvalid())
7487 return ExprError();
7489 // For a pointer, the argument declaration is the pointee. Take its address.
7490 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7491 if (ParamType->isPointerType() && !ElemT.isNull() &&
7492 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {
7493 // Decay an array argument if we want a pointer to its first element.
7494 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
7495 if (RefExpr.isInvalid())
7496 return ExprError();
7497 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7498 // For any other pointer, take the address (or form a pointer-to-member).
7499 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
7500 if (RefExpr.isInvalid())
7501 return ExprError();
7502 } else if (ParamType->isRecordType()) {
7503 assert(isa<TemplateParamObjectDecl>(VD) &&
7504 "arg for class template param not a template parameter object");
7505 // No conversions apply in this case.
7506 return RefExpr;
7507 } else {
7508 assert(ParamType->isReferenceType() &&
7509 "unexpected type for decl template argument");
7510 if (NonTypeTemplateParmDecl *NTTP =
7511 dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {
7512 QualType TemplateParamType = NTTP->getType();
7513 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7514 if (AT && AT->isDecltypeAuto()) {
7515 RefExpr = new (getASTContext()) SubstNonTypeTemplateParmExpr(
7516 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7517 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7518 /*PackIndex=*/std::nullopt,
7519 /*RefParam=*/true);
7524 // At this point we should have the right value category.
7525 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7526 "value kind mismatch for non-type template argument");
7528 // The type of the template parameter can differ from the type of the
7529 // argument in various ways; convert it now if necessary.
7530 QualType DestExprType = ParamType.getNonLValueExprType(Context);
7531 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {
7532 CastKind CK;
7533 QualType Ignored;
7534 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||
7535 IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) {
7536 CK = CK_NoOp;
7537 } else if (ParamType->isVoidPointerType() &&
7538 RefExpr.get()->getType()->isPointerType()) {
7539 CK = CK_BitCast;
7540 } else {
7541 // FIXME: Pointers to members can need conversion derived-to-base or
7542 // base-to-derived conversions. We currently don't retain enough
7543 // information to convert properly (we need to track a cast path or
7544 // subobject number in the template argument).
7545 llvm_unreachable(
7546 "unexpected conversion required for non-type template argument");
7548 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,
7549 RefExpr.get()->getValueKind());
7552 return RefExpr;
7555 /// Construct a new expression that refers to the given
7556 /// integral template argument with the given source-location
7557 /// information.
7559 /// This routine takes care of the mapping from an integral template
7560 /// argument (which may have any integral type) to the appropriate
7561 /// literal value.
7562 static Expr *BuildExpressionFromIntegralTemplateArgumentValue(
7563 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
7564 assert(OrigT->isIntegralOrEnumerationType());
7566 // If this is an enum type that we're instantiating, we need to use an integer
7567 // type the same size as the enumerator. We don't want to build an
7568 // IntegerLiteral with enum type. The integer type of an enum type can be of
7569 // any integral type with C++11 enum classes, make sure we create the right
7570 // type of literal for it.
7571 QualType T = OrigT;
7572 if (const EnumType *ET = OrigT->getAs<EnumType>())
7573 T = ET->getDecl()->getIntegerType();
7575 Expr *E;
7576 if (T->isAnyCharacterType()) {
7577 CharacterLiteralKind Kind;
7578 if (T->isWideCharType())
7579 Kind = CharacterLiteralKind::Wide;
7580 else if (T->isChar8Type() && S.getLangOpts().Char8)
7581 Kind = CharacterLiteralKind::UTF8;
7582 else if (T->isChar16Type())
7583 Kind = CharacterLiteralKind::UTF16;
7584 else if (T->isChar32Type())
7585 Kind = CharacterLiteralKind::UTF32;
7586 else
7587 Kind = CharacterLiteralKind::Ascii;
7589 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
7590 } else if (T->isBooleanType()) {
7591 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);
7592 } else {
7593 E = IntegerLiteral::Create(S.Context, Int, T, Loc);
7596 if (OrigT->isEnumeralType()) {
7597 // FIXME: This is a hack. We need a better way to handle substituted
7598 // non-type template parameters.
7599 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,
7600 nullptr, S.CurFPFeatureOverrides(),
7601 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),
7602 Loc, Loc);
7605 return E;
7608 static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(
7609 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
7610 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
7611 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
7612 ILE->setType(T);
7613 return ILE;
7616 switch (Val.getKind()) {
7617 case APValue::AddrLabelDiff:
7618 // This cannot occur in a template argument at all.
7619 case APValue::Array:
7620 case APValue::Struct:
7621 case APValue::Union:
7622 // These can only occur within a template parameter object, which is
7623 // represented as a TemplateArgument::Declaration.
7624 llvm_unreachable("unexpected template argument value");
7626 case APValue::Int:
7627 return BuildExpressionFromIntegralTemplateArgumentValue(S, T, Val.getInt(),
7628 Loc);
7630 case APValue::Float:
7631 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,
7632 T, Loc);
7634 case APValue::FixedPoint:
7635 return FixedPointLiteral::CreateFromRawInt(
7636 S.Context, Val.getFixedPoint().getValue(), T, Loc,
7637 Val.getFixedPoint().getScale());
7639 case APValue::ComplexInt: {
7640 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7641 return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(
7642 S, ElemT, Val.getComplexIntReal(), Loc),
7643 BuildExpressionFromIntegralTemplateArgumentValue(
7644 S, ElemT, Val.getComplexIntImag(), Loc)});
7647 case APValue::ComplexFloat: {
7648 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7649 return MakeInitList(
7650 {FloatingLiteral::Create(S.Context, Val.getComplexFloatReal(), true,
7651 ElemT, Loc),
7652 FloatingLiteral::Create(S.Context, Val.getComplexFloatImag(), true,
7653 ElemT, Loc)});
7656 case APValue::Vector: {
7657 QualType ElemT = T->castAs<VectorType>()->getElementType();
7658 llvm::SmallVector<Expr *, 8> Elts;
7659 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
7660 Elts.push_back(BuildExpressionFromNonTypeTemplateArgumentValue(
7661 S, ElemT, Val.getVectorElt(I), Loc));
7662 return MakeInitList(Elts);
7665 case APValue::None:
7666 case APValue::Indeterminate:
7667 llvm_unreachable("Unexpected APValue kind.");
7668 case APValue::LValue:
7669 case APValue::MemberPointer:
7670 // There isn't necessarily a valid equivalent source-level syntax for
7671 // these; in particular, a naive lowering might violate access control.
7672 // So for now we lower to a ConstantExpr holding the value, wrapped around
7673 // an OpaqueValueExpr.
7674 // FIXME: We should have a better representation for this.
7675 ExprValueKind VK = VK_PRValue;
7676 if (T->isReferenceType()) {
7677 T = T->getPointeeType();
7678 VK = VK_LValue;
7680 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
7681 return ConstantExpr::Create(S.Context, OVE, Val);
7683 llvm_unreachable("Unhandled APValue::ValueKind enum");
7686 ExprResult
7687 Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
7688 SourceLocation Loc) {
7689 switch (Arg.getKind()) {
7690 case TemplateArgument::Null:
7691 case TemplateArgument::Type:
7692 case TemplateArgument::Template:
7693 case TemplateArgument::TemplateExpansion:
7694 case TemplateArgument::Pack:
7695 llvm_unreachable("not a non-type template argument");
7697 case TemplateArgument::Expression:
7698 return Arg.getAsExpr();
7700 case TemplateArgument::NullPtr:
7701 case TemplateArgument::Declaration:
7702 return BuildExpressionFromDeclTemplateArgument(
7703 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);
7705 case TemplateArgument::Integral:
7706 return BuildExpressionFromIntegralTemplateArgumentValue(
7707 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);
7709 case TemplateArgument::StructuralValue:
7710 return BuildExpressionFromNonTypeTemplateArgumentValue(
7711 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);
7713 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
7716 /// Match two template parameters within template parameter lists.
7717 static bool MatchTemplateParameterKind(
7718 Sema &S, NamedDecl *New,
7719 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
7720 const NamedDecl *OldInstFrom, bool Complain,
7721 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
7722 // Check the actual kind (type, non-type, template).
7723 if (Old->getKind() != New->getKind()) {
7724 if (Complain) {
7725 unsigned NextDiag = diag::err_template_param_different_kind;
7726 if (TemplateArgLoc.isValid()) {
7727 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7728 NextDiag = diag::note_template_param_different_kind;
7730 S.Diag(New->getLocation(), NextDiag)
7731 << (Kind != Sema::TPL_TemplateMatch);
7732 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
7733 << (Kind != Sema::TPL_TemplateMatch);
7736 return false;
7739 // Check that both are parameter packs or neither are parameter packs.
7740 // However, if we are matching a template template argument to a
7741 // template template parameter, the template template parameter can have
7742 // a parameter pack where the template template argument does not.
7743 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
7744 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
7745 Old->isTemplateParameterPack())) {
7746 if (Complain) {
7747 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7748 if (TemplateArgLoc.isValid()) {
7749 S.Diag(TemplateArgLoc,
7750 diag::err_template_arg_template_params_mismatch);
7751 NextDiag = diag::note_template_parameter_pack_non_pack;
7754 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
7755 : isa<NonTypeTemplateParmDecl>(New)? 1
7756 : 2;
7757 S.Diag(New->getLocation(), NextDiag)
7758 << ParamKind << New->isParameterPack();
7759 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
7760 << ParamKind << Old->isParameterPack();
7763 return false;
7766 // For non-type template parameters, check the type of the parameter.
7767 if (NonTypeTemplateParmDecl *OldNTTP
7768 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
7769 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
7771 // If we are matching a template template argument to a template
7772 // template parameter and one of the non-type template parameter types
7773 // is dependent, then we must wait until template instantiation time
7774 // to actually compare the arguments.
7775 if (Kind != Sema::TPL_TemplateTemplateArgumentMatch ||
7776 (!OldNTTP->getType()->isDependentType() &&
7777 !NewNTTP->getType()->isDependentType())) {
7778 // C++20 [temp.over.link]p6:
7779 // Two [non-type] template-parameters are equivalent [if] they have
7780 // equivalent types ignoring the use of type-constraints for
7781 // placeholder types
7782 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());
7783 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());
7784 if (!S.Context.hasSameType(OldType, NewType)) {
7785 if (Complain) {
7786 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
7787 if (TemplateArgLoc.isValid()) {
7788 S.Diag(TemplateArgLoc,
7789 diag::err_template_arg_template_params_mismatch);
7790 NextDiag = diag::note_template_nontype_parm_different_type;
7792 S.Diag(NewNTTP->getLocation(), NextDiag)
7793 << NewNTTP->getType()
7794 << (Kind != Sema::TPL_TemplateMatch);
7795 S.Diag(OldNTTP->getLocation(),
7796 diag::note_template_nontype_parm_prev_declaration)
7797 << OldNTTP->getType();
7800 return false;
7804 // For template template parameters, check the template parameter types.
7805 // The template parameter lists of template template
7806 // parameters must agree.
7807 else if (TemplateTemplateParmDecl *OldTTP =
7808 dyn_cast<TemplateTemplateParmDecl>(Old)) {
7809 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
7810 if (!S.TemplateParameterListsAreEqual(
7811 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
7812 OldTTP->getTemplateParameters(), Complain,
7813 (Kind == Sema::TPL_TemplateMatch
7814 ? Sema::TPL_TemplateTemplateParmMatch
7815 : Kind),
7816 TemplateArgLoc))
7817 return false;
7820 if (Kind != Sema::TPL_TemplateParamsEquivalent &&
7821 Kind != Sema::TPL_TemplateTemplateArgumentMatch &&
7822 !isa<TemplateTemplateParmDecl>(Old)) {
7823 const Expr *NewC = nullptr, *OldC = nullptr;
7825 if (isa<TemplateTypeParmDecl>(New)) {
7826 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())
7827 NewC = TC->getImmediatelyDeclaredConstraint();
7828 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())
7829 OldC = TC->getImmediatelyDeclaredConstraint();
7830 } else if (isa<NonTypeTemplateParmDecl>(New)) {
7831 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)
7832 ->getPlaceholderTypeConstraint())
7833 NewC = E;
7834 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)
7835 ->getPlaceholderTypeConstraint())
7836 OldC = E;
7837 } else
7838 llvm_unreachable("unexpected template parameter type");
7840 auto Diagnose = [&] {
7841 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
7842 diag::err_template_different_type_constraint);
7843 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
7844 diag::note_template_prev_declaration) << /*declaration*/0;
7847 if (!NewC != !OldC) {
7848 if (Complain)
7849 Diagnose();
7850 return false;
7853 if (NewC) {
7854 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,
7855 NewC)) {
7856 if (Complain)
7857 Diagnose();
7858 return false;
7863 return true;
7866 /// Diagnose a known arity mismatch when comparing template argument
7867 /// lists.
7868 static
7869 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
7870 TemplateParameterList *New,
7871 TemplateParameterList *Old,
7872 Sema::TemplateParameterListEqualKind Kind,
7873 SourceLocation TemplateArgLoc) {
7874 unsigned NextDiag = diag::err_template_param_list_different_arity;
7875 if (TemplateArgLoc.isValid()) {
7876 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
7877 NextDiag = diag::note_template_param_list_different_arity;
7879 S.Diag(New->getTemplateLoc(), NextDiag)
7880 << (New->size() > Old->size())
7881 << (Kind != Sema::TPL_TemplateMatch)
7882 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
7883 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
7884 << (Kind != Sema::TPL_TemplateMatch)
7885 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
7888 bool Sema::TemplateParameterListsAreEqual(
7889 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
7890 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
7891 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
7892 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
7893 if (Complain)
7894 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7895 TemplateArgLoc);
7897 return false;
7900 // C++0x [temp.arg.template]p3:
7901 // A template-argument matches a template template-parameter (call it P)
7902 // when each of the template parameters in the template-parameter-list of
7903 // the template-argument's corresponding class template or alias template
7904 // (call it A) matches the corresponding template parameter in the
7905 // template-parameter-list of P. [...]
7906 TemplateParameterList::iterator NewParm = New->begin();
7907 TemplateParameterList::iterator NewParmEnd = New->end();
7908 for (TemplateParameterList::iterator OldParm = Old->begin(),
7909 OldParmEnd = Old->end();
7910 OldParm != OldParmEnd; ++OldParm) {
7911 if (Kind != TPL_TemplateTemplateArgumentMatch ||
7912 !(*OldParm)->isTemplateParameterPack()) {
7913 if (NewParm == NewParmEnd) {
7914 if (Complain)
7915 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7916 TemplateArgLoc);
7918 return false;
7921 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7922 OldInstFrom, Complain, Kind,
7923 TemplateArgLoc))
7924 return false;
7926 ++NewParm;
7927 continue;
7930 // C++0x [temp.arg.template]p3:
7931 // [...] When P's template- parameter-list contains a template parameter
7932 // pack (14.5.3), the template parameter pack will match zero or more
7933 // template parameters or template parameter packs in the
7934 // template-parameter-list of A with the same type and form as the
7935 // template parameter pack in P (ignoring whether those template
7936 // parameters are template parameter packs).
7937 for (; NewParm != NewParmEnd; ++NewParm) {
7938 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,
7939 OldInstFrom, Complain, Kind,
7940 TemplateArgLoc))
7941 return false;
7945 // Make sure we exhausted all of the arguments.
7946 if (NewParm != NewParmEnd) {
7947 if (Complain)
7948 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
7949 TemplateArgLoc);
7951 return false;
7954 if (Kind != TPL_TemplateTemplateArgumentMatch &&
7955 Kind != TPL_TemplateParamsEquivalent) {
7956 const Expr *NewRC = New->getRequiresClause();
7957 const Expr *OldRC = Old->getRequiresClause();
7959 auto Diagnose = [&] {
7960 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
7961 diag::err_template_different_requires_clause);
7962 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
7963 diag::note_template_prev_declaration) << /*declaration*/0;
7966 if (!NewRC != !OldRC) {
7967 if (Complain)
7968 Diagnose();
7969 return false;
7972 if (NewRC) {
7973 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,
7974 NewRC)) {
7975 if (Complain)
7976 Diagnose();
7977 return false;
7982 return true;
7985 bool
7986 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
7987 if (!S)
7988 return false;
7990 // Find the nearest enclosing declaration scope.
7991 S = S->getDeclParent();
7993 // C++ [temp.pre]p6: [P2096]
7994 // A template, explicit specialization, or partial specialization shall not
7995 // have C linkage.
7996 DeclContext *Ctx = S->getEntity();
7997 if (Ctx && Ctx->isExternCContext()) {
7998 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
7999 << TemplateParams->getSourceRange();
8000 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8001 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
8002 return true;
8004 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8006 // C++ [temp]p2:
8007 // A template-declaration can appear only as a namespace scope or
8008 // class scope declaration.
8009 // C++ [temp.expl.spec]p3:
8010 // An explicit specialization may be declared in any scope in which the
8011 // corresponding primary template may be defined.
8012 // C++ [temp.class.spec]p6: [P2096]
8013 // A partial specialization may be declared in any scope in which the
8014 // corresponding primary template may be defined.
8015 if (Ctx) {
8016 if (Ctx->isFileContext())
8017 return false;
8018 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
8019 // C++ [temp.mem]p2:
8020 // A local class shall not have member templates.
8021 if (RD->isLocalClass())
8022 return Diag(TemplateParams->getTemplateLoc(),
8023 diag::err_template_inside_local_class)
8024 << TemplateParams->getSourceRange();
8025 else
8026 return false;
8030 return Diag(TemplateParams->getTemplateLoc(),
8031 diag::err_template_outside_namespace_or_class_scope)
8032 << TemplateParams->getSourceRange();
8035 /// Determine what kind of template specialization the given declaration
8036 /// is.
8037 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8038 if (!D)
8039 return TSK_Undeclared;
8041 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
8042 return Record->getTemplateSpecializationKind();
8043 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
8044 return Function->getTemplateSpecializationKind();
8045 if (VarDecl *Var = dyn_cast<VarDecl>(D))
8046 return Var->getTemplateSpecializationKind();
8048 return TSK_Undeclared;
8051 /// Check whether a specialization is well-formed in the current
8052 /// context.
8054 /// This routine determines whether a template specialization can be declared
8055 /// in the current context (C++ [temp.expl.spec]p2).
8057 /// \param S the semantic analysis object for which this check is being
8058 /// performed.
8060 /// \param Specialized the entity being specialized or instantiated, which
8061 /// may be a kind of template (class template, function template, etc.) or
8062 /// a member of a class template (member function, static data member,
8063 /// member class).
8065 /// \param PrevDecl the previous declaration of this entity, if any.
8067 /// \param Loc the location of the explicit specialization or instantiation of
8068 /// this entity.
8070 /// \param IsPartialSpecialization whether this is a partial specialization of
8071 /// a class template.
8073 /// \returns true if there was an error that we cannot recover from, false
8074 /// otherwise.
8075 static bool CheckTemplateSpecializationScope(Sema &S,
8076 NamedDecl *Specialized,
8077 NamedDecl *PrevDecl,
8078 SourceLocation Loc,
8079 bool IsPartialSpecialization) {
8080 // Keep these "kind" numbers in sync with the %select statements in the
8081 // various diagnostics emitted by this routine.
8082 int EntityKind = 0;
8083 if (isa<ClassTemplateDecl>(Specialized))
8084 EntityKind = IsPartialSpecialization? 1 : 0;
8085 else if (isa<VarTemplateDecl>(Specialized))
8086 EntityKind = IsPartialSpecialization ? 3 : 2;
8087 else if (isa<FunctionTemplateDecl>(Specialized))
8088 EntityKind = 4;
8089 else if (isa<CXXMethodDecl>(Specialized))
8090 EntityKind = 5;
8091 else if (isa<VarDecl>(Specialized))
8092 EntityKind = 6;
8093 else if (isa<RecordDecl>(Specialized))
8094 EntityKind = 7;
8095 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
8096 EntityKind = 8;
8097 else {
8098 S.Diag(Loc, diag::err_template_spec_unknown_kind)
8099 << S.getLangOpts().CPlusPlus11;
8100 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8101 return true;
8104 // C++ [temp.expl.spec]p2:
8105 // An explicit specialization may be declared in any scope in which
8106 // the corresponding primary template may be defined.
8107 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8108 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
8109 << Specialized;
8110 return true;
8113 // C++ [temp.class.spec]p6:
8114 // A class template partial specialization may be declared in any
8115 // scope in which the primary template may be defined.
8116 DeclContext *SpecializedContext =
8117 Specialized->getDeclContext()->getRedeclContext();
8118 DeclContext *DC = S.CurContext->getRedeclContext();
8120 // Make sure that this redeclaration (or definition) occurs in the same
8121 // scope or an enclosing namespace.
8122 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)
8123 : DC->Equals(SpecializedContext))) {
8124 if (isa<TranslationUnitDecl>(SpecializedContext))
8125 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
8126 << EntityKind << Specialized;
8127 else {
8128 auto *ND = cast<NamedDecl>(SpecializedContext);
8129 int Diag = diag::err_template_spec_redecl_out_of_scope;
8130 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8131 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8132 S.Diag(Loc, Diag) << EntityKind << Specialized
8133 << ND << isa<CXXRecordDecl>(ND);
8136 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
8138 // Don't allow specializing in the wrong class during error recovery.
8139 // Otherwise, things can go horribly wrong.
8140 if (DC->isRecord())
8141 return true;
8144 return false;
8147 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8148 if (!E->isTypeDependent())
8149 return SourceLocation();
8150 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8151 Checker.TraverseStmt(E);
8152 if (Checker.MatchLoc.isInvalid())
8153 return E->getSourceRange();
8154 return Checker.MatchLoc;
8157 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8158 if (!TL.getType()->isDependentType())
8159 return SourceLocation();
8160 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8161 Checker.TraverseTypeLoc(TL);
8162 if (Checker.MatchLoc.isInvalid())
8163 return TL.getSourceRange();
8164 return Checker.MatchLoc;
8167 /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8168 /// that checks non-type template partial specialization arguments.
8169 static bool CheckNonTypeTemplatePartialSpecializationArgs(
8170 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8171 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8172 for (unsigned I = 0; I != NumArgs; ++I) {
8173 if (Args[I].getKind() == TemplateArgument::Pack) {
8174 if (CheckNonTypeTemplatePartialSpecializationArgs(
8175 S, TemplateNameLoc, Param, Args[I].pack_begin(),
8176 Args[I].pack_size(), IsDefaultArgument))
8177 return true;
8179 continue;
8182 if (Args[I].getKind() != TemplateArgument::Expression)
8183 continue;
8185 Expr *ArgExpr = Args[I].getAsExpr();
8187 // We can have a pack expansion of any of the bullets below.
8188 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
8189 ArgExpr = Expansion->getPattern();
8191 // Strip off any implicit casts we added as part of type checking.
8192 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8193 ArgExpr = ICE->getSubExpr();
8195 // C++ [temp.class.spec]p8:
8196 // A non-type argument is non-specialized if it is the name of a
8197 // non-type parameter. All other non-type arguments are
8198 // specialized.
8200 // Below, we check the two conditions that only apply to
8201 // specialized non-type arguments, so skip any non-specialized
8202 // arguments.
8203 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
8204 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
8205 continue;
8207 // C++ [temp.class.spec]p9:
8208 // Within the argument list of a class template partial
8209 // specialization, the following restrictions apply:
8210 // -- A partially specialized non-type argument expression
8211 // shall not involve a template parameter of the partial
8212 // specialization except when the argument expression is a
8213 // simple identifier.
8214 // -- The type of a template parameter corresponding to a
8215 // specialized non-type argument shall not be dependent on a
8216 // parameter of the specialization.
8217 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8218 // We implement a compromise between the original rules and DR1315:
8219 // -- A specialized non-type template argument shall not be
8220 // type-dependent and the corresponding template parameter
8221 // shall have a non-dependent type.
8222 SourceRange ParamUseRange =
8223 findTemplateParameterInType(Param->getDepth(), ArgExpr);
8224 if (ParamUseRange.isValid()) {
8225 if (IsDefaultArgument) {
8226 S.Diag(TemplateNameLoc,
8227 diag::err_dependent_non_type_arg_in_partial_spec);
8228 S.Diag(ParamUseRange.getBegin(),
8229 diag::note_dependent_non_type_default_arg_in_partial_spec)
8230 << ParamUseRange;
8231 } else {
8232 S.Diag(ParamUseRange.getBegin(),
8233 diag::err_dependent_non_type_arg_in_partial_spec)
8234 << ParamUseRange;
8236 return true;
8239 ParamUseRange = findTemplateParameter(
8240 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
8241 if (ParamUseRange.isValid()) {
8242 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8243 diag::err_dependent_typed_non_type_arg_in_partial_spec)
8244 << Param->getType();
8245 S.NoteTemplateParameterLocation(*Param);
8246 return true;
8250 return false;
8253 bool Sema::CheckTemplatePartialSpecializationArgs(
8254 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8255 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8256 // We have to be conservative when checking a template in a dependent
8257 // context.
8258 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8259 return false;
8261 TemplateParameterList *TemplateParams =
8262 PrimaryTemplate->getTemplateParameters();
8263 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8264 NonTypeTemplateParmDecl *Param
8265 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
8266 if (!Param)
8267 continue;
8269 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
8270 Param, &TemplateArgs[I],
8271 1, I >= NumExplicit))
8272 return true;
8275 return false;
8278 DeclResult Sema::ActOnClassTemplateSpecialization(
8279 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8280 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8281 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8282 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8283 assert(TUK != TagUseKind::Reference && "References are not specializations");
8285 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8286 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8287 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8289 // Find the class template we're specializing
8290 TemplateName Name = TemplateId.Template.get();
8291 ClassTemplateDecl *ClassTemplate
8292 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
8294 if (!ClassTemplate) {
8295 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
8296 << (Name.getAsTemplateDecl() &&
8297 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
8298 return true;
8301 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8302 auto Message = DSA->getMessage();
8303 Diag(TemplateNameLoc, diag::warn_invalid_specialization)
8304 << ClassTemplate << !Message.empty() << Message;
8305 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
8308 if (S->isTemplateParamScope())
8309 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());
8311 DeclContext *DC = ClassTemplate->getDeclContext();
8313 bool isMemberSpecialization = false;
8314 bool isPartialSpecialization = false;
8316 if (SS.isSet()) {
8317 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8318 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
8319 TemplateNameLoc, &TemplateId,
8320 /*IsMemberSpecialization=*/false))
8321 return true;
8324 // Check the validity of the template headers that introduce this
8325 // template.
8326 // FIXME: We probably shouldn't complain about these headers for
8327 // friend declarations.
8328 bool Invalid = false;
8329 TemplateParameterList *TemplateParams =
8330 MatchTemplateParametersToScopeSpecifier(
8331 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,
8332 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);
8333 if (Invalid)
8334 return true;
8336 // Check that we can declare a template specialization here.
8337 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8338 return true;
8340 if (TemplateParams && DC->isDependentContext()) {
8341 ContextRAII SavedContext(*this, DC);
8342 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8343 return true;
8346 if (TemplateParams && TemplateParams->size() > 0) {
8347 isPartialSpecialization = true;
8349 if (TUK == TagUseKind::Friend) {
8350 Diag(KWLoc, diag::err_partial_specialization_friend)
8351 << SourceRange(LAngleLoc, RAngleLoc);
8352 return true;
8355 // C++ [temp.class.spec]p10:
8356 // The template parameter list of a specialization shall not
8357 // contain default template argument values.
8358 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8359 Decl *Param = TemplateParams->getParam(I);
8360 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
8361 if (TTP->hasDefaultArgument()) {
8362 Diag(TTP->getDefaultArgumentLoc(),
8363 diag::err_default_arg_in_partial_spec);
8364 TTP->removeDefaultArgument();
8366 } else if (NonTypeTemplateParmDecl *NTTP
8367 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
8368 if (NTTP->hasDefaultArgument()) {
8369 Diag(NTTP->getDefaultArgumentLoc(),
8370 diag::err_default_arg_in_partial_spec)
8371 << NTTP->getDefaultArgument().getSourceRange();
8372 NTTP->removeDefaultArgument();
8374 } else {
8375 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
8376 if (TTP->hasDefaultArgument()) {
8377 Diag(TTP->getDefaultArgument().getLocation(),
8378 diag::err_default_arg_in_partial_spec)
8379 << TTP->getDefaultArgument().getSourceRange();
8380 TTP->removeDefaultArgument();
8384 } else if (TemplateParams) {
8385 if (TUK == TagUseKind::Friend)
8386 Diag(KWLoc, diag::err_template_spec_friend)
8387 << FixItHint::CreateRemoval(
8388 SourceRange(TemplateParams->getTemplateLoc(),
8389 TemplateParams->getRAngleLoc()))
8390 << SourceRange(LAngleLoc, RAngleLoc);
8391 } else {
8392 assert(TUK == TagUseKind::Friend &&
8393 "should have a 'template<>' for this decl");
8396 // Check that the specialization uses the same tag kind as the
8397 // original template.
8398 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8399 assert(Kind != TagTypeKind::Enum &&
8400 "Invalid enum tag in class template spec!");
8401 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,
8402 TUK == TagUseKind::Definition, KWLoc,
8403 ClassTemplate->getIdentifier())) {
8404 Diag(KWLoc, diag::err_use_with_wrong_tag)
8405 << ClassTemplate
8406 << FixItHint::CreateReplacement(KWLoc,
8407 ClassTemplate->getTemplatedDecl()->getKindName());
8408 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8409 diag::note_previous_use);
8410 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8413 // Translate the parser's template argument list in our AST format.
8414 TemplateArgumentListInfo TemplateArgs =
8415 makeTemplateArgumentListInfo(*this, TemplateId);
8417 // Check for unexpanded parameter packs in any of the template arguments.
8418 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8419 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
8420 isPartialSpecialization
8421 ? UPPC_PartialSpecialization
8422 : UPPC_ExplicitSpecialization))
8423 return true;
8425 // Check that the template argument list is well-formed for this
8426 // template.
8427 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
8428 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
8429 /*DefaultArgs=*/{},
8430 /*PartialTemplateArgs=*/false, SugaredConverted,
8431 CanonicalConverted,
8432 /*UpdateArgsWithConversions=*/true))
8433 return true;
8435 // Find the class template (partial) specialization declaration that
8436 // corresponds to these arguments.
8437 if (isPartialSpecialization) {
8438 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
8439 TemplateArgs.size(),
8440 CanonicalConverted))
8441 return true;
8443 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8444 // also do it during instantiation.
8445 if (!Name.isDependent() &&
8446 !TemplateSpecializationType::anyDependentTemplateArguments(
8447 TemplateArgs, CanonicalConverted)) {
8448 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
8449 << ClassTemplate->getDeclName();
8450 isPartialSpecialization = false;
8451 Invalid = true;
8455 void *InsertPos = nullptr;
8456 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8458 if (isPartialSpecialization)
8459 PrevDecl = ClassTemplate->findPartialSpecialization(
8460 CanonicalConverted, TemplateParams, InsertPos);
8461 else
8462 PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
8464 ClassTemplateSpecializationDecl *Specialization = nullptr;
8466 // Check whether we can declare a class template specialization in
8467 // the current scope.
8468 if (TUK != TagUseKind::Friend &&
8469 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
8470 TemplateNameLoc,
8471 isPartialSpecialization))
8472 return true;
8474 // The canonical type
8475 QualType CanonType;
8476 if (isPartialSpecialization) {
8477 // Build the canonical type that describes the converted template
8478 // arguments of the class template partial specialization.
8479 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8480 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8481 CanonicalConverted);
8483 if (Context.hasSameType(CanonType,
8484 ClassTemplate->getInjectedClassNameSpecialization()) &&
8485 (!Context.getLangOpts().CPlusPlus20 ||
8486 !TemplateParams->hasAssociatedConstraints())) {
8487 // C++ [temp.class.spec]p9b3:
8489 // -- The argument list of the specialization shall not be identical
8490 // to the implicit argument list of the primary template.
8492 // This rule has since been removed, because it's redundant given DR1495,
8493 // but we keep it because it produces better diagnostics and recovery.
8494 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
8495 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8496 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
8497 return CheckClassTemplate(
8498 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),
8499 TemplateNameLoc, Attr, TemplateParams, AS_none,
8500 /*ModulePrivateLoc=*/SourceLocation(),
8501 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
8502 TemplateParameterLists.data());
8505 // Create a new class template partial specialization declaration node.
8506 ClassTemplatePartialSpecializationDecl *PrevPartial
8507 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
8508 ClassTemplatePartialSpecializationDecl *Partial =
8509 ClassTemplatePartialSpecializationDecl::Create(
8510 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
8511 ClassTemplate, CanonicalConverted, CanonType, PrevPartial);
8512 Partial->setTemplateArgsAsWritten(TemplateArgs);
8513 SetNestedNameSpecifier(*this, Partial, SS);
8514 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8515 Partial->setTemplateParameterListsInfo(
8516 Context, TemplateParameterLists.drop_back(1));
8519 if (!PrevPartial)
8520 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
8521 Specialization = Partial;
8523 // If we are providing an explicit specialization of a member class
8524 // template specialization, make a note of that.
8525 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8526 PrevPartial->setMemberSpecialization();
8528 CheckTemplatePartialSpecialization(Partial);
8529 } else {
8530 // Create a new class template specialization declaration node for
8531 // this explicit specialization or friend declaration.
8532 Specialization = ClassTemplateSpecializationDecl::Create(
8533 Context, Kind, DC, KWLoc, TemplateNameLoc, ClassTemplate,
8534 CanonicalConverted, PrevDecl);
8535 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8536 SetNestedNameSpecifier(*this, Specialization, SS);
8537 if (TemplateParameterLists.size() > 0) {
8538 Specialization->setTemplateParameterListsInfo(Context,
8539 TemplateParameterLists);
8542 if (!PrevDecl)
8543 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8545 if (CurContext->isDependentContext()) {
8546 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
8547 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
8548 CanonicalConverted);
8549 } else {
8550 CanonType = Context.getTypeDeclType(Specialization);
8554 // C++ [temp.expl.spec]p6:
8555 // If a template, a member template or the member of a class template is
8556 // explicitly specialized then that specialization shall be declared
8557 // before the first use of that specialization that would cause an implicit
8558 // instantiation to take place, in every translation unit in which such a
8559 // use occurs; no diagnostic is required.
8560 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8561 bool Okay = false;
8562 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8563 // Is there any previous explicit specialization declaration?
8564 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8565 Okay = true;
8566 break;
8570 if (!Okay) {
8571 SourceRange Range(TemplateNameLoc, RAngleLoc);
8572 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
8573 << Context.getTypeDeclType(Specialization) << Range;
8575 Diag(PrevDecl->getPointOfInstantiation(),
8576 diag::note_instantiation_required_here)
8577 << (PrevDecl->getTemplateSpecializationKind()
8578 != TSK_ImplicitInstantiation);
8579 return true;
8583 // If this is not a friend, note that this is an explicit specialization.
8584 if (TUK != TagUseKind::Friend)
8585 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8587 // Check that this isn't a redefinition of this specialization.
8588 if (TUK == TagUseKind::Definition) {
8589 RecordDecl *Def = Specialization->getDefinition();
8590 NamedDecl *Hidden = nullptr;
8591 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
8592 SkipBody->ShouldSkip = true;
8593 SkipBody->Previous = Def;
8594 makeMergedDefinitionVisible(Hidden);
8595 } else if (Def) {
8596 SourceRange Range(TemplateNameLoc, RAngleLoc);
8597 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
8598 Diag(Def->getLocation(), diag::note_previous_definition);
8599 Specialization->setInvalidDecl();
8600 return true;
8604 ProcessDeclAttributeList(S, Specialization, Attr);
8605 ProcessAPINotes(Specialization);
8607 // Add alignment attributes if necessary; these attributes are checked when
8608 // the ASTContext lays out the structure.
8609 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8610 AddAlignmentAttributesForRecord(Specialization);
8611 AddMsStructLayoutForRecord(Specialization);
8614 if (ModulePrivateLoc.isValid())
8615 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
8616 << (isPartialSpecialization? 1 : 0)
8617 << FixItHint::CreateRemoval(ModulePrivateLoc);
8619 // C++ [temp.expl.spec]p9:
8620 // A template explicit specialization is in the scope of the
8621 // namespace in which the template was defined.
8623 // We actually implement this paragraph where we set the semantic
8624 // context (in the creation of the ClassTemplateSpecializationDecl),
8625 // but we also maintain the lexical context where the actual
8626 // definition occurs.
8627 Specialization->setLexicalDeclContext(CurContext);
8629 // We may be starting the definition of this specialization.
8630 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
8631 Specialization->startDefinition();
8633 if (TUK == TagUseKind::Friend) {
8634 // Build the fully-sugared type for this class template
8635 // specialization as the user wrote in the specialization
8636 // itself. This means that we'll pretty-print the type retrieved
8637 // from the specialization's declaration the way that the user
8638 // actually wrote the specialization, rather than formatting the
8639 // name based on the "canonical" representation used to store the
8640 // template arguments in the specialization.
8641 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
8642 Name, TemplateNameLoc, TemplateArgs, CanonType);
8643 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
8644 TemplateNameLoc,
8645 WrittenTy,
8646 /*FIXME:*/KWLoc);
8647 Friend->setAccess(AS_public);
8648 CurContext->addDecl(Friend);
8649 } else {
8650 // Add the specialization into its lexical context, so that it can
8651 // be seen when iterating through the list of declarations in that
8652 // context. However, specializations are not found by name lookup.
8653 CurContext->addDecl(Specialization);
8656 if (SkipBody && SkipBody->ShouldSkip)
8657 return SkipBody->Previous;
8659 Specialization->setInvalidDecl(Invalid);
8660 inferGslOwnerPointerAttribute(Specialization);
8661 return Specialization;
8664 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
8665 MultiTemplateParamsArg TemplateParameterLists,
8666 Declarator &D) {
8667 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8668 ActOnDocumentableDecl(NewDecl);
8669 return NewDecl;
8672 ConceptDecl *Sema::ActOnStartConceptDefinition(
8673 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8674 const IdentifierInfo *Name, SourceLocation NameLoc) {
8675 DeclContext *DC = CurContext;
8677 if (!DC->getRedeclContext()->isFileContext()) {
8678 Diag(NameLoc,
8679 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8680 return nullptr;
8683 if (TemplateParameterLists.size() > 1) {
8684 Diag(NameLoc, diag::err_concept_extra_headers);
8685 return nullptr;
8688 TemplateParameterList *Params = TemplateParameterLists.front();
8690 if (Params->size() == 0) {
8691 Diag(NameLoc, diag::err_concept_no_parameters);
8692 return nullptr;
8695 // Ensure that the parameter pack, if present, is the last parameter in the
8696 // template.
8697 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
8698 ParamEnd = Params->end();
8699 ParamIt != ParamEnd; ++ParamIt) {
8700 Decl const *Param = *ParamIt;
8701 if (Param->isParameterPack()) {
8702 if (++ParamIt == ParamEnd)
8703 break;
8704 Diag(Param->getLocation(),
8705 diag::err_template_param_pack_must_be_last_template_parameter);
8706 return nullptr;
8710 ConceptDecl *NewDecl =
8711 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);
8713 if (NewDecl->hasAssociatedConstraints()) {
8714 // C++2a [temp.concept]p4:
8715 // A concept shall not have associated constraints.
8716 Diag(NameLoc, diag::err_concept_no_associated_constraints);
8717 NewDecl->setInvalidDecl();
8720 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
8721 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8722 forRedeclarationInCurContext());
8723 LookupName(Previous, S);
8724 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
8725 /*AllowInlineNamespace*/ false);
8727 // We cannot properly handle redeclarations until we parse the constraint
8728 // expression, so only inject the name if we are sure we are not redeclaring a
8729 // symbol
8730 if (Previous.empty())
8731 PushOnScopeChains(NewDecl, S, true);
8733 return NewDecl;
8736 static bool RemoveLookupResult(LookupResult &R, NamedDecl *C) {
8737 bool Found = false;
8738 LookupResult::Filter F = R.makeFilter();
8739 while (F.hasNext()) {
8740 NamedDecl *D = F.next();
8741 if (D == C) {
8742 F.erase();
8743 Found = true;
8744 break;
8747 F.done();
8748 return Found;
8751 ConceptDecl *
8752 Sema::ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
8753 Expr *ConstraintExpr,
8754 const ParsedAttributesView &Attrs) {
8755 assert(!C->hasDefinition() && "Concept already defined");
8756 if (DiagnoseUnexpandedParameterPack(ConstraintExpr))
8757 return nullptr;
8758 C->setDefinition(ConstraintExpr);
8759 ProcessDeclAttributeList(S, C, Attrs);
8761 // Check for conflicting previous declaration.
8762 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
8763 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8764 forRedeclarationInCurContext());
8765 LookupName(Previous, S);
8766 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,
8767 /*AllowInlineNamespace*/ false);
8768 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);
8769 bool AddToScope = true;
8770 CheckConceptRedefinition(C, Previous, AddToScope);
8772 ActOnDocumentableDecl(C);
8773 if (!WasAlreadyAdded && AddToScope)
8774 PushOnScopeChains(C, S);
8776 return C;
8779 void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
8780 LookupResult &Previous, bool &AddToScope) {
8781 AddToScope = true;
8783 if (Previous.empty())
8784 return;
8786 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());
8787 if (!OldConcept) {
8788 auto *Old = Previous.getRepresentativeDecl();
8789 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
8790 << NewDecl->getDeclName();
8791 notePreviousDefinition(Old, NewDecl->getLocation());
8792 AddToScope = false;
8793 return;
8795 // Check if we can merge with a concept declaration.
8796 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
8797 if (!IsSame) {
8798 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
8799 << NewDecl->getDeclName();
8800 notePreviousDefinition(OldConcept, NewDecl->getLocation());
8801 AddToScope = false;
8802 return;
8804 if (hasReachableDefinition(OldConcept) &&
8805 IsRedefinitionInModule(NewDecl, OldConcept)) {
8806 Diag(NewDecl->getLocation(), diag::err_redefinition)
8807 << NewDecl->getDeclName();
8808 notePreviousDefinition(OldConcept, NewDecl->getLocation());
8809 AddToScope = false;
8810 return;
8812 if (!Previous.isSingleResult()) {
8813 // FIXME: we should produce an error in case of ambig and failed lookups.
8814 // Other decls (e.g. namespaces) also have this shortcoming.
8815 return;
8817 // We unwrap canonical decl late to check for module visibility.
8818 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
8821 bool Sema::CheckConceptUseInDefinition(ConceptDecl *Concept,
8822 SourceLocation Loc) {
8823 if (!Concept->isInvalidDecl() && !Concept->hasDefinition()) {
8824 Diag(Loc, diag::err_recursive_concept) << Concept;
8825 Diag(Concept->getLocation(), diag::note_declared_at);
8826 return true;
8828 return false;
8831 /// \brief Strips various properties off an implicit instantiation
8832 /// that has just been explicitly specialized.
8833 static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
8834 if (MinGW || (isa<FunctionDecl>(D) &&
8835 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
8836 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
8838 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
8839 FD->setInlineSpecified(false);
8842 /// Compute the diagnostic location for an explicit instantiation
8843 // declaration or definition.
8844 static SourceLocation DiagLocForExplicitInstantiation(
8845 NamedDecl* D, SourceLocation PointOfInstantiation) {
8846 // Explicit instantiations following a specialization have no effect and
8847 // hence no PointOfInstantiation. In that case, walk decl backwards
8848 // until a valid name loc is found.
8849 SourceLocation PrevDiagLoc = PointOfInstantiation;
8850 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
8851 Prev = Prev->getPreviousDecl()) {
8852 PrevDiagLoc = Prev->getLocation();
8854 assert(PrevDiagLoc.isValid() &&
8855 "Explicit instantiation without point of instantiation?");
8856 return PrevDiagLoc;
8859 bool
8860 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
8861 TemplateSpecializationKind NewTSK,
8862 NamedDecl *PrevDecl,
8863 TemplateSpecializationKind PrevTSK,
8864 SourceLocation PrevPointOfInstantiation,
8865 bool &HasNoEffect) {
8866 HasNoEffect = false;
8868 switch (NewTSK) {
8869 case TSK_Undeclared:
8870 case TSK_ImplicitInstantiation:
8871 assert(
8872 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
8873 "previous declaration must be implicit!");
8874 return false;
8876 case TSK_ExplicitSpecialization:
8877 switch (PrevTSK) {
8878 case TSK_Undeclared:
8879 case TSK_ExplicitSpecialization:
8880 // Okay, we're just specializing something that is either already
8881 // explicitly specialized or has merely been mentioned without any
8882 // instantiation.
8883 return false;
8885 case TSK_ImplicitInstantiation:
8886 if (PrevPointOfInstantiation.isInvalid()) {
8887 // The declaration itself has not actually been instantiated, so it is
8888 // still okay to specialize it.
8889 StripImplicitInstantiation(
8890 PrevDecl,
8891 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
8892 return false;
8894 // Fall through
8895 [[fallthrough]];
8897 case TSK_ExplicitInstantiationDeclaration:
8898 case TSK_ExplicitInstantiationDefinition:
8899 assert((PrevTSK == TSK_ImplicitInstantiation ||
8900 PrevPointOfInstantiation.isValid()) &&
8901 "Explicit instantiation without point of instantiation?");
8903 // C++ [temp.expl.spec]p6:
8904 // If a template, a member template or the member of a class template
8905 // is explicitly specialized then that specialization shall be declared
8906 // before the first use of that specialization that would cause an
8907 // implicit instantiation to take place, in every translation unit in
8908 // which such a use occurs; no diagnostic is required.
8909 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8910 // Is there any previous explicit specialization declaration?
8911 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
8912 return false;
8915 Diag(NewLoc, diag::err_specialization_after_instantiation)
8916 << PrevDecl;
8917 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
8918 << (PrevTSK != TSK_ImplicitInstantiation);
8920 return true;
8922 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
8924 case TSK_ExplicitInstantiationDeclaration:
8925 switch (PrevTSK) {
8926 case TSK_ExplicitInstantiationDeclaration:
8927 // This explicit instantiation declaration is redundant (that's okay).
8928 HasNoEffect = true;
8929 return false;
8931 case TSK_Undeclared:
8932 case TSK_ImplicitInstantiation:
8933 // We're explicitly instantiating something that may have already been
8934 // implicitly instantiated; that's fine.
8935 return false;
8937 case TSK_ExplicitSpecialization:
8938 // C++0x [temp.explicit]p4:
8939 // For a given set of template parameters, if an explicit instantiation
8940 // of a template appears after a declaration of an explicit
8941 // specialization for that template, the explicit instantiation has no
8942 // effect.
8943 HasNoEffect = true;
8944 return false;
8946 case TSK_ExplicitInstantiationDefinition:
8947 // C++0x [temp.explicit]p10:
8948 // If an entity is the subject of both an explicit instantiation
8949 // declaration and an explicit instantiation definition in the same
8950 // translation unit, the definition shall follow the declaration.
8951 Diag(NewLoc,
8952 diag::err_explicit_instantiation_declaration_after_definition);
8954 // Explicit instantiations following a specialization have no effect and
8955 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
8956 // until a valid name loc is found.
8957 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
8958 diag::note_explicit_instantiation_definition_here);
8959 HasNoEffect = true;
8960 return false;
8962 llvm_unreachable("Unexpected TemplateSpecializationKind!");
8964 case TSK_ExplicitInstantiationDefinition:
8965 switch (PrevTSK) {
8966 case TSK_Undeclared:
8967 case TSK_ImplicitInstantiation:
8968 // We're explicitly instantiating something that may have already been
8969 // implicitly instantiated; that's fine.
8970 return false;
8972 case TSK_ExplicitSpecialization:
8973 // C++ DR 259, C++0x [temp.explicit]p4:
8974 // For a given set of template parameters, if an explicit
8975 // instantiation of a template appears after a declaration of
8976 // an explicit specialization for that template, the explicit
8977 // instantiation has no effect.
8978 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
8979 << PrevDecl;
8980 Diag(PrevDecl->getLocation(),
8981 diag::note_previous_template_specialization);
8982 HasNoEffect = true;
8983 return false;
8985 case TSK_ExplicitInstantiationDeclaration:
8986 // We're explicitly instantiating a definition for something for which we
8987 // were previously asked to suppress instantiations. That's fine.
8989 // C++0x [temp.explicit]p4:
8990 // For a given set of template parameters, if an explicit instantiation
8991 // of a template appears after a declaration of an explicit
8992 // specialization for that template, the explicit instantiation has no
8993 // effect.
8994 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8995 // Is there any previous explicit specialization declaration?
8996 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
8997 HasNoEffect = true;
8998 break;
9002 return false;
9004 case TSK_ExplicitInstantiationDefinition:
9005 // C++0x [temp.spec]p5:
9006 // For a given template and a given set of template-arguments,
9007 // - an explicit instantiation definition shall appear at most once
9008 // in a program,
9010 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9011 Diag(NewLoc, (getLangOpts().MSVCCompat)
9012 ? diag::ext_explicit_instantiation_duplicate
9013 : diag::err_explicit_instantiation_duplicate)
9014 << PrevDecl;
9015 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9016 diag::note_previous_explicit_instantiation);
9017 HasNoEffect = true;
9018 return false;
9022 llvm_unreachable("Missing specialization/instantiation case?");
9025 bool Sema::CheckDependentFunctionTemplateSpecialization(
9026 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9027 LookupResult &Previous) {
9028 // Remove anything from Previous that isn't a function template in
9029 // the correct context.
9030 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9031 LookupResult::Filter F = Previous.makeFilter();
9032 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9033 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9034 while (F.hasNext()) {
9035 NamedDecl *D = F.next()->getUnderlyingDecl();
9036 if (!isa<FunctionTemplateDecl>(D)) {
9037 F.erase();
9038 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));
9039 continue;
9042 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9043 D->getDeclContext()->getRedeclContext())) {
9044 F.erase();
9045 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));
9046 continue;
9049 F.done();
9051 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9052 if (Previous.empty()) {
9053 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
9054 << IsFriend;
9055 for (auto &P : DiscardedCandidates)
9056 Diag(P.second->getLocation(),
9057 diag::note_dependent_function_template_spec_discard_reason)
9058 << P.first << IsFriend;
9059 return true;
9062 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
9063 ExplicitTemplateArgs);
9064 return false;
9067 bool Sema::CheckFunctionTemplateSpecialization(
9068 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9069 LookupResult &Previous, bool QualifiedFriend) {
9070 // The set of function template specializations that could match this
9071 // explicit function template specialization.
9072 UnresolvedSet<8> Candidates;
9073 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9074 /*ForTakingAddress=*/false);
9076 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9077 ConvertedTemplateArgs;
9079 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9080 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9081 I != E; ++I) {
9082 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9083 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
9084 // Only consider templates found within the same semantic lookup scope as
9085 // FD.
9086 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9087 Ovl->getDeclContext()->getRedeclContext()))
9088 continue;
9090 QualType FT = FD->getType();
9091 // C++11 [dcl.constexpr]p8:
9092 // A constexpr specifier for a non-static member function that is not
9093 // a constructor declares that member function to be const.
9095 // When matching a constexpr member function template specialization
9096 // against the primary template, we don't yet know whether the
9097 // specialization has an implicit 'const' (because we don't know whether
9098 // it will be a static member function until we know which template it
9099 // specializes). This rule was removed in C++14.
9100 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);
9101 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9102 !isa<CXXConstructorDecl, CXXDestructorDecl>(NewMD)) {
9103 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
9104 if (OldMD && OldMD->isConst()) {
9105 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9106 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9107 EPI.TypeQuals.addConst();
9108 FT = Context.getFunctionType(FPT->getReturnType(),
9109 FPT->getParamTypes(), EPI);
9113 TemplateArgumentListInfo Args;
9114 if (ExplicitTemplateArgs)
9115 Args = *ExplicitTemplateArgs;
9117 // C++ [temp.expl.spec]p11:
9118 // A trailing template-argument can be left unspecified in the
9119 // template-id naming an explicit function template specialization
9120 // provided it can be deduced from the function argument type.
9121 // Perform template argument deduction to determine whether we may be
9122 // specializing this template.
9123 // FIXME: It is somewhat wasteful to build
9124 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9125 FunctionDecl *Specialization = nullptr;
9126 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9127 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
9128 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
9129 TDK != TemplateDeductionResult::Success) {
9130 // Template argument deduction failed; record why it failed, so
9131 // that we can provide nifty diagnostics.
9132 FailedCandidates.addCandidate().set(
9133 I.getPair(), FunTmpl->getTemplatedDecl(),
9134 MakeDeductionFailureInfo(Context, TDK, Info));
9135 (void)TDK;
9136 continue;
9139 // Target attributes are part of the cuda function signature, so
9140 // the deduced template's cuda target must match that of the
9141 // specialization. Given that C++ template deduction does not
9142 // take target attributes into account, we reject candidates
9143 // here that have a different target.
9144 if (LangOpts.CUDA &&
9145 CUDA().IdentifyTarget(Specialization,
9146 /* IgnoreImplicitHDAttr = */ true) !=
9147 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {
9148 FailedCandidates.addCandidate().set(
9149 I.getPair(), FunTmpl->getTemplatedDecl(),
9150 MakeDeductionFailureInfo(
9151 Context, TemplateDeductionResult::CUDATargetMismatch, Info));
9152 continue;
9155 // Record this candidate.
9156 if (ExplicitTemplateArgs)
9157 ConvertedTemplateArgs[Specialization] = std::move(Args);
9158 Candidates.addDecl(Specialization, I.getAccess());
9162 // For a qualified friend declaration (with no explicit marker to indicate
9163 // that a template specialization was intended), note all (template and
9164 // non-template) candidates.
9165 if (QualifiedFriend && Candidates.empty()) {
9166 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
9167 << FD->getDeclName() << FDLookupContext;
9168 // FIXME: We should form a single candidate list and diagnose all
9169 // candidates at once, to get proper sorting and limiting.
9170 for (auto *OldND : Previous) {
9171 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))
9172 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);
9174 FailedCandidates.NoteCandidates(*this, FD->getLocation());
9175 return true;
9178 // Find the most specialized function template.
9179 UnresolvedSetIterator Result = getMostSpecialized(
9180 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
9181 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
9182 PDiag(diag::err_function_template_spec_ambiguous)
9183 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9184 PDiag(diag::note_function_template_spec_matched));
9186 if (Result == Candidates.end())
9187 return true;
9189 // Ignore access information; it doesn't figure into redeclaration checking.
9190 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
9192 if (const auto *PT = Specialization->getPrimaryTemplate();
9193 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9194 auto Message = DSA->getMessage();
9195 Diag(FD->getLocation(), diag::warn_invalid_specialization)
9196 << PT << !Message.empty() << Message;
9197 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;
9200 // C++23 [except.spec]p13:
9201 // An exception specification is considered to be needed when:
9202 // - [...]
9203 // - the exception specification is compared to that of another declaration
9204 // (e.g., an explicit specialization or an overriding virtual function);
9205 // - [...]
9207 // The exception specification of a defaulted function is evaluated as
9208 // described above only when needed; similarly, the noexcept-specifier of a
9209 // specialization of a function template or member function of a class
9210 // template is instantiated only when needed.
9212 // The standard doesn't specify what the "comparison with another declaration"
9213 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9214 // not state which properties of an explicit specialization must match the
9215 // primary template.
9217 // We assume that an explicit specialization must correspond with (per
9218 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9219 // the declaration produced by substitution into the function template.
9221 // Since the determination whether two function declarations correspond does
9222 // not consider exception specification, we only need to instantiate it once
9223 // we determine the primary template when comparing types per
9224 // [basic.link]p11.1.
9225 auto *SpecializationFPT =
9226 Specialization->getType()->castAs<FunctionProtoType>();
9227 // If the function has a dependent exception specification, resolve it after
9228 // we have selected the primary template so we can check whether it matches.
9229 if (getLangOpts().CPlusPlus17 &&
9230 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
9231 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))
9232 return true;
9234 FunctionTemplateSpecializationInfo *SpecInfo
9235 = Specialization->getTemplateSpecializationInfo();
9236 assert(SpecInfo && "Function template specialization info missing?");
9238 // Note: do not overwrite location info if previous template
9239 // specialization kind was explicit.
9240 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9241 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9242 Specialization->setLocation(FD->getLocation());
9243 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9244 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9245 // function can differ from the template declaration with respect to
9246 // the constexpr specifier.
9247 // FIXME: We need an update record for this AST mutation.
9248 // FIXME: What if there are multiple such prior declarations (for instance,
9249 // from different modules)?
9250 Specialization->setConstexprKind(FD->getConstexprKind());
9253 // FIXME: Check if the prior specialization has a point of instantiation.
9254 // If so, we have run afoul of .
9256 // If this is a friend declaration, then we're not really declaring
9257 // an explicit specialization.
9258 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9260 // Check the scope of this explicit specialization.
9261 if (!isFriend &&
9262 CheckTemplateSpecializationScope(*this,
9263 Specialization->getPrimaryTemplate(),
9264 Specialization, FD->getLocation(),
9265 false))
9266 return true;
9268 // C++ [temp.expl.spec]p6:
9269 // If a template, a member template or the member of a class template is
9270 // explicitly specialized then that specialization shall be declared
9271 // before the first use of that specialization that would cause an implicit
9272 // instantiation to take place, in every translation unit in which such a
9273 // use occurs; no diagnostic is required.
9274 bool HasNoEffect = false;
9275 if (!isFriend &&
9276 CheckSpecializationInstantiationRedecl(FD->getLocation(),
9277 TSK_ExplicitSpecialization,
9278 Specialization,
9279 SpecInfo->getTemplateSpecializationKind(),
9280 SpecInfo->getPointOfInstantiation(),
9281 HasNoEffect))
9282 return true;
9284 // Mark the prior declaration as an explicit specialization, so that later
9285 // clients know that this is an explicit specialization.
9286 if (!isFriend) {
9287 // Since explicit specializations do not inherit '=delete' from their
9288 // primary function template - check if the 'specialization' that was
9289 // implicitly generated (during template argument deduction for partial
9290 // ordering) from the most specialized of all the function templates that
9291 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9292 // first check that it was implicitly generated during template argument
9293 // deduction by making sure it wasn't referenced, and then reset the deleted
9294 // flag to not-deleted, so that we can inherit that information from 'FD'.
9295 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9296 !Specialization->getCanonicalDecl()->isReferenced()) {
9297 // FIXME: This assert will not hold in the presence of modules.
9298 assert(
9299 Specialization->getCanonicalDecl() == Specialization &&
9300 "This must be the only existing declaration of this specialization");
9301 // FIXME: We need an update record for this AST mutation.
9302 Specialization->setDeletedAsWritten(false);
9304 // FIXME: We need an update record for this AST mutation.
9305 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9306 MarkUnusedFileScopedDecl(Specialization);
9309 // Turn the given function declaration into a function template
9310 // specialization, with the template arguments from the previous
9311 // specialization.
9312 // Take copies of (semantic and syntactic) template argument lists.
9313 TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy(
9314 Context, Specialization->getTemplateSpecializationArgs()->asArray());
9315 FD->setFunctionTemplateSpecialization(
9316 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
9317 SpecInfo->getTemplateSpecializationKind(),
9318 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9320 // A function template specialization inherits the target attributes
9321 // of its template. (We require the attributes explicitly in the
9322 // code to match, but a template may have implicit attributes by
9323 // virtue e.g. of being constexpr, and it passes these implicit
9324 // attributes on to its specializations.)
9325 if (LangOpts.CUDA)
9326 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());
9328 // The "previous declaration" for this function template specialization is
9329 // the prior function template specialization.
9330 Previous.clear();
9331 Previous.addDecl(Specialization);
9332 return false;
9335 bool
9336 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9337 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9338 "Only for non-template members");
9340 // Try to find the member we are instantiating.
9341 NamedDecl *FoundInstantiation = nullptr;
9342 NamedDecl *Instantiation = nullptr;
9343 NamedDecl *InstantiatedFrom = nullptr;
9344 MemberSpecializationInfo *MSInfo = nullptr;
9346 if (Previous.empty()) {
9347 // Nowhere to look anyway.
9348 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
9349 UnresolvedSet<8> Candidates;
9350 for (NamedDecl *Candidate : Previous) {
9351 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());
9352 // Ignore any candidates that aren't member functions.
9353 if (!Method)
9354 continue;
9356 QualType Adjusted = Function->getType();
9357 if (!hasExplicitCallingConv(Adjusted))
9358 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
9359 // Ignore any candidates with the wrong type.
9360 // This doesn't handle deduced return types, but both function
9361 // declarations should be undeduced at this point.
9362 // FIXME: The exception specification should probably be ignored when
9363 // comparing the types.
9364 if (!Context.hasSameType(Adjusted, Method->getType()))
9365 continue;
9367 // Ignore any candidates with unsatisfied constraints.
9368 if (ConstraintSatisfaction Satisfaction;
9369 Method->getTrailingRequiresClause() &&
9370 (CheckFunctionConstraints(Method, Satisfaction,
9371 /*UsageLoc=*/Member->getLocation(),
9372 /*ForOverloadResolution=*/true) ||
9373 !Satisfaction.IsSatisfied))
9374 continue;
9376 Candidates.addDecl(Candidate);
9379 // If we have no viable candidates left after filtering, we are done.
9380 if (Candidates.empty())
9381 return false;
9383 // Find the function that is more constrained than every other function it
9384 // has been compared to.
9385 UnresolvedSetIterator Best = Candidates.begin();
9386 CXXMethodDecl *BestMethod = nullptr;
9387 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9388 I != E; ++I) {
9389 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9390 if (I == Best ||
9391 getMoreConstrainedFunction(Method, BestMethod) == Method) {
9392 Best = I;
9393 BestMethod = Method;
9397 FoundInstantiation = *Best;
9398 Instantiation = BestMethod;
9399 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9400 MSInfo = BestMethod->getMemberSpecializationInfo();
9402 // Make sure the best candidate is more constrained than all of the others.
9403 bool Ambiguous = false;
9404 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9405 I != E; ++I) {
9406 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());
9407 if (I != Best &&
9408 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {
9409 Ambiguous = true;
9410 break;
9414 if (Ambiguous) {
9415 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)
9416 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9417 for (NamedDecl *Candidate : Candidates) {
9418 Candidate = Candidate->getUnderlyingDecl();
9419 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)
9420 << Candidate;
9422 return true;
9424 } else if (isa<VarDecl>(Member)) {
9425 VarDecl *PrevVar;
9426 if (Previous.isSingleResult() &&
9427 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
9428 if (PrevVar->isStaticDataMember()) {
9429 FoundInstantiation = Previous.getRepresentativeDecl();
9430 Instantiation = PrevVar;
9431 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9432 MSInfo = PrevVar->getMemberSpecializationInfo();
9434 } else if (isa<RecordDecl>(Member)) {
9435 CXXRecordDecl *PrevRecord;
9436 if (Previous.isSingleResult() &&
9437 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
9438 FoundInstantiation = Previous.getRepresentativeDecl();
9439 Instantiation = PrevRecord;
9440 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9441 MSInfo = PrevRecord->getMemberSpecializationInfo();
9443 } else if (isa<EnumDecl>(Member)) {
9444 EnumDecl *PrevEnum;
9445 if (Previous.isSingleResult() &&
9446 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
9447 FoundInstantiation = Previous.getRepresentativeDecl();
9448 Instantiation = PrevEnum;
9449 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9450 MSInfo = PrevEnum->getMemberSpecializationInfo();
9454 if (!Instantiation) {
9455 // There is no previous declaration that matches. Since member
9456 // specializations are always out-of-line, the caller will complain about
9457 // this mismatch later.
9458 return false;
9461 // A member specialization in a friend declaration isn't really declaring
9462 // an explicit specialization, just identifying a specific (possibly implicit)
9463 // specialization. Don't change the template specialization kind.
9465 // FIXME: Is this really valid? Other compilers reject.
9466 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9467 // Preserve instantiation information.
9468 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
9469 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
9470 cast<CXXMethodDecl>(InstantiatedFrom),
9471 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
9472 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
9473 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
9474 cast<CXXRecordDecl>(InstantiatedFrom),
9475 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
9478 Previous.clear();
9479 Previous.addDecl(FoundInstantiation);
9480 return false;
9483 // Make sure that this is a specialization of a member.
9484 if (!InstantiatedFrom) {
9485 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
9486 << Member;
9487 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
9488 return true;
9491 // C++ [temp.expl.spec]p6:
9492 // If a template, a member template or the member of a class template is
9493 // explicitly specialized then that specialization shall be declared
9494 // before the first use of that specialization that would cause an implicit
9495 // instantiation to take place, in every translation unit in which such a
9496 // use occurs; no diagnostic is required.
9497 assert(MSInfo && "Member specialization info missing?");
9499 bool HasNoEffect = false;
9500 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
9501 TSK_ExplicitSpecialization,
9502 Instantiation,
9503 MSInfo->getTemplateSpecializationKind(),
9504 MSInfo->getPointOfInstantiation(),
9505 HasNoEffect))
9506 return true;
9508 // Check the scope of this explicit specialization.
9509 if (CheckTemplateSpecializationScope(*this,
9510 InstantiatedFrom,
9511 Instantiation, Member->getLocation(),
9512 false))
9513 return true;
9515 // Note that this member specialization is an "instantiation of" the
9516 // corresponding member of the original template.
9517 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
9518 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
9519 if (InstantiationFunction->getTemplateSpecializationKind() ==
9520 TSK_ImplicitInstantiation) {
9521 // Explicit specializations of member functions of class templates do not
9522 // inherit '=delete' from the member function they are specializing.
9523 if (InstantiationFunction->isDeleted()) {
9524 // FIXME: This assert will not hold in the presence of modules.
9525 assert(InstantiationFunction->getCanonicalDecl() ==
9526 InstantiationFunction);
9527 // FIXME: We need an update record for this AST mutation.
9528 InstantiationFunction->setDeletedAsWritten(false);
9532 MemberFunction->setInstantiationOfMemberFunction(
9533 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9534 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
9535 MemberVar->setInstantiationOfStaticDataMember(
9536 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9537 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
9538 MemberClass->setInstantiationOfMemberClass(
9539 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9540 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
9541 MemberEnum->setInstantiationOfMemberEnum(
9542 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
9543 } else {
9544 llvm_unreachable("unknown member specialization kind");
9547 // Save the caller the trouble of having to figure out which declaration
9548 // this specialization matches.
9549 Previous.clear();
9550 Previous.addDecl(FoundInstantiation);
9551 return false;
9554 /// Complete the explicit specialization of a member of a class template by
9555 /// updating the instantiated member to be marked as an explicit specialization.
9557 /// \param OrigD The member declaration instantiated from the template.
9558 /// \param Loc The location of the explicit specialization of the member.
9559 template<typename DeclT>
9560 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
9561 SourceLocation Loc) {
9562 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9563 return;
9565 // FIXME: Inform AST mutation listeners of this AST mutation.
9566 // FIXME: If there are multiple in-class declarations of the member (from
9567 // multiple modules, or a declaration and later definition of a member type),
9568 // should we update all of them?
9569 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9570 OrigD->setLocation(Loc);
9573 void Sema::CompleteMemberSpecialization(NamedDecl *Member,
9574 LookupResult &Previous) {
9575 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
9576 if (Instantiation == Member)
9577 return;
9579 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
9580 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
9581 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
9582 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
9583 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
9584 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
9585 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
9586 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
9587 else
9588 llvm_unreachable("unknown member specialization kind");
9591 /// Check the scope of an explicit instantiation.
9593 /// \returns true if a serious error occurs, false otherwise.
9594 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
9595 SourceLocation InstLoc,
9596 bool WasQualifiedName) {
9597 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
9598 DeclContext *CurContext = S.CurContext->getRedeclContext();
9600 if (CurContext->isRecord()) {
9601 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
9602 << D;
9603 return true;
9606 // C++11 [temp.explicit]p3:
9607 // An explicit instantiation shall appear in an enclosing namespace of its
9608 // template. If the name declared in the explicit instantiation is an
9609 // unqualified name, the explicit instantiation shall appear in the
9610 // namespace where its template is declared or, if that namespace is inline
9611 // (7.3.1), any namespace from its enclosing namespace set.
9613 // This is DR275, which we do not retroactively apply to C++98/03.
9614 if (WasQualifiedName) {
9615 if (CurContext->Encloses(OrigContext))
9616 return false;
9617 } else {
9618 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
9619 return false;
9622 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
9623 if (WasQualifiedName)
9624 S.Diag(InstLoc,
9625 S.getLangOpts().CPlusPlus11?
9626 diag::err_explicit_instantiation_out_of_scope :
9627 diag::warn_explicit_instantiation_out_of_scope_0x)
9628 << D << NS;
9629 else
9630 S.Diag(InstLoc,
9631 S.getLangOpts().CPlusPlus11?
9632 diag::err_explicit_instantiation_unqualified_wrong_namespace :
9633 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
9634 << D << NS;
9635 } else
9636 S.Diag(InstLoc,
9637 S.getLangOpts().CPlusPlus11?
9638 diag::err_explicit_instantiation_must_be_global :
9639 diag::warn_explicit_instantiation_must_be_global_0x)
9640 << D;
9641 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
9642 return false;
9645 /// Common checks for whether an explicit instantiation of \p D is valid.
9646 static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
9647 SourceLocation InstLoc,
9648 bool WasQualifiedName,
9649 TemplateSpecializationKind TSK) {
9650 // C++ [temp.explicit]p13:
9651 // An explicit instantiation declaration shall not name a specialization of
9652 // a template with internal linkage.
9653 if (TSK == TSK_ExplicitInstantiationDeclaration &&
9654 D->getFormalLinkage() == Linkage::Internal) {
9655 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
9656 return true;
9659 // C++11 [temp.explicit]p3: [DR 275]
9660 // An explicit instantiation shall appear in an enclosing namespace of its
9661 // template.
9662 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
9663 return true;
9665 return false;
9668 /// Determine whether the given scope specifier has a template-id in it.
9669 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
9670 if (!SS.isSet())
9671 return false;
9673 // C++11 [temp.explicit]p3:
9674 // If the explicit instantiation is for a member function, a member class
9675 // or a static data member of a class template specialization, the name of
9676 // the class template specialization in the qualified-id for the member
9677 // name shall be a simple-template-id.
9679 // C++98 has the same restriction, just worded differently.
9680 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
9681 NNS = NNS->getPrefix())
9682 if (const Type *T = NNS->getAsType())
9683 if (isa<TemplateSpecializationType>(T))
9684 return true;
9686 return false;
9689 /// Make a dllexport or dllimport attr on a class template specialization take
9690 /// effect.
9691 static void dllExportImportClassTemplateSpecialization(
9692 Sema &S, ClassTemplateSpecializationDecl *Def) {
9693 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
9694 assert(A && "dllExportImportClassTemplateSpecialization called "
9695 "on Def without dllexport or dllimport");
9697 // We reject explicit instantiations in class scope, so there should
9698 // never be any delayed exported classes to worry about.
9699 assert(S.DelayedDllExportClasses.empty() &&
9700 "delayed exports present at explicit instantiation");
9701 S.checkClassLevelDLLAttribute(Def);
9703 // Propagate attribute to base class templates.
9704 for (auto &B : Def->bases()) {
9705 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
9706 B.getType()->getAsCXXRecordDecl()))
9707 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
9710 S.referenceDLLExportedClassMethods();
9713 DeclResult Sema::ActOnExplicitInstantiation(
9714 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
9715 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
9716 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
9717 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
9718 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
9719 // Find the class template we're specializing
9720 TemplateName Name = TemplateD.get();
9721 TemplateDecl *TD = Name.getAsTemplateDecl();
9722 // Check that the specialization uses the same tag kind as the
9723 // original template.
9724 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9725 assert(Kind != TagTypeKind::Enum &&
9726 "Invalid enum tag in class template explicit instantiation!");
9728 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
9730 if (!ClassTemplate) {
9731 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
9732 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag)
9733 << TD << NTK << llvm::to_underlying(Kind);
9734 Diag(TD->getLocation(), diag::note_previous_use);
9735 return true;
9738 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
9739 Kind, /*isDefinition*/false, KWLoc,
9740 ClassTemplate->getIdentifier())) {
9741 Diag(KWLoc, diag::err_use_with_wrong_tag)
9742 << ClassTemplate
9743 << FixItHint::CreateReplacement(KWLoc,
9744 ClassTemplate->getTemplatedDecl()->getKindName());
9745 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9746 diag::note_previous_use);
9747 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9750 // C++0x [temp.explicit]p2:
9751 // There are two forms of explicit instantiation: an explicit instantiation
9752 // definition and an explicit instantiation declaration. An explicit
9753 // instantiation declaration begins with the extern keyword. [...]
9754 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
9755 ? TSK_ExplicitInstantiationDefinition
9756 : TSK_ExplicitInstantiationDeclaration;
9758 if (TSK == TSK_ExplicitInstantiationDeclaration &&
9759 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9760 // Check for dllexport class template instantiation declarations,
9761 // except for MinGW mode.
9762 for (const ParsedAttr &AL : Attr) {
9763 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9764 Diag(ExternLoc,
9765 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9766 Diag(AL.getLoc(), diag::note_attribute);
9767 break;
9771 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9772 Diag(ExternLoc,
9773 diag::warn_attribute_dllexport_explicit_instantiation_decl);
9774 Diag(A->getLocation(), diag::note_attribute);
9778 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9779 // instantiation declarations for most purposes.
9780 bool DLLImportExplicitInstantiationDef = false;
9781 if (TSK == TSK_ExplicitInstantiationDefinition &&
9782 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9783 // Check for dllimport class template instantiation definitions.
9784 bool DLLImport =
9785 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
9786 for (const ParsedAttr &AL : Attr) {
9787 if (AL.getKind() == ParsedAttr::AT_DLLImport)
9788 DLLImport = true;
9789 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9790 // dllexport trumps dllimport here.
9791 DLLImport = false;
9792 break;
9795 if (DLLImport) {
9796 TSK = TSK_ExplicitInstantiationDeclaration;
9797 DLLImportExplicitInstantiationDef = true;
9801 // Translate the parser's template argument list in our AST format.
9802 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9803 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9805 // Check that the template argument list is well-formed for this
9806 // template.
9807 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
9808 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
9809 /*DefaultArgs=*/{}, false, SugaredConverted,
9810 CanonicalConverted,
9811 /*UpdateArgsWithConversions=*/true))
9812 return true;
9814 // Find the class template specialization declaration that
9815 // corresponds to these arguments.
9816 void *InsertPos = nullptr;
9817 ClassTemplateSpecializationDecl *PrevDecl =
9818 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
9820 TemplateSpecializationKind PrevDecl_TSK
9821 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
9823 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
9824 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
9825 // Check for dllexport class template instantiation definitions in MinGW
9826 // mode, if a previous declaration of the instantiation was seen.
9827 for (const ParsedAttr &AL : Attr) {
9828 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9829 Diag(AL.getLoc(),
9830 diag::warn_attribute_dllexport_explicit_instantiation_def);
9831 break;
9836 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
9837 SS.isSet(), TSK))
9838 return true;
9840 ClassTemplateSpecializationDecl *Specialization = nullptr;
9842 bool HasNoEffect = false;
9843 if (PrevDecl) {
9844 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
9845 PrevDecl, PrevDecl_TSK,
9846 PrevDecl->getPointOfInstantiation(),
9847 HasNoEffect))
9848 return PrevDecl;
9850 // Even though HasNoEffect == true means that this explicit instantiation
9851 // has no effect on semantics, we go on to put its syntax in the AST.
9853 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
9854 PrevDecl_TSK == TSK_Undeclared) {
9855 // Since the only prior class template specialization with these
9856 // arguments was referenced but not declared, reuse that
9857 // declaration node as our own, updating the source location
9858 // for the template name to reflect our new declaration.
9859 // (Other source locations will be updated later.)
9860 Specialization = PrevDecl;
9861 Specialization->setLocation(TemplateNameLoc);
9862 PrevDecl = nullptr;
9865 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9866 DLLImportExplicitInstantiationDef) {
9867 // The new specialization might add a dllimport attribute.
9868 HasNoEffect = false;
9872 if (!Specialization) {
9873 // Create a new class template specialization declaration node for
9874 // this explicit specialization.
9875 Specialization = ClassTemplateSpecializationDecl::Create(
9876 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
9877 ClassTemplate, CanonicalConverted, PrevDecl);
9878 SetNestedNameSpecifier(*this, Specialization, SS);
9880 // A MSInheritanceAttr attached to the previous declaration must be
9881 // propagated to the new node prior to instantiation.
9882 if (PrevDecl) {
9883 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
9884 auto *Clone = A->clone(getASTContext());
9885 Clone->setInherited(true);
9886 Specialization->addAttr(Clone);
9887 Consumer.AssignInheritanceModel(Specialization);
9891 if (!HasNoEffect && !PrevDecl) {
9892 // Insert the new specialization.
9893 ClassTemplate->AddSpecialization(Specialization, InsertPos);
9897 Specialization->setTemplateArgsAsWritten(TemplateArgs);
9899 // Set source locations for keywords.
9900 Specialization->setExternKeywordLoc(ExternLoc);
9901 Specialization->setTemplateKeywordLoc(TemplateLoc);
9902 Specialization->setBraceRange(SourceRange());
9904 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
9905 ProcessDeclAttributeList(S, Specialization, Attr);
9906 ProcessAPINotes(Specialization);
9908 // Add the explicit instantiation into its lexical context. However,
9909 // since explicit instantiations are never found by name lookup, we
9910 // just put it into the declaration context directly.
9911 Specialization->setLexicalDeclContext(CurContext);
9912 CurContext->addDecl(Specialization);
9914 // Syntax is now OK, so return if it has no other effect on semantics.
9915 if (HasNoEffect) {
9916 // Set the template specialization kind.
9917 Specialization->setTemplateSpecializationKind(TSK);
9918 return Specialization;
9921 // C++ [temp.explicit]p3:
9922 // A definition of a class template or class member template
9923 // shall be in scope at the point of the explicit instantiation of
9924 // the class template or class member template.
9926 // This check comes when we actually try to perform the
9927 // instantiation.
9928 ClassTemplateSpecializationDecl *Def
9929 = cast_or_null<ClassTemplateSpecializationDecl>(
9930 Specialization->getDefinition());
9931 if (!Def)
9932 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
9933 else if (TSK == TSK_ExplicitInstantiationDefinition) {
9934 MarkVTableUsed(TemplateNameLoc, Specialization, true);
9935 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
9938 // Instantiate the members of this class template specialization.
9939 Def = cast_or_null<ClassTemplateSpecializationDecl>(
9940 Specialization->getDefinition());
9941 if (Def) {
9942 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
9943 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
9944 // TSK_ExplicitInstantiationDefinition
9945 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
9946 (TSK == TSK_ExplicitInstantiationDefinition ||
9947 DLLImportExplicitInstantiationDef)) {
9948 // FIXME: Need to notify the ASTMutationListener that we did this.
9949 Def->setTemplateSpecializationKind(TSK);
9951 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
9952 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
9953 // An explicit instantiation definition can add a dll attribute to a
9954 // template with a previous instantiation declaration. MinGW doesn't
9955 // allow this.
9956 auto *A = cast<InheritableAttr>(
9957 getDLLAttr(Specialization)->clone(getASTContext()));
9958 A->setInherited(true);
9959 Def->addAttr(A);
9960 dllExportImportClassTemplateSpecialization(*this, Def);
9964 // Fix a TSK_ImplicitInstantiation followed by a
9965 // TSK_ExplicitInstantiationDefinition
9966 bool NewlyDLLExported =
9967 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
9968 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
9969 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
9970 // An explicit instantiation definition can add a dll attribute to a
9971 // template with a previous implicit instantiation. MinGW doesn't allow
9972 // this. We limit clang to only adding dllexport, to avoid potentially
9973 // strange codegen behavior. For example, if we extend this conditional
9974 // to dllimport, and we have a source file calling a method on an
9975 // implicitly instantiated template class instance and then declaring a
9976 // dllimport explicit instantiation definition for the same template
9977 // class, the codegen for the method call will not respect the dllimport,
9978 // while it will with cl. The Def will already have the DLL attribute,
9979 // since the Def and Specialization will be the same in the case of
9980 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
9981 // attribute to the Specialization; we just need to make it take effect.
9982 assert(Def == Specialization &&
9983 "Def and Specialization should match for implicit instantiation");
9984 dllExportImportClassTemplateSpecialization(*this, Def);
9987 // In MinGW mode, export the template instantiation if the declaration
9988 // was marked dllexport.
9989 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
9990 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
9991 PrevDecl->hasAttr<DLLExportAttr>()) {
9992 dllExportImportClassTemplateSpecialization(*this, Def);
9995 // Set the template specialization kind. Make sure it is set before
9996 // instantiating the members which will trigger ASTConsumer callbacks.
9997 Specialization->setTemplateSpecializationKind(TSK);
9998 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
9999 } else {
10001 // Set the template specialization kind.
10002 Specialization->setTemplateSpecializationKind(TSK);
10005 return Specialization;
10008 DeclResult
10009 Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10010 SourceLocation TemplateLoc, unsigned TagSpec,
10011 SourceLocation KWLoc, CXXScopeSpec &SS,
10012 IdentifierInfo *Name, SourceLocation NameLoc,
10013 const ParsedAttributesView &Attr) {
10015 bool Owned = false;
10016 bool IsDependent = false;
10017 Decl *TagD =
10018 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10019 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10020 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),
10021 false, TypeResult(), /*IsTypeSpecifier*/ false,
10022 /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside)
10023 .get();
10024 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10026 if (!TagD)
10027 return true;
10029 TagDecl *Tag = cast<TagDecl>(TagD);
10030 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10032 if (Tag->isInvalidDecl())
10033 return true;
10035 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
10036 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10037 if (!Pattern) {
10038 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
10039 << Context.getTypeDeclType(Record);
10040 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
10041 return true;
10044 // C++0x [temp.explicit]p2:
10045 // If the explicit instantiation is for a class or member class, the
10046 // elaborated-type-specifier in the declaration shall include a
10047 // simple-template-id.
10049 // C++98 has the same restriction, just worded differently.
10050 if (!ScopeSpecifierHasTemplateId(SS))
10051 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
10052 << Record << SS.getRange();
10054 // C++0x [temp.explicit]p2:
10055 // There are two forms of explicit instantiation: an explicit instantiation
10056 // definition and an explicit instantiation declaration. An explicit
10057 // instantiation declaration begins with the extern keyword. [...]
10058 TemplateSpecializationKind TSK
10059 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10060 : TSK_ExplicitInstantiationDeclaration;
10062 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
10064 // Verify that it is okay to explicitly instantiate here.
10065 CXXRecordDecl *PrevDecl
10066 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
10067 if (!PrevDecl && Record->getDefinition())
10068 PrevDecl = Record;
10069 if (PrevDecl) {
10070 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10071 bool HasNoEffect = false;
10072 assert(MSInfo && "No member specialization information?");
10073 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
10074 PrevDecl,
10075 MSInfo->getTemplateSpecializationKind(),
10076 MSInfo->getPointOfInstantiation(),
10077 HasNoEffect))
10078 return true;
10079 if (HasNoEffect)
10080 return TagD;
10083 CXXRecordDecl *RecordDef
10084 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10085 if (!RecordDef) {
10086 // C++ [temp.explicit]p3:
10087 // A definition of a member class of a class template shall be in scope
10088 // at the point of an explicit instantiation of the member class.
10089 CXXRecordDecl *Def
10090 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
10091 if (!Def) {
10092 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
10093 << 0 << Record->getDeclName() << Record->getDeclContext();
10094 Diag(Pattern->getLocation(), diag::note_forward_declaration)
10095 << Pattern;
10096 return true;
10097 } else {
10098 if (InstantiateClass(NameLoc, Record, Def,
10099 getTemplateInstantiationArgs(Record),
10100 TSK))
10101 return true;
10103 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
10104 if (!RecordDef)
10105 return true;
10109 // Instantiate all of the members of the class.
10110 InstantiateClassMembers(NameLoc, RecordDef,
10111 getTemplateInstantiationArgs(Record), TSK);
10113 if (TSK == TSK_ExplicitInstantiationDefinition)
10114 MarkVTableUsed(NameLoc, RecordDef, true);
10116 // FIXME: We don't have any representation for explicit instantiations of
10117 // member classes. Such a representation is not needed for compilation, but it
10118 // should be available for clients that want to see all of the declarations in
10119 // the source code.
10120 return TagD;
10123 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10124 SourceLocation ExternLoc,
10125 SourceLocation TemplateLoc,
10126 Declarator &D) {
10127 // Explicit instantiations always require a name.
10128 // TODO: check if/when DNInfo should replace Name.
10129 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10130 DeclarationName Name = NameInfo.getName();
10131 if (!Name) {
10132 if (!D.isInvalidType())
10133 Diag(D.getDeclSpec().getBeginLoc(),
10134 diag::err_explicit_instantiation_requires_name)
10135 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10137 return true;
10140 // Get the innermost enclosing declaration scope.
10141 S = S->getDeclParent();
10143 // Determine the type of the declaration.
10144 TypeSourceInfo *T = GetTypeForDeclarator(D);
10145 QualType R = T->getType();
10146 if (R.isNull())
10147 return true;
10149 // C++ [dcl.stc]p1:
10150 // A storage-class-specifier shall not be specified in [...] an explicit
10151 // instantiation (14.7.2) directive.
10152 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10153 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
10154 << Name;
10155 return true;
10156 } else if (D.getDeclSpec().getStorageClassSpec()
10157 != DeclSpec::SCS_unspecified) {
10158 // Complain about then remove the storage class specifier.
10159 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
10160 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10162 D.getMutableDeclSpec().ClearStorageClassSpecs();
10165 // C++0x [temp.explicit]p1:
10166 // [...] An explicit instantiation of a function template shall not use the
10167 // inline or constexpr specifiers.
10168 // Presumably, this also applies to member functions of class templates as
10169 // well.
10170 if (D.getDeclSpec().isInlineSpecified())
10171 Diag(D.getDeclSpec().getInlineSpecLoc(),
10172 getLangOpts().CPlusPlus11 ?
10173 diag::err_explicit_instantiation_inline :
10174 diag::warn_explicit_instantiation_inline_0x)
10175 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
10176 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10177 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10178 // not already specified.
10179 Diag(D.getDeclSpec().getConstexprSpecLoc(),
10180 diag::err_explicit_instantiation_constexpr);
10182 // A deduction guide is not on the list of entities that can be explicitly
10183 // instantiated.
10184 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10185 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
10186 << /*explicit instantiation*/ 0;
10187 return true;
10190 // C++0x [temp.explicit]p2:
10191 // There are two forms of explicit instantiation: an explicit instantiation
10192 // definition and an explicit instantiation declaration. An explicit
10193 // instantiation declaration begins with the extern keyword. [...]
10194 TemplateSpecializationKind TSK
10195 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10196 : TSK_ExplicitInstantiationDeclaration;
10198 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10199 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),
10200 /*ObjectType=*/QualType());
10202 if (!R->isFunctionType()) {
10203 // C++ [temp.explicit]p1:
10204 // A [...] static data member of a class template can be explicitly
10205 // instantiated from the member definition associated with its class
10206 // template.
10207 // C++1y [temp.explicit]p1:
10208 // A [...] variable [...] template specialization can be explicitly
10209 // instantiated from its template.
10210 if (Previous.isAmbiguous())
10211 return true;
10213 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10214 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10216 if (!PrevTemplate) {
10217 if (!Prev || !Prev->isStaticDataMember()) {
10218 // We expect to see a static data member here.
10219 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
10220 << Name;
10221 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10222 P != PEnd; ++P)
10223 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
10224 return true;
10227 if (!Prev->getInstantiatedFromStaticDataMember()) {
10228 // FIXME: Check for explicit specialization?
10229 Diag(D.getIdentifierLoc(),
10230 diag::err_explicit_instantiation_data_member_not_instantiated)
10231 << Prev;
10232 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
10233 // FIXME: Can we provide a note showing where this was declared?
10234 return true;
10236 } else {
10237 // Explicitly instantiate a variable template.
10239 // C++1y [dcl.spec.auto]p6:
10240 // ... A program that uses auto or decltype(auto) in a context not
10241 // explicitly allowed in this section is ill-formed.
10243 // This includes auto-typed variable template instantiations.
10244 if (R->isUndeducedType()) {
10245 Diag(T->getTypeLoc().getBeginLoc(),
10246 diag::err_auto_not_allowed_var_inst);
10247 return true;
10250 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10251 // C++1y [temp.explicit]p3:
10252 // If the explicit instantiation is for a variable, the unqualified-id
10253 // in the declaration shall be a template-id.
10254 Diag(D.getIdentifierLoc(),
10255 diag::err_explicit_instantiation_without_template_id)
10256 << PrevTemplate;
10257 Diag(PrevTemplate->getLocation(),
10258 diag::note_explicit_instantiation_here);
10259 return true;
10262 // Translate the parser's template argument list into our AST format.
10263 TemplateArgumentListInfo TemplateArgs =
10264 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10266 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
10267 D.getIdentifierLoc(), TemplateArgs);
10268 if (Res.isInvalid())
10269 return true;
10271 if (!Res.isUsable()) {
10272 // We somehow specified dependent template arguments in an explicit
10273 // instantiation. This should probably only happen during error
10274 // recovery.
10275 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
10276 return true;
10279 // Ignore access control bits, we don't need them for redeclaration
10280 // checking.
10281 Prev = cast<VarDecl>(Res.get());
10284 // C++0x [temp.explicit]p2:
10285 // If the explicit instantiation is for a member function, a member class
10286 // or a static data member of a class template specialization, the name of
10287 // the class template specialization in the qualified-id for the member
10288 // name shall be a simple-template-id.
10290 // C++98 has the same restriction, just worded differently.
10292 // This does not apply to variable template specializations, where the
10293 // template-id is in the unqualified-id instead.
10294 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
10295 Diag(D.getIdentifierLoc(),
10296 diag::ext_explicit_instantiation_without_qualified_id)
10297 << Prev << D.getCXXScopeSpec().getRange();
10299 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
10301 // Verify that it is okay to explicitly instantiate here.
10302 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10303 SourceLocation POI = Prev->getPointOfInstantiation();
10304 bool HasNoEffect = false;
10305 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
10306 PrevTSK, POI, HasNoEffect))
10307 return true;
10309 if (!HasNoEffect) {
10310 // Instantiate static data member or variable template.
10311 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10312 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {
10313 VTSD->setExternKeywordLoc(ExternLoc);
10314 VTSD->setTemplateKeywordLoc(TemplateLoc);
10317 // Merge attributes.
10318 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
10319 if (PrevTemplate)
10320 ProcessAPINotes(Prev);
10322 if (TSK == TSK_ExplicitInstantiationDefinition)
10323 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
10326 // Check the new variable specialization against the parsed input.
10327 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
10328 Diag(T->getTypeLoc().getBeginLoc(),
10329 diag::err_invalid_var_template_spec_type)
10330 << 0 << PrevTemplate << R << Prev->getType();
10331 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
10332 << 2 << PrevTemplate->getDeclName();
10333 return true;
10336 // FIXME: Create an ExplicitInstantiation node?
10337 return (Decl*) nullptr;
10340 // If the declarator is a template-id, translate the parser's template
10341 // argument list into our AST format.
10342 bool HasExplicitTemplateArgs = false;
10343 TemplateArgumentListInfo TemplateArgs;
10344 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10345 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
10346 HasExplicitTemplateArgs = true;
10349 // C++ [temp.explicit]p1:
10350 // A [...] function [...] can be explicitly instantiated from its template.
10351 // A member function [...] of a class template can be explicitly
10352 // instantiated from the member definition associated with its class
10353 // template.
10354 UnresolvedSet<8> TemplateMatches;
10355 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10356 OverloadCandidateSet::CSK_Normal);
10357 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10358 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10359 P != PEnd; ++P) {
10360 NamedDecl *Prev = *P;
10361 if (!HasExplicitTemplateArgs) {
10362 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
10363 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
10364 /*AdjustExceptionSpec*/true);
10365 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
10366 if (Method->getPrimaryTemplate()) {
10367 TemplateMatches.addDecl(Method, P.getAccess());
10368 } else {
10369 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10370 C.FoundDecl = P.getPair();
10371 C.Function = Method;
10372 C.Viable = true;
10373 ConstraintSatisfaction S;
10374 if (Method->getTrailingRequiresClause() &&
10375 (CheckFunctionConstraints(Method, S, D.getIdentifierLoc(),
10376 /*ForOverloadResolution=*/true) ||
10377 !S.IsSatisfied)) {
10378 C.Viable = false;
10379 C.FailureKind = ovl_fail_constraints_not_satisfied;
10386 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
10387 if (!FunTmpl)
10388 continue;
10390 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10391 FunctionDecl *Specialization = nullptr;
10392 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
10393 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,
10394 Specialization, Info);
10395 TDK != TemplateDeductionResult::Success) {
10396 // Keep track of almost-matches.
10397 FailedTemplateCandidates.addCandidate().set(
10398 P.getPair(), FunTmpl->getTemplatedDecl(),
10399 MakeDeductionFailureInfo(Context, TDK, Info));
10400 (void)TDK;
10401 continue;
10404 // Target attributes are part of the cuda function signature, so
10405 // the cuda target of the instantiated function must match that of its
10406 // template. Given that C++ template deduction does not take
10407 // target attributes into account, we reject candidates here that
10408 // have a different target.
10409 if (LangOpts.CUDA &&
10410 CUDA().IdentifyTarget(Specialization,
10411 /* IgnoreImplicitHDAttr = */ true) !=
10412 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {
10413 FailedTemplateCandidates.addCandidate().set(
10414 P.getPair(), FunTmpl->getTemplatedDecl(),
10415 MakeDeductionFailureInfo(
10416 Context, TemplateDeductionResult::CUDATargetMismatch, Info));
10417 continue;
10420 TemplateMatches.addDecl(Specialization, P.getAccess());
10423 FunctionDecl *Specialization = nullptr;
10424 if (!NonTemplateMatches.empty()) {
10425 unsigned Msg = 0;
10426 OverloadCandidateDisplayKind DisplayKind;
10427 OverloadCandidateSet::iterator Best;
10428 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),
10429 Best)) {
10430 case OR_Success:
10431 case OR_Deleted:
10432 Specialization = cast<FunctionDecl>(Best->Function);
10433 break;
10434 case OR_Ambiguous:
10435 Msg = diag::err_explicit_instantiation_ambiguous;
10436 DisplayKind = OCD_AmbiguousCandidates;
10437 break;
10438 case OR_No_Viable_Function:
10439 Msg = diag::err_explicit_instantiation_no_candidate;
10440 DisplayKind = OCD_AllCandidates;
10441 break;
10443 if (Msg) {
10444 PartialDiagnostic Diag = PDiag(Msg) << Name;
10445 NonTemplateMatches.NoteCandidates(
10446 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,
10447 {});
10448 return true;
10452 if (!Specialization) {
10453 // Find the most specialized function template specialization.
10454 UnresolvedSetIterator Result = getMostSpecialized(
10455 TemplateMatches.begin(), TemplateMatches.end(),
10456 FailedTemplateCandidates, D.getIdentifierLoc(),
10457 PDiag(diag::err_explicit_instantiation_not_known) << Name,
10458 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
10459 PDiag(diag::note_explicit_instantiation_candidate));
10461 if (Result == TemplateMatches.end())
10462 return true;
10464 // Ignore access control bits, we don't need them for redeclaration checking.
10465 Specialization = cast<FunctionDecl>(*Result);
10468 // C++11 [except.spec]p4
10469 // In an explicit instantiation an exception-specification may be specified,
10470 // but is not required.
10471 // If an exception-specification is specified in an explicit instantiation
10472 // directive, it shall be compatible with the exception-specifications of
10473 // other declarations of that function.
10474 if (auto *FPT = R->getAs<FunctionProtoType>())
10475 if (FPT->hasExceptionSpec()) {
10476 unsigned DiagID =
10477 diag::err_mismatched_exception_spec_explicit_instantiation;
10478 if (getLangOpts().MicrosoftExt)
10479 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10480 bool Result = CheckEquivalentExceptionSpec(
10481 PDiag(DiagID) << Specialization->getType(),
10482 PDiag(diag::note_explicit_instantiation_here),
10483 Specialization->getType()->getAs<FunctionProtoType>(),
10484 Specialization->getLocation(), FPT, D.getBeginLoc());
10485 // In Microsoft mode, mismatching exception specifications just cause a
10486 // warning.
10487 if (!getLangOpts().MicrosoftExt && Result)
10488 return true;
10491 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10492 Diag(D.getIdentifierLoc(),
10493 diag::err_explicit_instantiation_member_function_not_instantiated)
10494 << Specialization
10495 << (Specialization->getTemplateSpecializationKind() ==
10496 TSK_ExplicitSpecialization);
10497 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
10498 return true;
10501 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10502 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10503 PrevDecl = Specialization;
10505 if (PrevDecl) {
10506 bool HasNoEffect = false;
10507 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
10508 PrevDecl,
10509 PrevDecl->getTemplateSpecializationKind(),
10510 PrevDecl->getPointOfInstantiation(),
10511 HasNoEffect))
10512 return true;
10514 // FIXME: We may still want to build some representation of this
10515 // explicit specialization.
10516 if (HasNoEffect)
10517 return (Decl*) nullptr;
10520 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10521 // functions
10522 // valarray<size_t>::valarray(size_t) and
10523 // valarray<size_t>::~valarray()
10524 // that it declared to have internal linkage with the internal_linkage
10525 // attribute. Ignore the explicit instantiation declaration in this case.
10526 if (Specialization->hasAttr<InternalLinkageAttr>() &&
10527 TSK == TSK_ExplicitInstantiationDeclaration) {
10528 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
10529 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
10530 RD->isInStdNamespace())
10531 return (Decl*) nullptr;
10534 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
10535 ProcessAPINotes(Specialization);
10537 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10538 // instantiation declarations.
10539 if (TSK == TSK_ExplicitInstantiationDefinition &&
10540 Specialization->hasAttr<DLLImportAttr>() &&
10541 Context.getTargetInfo().getCXXABI().isMicrosoft())
10542 TSK = TSK_ExplicitInstantiationDeclaration;
10544 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
10546 if (Specialization->isDefined()) {
10547 // Let the ASTConsumer know that this function has been explicitly
10548 // instantiated now, and its linkage might have changed.
10549 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
10550 } else if (TSK == TSK_ExplicitInstantiationDefinition)
10551 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
10553 // C++0x [temp.explicit]p2:
10554 // If the explicit instantiation is for a member function, a member class
10555 // or a static data member of a class template specialization, the name of
10556 // the class template specialization in the qualified-id for the member
10557 // name shall be a simple-template-id.
10559 // C++98 has the same restriction, just worded differently.
10560 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10561 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10562 D.getCXXScopeSpec().isSet() &&
10563 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
10564 Diag(D.getIdentifierLoc(),
10565 diag::ext_explicit_instantiation_without_qualified_id)
10566 << Specialization << D.getCXXScopeSpec().getRange();
10568 CheckExplicitInstantiation(
10569 *this,
10570 FunTmpl ? (NamedDecl *)FunTmpl
10571 : Specialization->getInstantiatedFromMemberFunction(),
10572 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
10574 // FIXME: Create some kind of ExplicitInstantiationDecl here.
10575 return (Decl*) nullptr;
10578 TypeResult Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10579 const CXXScopeSpec &SS,
10580 const IdentifierInfo *Name,
10581 SourceLocation TagLoc,
10582 SourceLocation NameLoc) {
10583 // This has to hold, because SS is expected to be defined.
10584 assert(Name && "Expected a name in a dependent tag");
10586 NestedNameSpecifier *NNS = SS.getScopeRep();
10587 if (!NNS)
10588 return true;
10590 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
10592 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
10593 Diag(NameLoc, diag::err_dependent_tag_decl)
10594 << (TUK == TagUseKind::Definition) << llvm::to_underlying(Kind)
10595 << SS.getRange();
10596 return true;
10599 // Create the resulting type.
10600 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
10601 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
10603 // Create type-source location information for this type.
10604 TypeLocBuilder TLB;
10605 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
10606 TL.setElaboratedKeywordLoc(TagLoc);
10607 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10608 TL.setNameLoc(NameLoc);
10609 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
10612 TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
10613 const CXXScopeSpec &SS,
10614 const IdentifierInfo &II,
10615 SourceLocation IdLoc,
10616 ImplicitTypenameContext IsImplicitTypename) {
10617 if (SS.isInvalid())
10618 return true;
10620 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10621 Diag(TypenameLoc,
10622 getLangOpts().CPlusPlus11 ?
10623 diag::warn_cxx98_compat_typename_outside_of_template :
10624 diag::ext_typename_outside_of_template)
10625 << FixItHint::CreateRemoval(TypenameLoc);
10627 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10628 TypeSourceInfo *TSI = nullptr;
10629 QualType T =
10630 CheckTypenameType((TypenameLoc.isValid() ||
10631 IsImplicitTypename == ImplicitTypenameContext::Yes)
10632 ? ElaboratedTypeKeyword::Typename
10633 : ElaboratedTypeKeyword::None,
10634 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,
10635 /*DeducedTSTContext=*/true);
10636 if (T.isNull())
10637 return true;
10638 return CreateParsedType(T, TSI);
10641 TypeResult
10642 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
10643 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
10644 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
10645 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
10646 ASTTemplateArgsPtr TemplateArgsIn,
10647 SourceLocation RAngleLoc) {
10648 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10649 Diag(TypenameLoc,
10650 getLangOpts().CPlusPlus11 ?
10651 diag::warn_cxx98_compat_typename_outside_of_template :
10652 diag::ext_typename_outside_of_template)
10653 << FixItHint::CreateRemoval(TypenameLoc);
10655 // Strangely, non-type results are not ignored by this lookup, so the
10656 // program is ill-formed if it finds an injected-class-name.
10657 if (TypenameLoc.isValid()) {
10658 auto *LookupRD =
10659 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
10660 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10661 Diag(TemplateIILoc,
10662 diag::ext_out_of_line_qualified_id_type_names_constructor)
10663 << TemplateII << 0 /*injected-class-name used as template name*/
10664 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10668 // Translate the parser's template argument list in our AST format.
10669 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10670 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10672 TemplateName Template = TemplateIn.get();
10673 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
10674 // Construct a dependent template specialization type.
10675 assert(DTN && "dependent template has non-dependent name?");
10676 assert(DTN->getQualifier() == SS.getScopeRep());
10678 if (!DTN->isIdentifier()) {
10679 Diag(TemplateIILoc, diag::err_template_id_not_a_type) << Template;
10680 NoteAllFoundTemplates(Template);
10681 return true;
10684 QualType T = Context.getDependentTemplateSpecializationType(
10685 ElaboratedTypeKeyword::Typename, DTN->getQualifier(),
10686 DTN->getIdentifier(), TemplateArgs.arguments());
10688 // Create source-location information for this type.
10689 TypeLocBuilder Builder;
10690 DependentTemplateSpecializationTypeLoc SpecTL
10691 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
10692 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
10693 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
10694 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10695 SpecTL.setTemplateNameLoc(TemplateIILoc);
10696 SpecTL.setLAngleLoc(LAngleLoc);
10697 SpecTL.setRAngleLoc(RAngleLoc);
10698 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10699 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10700 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
10703 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
10704 if (T.isNull())
10705 return true;
10707 // Provide source-location information for the template specialization type.
10708 TypeLocBuilder Builder;
10709 TemplateSpecializationTypeLoc SpecTL
10710 = Builder.push<TemplateSpecializationTypeLoc>(T);
10711 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10712 SpecTL.setTemplateNameLoc(TemplateIILoc);
10713 SpecTL.setLAngleLoc(LAngleLoc);
10714 SpecTL.setRAngleLoc(RAngleLoc);
10715 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10716 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
10718 T = Context.getElaboratedType(ElaboratedTypeKeyword::Typename,
10719 SS.getScopeRep(), T);
10720 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
10721 TL.setElaboratedKeywordLoc(TypenameLoc);
10722 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10724 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
10725 return CreateParsedType(T, TSI);
10728 /// Determine whether this failed name lookup should be treated as being
10729 /// disabled by a usage of std::enable_if.
10730 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
10731 SourceRange &CondRange, Expr *&Cond) {
10732 // We must be looking for a ::type...
10733 if (!II.isStr("type"))
10734 return false;
10736 // ... within an explicitly-written template specialization...
10737 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
10738 return false;
10739 TypeLoc EnableIfTy = NNS.getTypeLoc();
10740 TemplateSpecializationTypeLoc EnableIfTSTLoc =
10741 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
10742 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
10743 return false;
10744 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
10746 // ... which names a complete class template declaration...
10747 const TemplateDecl *EnableIfDecl =
10748 EnableIfTST->getTemplateName().getAsTemplateDecl();
10749 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
10750 return false;
10752 // ... called "enable_if".
10753 const IdentifierInfo *EnableIfII =
10754 EnableIfDecl->getDeclName().getAsIdentifierInfo();
10755 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
10756 return false;
10758 // Assume the first template argument is the condition.
10759 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
10761 // Dig out the condition.
10762 Cond = nullptr;
10763 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
10764 != TemplateArgument::Expression)
10765 return true;
10767 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
10769 // Ignore Boolean literals; they add no value.
10770 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
10771 Cond = nullptr;
10773 return true;
10776 QualType
10777 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
10778 SourceLocation KeywordLoc,
10779 NestedNameSpecifierLoc QualifierLoc,
10780 const IdentifierInfo &II,
10781 SourceLocation IILoc,
10782 TypeSourceInfo **TSI,
10783 bool DeducedTSTContext) {
10784 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
10785 DeducedTSTContext);
10786 if (T.isNull())
10787 return QualType();
10789 *TSI = Context.CreateTypeSourceInfo(T);
10790 if (isa<DependentNameType>(T)) {
10791 DependentNameTypeLoc TL =
10792 (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
10793 TL.setElaboratedKeywordLoc(KeywordLoc);
10794 TL.setQualifierLoc(QualifierLoc);
10795 TL.setNameLoc(IILoc);
10796 } else {
10797 ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
10798 TL.setElaboratedKeywordLoc(KeywordLoc);
10799 TL.setQualifierLoc(QualifierLoc);
10800 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
10802 return T;
10805 /// Build the type that describes a C++ typename specifier,
10806 /// e.g., "typename T::type".
10807 QualType
10808 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
10809 SourceLocation KeywordLoc,
10810 NestedNameSpecifierLoc QualifierLoc,
10811 const IdentifierInfo &II,
10812 SourceLocation IILoc, bool DeducedTSTContext) {
10813 CXXScopeSpec SS;
10814 SS.Adopt(QualifierLoc);
10816 DeclContext *Ctx = nullptr;
10817 if (QualifierLoc) {
10818 Ctx = computeDeclContext(SS);
10819 if (!Ctx) {
10820 // If the nested-name-specifier is dependent and couldn't be
10821 // resolved to a type, build a typename type.
10822 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
10823 return Context.getDependentNameType(Keyword,
10824 QualifierLoc.getNestedNameSpecifier(),
10825 &II);
10828 // If the nested-name-specifier refers to the current instantiation,
10829 // the "typename" keyword itself is superfluous. In C++03, the
10830 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
10831 // allows such extraneous "typename" keywords, and we retroactively
10832 // apply this DR to C++03 code with only a warning. In any case we continue.
10834 if (RequireCompleteDeclContext(SS, Ctx))
10835 return QualType();
10838 DeclarationName Name(&II);
10839 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
10840 if (Ctx)
10841 LookupQualifiedName(Result, Ctx, SS);
10842 else
10843 LookupName(Result, CurScope);
10844 unsigned DiagID = 0;
10845 Decl *Referenced = nullptr;
10846 switch (Result.getResultKind()) {
10847 case LookupResult::NotFound: {
10848 // If we're looking up 'type' within a template named 'enable_if', produce
10849 // a more specific diagnostic.
10850 SourceRange CondRange;
10851 Expr *Cond = nullptr;
10852 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {
10853 // If we have a condition, narrow it down to the specific failed
10854 // condition.
10855 if (Cond) {
10856 Expr *FailedCond;
10857 std::string FailedDescription;
10858 std::tie(FailedCond, FailedDescription) =
10859 findFailedBooleanCondition(Cond);
10861 Diag(FailedCond->getExprLoc(),
10862 diag::err_typename_nested_not_found_requirement)
10863 << FailedDescription
10864 << FailedCond->getSourceRange();
10865 return QualType();
10868 Diag(CondRange.getBegin(),
10869 diag::err_typename_nested_not_found_enable_if)
10870 << Ctx << CondRange;
10871 return QualType();
10874 DiagID = Ctx ? diag::err_typename_nested_not_found
10875 : diag::err_unknown_typename;
10876 break;
10879 case LookupResult::FoundUnresolvedValue: {
10880 // We found a using declaration that is a value. Most likely, the using
10881 // declaration itself is meant to have the 'typename' keyword.
10882 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10883 IILoc);
10884 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
10885 << Name << Ctx << FullRange;
10886 if (UnresolvedUsingValueDecl *Using
10887 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
10888 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
10889 Diag(Loc, diag::note_using_value_decl_missing_typename)
10890 << FixItHint::CreateInsertion(Loc, "typename ");
10893 // Fall through to create a dependent typename type, from which we can recover
10894 // better.
10895 [[fallthrough]];
10897 case LookupResult::NotFoundInCurrentInstantiation:
10898 // Okay, it's a member of an unknown instantiation.
10899 return Context.getDependentNameType(Keyword,
10900 QualifierLoc.getNestedNameSpecifier(),
10901 &II);
10903 case LookupResult::Found:
10904 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
10905 // C++ [class.qual]p2:
10906 // In a lookup in which function names are not ignored and the
10907 // nested-name-specifier nominates a class C, if the name specified
10908 // after the nested-name-specifier, when looked up in C, is the
10909 // injected-class-name of C [...] then the name is instead considered
10910 // to name the constructor of class C.
10912 // Unlike in an elaborated-type-specifier, function names are not ignored
10913 // in typename-specifier lookup. However, they are ignored in all the
10914 // contexts where we form a typename type with no keyword (that is, in
10915 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
10917 // FIXME: That's not strictly true: mem-initializer-id lookup does not
10918 // ignore functions, but that appears to be an oversight.
10919 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
10920 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
10921 if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD &&
10922 FoundRD->isInjectedClassName() &&
10923 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
10924 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
10925 << &II << 1 << 0 /*'typename' keyword used*/;
10927 // We found a type. Build an ElaboratedType, since the
10928 // typename-specifier was just sugar.
10929 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
10930 return Context.getElaboratedType(Keyword,
10931 QualifierLoc.getNestedNameSpecifier(),
10932 Context.getTypeDeclType(Type));
10935 // C++ [dcl.type.simple]p2:
10936 // A type-specifier of the form
10937 // typename[opt] nested-name-specifier[opt] template-name
10938 // is a placeholder for a deduced class type [...].
10939 if (getLangOpts().CPlusPlus17) {
10940 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
10941 if (!DeducedTSTContext) {
10942 QualType T(QualifierLoc
10943 ? QualifierLoc.getNestedNameSpecifier()->getAsType()
10944 : nullptr, 0);
10945 if (!T.isNull())
10946 Diag(IILoc, diag::err_dependent_deduced_tst)
10947 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << T;
10948 else
10949 Diag(IILoc, diag::err_deduced_tst)
10950 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD));
10951 NoteTemplateLocation(*TD);
10952 return QualType();
10954 return Context.getElaboratedType(
10955 Keyword, QualifierLoc.getNestedNameSpecifier(),
10956 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
10957 QualType(), false));
10961 DiagID = Ctx ? diag::err_typename_nested_not_type
10962 : diag::err_typename_not_type;
10963 Referenced = Result.getFoundDecl();
10964 break;
10966 case LookupResult::FoundOverloaded:
10967 DiagID = Ctx ? diag::err_typename_nested_not_type
10968 : diag::err_typename_not_type;
10969 Referenced = *Result.begin();
10970 break;
10972 case LookupResult::Ambiguous:
10973 return QualType();
10976 // If we get here, it's because name lookup did not find a
10977 // type. Emit an appropriate diagnostic and return an error.
10978 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
10979 IILoc);
10980 if (Ctx)
10981 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
10982 else
10983 Diag(IILoc, DiagID) << FullRange << Name;
10984 if (Referenced)
10985 Diag(Referenced->getLocation(),
10986 Ctx ? diag::note_typename_member_refers_here
10987 : diag::note_typename_refers_here)
10988 << Name;
10989 return QualType();
10992 namespace {
10993 // See Sema::RebuildTypeInCurrentInstantiation
10994 class CurrentInstantiationRebuilder
10995 : public TreeTransform<CurrentInstantiationRebuilder> {
10996 SourceLocation Loc;
10997 DeclarationName Entity;
10999 public:
11000 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11002 CurrentInstantiationRebuilder(Sema &SemaRef,
11003 SourceLocation Loc,
11004 DeclarationName Entity)
11005 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11006 Loc(Loc), Entity(Entity) { }
11008 /// Determine whether the given type \p T has already been
11009 /// transformed.
11011 /// For the purposes of type reconstruction, a type has already been
11012 /// transformed if it is NULL or if it is not dependent.
11013 bool AlreadyTransformed(QualType T) {
11014 return T.isNull() || !T->isInstantiationDependentType();
11017 /// Returns the location of the entity whose type is being
11018 /// rebuilt.
11019 SourceLocation getBaseLocation() { return Loc; }
11021 /// Returns the name of the entity whose type is being rebuilt.
11022 DeclarationName getBaseEntity() { return Entity; }
11024 /// Sets the "base" location and entity when that
11025 /// information is known based on another transformation.
11026 void setBase(SourceLocation Loc, DeclarationName Entity) {
11027 this->Loc = Loc;
11028 this->Entity = Entity;
11031 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11032 // Lambdas never need to be transformed.
11033 return E;
11036 } // end anonymous namespace
11038 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11039 SourceLocation Loc,
11040 DeclarationName Name) {
11041 if (!T || !T->getType()->isInstantiationDependentType())
11042 return T;
11044 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11045 return Rebuilder.TransformType(T);
11048 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11049 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11050 DeclarationName());
11051 return Rebuilder.TransformExpr(E);
11054 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11055 if (SS.isInvalid())
11056 return true;
11058 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11059 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11060 DeclarationName());
11061 NestedNameSpecifierLoc Rebuilt
11062 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
11063 if (!Rebuilt)
11064 return true;
11066 SS.Adopt(Rebuilt);
11067 return false;
11070 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11071 TemplateParameterList *Params) {
11072 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11073 Decl *Param = Params->getParam(I);
11075 // There is nothing to rebuild in a type parameter.
11076 if (isa<TemplateTypeParmDecl>(Param))
11077 continue;
11079 // Rebuild the template parameter list of a template template parameter.
11080 if (TemplateTemplateParmDecl *TTP
11081 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
11082 if (RebuildTemplateParamsInCurrentInstantiation(
11083 TTP->getTemplateParameters()))
11084 return true;
11086 continue;
11089 // Rebuild the type of a non-type template parameter.
11090 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
11091 TypeSourceInfo *NewTSI
11092 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
11093 NTTP->getLocation(),
11094 NTTP->getDeclName());
11095 if (!NewTSI)
11096 return true;
11098 if (NewTSI->getType()->isUndeducedType()) {
11099 // C++17 [temp.dep.expr]p3:
11100 // An id-expression is type-dependent if it contains
11101 // - an identifier associated by name lookup with a non-type
11102 // template-parameter declared with a type that contains a
11103 // placeholder type (7.1.7.4),
11104 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);
11107 if (NewTSI != NTTP->getTypeSourceInfo()) {
11108 NTTP->setTypeSourceInfo(NewTSI);
11109 NTTP->setType(NewTSI->getType());
11113 return false;
11116 std::string
11117 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11118 const TemplateArgumentList &Args) {
11119 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
11122 std::string
11123 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11124 const TemplateArgument *Args,
11125 unsigned NumArgs) {
11126 SmallString<128> Str;
11127 llvm::raw_svector_ostream Out(Str);
11129 if (!Params || Params->size() == 0 || NumArgs == 0)
11130 return std::string();
11132 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11133 if (I >= NumArgs)
11134 break;
11136 if (I == 0)
11137 Out << "[with ";
11138 else
11139 Out << ", ";
11141 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
11142 Out << Id->getName();
11143 } else {
11144 Out << '$' << I;
11147 Out << " = ";
11148 Args[I].print(getPrintingPolicy(), Out,
11149 TemplateParameterList::shouldIncludeTypeForArgument(
11150 getPrintingPolicy(), Params, I));
11153 Out << ']';
11154 return std::string(Out.str());
11157 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11158 CachedTokens &Toks) {
11159 if (!FD)
11160 return;
11162 auto LPT = std::make_unique<LateParsedTemplate>();
11164 // Take tokens to avoid allocations
11165 LPT->Toks.swap(Toks);
11166 LPT->D = FnD;
11167 LPT->FPO = getCurFPFeatures();
11168 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
11170 FD->setLateTemplateParsed(true);
11173 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11174 if (!FD)
11175 return;
11176 FD->setLateTemplateParsed(false);
11179 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11180 DeclContext *DC = CurContext;
11182 while (DC) {
11183 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
11184 const FunctionDecl *FD = RD->isLocalClass();
11185 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11186 } else if (DC->isTranslationUnit() || DC->isNamespace())
11187 return false;
11189 DC = DC->getParent();
11191 return false;
11194 namespace {
11195 /// Walk the path from which a declaration was instantiated, and check
11196 /// that every explicit specialization along that path is visible. This enforces
11197 /// C++ [temp.expl.spec]/6:
11199 /// If a template, a member template or a member of a class template is
11200 /// explicitly specialized then that specialization shall be declared before
11201 /// the first use of that specialization that would cause an implicit
11202 /// instantiation to take place, in every translation unit in which such a
11203 /// use occurs; no diagnostic is required.
11205 /// and also C++ [temp.class.spec]/1:
11207 /// A partial specialization shall be declared before the first use of a
11208 /// class template specialization that would make use of the partial
11209 /// specialization as the result of an implicit or explicit instantiation
11210 /// in every translation unit in which such a use occurs; no diagnostic is
11211 /// required.
11212 class ExplicitSpecializationVisibilityChecker {
11213 Sema &S;
11214 SourceLocation Loc;
11215 llvm::SmallVector<Module *, 8> Modules;
11216 Sema::AcceptableKind Kind;
11218 public:
11219 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11220 Sema::AcceptableKind Kind)
11221 : S(S), Loc(Loc), Kind(Kind) {}
11223 void check(NamedDecl *ND) {
11224 if (auto *FD = dyn_cast<FunctionDecl>(ND))
11225 return checkImpl(FD);
11226 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
11227 return checkImpl(RD);
11228 if (auto *VD = dyn_cast<VarDecl>(ND))
11229 return checkImpl(VD);
11230 if (auto *ED = dyn_cast<EnumDecl>(ND))
11231 return checkImpl(ED);
11234 private:
11235 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11236 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11237 : Sema::MissingImportKind::ExplicitSpecialization;
11238 const bool Recover = true;
11240 // If we got a custom set of modules (because only a subset of the
11241 // declarations are interesting), use them, otherwise let
11242 // diagnoseMissingImport intelligently pick some.
11243 if (Modules.empty())
11244 S.diagnoseMissingImport(Loc, D, Kind, Recover);
11245 else
11246 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
11249 bool CheckMemberSpecialization(const NamedDecl *D) {
11250 return Kind == Sema::AcceptableKind::Visible
11251 ? S.hasVisibleMemberSpecialization(D)
11252 : S.hasReachableMemberSpecialization(D);
11255 bool CheckExplicitSpecialization(const NamedDecl *D) {
11256 return Kind == Sema::AcceptableKind::Visible
11257 ? S.hasVisibleExplicitSpecialization(D)
11258 : S.hasReachableExplicitSpecialization(D);
11261 bool CheckDeclaration(const NamedDecl *D) {
11262 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11263 : S.hasReachableDeclaration(D);
11266 // Check a specific declaration. There are three problematic cases:
11268 // 1) The declaration is an explicit specialization of a template
11269 // specialization.
11270 // 2) The declaration is an explicit specialization of a member of an
11271 // templated class.
11272 // 3) The declaration is an instantiation of a template, and that template
11273 // is an explicit specialization of a member of a templated class.
11275 // We don't need to go any deeper than that, as the instantiation of the
11276 // surrounding class / etc is not triggered by whatever triggered this
11277 // instantiation, and thus should be checked elsewhere.
11278 template<typename SpecDecl>
11279 void checkImpl(SpecDecl *Spec) {
11280 bool IsHiddenExplicitSpecialization = false;
11281 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
11282 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11283 ? !CheckMemberSpecialization(Spec)
11284 : !CheckExplicitSpecialization(Spec);
11285 } else {
11286 checkInstantiated(Spec);
11289 if (IsHiddenExplicitSpecialization)
11290 diagnose(Spec->getMostRecentDecl(), false);
11293 void checkInstantiated(FunctionDecl *FD) {
11294 if (auto *TD = FD->getPrimaryTemplate())
11295 checkTemplate(TD);
11298 void checkInstantiated(CXXRecordDecl *RD) {
11299 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
11300 if (!SD)
11301 return;
11303 auto From = SD->getSpecializedTemplateOrPartial();
11304 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11305 checkTemplate(TD);
11306 else if (auto *TD =
11307 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11308 if (!CheckDeclaration(TD))
11309 diagnose(TD, true);
11310 checkTemplate(TD);
11314 void checkInstantiated(VarDecl *RD) {
11315 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
11316 if (!SD)
11317 return;
11319 auto From = SD->getSpecializedTemplateOrPartial();
11320 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11321 checkTemplate(TD);
11322 else if (auto *TD =
11323 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11324 if (!CheckDeclaration(TD))
11325 diagnose(TD, true);
11326 checkTemplate(TD);
11330 void checkInstantiated(EnumDecl *FD) {}
11332 template<typename TemplDecl>
11333 void checkTemplate(TemplDecl *TD) {
11334 if (TD->isMemberSpecialization()) {
11335 if (!CheckMemberSpecialization(TD))
11336 diagnose(TD->getMostRecentDecl(), false);
11340 } // end anonymous namespace
11342 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
11343 if (!getLangOpts().Modules)
11344 return;
11346 ExplicitSpecializationVisibilityChecker(*this, Loc,
11347 Sema::AcceptableKind::Visible)
11348 .check(Spec);
11351 void Sema::checkSpecializationReachability(SourceLocation Loc,
11352 NamedDecl *Spec) {
11353 if (!getLangOpts().CPlusPlusModules)
11354 return checkSpecializationVisibility(Loc, Spec);
11356 ExplicitSpecializationVisibilityChecker(*this, Loc,
11357 Sema::AcceptableKind::Reachable)
11358 .check(Spec);
11361 SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
11362 if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
11363 return N->getLocation();
11364 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {
11365 if (!FD->isFunctionTemplateSpecialization())
11366 return FD->getLocation();
11367 } else if (!isa<ClassTemplateSpecializationDecl,
11368 VarTemplateSpecializationDecl>(N)) {
11369 return N->getLocation();
11371 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11372 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11373 continue;
11374 return CSC.PointOfInstantiation;
11376 return N->getLocation();