1 //===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for C++ templates.
10 //===----------------------------------------------------------------------===//
12 #include "TreeTransform.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/DeclFriend.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/RecursiveASTVisitor.h"
20 #include "clang/AST/TypeVisitor.h"
21 #include "clang/Basic/Builtins.h"
22 #include "clang/Basic/LangOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/DeclSpec.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/ParsedTemplate.h"
28 #include "clang/Sema/Scope.h"
29 #include "clang/Sema/SemaInternal.h"
30 #include "clang/Sema/Template.h"
31 #include "clang/Sema/TemplateDeduction.h"
32 #include "llvm/ADT/SmallBitVector.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/StringExtras.h"
37 using namespace clang;
40 // Exported for use by Parser.
42 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
44 if (!N) return SourceRange();
45 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
49 /// \brief [temp.constr.decl]p2: A template's associated constraints are
50 /// defined as a single constraint-expression derived from the introduced
51 /// constraint-expressions [ ... ].
53 /// \param Params The template parameter list and optional requires-clause.
55 /// \param FD The underlying templated function declaration for a function
57 static Expr *formAssociatedConstraints(TemplateParameterList *Params,
61 static Expr *clang::formAssociatedConstraints(TemplateParameterList *Params,
63 // FIXME: Concepts: collect additional introduced constraint-expressions
64 assert(!FD && "Cannot collect constraints from function declaration yet.");
65 return Params->getRequiresClause();
68 /// \brief Determine whether the declaration found is acceptable as the name
69 /// of a template and, if so, return that template declaration. Otherwise,
71 static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
73 bool AllowFunctionTemplates) {
74 NamedDecl *D = Orig->getUnderlyingDecl();
76 if (isa<TemplateDecl>(D)) {
77 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
83 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
84 // C++ [temp.local]p1:
85 // Like normal (non-template) classes, class templates have an
86 // injected-class-name (Clause 9). The injected-class-name
87 // can be used with or without a template-argument-list. When
88 // it is used without a template-argument-list, it is
89 // equivalent to the injected-class-name followed by the
90 // template-parameters of the class template enclosed in
91 // <>. When it is used with a template-argument-list, it
92 // refers to the specified class template specialization,
93 // which could be the current specialization or another
95 if (Record->isInjectedClassName()) {
96 Record = cast<CXXRecordDecl>(Record->getDeclContext());
97 if (Record->getDescribedClassTemplate())
98 return Record->getDescribedClassTemplate();
100 if (ClassTemplateSpecializationDecl *Spec
101 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
102 return Spec->getSpecializedTemplate();
111 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
112 bool AllowFunctionTemplates) {
113 // The set of class templates we've already seen.
114 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
115 LookupResult::Filter filter = R.makeFilter();
116 while (filter.hasNext()) {
117 NamedDecl *Orig = filter.next();
118 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
119 AllowFunctionTemplates);
122 else if (Repl != Orig) {
124 // C++ [temp.local]p3:
125 // A lookup that finds an injected-class-name (10.2) can result in an
126 // ambiguity in certain cases (for example, if it is found in more than
127 // one base class). If all of the injected-class-names that are found
128 // refer to specializations of the same class template, and if the name
129 // is used as a template-name, the reference refers to the class
130 // template itself and not a specialization thereof, and is not
132 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
133 if (!ClassTemplates.insert(ClassTmpl).second) {
138 // FIXME: we promote access to public here as a workaround to
139 // the fact that LookupResult doesn't let us remember that we
140 // found this template through a particular injected class name,
141 // which means we end up doing nasty things to the invariants.
142 // Pretending that access is public is *much* safer.
143 filter.replace(Repl, AS_public);
149 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
150 bool AllowFunctionTemplates) {
151 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
152 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
158 TemplateNameKind Sema::isTemplateName(Scope *S,
160 bool hasTemplateKeyword,
162 ParsedType ObjectTypePtr,
163 bool EnteringContext,
164 TemplateTy &TemplateResult,
165 bool &MemberOfUnknownSpecialization) {
166 assert(getLangOpts().CPlusPlus && "No template names in C!");
168 DeclarationName TName;
169 MemberOfUnknownSpecialization = false;
171 switch (Name.getKind()) {
172 case UnqualifiedIdKind::IK_Identifier:
173 TName = DeclarationName(Name.Identifier);
176 case UnqualifiedIdKind::IK_OperatorFunctionId:
177 TName = Context.DeclarationNames.getCXXOperatorName(
178 Name.OperatorFunctionId.Operator);
181 case UnqualifiedIdKind::IK_LiteralOperatorId:
182 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
186 return TNK_Non_template;
189 QualType ObjectType = ObjectTypePtr.get();
191 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
192 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
193 MemberOfUnknownSpecialization);
194 if (R.empty()) return TNK_Non_template;
195 if (R.isAmbiguous()) {
196 // Suppress diagnostics; we'll redo this lookup later.
197 R.suppressDiagnostics();
199 // FIXME: we might have ambiguous templates, in which case we
200 // should at least parse them properly!
201 return TNK_Non_template;
204 TemplateName Template;
205 TemplateNameKind TemplateKind;
207 unsigned ResultCount = R.end() - R.begin();
208 if (ResultCount > 1) {
209 // We assume that we'll preserve the qualifier from a function
210 // template name in other ways.
211 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
212 TemplateKind = TNK_Function_template;
214 // We'll do this lookup again later.
215 R.suppressDiagnostics();
217 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
219 if (SS.isSet() && !SS.isInvalid()) {
220 NestedNameSpecifier *Qualifier = SS.getScopeRep();
221 Template = Context.getQualifiedTemplateName(Qualifier,
222 hasTemplateKeyword, TD);
224 Template = TemplateName(TD);
227 if (isa<FunctionTemplateDecl>(TD)) {
228 TemplateKind = TNK_Function_template;
230 // We'll do this lookup again later.
231 R.suppressDiagnostics();
233 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
234 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
235 isa<BuiltinTemplateDecl>(TD));
237 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
241 TemplateResult = TemplateTy::make(Template);
245 bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
246 SourceLocation NameLoc,
247 ParsedTemplateTy *Template) {
249 bool MemberOfUnknownSpecialization = false;
251 // We could use redeclaration lookup here, but we don't need to: the
252 // syntactic form of a deduction guide is enough to identify it even
253 // if we can't look up the template name at all.
254 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
255 LookupTemplateName(R, S, SS, /*ObjectType*/QualType(),
256 /*EnteringContext*/false, MemberOfUnknownSpecialization);
258 if (R.empty()) return false;
259 if (R.isAmbiguous()) {
260 // FIXME: Diagnose an ambiguity if we find at least one template.
261 R.suppressDiagnostics();
265 // We only treat template-names that name type templates as valid deduction
267 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
268 if (!TD || !getAsTypeTemplateDecl(TD))
272 *Template = TemplateTy::make(TemplateName(TD));
276 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
277 SourceLocation IILoc,
279 const CXXScopeSpec *SS,
280 TemplateTy &SuggestedTemplate,
281 TemplateNameKind &SuggestedKind) {
282 // We can't recover unless there's a dependent scope specifier preceding the
284 // FIXME: Typo correction?
285 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
286 computeDeclContext(*SS))
289 // The code is missing a 'template' keyword prior to the dependent template
291 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
292 Diag(IILoc, diag::err_template_kw_missing)
293 << Qualifier << II.getName()
294 << FixItHint::CreateInsertion(IILoc, "template ");
296 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
297 SuggestedKind = TNK_Dependent_template_name;
301 void Sema::LookupTemplateName(LookupResult &Found,
302 Scope *S, CXXScopeSpec &SS,
304 bool EnteringContext,
305 bool &MemberOfUnknownSpecialization) {
306 // Determine where to perform name lookup
307 MemberOfUnknownSpecialization = false;
308 DeclContext *LookupCtx = nullptr;
309 bool isDependent = false;
310 if (!ObjectType.isNull()) {
311 // This nested-name-specifier occurs in a member access expression, e.g.,
312 // x->B::f, and we are looking into the type of the object.
313 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
314 LookupCtx = computeDeclContext(ObjectType);
315 isDependent = ObjectType->isDependentType();
316 assert((isDependent || !ObjectType->isIncompleteType() ||
317 ObjectType->castAs<TagType>()->isBeingDefined()) &&
318 "Caller should have completed object type");
320 // Template names cannot appear inside an Objective-C class or object type.
321 if (ObjectType->isObjCObjectOrInterfaceType()) {
325 } else if (SS.isSet()) {
326 // This nested-name-specifier occurs after another nested-name-specifier,
327 // so long into the context associated with the prior nested-name-specifier.
328 LookupCtx = computeDeclContext(SS, EnteringContext);
329 isDependent = isDependentScopeSpecifier(SS);
331 // The declaration context must be complete.
332 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
336 bool ObjectTypeSearchedInScope = false;
337 bool AllowFunctionTemplatesInLookup = true;
339 // Perform "qualified" name lookup into the declaration context we
340 // computed, which is either the type of the base of a member access
341 // expression or the declaration context associated with a prior
342 // nested-name-specifier.
343 LookupQualifiedName(Found, LookupCtx);
344 if (!ObjectType.isNull() && Found.empty()) {
345 // C++ [basic.lookup.classref]p1:
346 // In a class member access expression (5.2.5), if the . or -> token is
347 // immediately followed by an identifier followed by a <, the
348 // identifier must be looked up to determine whether the < is the
349 // beginning of a template argument list (14.2) or a less-than operator.
350 // The identifier is first looked up in the class of the object
351 // expression. If the identifier is not found, it is then looked up in
352 // the context of the entire postfix-expression and shall name a class
353 // or function template.
354 if (S) LookupName(Found, S);
355 ObjectTypeSearchedInScope = true;
356 AllowFunctionTemplatesInLookup = false;
358 } else if (isDependent && (!S || ObjectType.isNull())) {
359 // We cannot look into a dependent object type or nested nme
361 MemberOfUnknownSpecialization = true;
364 // Perform unqualified name lookup in the current scope.
365 LookupName(Found, S);
367 if (!ObjectType.isNull())
368 AllowFunctionTemplatesInLookup = false;
371 if (Found.empty() && !isDependent) {
372 // If we did not find any names, attempt to correct any typos.
373 DeclarationName Name = Found.getLookupName();
375 // Simple filter callback that, for keywords, only accepts the C++ *_cast
376 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
377 FilterCCC->WantTypeSpecifiers = false;
378 FilterCCC->WantExpressionKeywords = false;
379 FilterCCC->WantRemainingKeywords = false;
380 FilterCCC->WantCXXNamedCasts = true;
381 if (TypoCorrection Corrected = CorrectTypo(
382 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
383 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
384 Found.setLookupName(Corrected.getCorrection());
385 if (auto *ND = Corrected.getFoundDecl())
387 FilterAcceptableTemplateNames(Found);
388 if (!Found.empty()) {
390 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
391 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
392 Name.getAsString() == CorrectedStr;
393 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
394 << Name << LookupCtx << DroppedSpecifier
397 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
401 Found.setLookupName(Name);
405 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
408 MemberOfUnknownSpecialization = true;
412 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
413 !getLangOpts().CPlusPlus11) {
414 // C++03 [basic.lookup.classref]p1:
415 // [...] If the lookup in the class of the object expression finds a
416 // template, the name is also looked up in the context of the entire
417 // postfix-expression and [...]
419 // Note: C++11 does not perform this second lookup.
420 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
422 LookupName(FoundOuter, S);
423 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
425 if (FoundOuter.empty()) {
426 // - if the name is not found, the name found in the class of the
427 // object expression is used, otherwise
428 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
429 FoundOuter.isAmbiguous()) {
430 // - if the name is found in the context of the entire
431 // postfix-expression and does not name a class template, the name
432 // found in the class of the object expression is used, otherwise
434 } else if (!Found.isSuppressingDiagnostics()) {
435 // - if the name found is a class template, it must refer to the same
436 // entity as the one found in the class of the object expression,
437 // otherwise the program is ill-formed.
438 if (!Found.isSingleResult() ||
439 Found.getFoundDecl()->getCanonicalDecl()
440 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
441 Diag(Found.getNameLoc(),
442 diag::ext_nested_name_member_ref_lookup_ambiguous)
443 << Found.getLookupName()
445 Diag(Found.getRepresentativeDecl()->getLocation(),
446 diag::note_ambig_member_ref_object_type)
448 Diag(FoundOuter.getFoundDecl()->getLocation(),
449 diag::note_ambig_member_ref_scope);
451 // Recover by taking the template that we found in the object
452 // expression's type.
458 void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
460 SourceLocation Greater) {
461 if (TemplateName.isInvalid())
464 DeclarationNameInfo NameInfo;
466 LookupNameKind LookupKind;
468 DeclContext *LookupCtx = nullptr;
469 NamedDecl *Found = nullptr;
471 // Figure out what name we looked up.
472 if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
473 NameInfo = ME->getMemberNameInfo();
474 SS.Adopt(ME->getQualifierLoc());
475 LookupKind = LookupMemberName;
476 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
477 Found = ME->getMemberDecl();
479 auto *DRE = cast<DeclRefExpr>(TemplateName.get());
480 NameInfo = DRE->getNameInfo();
481 SS.Adopt(DRE->getQualifierLoc());
482 LookupKind = LookupOrdinaryName;
483 Found = DRE->getFoundDecl();
486 // Try to correct the name by looking for templates and C++ named casts.
487 struct TemplateCandidateFilter : CorrectionCandidateCallback {
488 TemplateCandidateFilter() {
489 WantTypeSpecifiers = false;
490 WantExpressionKeywords = false;
491 WantRemainingKeywords = false;
492 WantCXXNamedCasts = true;
494 bool ValidateCandidate(const TypoCorrection &Candidate) override {
495 if (auto *ND = Candidate.getCorrectionDecl())
496 return isAcceptableTemplateName(ND->getASTContext(), ND, true);
497 return Candidate.isKeyword();
501 DeclarationName Name = NameInfo.getName();
502 if (TypoCorrection Corrected =
503 CorrectTypo(NameInfo, LookupKind, S, &SS,
504 llvm::make_unique<TemplateCandidateFilter>(),
505 CTK_ErrorRecovery, LookupCtx)) {
506 auto *ND = Corrected.getFoundDecl();
508 ND = isAcceptableTemplateName(Context, ND,
509 /*AllowFunctionTemplates*/ true);
510 if (ND || Corrected.isKeyword()) {
512 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
513 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
514 Name.getAsString() == CorrectedStr;
515 diagnoseTypo(Corrected,
516 PDiag(diag::err_non_template_in_member_template_id_suggest)
517 << Name << LookupCtx << DroppedSpecifier
518 << SS.getRange(), false);
520 diagnoseTypo(Corrected,
521 PDiag(diag::err_non_template_in_template_id_suggest)
525 Diag(Found->getLocation(),
526 diag::note_non_template_in_template_id_found);
531 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
532 << Name << SourceRange(Less, Greater);
534 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
537 /// ActOnDependentIdExpression - Handle a dependent id-expression that
538 /// was just parsed. This is only possible with an explicit scope
539 /// specifier naming a dependent type.
541 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
542 SourceLocation TemplateKWLoc,
543 const DeclarationNameInfo &NameInfo,
544 bool isAddressOfOperand,
545 const TemplateArgumentListInfo *TemplateArgs) {
546 DeclContext *DC = getFunctionLevelDeclContext();
548 // C++11 [expr.prim.general]p12:
549 // An id-expression that denotes a non-static data member or non-static
550 // member function of a class can only be used:
552 // - if that id-expression denotes a non-static data member and it
553 // appears in an unevaluated operand.
555 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
556 // CXXDependentScopeMemberExpr. The former can instantiate to either
557 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
558 // always a MemberExpr.
559 bool MightBeCxx11UnevalField =
560 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
562 // Check if the nested name specifier is an enum type.
564 if (NestedNameSpecifier *NNS = SS.getScopeRep())
565 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
567 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
568 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
569 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
571 // Since the 'this' expression is synthesized, we don't need to
572 // perform the double-lookup check.
573 NamedDecl *FirstQualifierInScope = nullptr;
575 return CXXDependentScopeMemberExpr::Create(
576 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
577 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
578 FirstQualifierInScope, NameInfo, TemplateArgs);
581 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
585 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
586 SourceLocation TemplateKWLoc,
587 const DeclarationNameInfo &NameInfo,
588 const TemplateArgumentListInfo *TemplateArgs) {
589 return DependentScopeDeclRefExpr::Create(
590 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
595 /// Determine whether we would be unable to instantiate this template (because
596 /// it either has no definition, or is in the process of being instantiated).
597 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
598 NamedDecl *Instantiation,
599 bool InstantiatedFromMember,
600 const NamedDecl *Pattern,
601 const NamedDecl *PatternDef,
602 TemplateSpecializationKind TSK,
603 bool Complain /*= true*/) {
604 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
605 isa<VarDecl>(Instantiation));
607 bool IsEntityBeingDefined = false;
608 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
609 IsEntityBeingDefined = TD->isBeingDefined();
611 if (PatternDef && !IsEntityBeingDefined) {
612 NamedDecl *SuggestedDef = nullptr;
613 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
614 /*OnlyNeedComplete*/false)) {
615 // If we're allowed to diagnose this and recover, do so.
616 bool Recover = Complain && !isSFINAEContext();
618 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
619 Sema::MissingImportKind::Definition, Recover);
625 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
628 llvm::Optional<unsigned> Note;
629 QualType InstantiationTy;
630 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
631 InstantiationTy = Context.getTypeDeclType(TD);
633 Diag(PointOfInstantiation,
634 diag::err_template_instantiate_within_definition)
635 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
637 // Not much point in noting the template declaration here, since
638 // we're lexically inside it.
639 Instantiation->setInvalidDecl();
640 } else if (InstantiatedFromMember) {
641 if (isa<FunctionDecl>(Instantiation)) {
642 Diag(PointOfInstantiation,
643 diag::err_explicit_instantiation_undefined_member)
644 << /*member function*/ 1 << Instantiation->getDeclName()
645 << Instantiation->getDeclContext();
646 Note = diag::note_explicit_instantiation_here;
648 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
649 Diag(PointOfInstantiation,
650 diag::err_implicit_instantiate_member_undefined)
652 Note = diag::note_member_declared_at;
655 if (isa<FunctionDecl>(Instantiation)) {
656 Diag(PointOfInstantiation,
657 diag::err_explicit_instantiation_undefined_func_template)
659 Note = diag::note_explicit_instantiation_here;
660 } else if (isa<TagDecl>(Instantiation)) {
661 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
662 << (TSK != TSK_ImplicitInstantiation)
664 Note = diag::note_template_decl_here;
666 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
667 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
668 Diag(PointOfInstantiation,
669 diag::err_explicit_instantiation_undefined_var_template)
671 Instantiation->setInvalidDecl();
673 Diag(PointOfInstantiation,
674 diag::err_explicit_instantiation_undefined_member)
675 << /*static data member*/ 2 << Instantiation->getDeclName()
676 << Instantiation->getDeclContext();
677 Note = diag::note_explicit_instantiation_here;
680 if (Note) // Diagnostics were emitted.
681 Diag(Pattern->getLocation(), Note.getValue());
683 // In general, Instantiation isn't marked invalid to get more than one
684 // error for multiple undefined instantiations. But the code that does
685 // explicit declaration -> explicit definition conversion can't handle
686 // invalid declarations, so mark as invalid in that case.
687 if (TSK == TSK_ExplicitInstantiationDeclaration)
688 Instantiation->setInvalidDecl();
692 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
693 /// that the template parameter 'PrevDecl' is being shadowed by a new
694 /// declaration at location Loc. Returns true to indicate that this is
695 /// an error, and false otherwise.
696 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
697 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
699 // Microsoft Visual C++ permits template parameters to be shadowed.
700 if (getLangOpts().MicrosoftExt)
703 // C++ [temp.local]p4:
704 // A template-parameter shall not be redeclared within its
705 // scope (including nested scopes).
706 Diag(Loc, diag::err_template_param_shadow)
707 << cast<NamedDecl>(PrevDecl)->getDeclName();
708 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
711 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
712 /// the parameter D to reference the templated declaration and return a pointer
713 /// to the template declaration. Otherwise, do nothing to D and return null.
714 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
715 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
716 D = Temp->getTemplatedDecl();
722 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
723 SourceLocation EllipsisLoc) const {
724 assert(Kind == Template &&
725 "Only template template arguments can be pack expansions here");
726 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
727 "Template template argument pack expansion without packs");
728 ParsedTemplateArgument Result(*this);
729 Result.EllipsisLoc = EllipsisLoc;
733 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
734 const ParsedTemplateArgument &Arg) {
736 switch (Arg.getKind()) {
737 case ParsedTemplateArgument::Type: {
739 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
741 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
742 return TemplateArgumentLoc(TemplateArgument(T), DI);
745 case ParsedTemplateArgument::NonType: {
746 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
747 return TemplateArgumentLoc(TemplateArgument(E), E);
750 case ParsedTemplateArgument::Template: {
751 TemplateName Template = Arg.getAsTemplate().get();
752 TemplateArgument TArg;
753 if (Arg.getEllipsisLoc().isValid())
754 TArg = TemplateArgument(Template, Optional<unsigned int>());
757 return TemplateArgumentLoc(TArg,
758 Arg.getScopeSpec().getWithLocInContext(
761 Arg.getEllipsisLoc());
765 llvm_unreachable("Unhandled parsed template argument");
768 /// \brief Translates template arguments as provided by the parser
769 /// into template arguments used by semantic analysis.
770 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
771 TemplateArgumentListInfo &TemplateArgs) {
772 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
773 TemplateArgs.addArgument(translateTemplateArgument(*this,
777 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
779 IdentifierInfo *Name) {
780 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
781 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
782 if (PrevDecl && PrevDecl->isTemplateParameter())
783 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
786 /// ActOnTypeParameter - Called when a C++ template type parameter
787 /// (e.g., "typename T") has been parsed. Typename specifies whether
788 /// the keyword "typename" was used to declare the type parameter
789 /// (otherwise, "class" was used), and KeyLoc is the location of the
790 /// "class" or "typename" keyword. ParamName is the name of the
791 /// parameter (NULL indicates an unnamed template parameter) and
792 /// ParamNameLoc is the location of the parameter name (if any).
793 /// If the type parameter has a default argument, it will be added
794 /// later via ActOnTypeParameterDefault.
795 NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
796 SourceLocation EllipsisLoc,
797 SourceLocation KeyLoc,
798 IdentifierInfo *ParamName,
799 SourceLocation ParamNameLoc,
800 unsigned Depth, unsigned Position,
801 SourceLocation EqualLoc,
802 ParsedType DefaultArg) {
803 assert(S->isTemplateParamScope() &&
804 "Template type parameter not in template parameter scope!");
806 SourceLocation Loc = ParamNameLoc;
810 bool IsParameterPack = EllipsisLoc.isValid();
811 TemplateTypeParmDecl *Param
812 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
813 KeyLoc, Loc, Depth, Position, ParamName,
814 Typename, IsParameterPack);
815 Param->setAccess(AS_public);
818 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
820 // Add the template parameter into the current scope.
822 IdResolver.AddDecl(Param);
825 // C++0x [temp.param]p9:
826 // A default template-argument may be specified for any kind of
827 // template-parameter that is not a template parameter pack.
828 if (DefaultArg && IsParameterPack) {
829 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
830 DefaultArg = nullptr;
833 // Handle the default argument, if provided.
835 TypeSourceInfo *DefaultTInfo;
836 GetTypeFromParser(DefaultArg, &DefaultTInfo);
838 assert(DefaultTInfo && "expected source information for type");
840 // Check for unexpanded parameter packs.
841 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
842 UPPC_DefaultArgument))
845 // Check the template argument itself.
846 if (CheckTemplateArgument(Param, DefaultTInfo)) {
847 Param->setInvalidDecl();
851 Param->setDefaultArgument(DefaultTInfo);
857 /// \brief Check that the type of a non-type template parameter is
860 /// \returns the (possibly-promoted) parameter type if valid;
861 /// otherwise, produces a diagnostic and returns a NULL type.
862 QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
863 SourceLocation Loc) {
864 if (TSI->getType()->isUndeducedType()) {
865 // C++1z [temp.dep.expr]p3:
866 // An id-expression is type-dependent if it contains
867 // - an identifier associated by name lookup with a non-type
868 // template-parameter declared with a type that contains a
869 // placeholder type (7.1.7.4),
870 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
873 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
876 QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
877 SourceLocation Loc) {
878 // We don't allow variably-modified types as the type of non-type template
880 if (T->isVariablyModifiedType()) {
881 Diag(Loc, diag::err_variably_modified_nontype_template_param)
886 // C++ [temp.param]p4:
888 // A non-type template-parameter shall have one of the following
889 // (optionally cv-qualified) types:
891 // -- integral or enumeration type,
892 if (T->isIntegralOrEnumerationType() ||
893 // -- pointer to object or pointer to function,
894 T->isPointerType() ||
895 // -- reference to object or reference to function,
896 T->isReferenceType() ||
897 // -- pointer to member,
898 T->isMemberPointerType() ||
899 // -- std::nullptr_t.
900 T->isNullPtrType() ||
901 // If T is a dependent type, we can't do the check now, so we
902 // assume that it is well-formed.
903 T->isDependentType() ||
904 // Allow use of auto in template parameter declarations.
905 T->isUndeducedType()) {
906 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
907 // are ignored when determining its type.
908 return T.getUnqualifiedType();
911 // C++ [temp.param]p8:
913 // A non-type template-parameter of type "array of T" or
914 // "function returning T" is adjusted to be of type "pointer to
915 // T" or "pointer to function returning T", respectively.
916 else if (T->isArrayType() || T->isFunctionType())
917 return Context.getDecayedType(T);
919 Diag(Loc, diag::err_template_nontype_parm_bad_type)
925 NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
928 SourceLocation EqualLoc,
930 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
932 // Check that we have valid decl-specifiers specified.
933 auto CheckValidDeclSpecifiers = [this, &D] {
936 // template-parameter:
\r
938 // parameter-declaration
\r
940 // ... A storage class shall not be specified in a template-parameter
943 // The typedef specifier [...] shall not be used in the decl-specifier-seq
944 // of a parameter-declaration
945 const DeclSpec &DS = D.getDeclSpec();
946 auto EmitDiag = [this](SourceLocation Loc) {
947 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
948 << FixItHint::CreateRemoval(Loc);
950 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
951 EmitDiag(DS.getStorageClassSpecLoc());
953 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
954 EmitDiag(DS.getThreadStorageClassSpecLoc());
957 // The inline specifier can be applied only to the declaration or
958 // definition of a variable or function.
960 if (DS.isInlineSpecified())
961 EmitDiag(DS.getInlineSpecLoc());
963 // [dcl.constexpr]p1:
964 // The constexpr specifier shall be applied only to the definition of a
965 // variable or variable template or the declaration of a function or
966 // function template.
968 if (DS.isConstexprSpecified())
969 EmitDiag(DS.getConstexprSpecLoc());
972 // Function-specifiers can be used only in function declarations.
974 if (DS.isVirtualSpecified())
975 EmitDiag(DS.getVirtualSpecLoc());
977 if (DS.isExplicitSpecified())
978 EmitDiag(DS.getExplicitSpecLoc());
980 if (DS.isNoreturnSpecified())
981 EmitDiag(DS.getNoreturnSpecLoc());
984 CheckValidDeclSpecifiers();
986 if (TInfo->getType()->isUndeducedType()) {
987 Diag(D.getIdentifierLoc(),
988 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
989 << QualType(TInfo->getType()->getContainedAutoType(), 0);
992 assert(S->isTemplateParamScope() &&
993 "Non-type template parameter not in template parameter scope!");
994 bool Invalid = false;
996 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
998 T = Context.IntTy; // Recover with an 'int' type.
1002 IdentifierInfo *ParamName = D.getIdentifier();
1003 bool IsParameterPack = D.hasEllipsis();
1004 NonTypeTemplateParmDecl *Param
1005 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1007 D.getIdentifierLoc(),
1008 Depth, Position, ParamName, T,
1009 IsParameterPack, TInfo);
1010 Param->setAccess(AS_public);
1013 Param->setInvalidDecl();
1016 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1019 // Add the template parameter into the current scope.
1021 IdResolver.AddDecl(Param);
1024 // C++0x [temp.param]p9:
1025 // A default template-argument may be specified for any kind of
1026 // template-parameter that is not a template parameter pack.
1027 if (Default && IsParameterPack) {
1028 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1032 // Check the well-formedness of the default template argument, if provided.
1034 // Check for unexpanded parameter packs.
1035 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1038 TemplateArgument Converted;
1039 ExprResult DefaultRes =
1040 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
1041 if (DefaultRes.isInvalid()) {
1042 Param->setInvalidDecl();
1045 Default = DefaultRes.get();
1047 Param->setDefaultArgument(Default);
1053 /// ActOnTemplateTemplateParameter - Called when a C++ template template
1054 /// parameter (e.g. T in template <template \<typename> class T> class array)
1055 /// has been parsed. S is the current scope.
1056 NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1057 SourceLocation TmpLoc,
1058 TemplateParameterList *Params,
1059 SourceLocation EllipsisLoc,
1060 IdentifierInfo *Name,
1061 SourceLocation NameLoc,
1064 SourceLocation EqualLoc,
1065 ParsedTemplateArgument Default) {
1066 assert(S->isTemplateParamScope() &&
1067 "Template template parameter not in template parameter scope!");
1069 // Construct the parameter object.
1070 bool IsParameterPack = EllipsisLoc.isValid();
1071 TemplateTemplateParmDecl *Param =
1072 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1073 NameLoc.isInvalid()? TmpLoc : NameLoc,
1074 Depth, Position, IsParameterPack,
1076 Param->setAccess(AS_public);
1078 // If the template template parameter has a name, then link the identifier
1079 // into the scope and lookup mechanisms.
1081 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1084 IdResolver.AddDecl(Param);
1087 if (Params->size() == 0) {
1088 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1089 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1090 Param->setInvalidDecl();
1093 // C++0x [temp.param]p9:
1094 // A default template-argument may be specified for any kind of
1095 // template-parameter that is not a template parameter pack.
1096 if (IsParameterPack && !Default.isInvalid()) {
1097 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1098 Default = ParsedTemplateArgument();
1101 if (!Default.isInvalid()) {
1102 // Check only that we have a template template argument. We don't want to
1103 // try to check well-formedness now, because our template template parameter
1104 // might have dependent types in its template parameters, which we wouldn't
1105 // be able to match now.
1107 // If none of the template template parameter's template arguments mention
1108 // other template parameters, we could actually perform more checking here.
1109 // However, it isn't worth doing.
1110 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1111 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1112 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1113 << DefaultArg.getSourceRange();
1117 // Check for unexpanded parameter packs.
1118 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1119 DefaultArg.getArgument().getAsTemplate(),
1120 UPPC_DefaultArgument))
1123 Param->setDefaultArgument(Context, DefaultArg);
1129 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1130 /// constrained by RequiresClause, that contains the template parameters in
1132 TemplateParameterList *
1133 Sema::ActOnTemplateParameterList(unsigned Depth,
1134 SourceLocation ExportLoc,
1135 SourceLocation TemplateLoc,
1136 SourceLocation LAngleLoc,
1137 ArrayRef<NamedDecl *> Params,
1138 SourceLocation RAngleLoc,
1139 Expr *RequiresClause) {
1140 if (ExportLoc.isValid())
1141 Diag(ExportLoc, diag::warn_template_export_unsupported);
1143 return TemplateParameterList::Create(
1144 Context, TemplateLoc, LAngleLoc,
1145 llvm::makeArrayRef(Params.data(), Params.size()),
1146 RAngleLoc, RequiresClause);
1149 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1151 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
1155 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
1156 SourceLocation KWLoc, CXXScopeSpec &SS,
1157 IdentifierInfo *Name, SourceLocation NameLoc,
1158 AttributeList *Attr,
1159 TemplateParameterList *TemplateParams,
1160 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1161 SourceLocation FriendLoc,
1162 unsigned NumOuterTemplateParamLists,
1163 TemplateParameterList** OuterTemplateParamLists,
1164 SkipBodyInfo *SkipBody) {
1165 assert(TemplateParams && TemplateParams->size() > 0 &&
1166 "No template parameters");
1167 assert(TUK != TUK_Reference && "Can only declare or define class templates");
1168 bool Invalid = false;
1170 // Check that we can declare a template here.
1171 if (CheckTemplateDeclScope(S, TemplateParams))
1174 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1175 assert(Kind != TTK_Enum && "can't build template of enumerated type");
1177 // There is no such thing as an unnamed class template.
1179 Diag(KWLoc, diag::err_template_unnamed_class);
1183 // Find any previous declaration with this name. For a friend with no
1184 // scope explicitly specified, we only look for tag declarations (per
1185 // C++11 [basic.lookup.elab]p2).
1186 DeclContext *SemanticContext;
1187 LookupResult Previous(*this, Name, NameLoc,
1188 (SS.isEmpty() && TUK == TUK_Friend)
1189 ? LookupTagName : LookupOrdinaryName,
1190 forRedeclarationInCurContext());
1191 if (SS.isNotEmpty() && !SS.isInvalid()) {
1192 SemanticContext = computeDeclContext(SS, true);
1193 if (!SemanticContext) {
1194 // FIXME: Horrible, horrible hack! We can't currently represent this
1195 // in the AST, and historically we have just ignored such friend
1196 // class templates, so don't complain here.
1197 Diag(NameLoc, TUK == TUK_Friend
1198 ? diag::warn_template_qualified_friend_ignored
1199 : diag::err_template_qualified_declarator_no_match)
1200 << SS.getScopeRep() << SS.getRange();
1201 return TUK != TUK_Friend;
1204 if (RequireCompleteDeclContext(SS, SemanticContext))
1207 // If we're adding a template to a dependent context, we may need to
1208 // rebuilding some of the types used within the template parameter list,
1209 // now that we know what the current instantiation is.
1210 if (SemanticContext->isDependentContext()) {
1211 ContextRAII SavedContext(*this, SemanticContext);
1212 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1214 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1215 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
1217 LookupQualifiedName(Previous, SemanticContext);
1219 SemanticContext = CurContext;
1221 // C++14 [class.mem]p14:
1222 // If T is the name of a class, then each of the following shall have a
1223 // name different from T:
1224 // -- every member template of class T
1225 if (TUK != TUK_Friend &&
1226 DiagnoseClassNameShadow(SemanticContext,
1227 DeclarationNameInfo(Name, NameLoc)))
1230 LookupName(Previous, S);
1233 if (Previous.isAmbiguous())
1236 NamedDecl *PrevDecl = nullptr;
1237 if (Previous.begin() != Previous.end())
1238 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1240 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1241 // Maybe we will complain about the shadowed template parameter.
1242 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1243 // Just pretend that we didn't see the previous declaration.
1247 // If there is a previous declaration with the same name, check
1248 // whether this is a valid redeclaration.
1249 ClassTemplateDecl *PrevClassTemplate =
1250 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1252 // We may have found the injected-class-name of a class template,
1253 // class template partial specialization, or class template specialization.
1254 // In these cases, grab the template that is being defined or specialized.
1255 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1256 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1257 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1259 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1260 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1262 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1263 ->getSpecializedTemplate();
1267 if (TUK == TUK_Friend) {
1268 // C++ [namespace.memdef]p3:
1269 // [...] When looking for a prior declaration of a class or a function
1270 // declared as a friend, and when the name of the friend class or
1271 // function is neither a qualified name nor a template-id, scopes outside
1272 // the innermost enclosing namespace scope are not considered.
1274 DeclContext *OutermostContext = CurContext;
1275 while (!OutermostContext->isFileContext())
1276 OutermostContext = OutermostContext->getLookupParent();
1279 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1280 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1281 SemanticContext = PrevDecl->getDeclContext();
1283 // Declarations in outer scopes don't matter. However, the outermost
1284 // context we computed is the semantic context for our new
1286 PrevDecl = PrevClassTemplate = nullptr;
1287 SemanticContext = OutermostContext;
1289 // Check that the chosen semantic context doesn't already contain a
1290 // declaration of this name as a non-tag type.
1291 Previous.clear(LookupOrdinaryName);
1292 DeclContext *LookupContext = SemanticContext;
1293 while (LookupContext->isTransparentContext())
1294 LookupContext = LookupContext->getLookupParent();
1295 LookupQualifiedName(Previous, LookupContext);
1297 if (Previous.isAmbiguous())
1300 if (Previous.begin() != Previous.end())
1301 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1304 } else if (PrevDecl &&
1305 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1307 PrevDecl = PrevClassTemplate = nullptr;
1309 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1310 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1312 !(PrevClassTemplate &&
1313 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1314 SemanticContext->getRedeclContext()))) {
1315 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1316 Diag(Shadow->getTargetDecl()->getLocation(),
1317 diag::note_using_decl_target);
1318 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1319 // Recover by ignoring the old declaration.
1320 PrevDecl = PrevClassTemplate = nullptr;
1324 // TODO Memory management; associated constraints are not always stored.
1325 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1327 if (PrevClassTemplate) {
1328 // Ensure that the template parameter lists are compatible. Skip this check
1329 // for a friend in a dependent context: the template parameter list itself
1330 // could be dependent.
1331 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1332 !TemplateParameterListsAreEqual(TemplateParams,
1333 PrevClassTemplate->getTemplateParameters(),
1338 // Check for matching associated constraints on redeclarations.
1339 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1340 const bool RedeclACMismatch = [&] {
1341 if (!(CurAC || PrevAC))
1342 return false; // Nothing to check; no mismatch.
1343 if (CurAC && PrevAC) {
1344 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1345 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1346 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1347 if (CurACInfo == PrevACInfo)
1348 return false; // All good; no mismatch.
1353 if (RedeclACMismatch) {
1354 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1355 diag::err_template_different_associated_constraints);
1356 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1357 diag::note_template_prev_declaration) << /*declaration*/0;
1361 // C++ [temp.class]p4:
1362 // In a redeclaration, partial specialization, explicit
1363 // specialization or explicit instantiation of a class template,
1364 // the class-key shall agree in kind with the original class
1365 // template declaration (7.1.5.3).
1366 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1367 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1368 TUK == TUK_Definition, KWLoc, Name)) {
1369 Diag(KWLoc, diag::err_use_with_wrong_tag)
1371 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1372 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1373 Kind = PrevRecordDecl->getTagKind();
1376 // Check for redefinition of this class template.
1377 if (TUK == TUK_Definition) {
1378 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1379 // If we have a prior definition that is not visible, treat this as
1380 // simply making that previous definition visible.
1381 NamedDecl *Hidden = nullptr;
1382 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1383 SkipBody->ShouldSkip = true;
1384 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1385 assert(Tmpl && "original definition of a class template is not a "
1387 makeMergedDefinitionVisible(Hidden);
1388 makeMergedDefinitionVisible(Tmpl);
1392 Diag(NameLoc, diag::err_redefinition) << Name;
1393 Diag(Def->getLocation(), diag::note_previous_definition);
1394 // FIXME: Would it make sense to try to "forget" the previous
1395 // definition, as part of error recovery?
1399 } else if (PrevDecl) {
1401 // A class template shall not have the same name as any other
1402 // template, class, function, object, enumeration, enumerator,
1403 // namespace, or type in the same scope (3.3), except as specified
1405 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1406 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1410 // Check the template parameter list of this declaration, possibly
1411 // merging in the template parameter list from the previous class
1412 // template declaration. Skip this check for a friend in a dependent
1413 // context, because the template parameter list might be dependent.
1414 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1415 CheckTemplateParameterList(
1417 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1419 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1420 SemanticContext->isDependentContext())
1421 ? TPC_ClassTemplateMember
1422 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1423 : TPC_ClassTemplate))
1427 // If the name of the template was qualified, we must be defining the
1428 // template out-of-line.
1429 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1430 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1431 : diag::err_member_decl_does_not_match)
1432 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1437 // If this is a templated friend in a dependent context we should not put it
1438 // on the redecl chain. In some cases, the templated friend can be the most
1439 // recent declaration tricking the template instantiator to make substitutions
1441 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1442 bool ShouldAddRedecl
1443 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1445 CXXRecordDecl *NewClass =
1446 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1447 PrevClassTemplate && ShouldAddRedecl ?
1448 PrevClassTemplate->getTemplatedDecl() : nullptr,
1449 /*DelayTypeCreation=*/true);
1450 SetNestedNameSpecifier(NewClass, SS);
1451 if (NumOuterTemplateParamLists > 0)
1452 NewClass->setTemplateParameterListsInfo(
1453 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1454 NumOuterTemplateParamLists));
1456 // Add alignment attributes if necessary; these attributes are checked when
1457 // the ASTContext lays out the structure.
1458 if (TUK == TUK_Definition) {
1459 AddAlignmentAttributesForRecord(NewClass);
1460 AddMsStructLayoutForRecord(NewClass);
1463 // Attach the associated constraints when the declaration will not be part of
1465 Expr *const ACtoAttach =
1466 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1468 ClassTemplateDecl *NewTemplate
1469 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1470 DeclarationName(Name), TemplateParams,
1471 NewClass, ACtoAttach);
1473 if (ShouldAddRedecl)
1474 NewTemplate->setPreviousDecl(PrevClassTemplate);
1476 NewClass->setDescribedClassTemplate(NewTemplate);
1478 if (ModulePrivateLoc.isValid())
1479 NewTemplate->setModulePrivate();
1481 // Build the type for the class template declaration now.
1482 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1483 T = Context.getInjectedClassNameType(NewClass, T);
1484 assert(T->isDependentType() && "Class template type is not dependent?");
1487 // If we are providing an explicit specialization of a member that is a
1488 // class template, make a note of that.
1489 if (PrevClassTemplate &&
1490 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1491 PrevClassTemplate->setMemberSpecialization();
1493 // Set the access specifier.
1494 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1495 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1497 // Set the lexical context of these templates
1498 NewClass->setLexicalDeclContext(CurContext);
1499 NewTemplate->setLexicalDeclContext(CurContext);
1501 if (TUK == TUK_Definition)
1502 NewClass->startDefinition();
1505 ProcessDeclAttributeList(S, NewClass, Attr);
1507 if (PrevClassTemplate)
1508 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1510 AddPushedVisibilityAttribute(NewClass);
1512 if (TUK != TUK_Friend) {
1513 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1515 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1516 Outer = Outer->getParent();
1517 PushOnScopeChains(NewTemplate, Outer);
1519 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1520 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1521 NewClass->setAccess(PrevClassTemplate->getAccess());
1524 NewTemplate->setObjectOfFriendDecl();
1526 // Friend templates are visible in fairly strange ways.
1527 if (!CurContext->isDependentContext()) {
1528 DeclContext *DC = SemanticContext->getRedeclContext();
1529 DC->makeDeclVisibleInContext(NewTemplate);
1530 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1531 PushOnScopeChains(NewTemplate, EnclosingScope,
1532 /* AddToContext = */ false);
1535 FriendDecl *Friend = FriendDecl::Create(
1536 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1537 Friend->setAccess(AS_public);
1538 CurContext->addDecl(Friend);
1541 if (PrevClassTemplate)
1542 CheckRedeclarationModuleOwnership(NewTemplate, PrevClassTemplate);
1545 NewTemplate->setInvalidDecl();
1546 NewClass->setInvalidDecl();
1549 ActOnDocumentableDecl(NewTemplate);
1555 /// Transform to convert portions of a constructor declaration into the
1556 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1557 struct ConvertConstructorToDeductionGuideTransform {
1558 ConvertConstructorToDeductionGuideTransform(Sema &S,
1559 ClassTemplateDecl *Template)
1560 : SemaRef(S), Template(Template) {}
1563 ClassTemplateDecl *Template;
1565 DeclContext *DC = Template->getDeclContext();
1566 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1567 DeclarationName DeductionGuideName =
1568 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1570 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1572 // Index adjustment to apply to convert depth-1 template parameters into
1573 // depth-0 template parameters.
1574 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1576 /// Transform a constructor declaration into a deduction guide.
1577 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1578 CXXConstructorDecl *CD) {
1579 SmallVector<TemplateArgument, 16> SubstArgs;
1581 LocalInstantiationScope Scope(SemaRef);
1583 // C++ [over.match.class.deduct]p1:
1584 // -- For each constructor of the class template designated by the
1585 // template-name, a function template with the following properties:
1587 // -- The template parameters are the template parameters of the class
1588 // template followed by the template parameters (including default
1589 // template arguments) of the constructor, if any.
1590 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1592 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1593 SmallVector<NamedDecl *, 16> AllParams;
1594 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1595 AllParams.insert(AllParams.begin(),
1596 TemplateParams->begin(), TemplateParams->end());
1597 SubstArgs.reserve(InnerParams->size());
1599 // Later template parameters could refer to earlier ones, so build up
1600 // a list of substituted template arguments as we go.
1601 for (NamedDecl *Param : *InnerParams) {
1602 MultiLevelTemplateArgumentList Args;
1603 Args.addOuterTemplateArguments(SubstArgs);
1604 Args.addOuterRetainedLevel();
1605 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1608 AllParams.push_back(NewParam);
1609 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1610 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1612 TemplateParams = TemplateParameterList::Create(
1613 SemaRef.Context, InnerParams->getTemplateLoc(),
1614 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1615 /*FIXME: RequiresClause*/ nullptr);
1618 // If we built a new template-parameter-list, track that we need to
1619 // substitute references to the old parameters into references to the
1621 MultiLevelTemplateArgumentList Args;
1623 Args.addOuterTemplateArguments(SubstArgs);
1624 Args.addOuterRetainedLevel();
1627 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
1628 .getAsAdjusted<FunctionProtoTypeLoc>();
1629 assert(FPTL && "no prototype for constructor declaration");
1631 // Transform the type of the function, adjusting the return type and
1632 // replacing references to the old parameters with references to the
1635 SmallVector<ParmVarDecl*, 8> Params;
1636 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1637 if (NewType.isNull())
1639 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1641 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1642 CD->getLocStart(), CD->getLocation(),
1646 /// Build a deduction guide with the specified parameter types.
1647 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1648 SourceLocation Loc = Template->getLocation();
1650 // Build the requested type.
1651 FunctionProtoType::ExtProtoInfo EPI;
1652 EPI.HasTrailingReturn = true;
1653 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1654 DeductionGuideName, EPI);
1655 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1657 FunctionProtoTypeLoc FPTL =
1658 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1660 // Build the parameters, needed during deduction / substitution.
1661 SmallVector<ParmVarDecl*, 4> Params;
1662 for (auto T : ParamTypes) {
1663 ParmVarDecl *NewParam = ParmVarDecl::Create(
1664 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1665 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1666 NewParam->setScopeInfo(0, Params.size());
1667 FPTL.setParam(Params.size(), NewParam);
1668 Params.push_back(NewParam);
1671 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1676 /// Transform a constructor template parameter into a deduction guide template
1677 /// parameter, rebuilding any internal references to earlier parameters and
1678 /// renumbering as we go.
1679 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1680 MultiLevelTemplateArgumentList &Args) {
1681 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1682 // TemplateTypeParmDecl's index cannot be changed after creation, so
1683 // substitute it directly.
1684 auto *NewTTP = TemplateTypeParmDecl::Create(
1685 SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1686 /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1687 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1688 TTP->isParameterPack());
1689 if (TTP->hasDefaultArgument()) {
1690 TypeSourceInfo *InstantiatedDefaultArg =
1691 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1692 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1693 if (InstantiatedDefaultArg)
1694 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1696 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1701 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1702 return transformTemplateParameterImpl(TTP, Args);
1704 return transformTemplateParameterImpl(
1705 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1707 template<typename TemplateParmDecl>
1709 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1710 MultiLevelTemplateArgumentList &Args) {
1711 // Ask the template instantiator to do the heavy lifting for us, then adjust
1712 // the index of the parameter once it's done.
1714 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1715 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1716 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1720 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1721 FunctionProtoTypeLoc TL,
1722 SmallVectorImpl<ParmVarDecl*> &Params,
1723 MultiLevelTemplateArgumentList &Args) {
1724 SmallVector<QualType, 4> ParamTypes;
1725 const FunctionProtoType *T = TL.getTypePtr();
1727 // -- The types of the function parameters are those of the constructor.
1728 for (auto *OldParam : TL.getParams()) {
1729 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
1732 ParamTypes.push_back(NewParam->getType());
1733 Params.push_back(NewParam);
1736 // -- The return type is the class template specialization designated by
1737 // the template-name and template arguments corresponding to the
1738 // template parameters obtained from the class template.
1740 // We use the injected-class-name type of the primary template instead.
1741 // This has the convenient property that it is different from any type that
1742 // the user can write in a deduction-guide (because they cannot enter the
1743 // context of the template), so implicit deduction guides can never collide
1744 // with explicit ones.
1745 QualType ReturnType = DeducedType;
1746 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1748 // Resolving a wording defect, we also inherit the variadicness of the
1750 FunctionProtoType::ExtProtoInfo EPI;
1751 EPI.Variadic = T->isVariadic();
1752 EPI.HasTrailingReturn = true;
1754 QualType Result = SemaRef.BuildFunctionType(
1755 ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1756 if (Result.isNull())
1759 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1760 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1761 NewTL.setLParenLoc(TL.getLParenLoc());
1762 NewTL.setRParenLoc(TL.getRParenLoc());
1763 NewTL.setExceptionSpecRange(SourceRange());
1764 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1765 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1766 NewTL.setParam(I, Params[I]);
1772 transformFunctionTypeParam(ParmVarDecl *OldParam,
1773 MultiLevelTemplateArgumentList &Args) {
1774 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
1775 TypeSourceInfo *NewDI;
1776 if (!Args.getNumLevels())
1778 else if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
1779 // Expand out the one and only element in each inner pack.
1780 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1782 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1783 OldParam->getLocation(), OldParam->getDeclName());
1784 if (!NewDI) return nullptr;
1786 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1787 PackTL.getTypePtr()->getNumExpansions());
1789 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1790 OldParam->getDeclName());
1794 // Canonicalize the type. This (for instance) replaces references to
1795 // typedef members of the current instantiations with the definitions of
1796 // those typedefs, avoiding triggering instantiation of the deduced type
1797 // during deduction.
1798 // FIXME: It would be preferable to retain type sugar and source
1799 // information here (and handle this in substitution instead).
1800 NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
1801 SemaRef.Context.getCanonicalType(NewDI->getType()),
1802 OldParam->getLocation());
1804 // Resolving a wording defect, we also inherit default arguments from the
1806 ExprResult NewDefArg;
1807 if (OldParam->hasDefaultArg()) {
1808 NewDefArg = Args.getNumLevels()
1809 ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
1810 : OldParam->getDefaultArg();
1811 if (NewDefArg.isInvalid())
1815 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1816 OldParam->getInnerLocStart(),
1817 OldParam->getLocation(),
1818 OldParam->getIdentifier(),
1821 OldParam->getStorageClass(),
1823 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1824 OldParam->getFunctionScopeIndex());
1828 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1829 bool Explicit, TypeSourceInfo *TInfo,
1830 SourceLocation LocStart, SourceLocation Loc,
1831 SourceLocation LocEnd) {
1832 DeclarationNameInfo Name(DeductionGuideName, Loc);
1833 ArrayRef<ParmVarDecl *> Params =
1834 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1836 // Build the implicit deduction guide template.
1838 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1839 Name, TInfo->getType(), TInfo, LocEnd);
1840 Guide->setImplicit();
1841 Guide->setParams(Params);
1843 for (auto *Param : Params)
1844 Param->setDeclContext(Guide);
1846 auto *GuideTemplate = FunctionTemplateDecl::Create(
1847 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1848 GuideTemplate->setImplicit();
1849 Guide->setDescribedFunctionTemplate(GuideTemplate);
1851 if (isa<CXXRecordDecl>(DC)) {
1852 Guide->setAccess(AS_public);
1853 GuideTemplate->setAccess(AS_public);
1856 DC->addDecl(GuideTemplate);
1857 return GuideTemplate;
1862 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1863 SourceLocation Loc) {
1864 DeclContext *DC = Template->getDeclContext();
1865 if (DC->isDependentContext())
1868 ConvertConstructorToDeductionGuideTransform Transform(
1869 *this, cast<ClassTemplateDecl>(Template));
1870 if (!isCompleteType(Loc, Transform.DeducedType))
1873 // Check whether we've already declared deduction guides for this template.
1874 // FIXME: Consider storing a flag on the template to indicate this.
1875 auto Existing = DC->lookup(Transform.DeductionGuideName);
1876 for (auto *D : Existing)
1877 if (D->isImplicit())
1880 // In case we were expanding a pack when we attempted to declare deduction
1881 // guides, turn off pack expansion for everything we're about to do.
1882 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1883 // Create a template instantiation record to track the "instantiation" of
1884 // constructors into deduction guides.
1885 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1886 // this substitution process actually fail?
1887 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1889 // Convert declared constructors into deduction guide templates.
1890 // FIXME: Skip constructors for which deduction must necessarily fail (those
1891 // for which some class template parameter without a default argument never
1892 // appears in a deduced context).
1893 bool AddedAny = false;
1894 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1895 D = D->getUnderlyingDecl();
1896 if (D->isInvalidDecl() || D->isImplicit())
1898 D = cast<NamedDecl>(D->getCanonicalDecl());
1900 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
1902 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
1903 // Class-scope explicit specializations (MS extension) do not result in
1904 // deduction guides.
1905 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
1908 Transform.transformConstructor(FTD, CD);
1912 // C++17 [over.match.class.deduct]
1913 // -- If C is not defined or does not declare any constructors, an
1914 // additional function template derived as above from a hypothetical
1917 Transform.buildSimpleDeductionGuide(None);
1919 // -- An additional function template derived as above from a hypothetical
1920 // constructor C(C), called the copy deduction candidate.
1921 cast<CXXDeductionGuideDecl>(
1922 cast<FunctionTemplateDecl>(
1923 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
1924 ->getTemplatedDecl())
1925 ->setIsCopyDeductionCandidate();
1928 /// \brief Diagnose the presence of a default template argument on a
1929 /// template parameter, which is ill-formed in certain contexts.
1931 /// \returns true if the default template argument should be dropped.
1932 static bool DiagnoseDefaultTemplateArgument(Sema &S,
1933 Sema::TemplateParamListContext TPC,
1934 SourceLocation ParamLoc,
1935 SourceRange DefArgRange) {
1937 case Sema::TPC_ClassTemplate:
1938 case Sema::TPC_VarTemplate:
1939 case Sema::TPC_TypeAliasTemplate:
1942 case Sema::TPC_FunctionTemplate:
1943 case Sema::TPC_FriendFunctionTemplateDefinition:
1944 // C++ [temp.param]p9:
1945 // A default template-argument shall not be specified in a
1946 // function template declaration or a function template
1948 // If a friend function template declaration specifies a default
1949 // template-argument, that declaration shall be a definition and shall be
1950 // the only declaration of the function template in the translation unit.
1951 // (C++98/03 doesn't have this wording; see DR226).
1952 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1953 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1954 : diag::ext_template_parameter_default_in_function_template)
1958 case Sema::TPC_ClassTemplateMember:
1959 // C++0x [temp.param]p9:
1960 // A default template-argument shall not be specified in the
1961 // template-parameter-lists of the definition of a member of a
1962 // class template that appears outside of the member's class.
1963 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1967 case Sema::TPC_FriendClassTemplate:
1968 case Sema::TPC_FriendFunctionTemplate:
1969 // C++ [temp.param]p9:
1970 // A default template-argument shall not be specified in a
1971 // friend template declaration.
1972 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1976 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1977 // for friend function templates if there is only a single
1978 // declaration (and it is a definition). Strange!
1981 llvm_unreachable("Invalid TemplateParamListContext!");
1984 /// \brief Check for unexpanded parameter packs within the template parameters
1985 /// of a template template parameter, recursively.
1986 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1987 TemplateTemplateParmDecl *TTP) {
1988 // A template template parameter which is a parameter pack is also a pack
1990 if (TTP->isParameterPack())
1993 TemplateParameterList *Params = TTP->getTemplateParameters();
1994 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1995 NamedDecl *P = Params->getParam(I);
1996 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1997 if (!NTTP->isParameterPack() &&
1998 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1999 NTTP->getTypeSourceInfo(),
2000 Sema::UPPC_NonTypeTemplateParameterType))
2006 if (TemplateTemplateParmDecl *InnerTTP
2007 = dyn_cast<TemplateTemplateParmDecl>(P))
2008 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2015 /// \brief Checks the validity of a template parameter list, possibly
2016 /// considering the template parameter list from a previous
2019 /// If an "old" template parameter list is provided, it must be
2020 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
2021 /// template parameter list.
2023 /// \param NewParams Template parameter list for a new template
2024 /// declaration. This template parameter list will be updated with any
2025 /// default arguments that are carried through from the previous
2026 /// template parameter list.
2028 /// \param OldParams If provided, template parameter list from a
2029 /// previous declaration of the same template. Default template
2030 /// arguments will be merged from the old template parameter list to
2031 /// the new template parameter list.
2033 /// \param TPC Describes the context in which we are checking the given
2034 /// template parameter list.
2036 /// \returns true if an error occurred, false otherwise.
2037 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2038 TemplateParameterList *OldParams,
2039 TemplateParamListContext TPC) {
2040 bool Invalid = false;
2042 // C++ [temp.param]p10:
2043 // The set of default template-arguments available for use with a
2044 // template declaration or definition is obtained by merging the
2045 // default arguments from the definition (if in scope) and all
2046 // declarations in scope in the same way default function
2047 // arguments are (8.3.6).
2048 bool SawDefaultArgument = false;
2049 SourceLocation PreviousDefaultArgLoc;
2051 // Dummy initialization to avoid warnings.
2052 TemplateParameterList::iterator OldParam = NewParams->end();
2054 OldParam = OldParams->begin();
2056 bool RemoveDefaultArguments = false;
2057 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2058 NewParamEnd = NewParams->end();
2059 NewParam != NewParamEnd; ++NewParam) {
2060 // Variables used to diagnose redundant default arguments
2061 bool RedundantDefaultArg = false;
2062 SourceLocation OldDefaultLoc;
2063 SourceLocation NewDefaultLoc;
2065 // Variable used to diagnose missing default arguments
2066 bool MissingDefaultArg = false;
2068 // Variable used to diagnose non-final parameter packs
2069 bool SawParameterPack = false;
2071 if (TemplateTypeParmDecl *NewTypeParm
2072 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2073 // Check the presence of a default argument here.
2074 if (NewTypeParm->hasDefaultArgument() &&
2075 DiagnoseDefaultTemplateArgument(*this, TPC,
2076 NewTypeParm->getLocation(),
2077 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2079 NewTypeParm->removeDefaultArgument();
2081 // Merge default arguments for template type parameters.
2082 TemplateTypeParmDecl *OldTypeParm
2083 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2084 if (NewTypeParm->isParameterPack()) {
2085 assert(!NewTypeParm->hasDefaultArgument() &&
2086 "Parameter packs can't have a default argument!");
2087 SawParameterPack = true;
2088 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2089 NewTypeParm->hasDefaultArgument()) {
2090 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2091 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2092 SawDefaultArgument = true;
2093 RedundantDefaultArg = true;
2094 PreviousDefaultArgLoc = NewDefaultLoc;
2095 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2096 // Merge the default argument from the old declaration to the
2098 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2099 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2100 } else if (NewTypeParm->hasDefaultArgument()) {
2101 SawDefaultArgument = true;
2102 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2103 } else if (SawDefaultArgument)
2104 MissingDefaultArg = true;
2105 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2106 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2107 // Check for unexpanded parameter packs.
2108 if (!NewNonTypeParm->isParameterPack() &&
2109 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2110 NewNonTypeParm->getTypeSourceInfo(),
2111 UPPC_NonTypeTemplateParameterType)) {
2116 // Check the presence of a default argument here.
2117 if (NewNonTypeParm->hasDefaultArgument() &&
2118 DiagnoseDefaultTemplateArgument(*this, TPC,
2119 NewNonTypeParm->getLocation(),
2120 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2121 NewNonTypeParm->removeDefaultArgument();
2124 // Merge default arguments for non-type template parameters
2125 NonTypeTemplateParmDecl *OldNonTypeParm
2126 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2127 if (NewNonTypeParm->isParameterPack()) {
2128 assert(!NewNonTypeParm->hasDefaultArgument() &&
2129 "Parameter packs can't have a default argument!");
2130 if (!NewNonTypeParm->isPackExpansion())
2131 SawParameterPack = true;
2132 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2133 NewNonTypeParm->hasDefaultArgument()) {
2134 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2135 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2136 SawDefaultArgument = true;
2137 RedundantDefaultArg = true;
2138 PreviousDefaultArgLoc = NewDefaultLoc;
2139 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2140 // Merge the default argument from the old declaration to the
2142 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2143 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2144 } else if (NewNonTypeParm->hasDefaultArgument()) {
2145 SawDefaultArgument = true;
2146 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2147 } else if (SawDefaultArgument)
2148 MissingDefaultArg = true;
2150 TemplateTemplateParmDecl *NewTemplateParm
2151 = cast<TemplateTemplateParmDecl>(*NewParam);
2153 // Check for unexpanded parameter packs, recursively.
2154 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2159 // Check the presence of a default argument here.
2160 if (NewTemplateParm->hasDefaultArgument() &&
2161 DiagnoseDefaultTemplateArgument(*this, TPC,
2162 NewTemplateParm->getLocation(),
2163 NewTemplateParm->getDefaultArgument().getSourceRange()))
2164 NewTemplateParm->removeDefaultArgument();
2166 // Merge default arguments for template template parameters
2167 TemplateTemplateParmDecl *OldTemplateParm
2168 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2169 if (NewTemplateParm->isParameterPack()) {
2170 assert(!NewTemplateParm->hasDefaultArgument() &&
2171 "Parameter packs can't have a default argument!");
2172 if (!NewTemplateParm->isPackExpansion())
2173 SawParameterPack = true;
2174 } else if (OldTemplateParm &&
2175 hasVisibleDefaultArgument(OldTemplateParm) &&
2176 NewTemplateParm->hasDefaultArgument()) {
2177 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2178 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2179 SawDefaultArgument = true;
2180 RedundantDefaultArg = true;
2181 PreviousDefaultArgLoc = NewDefaultLoc;
2182 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2183 // Merge the default argument from the old declaration to the
2185 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2186 PreviousDefaultArgLoc
2187 = OldTemplateParm->getDefaultArgument().getLocation();
2188 } else if (NewTemplateParm->hasDefaultArgument()) {
2189 SawDefaultArgument = true;
2190 PreviousDefaultArgLoc
2191 = NewTemplateParm->getDefaultArgument().getLocation();
2192 } else if (SawDefaultArgument)
2193 MissingDefaultArg = true;
2196 // C++11 [temp.param]p11:
2197 // If a template parameter of a primary class template or alias template
2198 // is a template parameter pack, it shall be the last template parameter.
2199 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2200 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2201 TPC == TPC_TypeAliasTemplate)) {
2202 Diag((*NewParam)->getLocation(),
2203 diag::err_template_param_pack_must_be_last_template_parameter);
2207 if (RedundantDefaultArg) {
2208 // C++ [temp.param]p12:
2209 // A template-parameter shall not be given default arguments
2210 // by two different declarations in the same scope.
2211 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2212 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2214 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2215 // C++ [temp.param]p11:
2216 // If a template-parameter of a class template has a default
2217 // template-argument, each subsequent template-parameter shall either
2218 // have a default template-argument supplied or be a template parameter
2220 Diag((*NewParam)->getLocation(),
2221 diag::err_template_param_default_arg_missing);
2222 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2224 RemoveDefaultArguments = true;
2227 // If we have an old template parameter list that we're merging
2228 // in, move on to the next parameter.
2233 // We were missing some default arguments at the end of the list, so remove
2234 // all of the default arguments.
2235 if (RemoveDefaultArguments) {
2236 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2237 NewParamEnd = NewParams->end();
2238 NewParam != NewParamEnd; ++NewParam) {
2239 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2240 TTP->removeDefaultArgument();
2241 else if (NonTypeTemplateParmDecl *NTTP
2242 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2243 NTTP->removeDefaultArgument();
2245 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2254 /// A class which looks for a use of a certain level of template
2256 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2257 typedef RecursiveASTVisitor<DependencyChecker> super;
2261 // Whether we're looking for a use of a template parameter that makes the
2262 // overall construct type-dependent / a dependent type. This is strictly
2263 // best-effort for now; we may fail to match at all for a dependent type
2264 // in some cases if this is set.
2265 bool IgnoreNonTypeDependent;
2268 SourceLocation MatchLoc;
2270 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2271 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2274 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2275 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2276 NamedDecl *ND = Params->getParam(0);
2277 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2278 Depth = PD->getDepth();
2279 } else if (NonTypeTemplateParmDecl *PD =
2280 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2281 Depth = PD->getDepth();
2283 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2287 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2288 if (ParmDepth >= Depth) {
2296 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2297 // Prune out non-type-dependent expressions if requested. This can
2298 // sometimes result in us failing to find a template parameter reference
2299 // (if a value-dependent expression creates a dependent type), but this
2300 // mode is best-effort only.
2301 if (auto *E = dyn_cast_or_null<Expr>(S))
2302 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2304 return super::TraverseStmt(S, Q);
2307 bool TraverseTypeLoc(TypeLoc TL) {
2308 if (IgnoreNonTypeDependent && !TL.isNull() &&
2309 !TL.getType()->isDependentType())
2311 return super::TraverseTypeLoc(TL);
2314 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2315 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2318 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2319 // For a best-effort search, keep looking until we find a location.
2320 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2323 bool TraverseTemplateName(TemplateName N) {
2324 if (TemplateTemplateParmDecl *PD =
2325 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2326 if (Matches(PD->getDepth()))
2328 return super::TraverseTemplateName(N);
2331 bool VisitDeclRefExpr(DeclRefExpr *E) {
2332 if (NonTypeTemplateParmDecl *PD =
2333 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2334 if (Matches(PD->getDepth(), E->getExprLoc()))
2336 return super::VisitDeclRefExpr(E);
2339 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2340 return TraverseType(T->getReplacementType());
2344 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2345 return TraverseTemplateArgument(T->getArgumentPack());
2348 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2349 return TraverseType(T->getInjectedSpecializationType());
2352 } // end anonymous namespace
2354 /// Determines whether a given type depends on the given parameter
2357 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2358 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2359 Checker.TraverseType(T);
2360 return Checker.Match;
2363 // Find the source range corresponding to the named type in the given
2364 // nested-name-specifier, if any.
2365 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2367 const CXXScopeSpec &SS) {
2368 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2369 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2370 if (const Type *CurType = NNS->getAsType()) {
2371 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2372 return NNSLoc.getTypeLoc().getSourceRange();
2376 NNSLoc = NNSLoc.getPrefix();
2379 return SourceRange();
2382 /// \brief Match the given template parameter lists to the given scope
2383 /// specifier, returning the template parameter list that applies to the
2386 /// \param DeclStartLoc the start of the declaration that has a scope
2387 /// specifier or a template parameter list.
2389 /// \param DeclLoc The location of the declaration itself.
2391 /// \param SS the scope specifier that will be matched to the given template
2392 /// parameter lists. This scope specifier precedes a qualified name that is
2395 /// \param TemplateId The template-id following the scope specifier, if there
2396 /// is one. Used to check for a missing 'template<>'.
2398 /// \param ParamLists the template parameter lists, from the outermost to the
2399 /// innermost template parameter lists.
2401 /// \param IsFriend Whether to apply the slightly different rules for
2402 /// matching template parameters to scope specifiers in friend
2405 /// \param IsMemberSpecialization will be set true if the scope specifier
2406 /// denotes a fully-specialized type, and therefore this is a declaration of
2407 /// a member specialization.
2409 /// \returns the template parameter list, if any, that corresponds to the
2410 /// name that is preceded by the scope specifier @p SS. This template
2411 /// parameter list may have template parameters (if we're declaring a
2412 /// template) or may have no template parameters (if we're declaring a
2413 /// template specialization), or may be NULL (if what we're declaring isn't
2414 /// itself a template).
2415 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2416 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2417 TemplateIdAnnotation *TemplateId,
2418 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2419 bool &IsMemberSpecialization, bool &Invalid) {
2420 IsMemberSpecialization = false;
2423 // The sequence of nested types to which we will match up the template
2424 // parameter lists. We first build this list by starting with the type named
2425 // by the nested-name-specifier and walking out until we run out of types.
2426 SmallVector<QualType, 4> NestedTypes;
2428 if (SS.getScopeRep()) {
2429 if (CXXRecordDecl *Record
2430 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2431 T = Context.getTypeDeclType(Record);
2433 T = QualType(SS.getScopeRep()->getAsType(), 0);
2436 // If we found an explicit specialization that prevents us from needing
2437 // 'template<>' headers, this will be set to the location of that
2438 // explicit specialization.
2439 SourceLocation ExplicitSpecLoc;
2441 while (!T.isNull()) {
2442 NestedTypes.push_back(T);
2444 // Retrieve the parent of a record type.
2445 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2446 // If this type is an explicit specialization, we're done.
2447 if (ClassTemplateSpecializationDecl *Spec
2448 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2449 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2450 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2451 ExplicitSpecLoc = Spec->getLocation();
2454 } else if (Record->getTemplateSpecializationKind()
2455 == TSK_ExplicitSpecialization) {
2456 ExplicitSpecLoc = Record->getLocation();
2460 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2461 T = Context.getTypeDeclType(Parent);
2467 if (const TemplateSpecializationType *TST
2468 = T->getAs<TemplateSpecializationType>()) {
2469 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2470 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2471 T = Context.getTypeDeclType(Parent);
2478 // Look one step prior in a dependent template specialization type.
2479 if (const DependentTemplateSpecializationType *DependentTST
2480 = T->getAs<DependentTemplateSpecializationType>()) {
2481 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2482 T = QualType(NNS->getAsType(), 0);
2488 // Look one step prior in a dependent name type.
2489 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2490 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2491 T = QualType(NNS->getAsType(), 0);
2497 // Retrieve the parent of an enumeration type.
2498 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2499 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2501 EnumDecl *Enum = EnumT->getDecl();
2503 // Get to the parent type.
2504 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2505 T = Context.getTypeDeclType(Parent);
2513 // Reverse the nested types list, since we want to traverse from the outermost
2514 // to the innermost while checking template-parameter-lists.
2515 std::reverse(NestedTypes.begin(), NestedTypes.end());
2517 // C++0x [temp.expl.spec]p17:
2518 // A member or a member template may be nested within many
2519 // enclosing class templates. In an explicit specialization for
2520 // such a member, the member declaration shall be preceded by a
2521 // template<> for each enclosing class template that is
2522 // explicitly specialized.
2523 bool SawNonEmptyTemplateParameterList = false;
2525 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2526 if (SawNonEmptyTemplateParameterList) {
2527 Diag(DeclLoc, diag::err_specialize_member_of_template)
2528 << !Recovery << Range;
2530 IsMemberSpecialization = false;
2537 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2538 // Check that we can have an explicit specialization here.
2539 if (CheckExplicitSpecialization(Range, true))
2542 // We don't have a template header, but we should.
2543 SourceLocation ExpectedTemplateLoc;
2544 if (!ParamLists.empty())
2545 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2547 ExpectedTemplateLoc = DeclStartLoc;
2549 Diag(DeclLoc, diag::err_template_spec_needs_header)
2551 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2555 unsigned ParamIdx = 0;
2556 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2558 T = NestedTypes[TypeIdx];
2560 // Whether we expect a 'template<>' header.
2561 bool NeedEmptyTemplateHeader = false;
2563 // Whether we expect a template header with parameters.
2564 bool NeedNonemptyTemplateHeader = false;
2566 // For a dependent type, the set of template parameters that we
2568 TemplateParameterList *ExpectedTemplateParams = nullptr;
2570 // C++0x [temp.expl.spec]p15:
2571 // A member or a member template may be nested within many enclosing
2572 // class templates. In an explicit specialization for such a member, the
2573 // member declaration shall be preceded by a template<> for each
2574 // enclosing class template that is explicitly specialized.
2575 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2576 if (ClassTemplatePartialSpecializationDecl *Partial
2577 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2578 ExpectedTemplateParams = Partial->getTemplateParameters();
2579 NeedNonemptyTemplateHeader = true;
2580 } else if (Record->isDependentType()) {
2581 if (Record->getDescribedClassTemplate()) {
2582 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2583 ->getTemplateParameters();
2584 NeedNonemptyTemplateHeader = true;
2586 } else if (ClassTemplateSpecializationDecl *Spec
2587 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2588 // C++0x [temp.expl.spec]p4:
2589 // Members of an explicitly specialized class template are defined
2590 // in the same manner as members of normal classes, and not using
2591 // the template<> syntax.
2592 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2593 NeedEmptyTemplateHeader = true;
2596 } else if (Record->getTemplateSpecializationKind()) {
2597 if (Record->getTemplateSpecializationKind()
2598 != TSK_ExplicitSpecialization &&
2599 TypeIdx == NumTypes - 1)
2600 IsMemberSpecialization = true;
2604 } else if (const TemplateSpecializationType *TST
2605 = T->getAs<TemplateSpecializationType>()) {
2606 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2607 ExpectedTemplateParams = Template->getTemplateParameters();
2608 NeedNonemptyTemplateHeader = true;
2610 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2611 // FIXME: We actually could/should check the template arguments here
2612 // against the corresponding template parameter list.
2613 NeedNonemptyTemplateHeader = false;
2616 // C++ [temp.expl.spec]p16:
2617 // In an explicit specialization declaration for a member of a class
2618 // template or a member template that ap- pears in namespace scope, the
2619 // member template and some of its enclosing class templates may remain
2620 // unspecialized, except that the declaration shall not explicitly
2621 // specialize a class member template if its en- closing class templates
2622 // are not explicitly specialized as well.
2623 if (ParamIdx < ParamLists.size()) {
2624 if (ParamLists[ParamIdx]->size() == 0) {
2625 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2629 SawNonEmptyTemplateParameterList = true;
2632 if (NeedEmptyTemplateHeader) {
2633 // If we're on the last of the types, and we need a 'template<>' header
2634 // here, then it's a member specialization.
2635 if (TypeIdx == NumTypes - 1)
2636 IsMemberSpecialization = true;
2638 if (ParamIdx < ParamLists.size()) {
2639 if (ParamLists[ParamIdx]->size() > 0) {
2640 // The header has template parameters when it shouldn't. Complain.
2641 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2642 diag::err_template_param_list_matches_nontemplate)
2644 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2645 ParamLists[ParamIdx]->getRAngleLoc())
2646 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2651 // Consume this template header.
2657 if (DiagnoseMissingExplicitSpecialization(
2658 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2664 if (NeedNonemptyTemplateHeader) {
2665 // In friend declarations we can have template-ids which don't
2666 // depend on the corresponding template parameter lists. But
2667 // assume that empty parameter lists are supposed to match this
2669 if (IsFriend && T->isDependentType()) {
2670 if (ParamIdx < ParamLists.size() &&
2671 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2672 ExpectedTemplateParams = nullptr;
2677 if (ParamIdx < ParamLists.size()) {
2678 // Check the template parameter list, if we can.
2679 if (ExpectedTemplateParams &&
2680 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2681 ExpectedTemplateParams,
2682 true, TPL_TemplateMatch))
2686 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2687 TPC_ClassTemplateMember))
2694 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2696 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2702 // If there were at least as many template-ids as there were template
2703 // parameter lists, then there are no template parameter lists remaining for
2704 // the declaration itself.
2705 if (ParamIdx >= ParamLists.size()) {
2706 if (TemplateId && !IsFriend) {
2707 // We don't have a template header for the declaration itself, but we
2709 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2710 TemplateId->RAngleLoc));
2712 // Fabricate an empty template parameter list for the invented header.
2713 return TemplateParameterList::Create(Context, SourceLocation(),
2714 SourceLocation(), None,
2715 SourceLocation(), nullptr);
2721 // If there were too many template parameter lists, complain about that now.
2722 if (ParamIdx < ParamLists.size() - 1) {
2723 bool HasAnyExplicitSpecHeader = false;
2724 bool AllExplicitSpecHeaders = true;
2725 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2726 if (ParamLists[I]->size() == 0)
2727 HasAnyExplicitSpecHeader = true;
2729 AllExplicitSpecHeaders = false;
2732 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2733 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2734 : diag::err_template_spec_extra_headers)
2735 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2736 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
2738 // If there was a specialization somewhere, such that 'template<>' is
2739 // not required, and there were any 'template<>' headers, note where the
2740 // specialization occurred.
2741 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2742 Diag(ExplicitSpecLoc,
2743 diag::note_explicit_template_spec_does_not_need_header)
2744 << NestedTypes.back();
2746 // We have a template parameter list with no corresponding scope, which
2747 // means that the resulting template declaration can't be instantiated
2748 // properly (we'll end up with dependent nodes when we shouldn't).
2749 if (!AllExplicitSpecHeaders)
2753 // C++ [temp.expl.spec]p16:
2754 // In an explicit specialization declaration for a member of a class
2755 // template or a member template that ap- pears in namespace scope, the
2756 // member template and some of its enclosing class templates may remain
2757 // unspecialized, except that the declaration shall not explicitly
2758 // specialize a class member template if its en- closing class templates
2759 // are not explicitly specialized as well.
2760 if (ParamLists.back()->size() == 0 &&
2761 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2765 // Return the last template parameter list, which corresponds to the
2766 // entity being declared.
2767 return ParamLists.back();
2770 void Sema::NoteAllFoundTemplates(TemplateName Name) {
2771 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2772 Diag(Template->getLocation(), diag::note_template_declared_here)
2773 << (isa<FunctionTemplateDecl>(Template)
2775 : isa<ClassTemplateDecl>(Template)
2777 : isa<VarTemplateDecl>(Template)
2779 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2780 << Template->getDeclName();
2784 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2785 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2788 Diag((*I)->getLocation(), diag::note_template_declared_here)
2789 << 0 << (*I)->getDeclName();
2796 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2797 const SmallVectorImpl<TemplateArgument> &Converted,
2798 SourceLocation TemplateLoc,
2799 TemplateArgumentListInfo &TemplateArgs) {
2800 ASTContext &Context = SemaRef.getASTContext();
2801 switch (BTD->getBuiltinTemplateKind()) {
2802 case BTK__make_integer_seq: {
2803 // Specializations of __make_integer_seq<S, T, N> are treated like
2804 // S<T, 0, ..., N-1>.
2806 // C++14 [inteseq.intseq]p1:
2807 // T shall be an integer type.
2808 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2809 SemaRef.Diag(TemplateArgs[1].getLocation(),
2810 diag::err_integer_sequence_integral_element_type);
2814 // C++14 [inteseq.make]p1:
2815 // If N is negative the program is ill-formed.
2816 TemplateArgument NumArgsArg = Converted[2];
2817 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2819 SemaRef.Diag(TemplateArgs[2].getLocation(),
2820 diag::err_integer_sequence_negative_length);
2824 QualType ArgTy = NumArgsArg.getIntegralType();
2825 TemplateArgumentListInfo SyntheticTemplateArgs;
2826 // The type argument gets reused as the first template argument in the
2827 // synthetic template argument list.
2828 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2829 // Expand N into 0 ... N-1.
2830 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2832 TemplateArgument TA(Context, I, ArgTy);
2833 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2834 TA, ArgTy, TemplateArgs[2].getLocation()));
2836 // The first template argument will be reused as the template decl that
2837 // our synthetic template arguments will be applied to.
2838 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2839 TemplateLoc, SyntheticTemplateArgs);
2842 case BTK__type_pack_element:
2843 // Specializations of
2844 // __type_pack_element<Index, T_1, ..., T_N>
2845 // are treated like T_Index.
2846 assert(Converted.size() == 2 &&
2847 "__type_pack_element should be given an index and a parameter pack");
2849 // If the Index is out of bounds, the program is ill-formed.
2850 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2851 llvm::APSInt Index = IndexArg.getAsIntegral();
2852 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2853 "type std::size_t, and hence be non-negative");
2854 if (Index >= Ts.pack_size()) {
2855 SemaRef.Diag(TemplateArgs[0].getLocation(),
2856 diag::err_type_pack_element_out_of_bounds);
2860 // We simply return the type at index `Index`.
2861 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2862 return Nth->getAsType();
2864 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2867 /// Determine whether this alias template is "enable_if_t".
2868 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
2869 return AliasTemplate->getName().equals("enable_if_t");
2872 /// Collect all of the separable terms in the given condition, which
2873 /// might be a conjunction.
2875 /// FIXME: The right answer is to convert the logical expression into
2876 /// disjunctive normal form, so we can find the first failed term
2877 /// within each possible clause.
2878 static void collectConjunctionTerms(Expr *Clause,
2879 SmallVectorImpl<Expr *> &Terms) {
2880 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
2881 if (BinOp->getOpcode() == BO_LAnd) {
2882 collectConjunctionTerms(BinOp->getLHS(), Terms);
2883 collectConjunctionTerms(BinOp->getRHS(), Terms);
2889 Terms.push_back(Clause);
2892 // The ranges-v3 library uses an odd pattern of a top-level "||" with
2893 // a left-hand side that is value-dependent but never true. Identify
2894 // the idiom and ignore that term.
2895 static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
2897 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
2898 if (!BinOp) return Cond;
2900 if (BinOp->getOpcode() != BO_LOr) return Cond;
2902 // With an inner '==' that has a literal on the right-hand side.
2903 Expr *LHS = BinOp->getLHS();
2904 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
2905 if (!InnerBinOp) return Cond;
2907 if (InnerBinOp->getOpcode() != BO_EQ ||
2908 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
2911 // If the inner binary operation came from a macro expansion named
2912 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
2913 // of the '||', which is the real, user-provided condition.
2914 SourceLocation Loc = InnerBinOp->getExprLoc();
2915 if (!Loc.isMacroID()) return Cond;
2917 StringRef MacroName = PP.getImmediateMacroName(Loc);
2918 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
2919 return BinOp->getRHS();
2924 std::pair<Expr *, std::string>
2925 Sema::findFailedBooleanCondition(Expr *Cond, bool AllowTopLevelCond) {
2926 Cond = lookThroughRangesV3Condition(PP, Cond);
2928 // Separate out all of the terms in a conjunction.
2929 SmallVector<Expr *, 4> Terms;
2930 collectConjunctionTerms(Cond, Terms);
2932 // Determine which term failed.
2933 Expr *FailedCond = nullptr;
2934 for (Expr *Term : Terms) {
2935 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
2937 // Literals are uninteresting.
2938 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
2939 isa<IntegerLiteral>(TermAsWritten))
2942 // The initialization of the parameter from the argument is
2943 // a constant-evaluated context.
2944 EnterExpressionEvaluationContext ConstantEvaluated(
2945 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2948 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
2950 FailedCond = TermAsWritten;
2956 if (!AllowTopLevelCond)
2957 return { nullptr, "" };
2959 FailedCond = Cond->IgnoreParenImpCasts();
2962 std::string Description;
2964 llvm::raw_string_ostream Out(Description);
2965 FailedCond->printPretty(Out, nullptr, getPrintingPolicy());
2967 return { FailedCond, Description };
2970 QualType Sema::CheckTemplateIdType(TemplateName Name,
2971 SourceLocation TemplateLoc,
2972 TemplateArgumentListInfo &TemplateArgs) {
2973 DependentTemplateName *DTN
2974 = Name.getUnderlying().getAsDependentTemplateName();
2975 if (DTN && DTN->isIdentifier())
2976 // When building a template-id where the template-name is dependent,
2977 // assume the template is a type template. Either our assumption is
2978 // correct, or the code is ill-formed and will be diagnosed when the
2979 // dependent name is substituted.
2980 return Context.getDependentTemplateSpecializationType(ETK_None,
2981 DTN->getQualifier(),
2982 DTN->getIdentifier(),
2985 TemplateDecl *Template = Name.getAsTemplateDecl();
2986 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2987 isa<VarTemplateDecl>(Template)) {
2988 // We might have a substituted template template parameter pack. If so,
2989 // build a template specialization type for it.
2990 if (Name.getAsSubstTemplateTemplateParmPack())
2991 return Context.getTemplateSpecializationType(Name, TemplateArgs);
2993 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2995 NoteAllFoundTemplates(Name);
2999 // Check that the template argument list is well-formed for this
3001 SmallVector<TemplateArgument, 4> Converted;
3002 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3008 bool InstantiationDependent = false;
3009 if (TypeAliasTemplateDecl *AliasTemplate =
3010 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3011 // Find the canonical type for this type alias template specialization.
3012 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3013 if (Pattern->isInvalidDecl())
3016 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3019 // Only substitute for the innermost template argument list.
3020 MultiLevelTemplateArgumentList TemplateArgLists;
3021 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
3022 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
3023 for (unsigned I = 0; I < Depth; ++I)
3024 TemplateArgLists.addOuterTemplateArguments(None);
3026 LocalInstantiationScope Scope(*this);
3027 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3028 if (Inst.isInvalid())
3031 CanonType = SubstType(Pattern->getUnderlyingType(),
3032 TemplateArgLists, AliasTemplate->getLocation(),
3033 AliasTemplate->getDeclName());
3034 if (CanonType.isNull()) {
3035 // If this was enable_if and we failed to find the nested type
3036 // within enable_if in a SFINAE context, dig out the specific
3037 // enable_if condition that failed and present that instead.
3038 if (isEnableIfAliasTemplate(AliasTemplate)) {
3039 if (auto DeductionInfo = isSFINAEContext()) {
3040 if (*DeductionInfo &&
3041 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3042 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3043 diag::err_typename_nested_not_found_enable_if &&
3044 TemplateArgs[0].getArgument().getKind()
3045 == TemplateArgument::Expression) {
3047 std::string FailedDescription;
3048 std::tie(FailedCond, FailedDescription) =
3049 findFailedBooleanCondition(
3050 TemplateArgs[0].getSourceExpression(),
3051 /*AllowTopLevelCond=*/true);
3053 // Remove the old SFINAE diagnostic.
3054 PartialDiagnosticAt OldDiag =
3055 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3056 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3058 // Add a new SFINAE diagnostic specifying which condition
3060 (*DeductionInfo)->addSFINAEDiagnostic(
3062 PDiag(diag::err_typename_nested_not_found_requirement)
3063 << FailedDescription
3064 << FailedCond->getSourceRange());
3071 } else if (Name.isDependent() ||
3072 TemplateSpecializationType::anyDependentTemplateArguments(
3073 TemplateArgs, InstantiationDependent)) {
3074 // This class template specialization is a dependent
3075 // type. Therefore, its canonical type is another class template
3076 // specialization type that contains all of the converted
3077 // arguments in canonical form. This ensures that, e.g., A<T> and
3078 // A<T, T> have identical types when A is declared as:
3080 // template<typename T, typename U = T> struct A;
3081 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3083 // This might work out to be a current instantiation, in which
3084 // case the canonical type needs to be the InjectedClassNameType.
3086 // TODO: in theory this could be a simple hashtable lookup; most
3087 // changes to CurContext don't change the set of current
3089 if (isa<ClassTemplateDecl>(Template)) {
3090 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3091 // If we get out to a namespace, we're done.
3092 if (Ctx->isFileContext()) break;
3094 // If this isn't a record, keep looking.
3095 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3096 if (!Record) continue;
3098 // Look for one of the two cases with InjectedClassNameTypes
3099 // and check whether it's the same template.
3100 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3101 !Record->getDescribedClassTemplate())
3104 // Fetch the injected class name type and check whether its
3105 // injected type is equal to the type we just built.
3106 QualType ICNT = Context.getTypeDeclType(Record);
3107 QualType Injected = cast<InjectedClassNameType>(ICNT)
3108 ->getInjectedSpecializationType();
3110 if (CanonType != Injected->getCanonicalTypeInternal())
3113 // If so, the canonical type of this TST is the injected
3114 // class name type of the record we just found.
3115 assert(ICNT.isCanonical());
3120 } else if (ClassTemplateDecl *ClassTemplate
3121 = dyn_cast<ClassTemplateDecl>(Template)) {
3122 // Find the class template specialization declaration that
3123 // corresponds to these arguments.
3124 void *InsertPos = nullptr;
3125 ClassTemplateSpecializationDecl *Decl
3126 = ClassTemplate->findSpecialization(Converted, InsertPos);
3128 // This is the first time we have referenced this class template
3129 // specialization. Create the canonical declaration and add it to
3130 // the set of specializations.
3131 Decl = ClassTemplateSpecializationDecl::Create(Context,
3132 ClassTemplate->getTemplatedDecl()->getTagKind(),
3133 ClassTemplate->getDeclContext(),
3134 ClassTemplate->getTemplatedDecl()->getLocStart(),
3135 ClassTemplate->getLocation(),
3137 Converted, nullptr);
3138 ClassTemplate->AddSpecialization(Decl, InsertPos);
3139 if (ClassTemplate->isOutOfLine())
3140 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3143 if (Decl->getSpecializationKind() == TSK_Undeclared) {
3144 MultiLevelTemplateArgumentList TemplateArgLists;
3145 TemplateArgLists.addOuterTemplateArguments(Converted);
3146 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
3150 // Diagnose uses of this specialization.
3151 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3153 CanonType = Context.getTypeDeclType(Decl);
3154 assert(isa<RecordType>(CanonType) &&
3155 "type of non-dependent specialization is not a RecordType");
3156 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3157 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3161 // Build the fully-sugared type for this class template
3162 // specialization, which refers back to the class template
3163 // specialization we created or found.
3164 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3168 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3169 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3170 SourceLocation TemplateIILoc,
3171 SourceLocation LAngleLoc,
3172 ASTTemplateArgsPtr TemplateArgsIn,
3173 SourceLocation RAngleLoc,
3174 bool IsCtorOrDtorName, bool IsClassName) {
3178 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3179 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3181 // C++ [temp.res]p3:
3182 // A qualified-id that refers to a type and in which the
3183 // nested-name-specifier depends on a template-parameter (14.6.2)
3184 // shall be prefixed by the keyword typename to indicate that the
3185 // qualified-id denotes a type, forming an
3186 // elaborated-type-specifier (7.1.5.3).
3187 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3188 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3189 << SS.getScopeRep() << TemplateII->getName();
3190 // Recover as if 'typename' were specified.
3191 // FIXME: This is not quite correct recovery as we don't transform SS
3192 // into the corresponding dependent form (and we don't diagnose missing
3193 // 'template' keywords within SS as a result).
3194 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3195 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3196 TemplateArgsIn, RAngleLoc);
3199 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3200 // it's not actually allowed to be used as a type in most cases. Because
3201 // we annotate it before we know whether it's valid, we have to check for
3203 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3204 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3206 TemplateKWLoc.isInvalid()
3207 ? diag::err_out_of_line_qualified_id_type_names_constructor
3208 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3209 << TemplateII << 0 /*injected-class-name used as template name*/
3210 << 1 /*if any keyword was present, it was 'template'*/;
3214 TemplateName Template = TemplateD.get();
3216 // Translate the parser's template argument list in our AST format.
3217 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3218 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3220 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3222 = Context.getDependentTemplateSpecializationType(ETK_None,
3223 DTN->getQualifier(),
3224 DTN->getIdentifier(),
3226 // Build type-source information.
3228 DependentTemplateSpecializationTypeLoc SpecTL
3229 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3230 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3231 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3232 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3233 SpecTL.setTemplateNameLoc(TemplateIILoc);
3234 SpecTL.setLAngleLoc(LAngleLoc);
3235 SpecTL.setRAngleLoc(RAngleLoc);
3236 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3237 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3238 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3241 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3242 if (Result.isNull())
3245 // Build type-source information.
3247 TemplateSpecializationTypeLoc SpecTL
3248 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3249 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3250 SpecTL.setTemplateNameLoc(TemplateIILoc);
3251 SpecTL.setLAngleLoc(LAngleLoc);
3252 SpecTL.setRAngleLoc(RAngleLoc);
3253 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3254 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3256 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3257 // constructor or destructor name (in such a case, the scope specifier
3258 // will be attached to the enclosing Decl or Expr node).
3259 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3260 // Create an elaborated-type-specifier containing the nested-name-specifier.
3261 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3262 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3263 ElabTL.setElaboratedKeywordLoc(SourceLocation());
3264 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3267 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3270 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3271 TypeSpecifierType TagSpec,
3272 SourceLocation TagLoc,
3274 SourceLocation TemplateKWLoc,
3275 TemplateTy TemplateD,
3276 SourceLocation TemplateLoc,
3277 SourceLocation LAngleLoc,
3278 ASTTemplateArgsPtr TemplateArgsIn,
3279 SourceLocation RAngleLoc) {
3280 TemplateName Template = TemplateD.get();
3282 // Translate the parser's template argument list in our AST format.
3283 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3284 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3286 // Determine the tag kind
3287 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3288 ElaboratedTypeKeyword Keyword
3289 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3291 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3292 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
3293 DTN->getQualifier(),
3294 DTN->getIdentifier(),
3297 // Build type-source information.
3299 DependentTemplateSpecializationTypeLoc SpecTL
3300 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3301 SpecTL.setElaboratedKeywordLoc(TagLoc);
3302 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3303 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3304 SpecTL.setTemplateNameLoc(TemplateLoc);
3305 SpecTL.setLAngleLoc(LAngleLoc);
3306 SpecTL.setRAngleLoc(RAngleLoc);
3307 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3308 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3309 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3312 if (TypeAliasTemplateDecl *TAT =
3313 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3314 // C++0x [dcl.type.elab]p2:
3315 // If the identifier resolves to a typedef-name or the simple-template-id
3316 // resolves to an alias template specialization, the
3317 // elaborated-type-specifier is ill-formed.
3318 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3319 << TAT << NTK_TypeAliasTemplate << TagKind;
3320 Diag(TAT->getLocation(), diag::note_declared_at);
3323 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3324 if (Result.isNull())
3325 return TypeResult(true);
3327 // Check the tag kind
3328 if (const RecordType *RT = Result->getAs<RecordType>()) {
3329 RecordDecl *D = RT->getDecl();
3331 IdentifierInfo *Id = D->getIdentifier();
3332 assert(Id && "templated class must have an identifier");
3334 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3336 Diag(TagLoc, diag::err_use_with_wrong_tag)
3338 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3339 Diag(D->getLocation(), diag::note_previous_use);
3343 // Provide source-location information for the template specialization.
3345 TemplateSpecializationTypeLoc SpecTL
3346 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3347 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3348 SpecTL.setTemplateNameLoc(TemplateLoc);
3349 SpecTL.setLAngleLoc(LAngleLoc);
3350 SpecTL.setRAngleLoc(RAngleLoc);
3351 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3352 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3354 // Construct an elaborated type containing the nested-name-specifier (if any)
3356 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3357 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3358 ElabTL.setElaboratedKeywordLoc(TagLoc);
3359 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3360 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3363 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3364 NamedDecl *PrevDecl,
3366 bool IsPartialSpecialization);
3368 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
3370 static bool isTemplateArgumentTemplateParameter(
3371 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3372 switch (Arg.getKind()) {
3373 case TemplateArgument::Null:
3374 case TemplateArgument::NullPtr:
3375 case TemplateArgument::Integral:
3376 case TemplateArgument::Declaration:
3377 case TemplateArgument::Pack:
3378 case TemplateArgument::TemplateExpansion:
3381 case TemplateArgument::Type: {
3382 QualType Type = Arg.getAsType();
3383 const TemplateTypeParmType *TPT =
3384 Arg.getAsType()->getAs<TemplateTypeParmType>();
3385 return TPT && !Type.hasQualifiers() &&
3386 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3389 case TemplateArgument::Expression: {
3390 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3391 if (!DRE || !DRE->getDecl())
3393 const NonTypeTemplateParmDecl *NTTP =
3394 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3395 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3398 case TemplateArgument::Template:
3399 const TemplateTemplateParmDecl *TTP =
3400 dyn_cast_or_null<TemplateTemplateParmDecl>(
3401 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3402 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3404 llvm_unreachable("unexpected kind of template argument");
3407 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3408 ArrayRef<TemplateArgument> Args) {
3409 if (Params->size() != Args.size())
3412 unsigned Depth = Params->getDepth();
3414 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3415 TemplateArgument Arg = Args[I];
3417 // If the parameter is a pack expansion, the argument must be a pack
3418 // whose only element is a pack expansion.
3419 if (Params->getParam(I)->isParameterPack()) {
3420 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3421 !Arg.pack_begin()->isPackExpansion())
3423 Arg = Arg.pack_begin()->getPackExpansionPattern();
3426 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3433 /// Convert the parser's template argument list representation into our form.
3434 static TemplateArgumentListInfo
3435 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3436 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3437 TemplateId.RAngleLoc);
3438 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3439 TemplateId.NumArgs);
3440 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3441 return TemplateArgs;
3444 template<typename PartialSpecDecl>
3445 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3446 if (Partial->getDeclContext()->isDependentContext())
3449 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3450 // for non-substitution-failure issues?
3451 TemplateDeductionInfo Info(Partial->getLocation());
3452 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3455 auto *Template = Partial->getSpecializedTemplate();
3456 S.Diag(Partial->getLocation(),
3457 diag::ext_partial_spec_not_more_specialized_than_primary)
3458 << isa<VarTemplateDecl>(Template);
3460 if (Info.hasSFINAEDiagnostic()) {
3461 PartialDiagnosticAt Diag = {SourceLocation(),
3462 PartialDiagnostic::NullDiagnostic()};
3463 Info.takeSFINAEDiagnostic(Diag);
3464 SmallString<128> SFINAEArgString;
3465 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3467 diag::note_partial_spec_not_more_specialized_than_primary)
3471 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3475 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3476 const llvm::SmallBitVector &DeducibleParams) {
3477 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3478 if (!DeducibleParams[I]) {
3479 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3480 if (Param->getDeclName())
3481 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3482 << Param->getDeclName();
3484 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3491 template<typename PartialSpecDecl>
3492 static void checkTemplatePartialSpecialization(Sema &S,
3493 PartialSpecDecl *Partial) {
3494 // C++1z [temp.class.spec]p8: (DR1495)
3495 // - The specialization shall be more specialized than the primary
3496 // template (14.5.5.2).
3497 checkMoreSpecializedThanPrimary(S, Partial);
3499 // C++ [temp.class.spec]p8: (DR1315)
3500 // - Each template-parameter shall appear at least once in the
3501 // template-id outside a non-deduced context.
3502 // C++1z [temp.class.spec.match]p3 (P0127R2)
3503 // If the template arguments of a partial specialization cannot be
3504 // deduced because of the structure of its template-parameter-list
3505 // and the template-id, the program is ill-formed.
3506 auto *TemplateParams = Partial->getTemplateParameters();
3507 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3508 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3509 TemplateParams->getDepth(), DeducibleParams);
3511 if (!DeducibleParams.all()) {
3512 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3513 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3514 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3515 << (NumNonDeducible > 1)
3516 << SourceRange(Partial->getLocation(),
3517 Partial->getTemplateArgsAsWritten()->RAngleLoc);
3518 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3522 void Sema::CheckTemplatePartialSpecialization(
3523 ClassTemplatePartialSpecializationDecl *Partial) {
3524 checkTemplatePartialSpecialization(*this, Partial);
3527 void Sema::CheckTemplatePartialSpecialization(
3528 VarTemplatePartialSpecializationDecl *Partial) {
3529 checkTemplatePartialSpecialization(*this, Partial);
3532 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3533 // C++1z [temp.param]p11:
3534 // A template parameter of a deduction guide template that does not have a
3535 // default-argument shall be deducible from the parameter-type-list of the
3536 // deduction guide template.
3537 auto *TemplateParams = TD->getTemplateParameters();
3538 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3539 MarkDeducedTemplateParameters(TD, DeducibleParams);
3540 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3541 // A parameter pack is deducible (to an empty pack).
3542 auto *Param = TemplateParams->getParam(I);
3543 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3544 DeducibleParams[I] = true;
3547 if (!DeducibleParams.all()) {
3548 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3549 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3550 << (NumNonDeducible > 1);
3551 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3555 DeclResult Sema::ActOnVarTemplateSpecialization(
3556 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3557 TemplateParameterList *TemplateParams, StorageClass SC,
3558 bool IsPartialSpecialization) {
3559 // D must be variable template id.
3560 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
3561 "Variable template specialization is declared with a template it.");
3563 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3564 TemplateArgumentListInfo TemplateArgs =
3565 makeTemplateArgumentListInfo(*this, *TemplateId);
3566 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3567 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3568 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3570 TemplateName Name = TemplateId->Template.get();
3572 // The template-id must name a variable template.
3573 VarTemplateDecl *VarTemplate =
3574 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3576 NamedDecl *FnTemplate;
3577 if (auto *OTS = Name.getAsOverloadedTemplate())
3578 FnTemplate = *OTS->begin();
3580 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3582 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3583 << FnTemplate->getDeclName();
3584 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3585 << IsPartialSpecialization;
3588 // Check for unexpanded parameter packs in any of the template arguments.
3589 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3590 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3591 UPPC_PartialSpecialization))
3594 // Check that the template argument list is well-formed for this
3596 SmallVector<TemplateArgument, 4> Converted;
3597 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3601 // Find the variable template (partial) specialization declaration that
3602 // corresponds to these arguments.
3603 if (IsPartialSpecialization) {
3604 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3605 TemplateArgs.size(), Converted))
3608 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3609 // also do them during instantiation.
3610 bool InstantiationDependent;
3611 if (!Name.isDependent() &&
3612 !TemplateSpecializationType::anyDependentTemplateArguments(
3613 TemplateArgs.arguments(),
3614 InstantiationDependent)) {
3615 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3616 << VarTemplate->getDeclName();
3617 IsPartialSpecialization = false;
3620 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3622 // C++ [temp.class.spec]p9b3:
3624 // -- The argument list of the specialization shall not be identical
3625 // to the implicit argument list of the primary template.
3626 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3627 << /*variable template*/ 1
3628 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3629 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3630 // FIXME: Recover from this by treating the declaration as a redeclaration
3631 // of the primary template.
3636 void *InsertPos = nullptr;
3637 VarTemplateSpecializationDecl *PrevDecl = nullptr;
3639 if (IsPartialSpecialization)
3640 // FIXME: Template parameter list matters too
3641 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
3643 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
3645 VarTemplateSpecializationDecl *Specialization = nullptr;
3647 // Check whether we can declare a variable template specialization in
3648 // the current scope.
3649 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3651 IsPartialSpecialization))
3654 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3655 // Since the only prior variable template specialization with these
3656 // arguments was referenced but not declared, reuse that
3657 // declaration node as our own, updating its source location and
3658 // the list of outer template parameters to reflect our new declaration.
3659 Specialization = PrevDecl;
3660 Specialization->setLocation(TemplateNameLoc);
3662 } else if (IsPartialSpecialization) {
3663 // Create a new class template partial specialization declaration node.
3664 VarTemplatePartialSpecializationDecl *PrevPartial =
3665 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
3666 VarTemplatePartialSpecializationDecl *Partial =
3667 VarTemplatePartialSpecializationDecl::Create(
3668 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3669 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
3670 Converted, TemplateArgs);
3673 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3674 Specialization = Partial;
3676 // If we are providing an explicit specialization of a member variable
3677 // template specialization, make a note of that.
3678 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3679 PrevPartial->setMemberSpecialization();
3681 CheckTemplatePartialSpecialization(Partial);
3683 // Create a new class template specialization declaration node for
3684 // this explicit specialization or friend declaration.
3685 Specialization = VarTemplateSpecializationDecl::Create(
3686 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
3687 VarTemplate, DI->getType(), DI, SC, Converted);
3688 Specialization->setTemplateArgsInfo(TemplateArgs);
3691 VarTemplate->AddSpecialization(Specialization, InsertPos);
3694 // C++ [temp.expl.spec]p6:
3695 // If a template, a member template or the member of a class template is
3696 // explicitly specialized then that specialization shall be declared
3697 // before the first use of that specialization that would cause an implicit
3698 // instantiation to take place, in every translation unit in which such a
3699 // use occurs; no diagnostic is required.
3700 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3702 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3703 // Is there any previous explicit specialization declaration?
3704 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3711 SourceRange Range(TemplateNameLoc, RAngleLoc);
3712 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3715 Diag(PrevDecl->getPointOfInstantiation(),
3716 diag::note_instantiation_required_here)
3717 << (PrevDecl->getTemplateSpecializationKind() !=
3718 TSK_ImplicitInstantiation);
3723 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3724 Specialization->setLexicalDeclContext(CurContext);
3726 // Add the specialization into its lexical context, so that it can
3727 // be seen when iterating through the list of declarations in that
3728 // context. However, specializations are not found by name lookup.
3729 CurContext->addDecl(Specialization);
3731 // Note that this is an explicit specialization.
3732 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3735 // Check that this isn't a redefinition of this specialization,
3736 // merging with previous declarations.
3737 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3738 forRedeclarationInCurContext());
3739 PrevSpec.addDecl(PrevDecl);
3740 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
3741 } else if (Specialization->isStaticDataMember() &&
3742 Specialization->isOutOfLine()) {
3743 Specialization->setAccess(VarTemplate->getAccess());
3746 // Link instantiations of static data members back to the template from
3747 // which they were instantiated.
3748 if (Specialization->isStaticDataMember())
3749 Specialization->setInstantiationOfStaticDataMember(
3750 VarTemplate->getTemplatedDecl(),
3751 Specialization->getSpecializationKind());
3753 return Specialization;
3757 /// \brief A partial specialization whose template arguments have matched
3758 /// a given template-id.
3759 struct PartialSpecMatchResult {
3760 VarTemplatePartialSpecializationDecl *Partial;
3761 TemplateArgumentList *Args;
3763 } // end anonymous namespace
3766 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3767 SourceLocation TemplateNameLoc,
3768 const TemplateArgumentListInfo &TemplateArgs) {
3769 assert(Template && "A variable template id without template?");
3771 // Check that the template argument list is well-formed for this template.
3772 SmallVector<TemplateArgument, 4> Converted;
3773 if (CheckTemplateArgumentList(
3774 Template, TemplateNameLoc,
3775 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
3779 // Find the variable template specialization declaration that
3780 // corresponds to these arguments.
3781 void *InsertPos = nullptr;
3782 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
3783 Converted, InsertPos)) {
3784 checkSpecializationVisibility(TemplateNameLoc, Spec);
3785 // If we already have a variable template specialization, return it.
3789 // This is the first time we have referenced this variable template
3790 // specialization. Create the canonical declaration and add it to
3791 // the set of specializations, based on the closest partial specialization
3792 // that it represents. That is,
3793 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3794 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
3796 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3797 bool AmbiguousPartialSpec = false;
3798 typedef PartialSpecMatchResult MatchResult;
3799 SmallVector<MatchResult, 4> Matched;
3800 SourceLocation PointOfInstantiation = TemplateNameLoc;
3801 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3802 /*ForTakingAddress=*/false);
3804 // 1. Attempt to find the closest partial specialization that this
3805 // specializes, if any.
3806 // If any of the template arguments is dependent, then this is probably
3807 // a placeholder for an incomplete declarative context; which must be
3808 // complete by instantiation time. Thus, do not search through the partial
3809 // specializations yet.
3810 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3811 // Perhaps better after unification of DeduceTemplateArguments() and
3812 // getMoreSpecializedPartialSpecialization().
3813 bool InstantiationDependent = false;
3814 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3815 TemplateArgs, InstantiationDependent)) {
3817 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3818 Template->getPartialSpecializations(PartialSpecs);
3820 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3821 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3822 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3824 if (TemplateDeductionResult Result =
3825 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3826 // Store the failed-deduction information for use in diagnostics, later.
3827 // TODO: Actually use the failed-deduction info?
3828 FailedCandidates.addCandidate().set(
3829 DeclAccessPair::make(Template, AS_public), Partial,
3830 MakeDeductionFailureInfo(Context, Result, Info));
3833 Matched.push_back(PartialSpecMatchResult());
3834 Matched.back().Partial = Partial;
3835 Matched.back().Args = Info.take();
3839 if (Matched.size() >= 1) {
3840 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3841 if (Matched.size() == 1) {
3842 // -- If exactly one matching specialization is found, the
3843 // instantiation is generated from that specialization.
3844 // We don't need to do anything for this.
3846 // -- If more than one matching specialization is found, the
3847 // partial order rules (14.5.4.2) are used to determine
3848 // whether one of the specializations is more specialized
3849 // than the others. If none of the specializations is more
3850 // specialized than all of the other matching
3851 // specializations, then the use of the variable template is
3852 // ambiguous and the program is ill-formed.
3853 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3854 PEnd = Matched.end();
3856 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3857 PointOfInstantiation) ==
3862 // Determine if the best partial specialization is more specialized than
3864 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3865 PEnd = Matched.end();
3867 if (P != Best && getMoreSpecializedPartialSpecialization(
3868 P->Partial, Best->Partial,
3869 PointOfInstantiation) != Best->Partial) {
3870 AmbiguousPartialSpec = true;
3876 // Instantiate using the best variable template partial specialization.
3877 InstantiationPattern = Best->Partial;
3878 InstantiationArgs = Best->Args;
3880 // -- If no match is found, the instantiation is generated
3881 // from the primary template.
3882 // InstantiationPattern = Template->getTemplatedDecl();
3886 // 2. Create the canonical declaration.
3887 // Note that we do not instantiate a definition until we see an odr-use
3888 // in DoMarkVarDeclReferenced().
3889 // FIXME: LateAttrs et al.?
3890 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3891 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3892 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3896 if (AmbiguousPartialSpec) {
3897 // Partial ordering did not produce a clear winner. Complain.
3898 Decl->setInvalidDecl();
3899 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3902 // Print the matching partial specializations.
3903 for (MatchResult P : Matched)
3904 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3905 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3910 if (VarTemplatePartialSpecializationDecl *D =
3911 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3912 Decl->setInstantiationOf(D, InstantiationArgs);
3914 checkSpecializationVisibility(TemplateNameLoc, Decl);
3916 assert(Decl && "No variable template specialization?");
3921 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3922 const DeclarationNameInfo &NameInfo,
3923 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3924 const TemplateArgumentListInfo *TemplateArgs) {
3926 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3928 if (Decl.isInvalid())
3931 VarDecl *Var = cast<VarDecl>(Decl.get());
3932 if (!Var->getTemplateSpecializationKind())
3933 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3936 // Build an ordinary singleton decl ref.
3937 return BuildDeclarationNameExpr(SS, NameInfo, Var,
3938 /*FoundD=*/nullptr, TemplateArgs);
3941 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
3942 SourceLocation TemplateKWLoc,
3945 const TemplateArgumentListInfo *TemplateArgs) {
3946 // FIXME: Can we do any checking at this point? I guess we could check the
3947 // template arguments that we have against the template name, if the template
3948 // name refers to a single template. That's not a terribly common case,
3950 // foo<int> could identify a single function unambiguously
3951 // This approach does NOT work, since f<int>(1);
3952 // gets resolved prior to resorting to overload resolution
3953 // i.e., template<class T> void f(double);
3954 // vs template<class T, class U> void f(U);
3956 // These should be filtered out by our callers.
3957 assert(!R.empty() && "empty lookup results when building templateid");
3958 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3960 // In C++1y, check variable template ids.
3961 bool InstantiationDependent;
3962 if (R.getAsSingle<VarTemplateDecl>() &&
3963 !TemplateSpecializationType::anyDependentTemplateArguments(
3964 *TemplateArgs, InstantiationDependent)) {
3965 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3966 R.getAsSingle<VarTemplateDecl>(),
3967 TemplateKWLoc, TemplateArgs);
3970 // We don't want lookup warnings at this point.
3971 R.suppressDiagnostics();
3973 UnresolvedLookupExpr *ULE
3974 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3975 SS.getWithLocInContext(Context),
3977 R.getLookupNameInfo(),
3978 RequiresADL, TemplateArgs,
3979 R.begin(), R.end());
3984 // We actually only call this from template instantiation.
3986 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
3987 SourceLocation TemplateKWLoc,
3988 const DeclarationNameInfo &NameInfo,
3989 const TemplateArgumentListInfo *TemplateArgs) {
3991 assert(TemplateArgs || TemplateKWLoc.isValid());
3993 if (!(DC = computeDeclContext(SS, false)) ||
3994 DC->isDependentContext() ||
3995 RequireCompleteDeclContext(SS, DC))
3996 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
3998 bool MemberOfUnknownSpecialization;
3999 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4000 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
4001 MemberOfUnknownSpecialization);
4003 if (R.isAmbiguous())
4007 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
4008 << NameInfo.getName() << SS.getRange();
4012 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4013 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4015 << NameInfo.getName().getAsString() << SS.getRange();
4016 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4020 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
4023 /// \brief Form a dependent template name.
4025 /// This action forms a dependent template name given the template
4026 /// name and its (presumably dependent) scope specifier. For
4027 /// example, given "MetaFun::template apply", the scope specifier \p
4028 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
4029 /// of the "template" keyword, and "apply" is the \p Name.
4030 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
4032 SourceLocation TemplateKWLoc,
4033 UnqualifiedId &Name,
4034 ParsedType ObjectType,
4035 bool EnteringContext,
4037 bool AllowInjectedClassName) {
4038 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4040 getLangOpts().CPlusPlus11 ?
4041 diag::warn_cxx98_compat_template_outside_of_template :
4042 diag::ext_template_outside_of_template)
4043 << FixItHint::CreateRemoval(TemplateKWLoc);
4045 DeclContext *LookupCtx = nullptr;
4047 LookupCtx = computeDeclContext(SS, EnteringContext);
4048 if (!LookupCtx && ObjectType)
4049 LookupCtx = computeDeclContext(ObjectType.get());
4051 // C++0x [temp.names]p5:
4052 // If a name prefixed by the keyword template is not the name of
4053 // a template, the program is ill-formed. [Note: the keyword
4054 // template may not be applied to non-template members of class
4055 // templates. -end note ] [ Note: as is the case with the
4056 // typename prefix, the template prefix is allowed in cases
4057 // where it is not strictly necessary; i.e., when the
4058 // nested-name-specifier or the expression on the left of the ->
4059 // or . is not dependent on a template-parameter, or the use
4060 // does not appear in the scope of a template. -end note]
4062 // Note: C++03 was more strict here, because it banned the use of
4063 // the "template" keyword prior to a template-name that was not a
4064 // dependent name. C++ DR468 relaxed this requirement (the
4065 // "template" keyword is now permitted). We follow the C++0x
4066 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4067 bool MemberOfUnknownSpecialization;
4068 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4069 ObjectType, EnteringContext, Result,
4070 MemberOfUnknownSpecialization);
4071 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
4072 isa<CXXRecordDecl>(LookupCtx) &&
4073 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
4074 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
4075 // This is a dependent template. Handle it below.
4076 } else if (TNK == TNK_Non_template) {
4077 Diag(Name.getLocStart(),
4078 diag::err_template_kw_refers_to_non_template)
4079 << GetNameFromUnqualifiedId(Name).getName()
4080 << Name.getSourceRange()
4082 return TNK_Non_template;
4084 // We found something; return it.
4085 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
4086 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
4087 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4088 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4089 // C++14 [class.qual]p2:
4090 // In a lookup in which function names are not ignored and the
4091 // nested-name-specifier nominates a class C, if the name specified
4092 // [...] is the injected-class-name of C, [...] the name is instead
4093 // considered to name the constructor
4095 // We don't get here if naming the constructor would be valid, so we
4096 // just reject immediately and recover by treating the
4097 // injected-class-name as naming the template.
4098 Diag(Name.getLocStart(),
4099 diag::ext_out_of_line_qualified_id_type_names_constructor)
4100 << Name.Identifier << 0 /*injected-class-name used as template name*/
4101 << 1 /*'template' keyword was used*/;
4107 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4109 switch (Name.getKind()) {
4110 case UnqualifiedIdKind::IK_Identifier:
4111 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4113 return TNK_Dependent_template_name;
4115 case UnqualifiedIdKind::IK_OperatorFunctionId:
4116 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
4117 Name.OperatorFunctionId.Operator));
4118 return TNK_Function_template;
4120 case UnqualifiedIdKind::IK_LiteralOperatorId:
4121 llvm_unreachable("literal operator id cannot have a dependent scope");
4127 Diag(Name.getLocStart(),
4128 diag::err_template_kw_refers_to_non_template)
4129 << GetNameFromUnqualifiedId(Name).getName()
4130 << Name.getSourceRange()
4132 return TNK_Non_template;
4135 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
4136 TemplateArgumentLoc &AL,
4137 SmallVectorImpl<TemplateArgument> &Converted) {
4138 const TemplateArgument &Arg = AL.getArgument();
4140 TypeSourceInfo *TSI = nullptr;
4142 // Check template type parameter.
4143 switch(Arg.getKind()) {
4144 case TemplateArgument::Type:
4145 // C++ [temp.arg.type]p1:
4146 // A template-argument for a template-parameter which is a
4147 // type shall be a type-id.
4148 ArgType = Arg.getAsType();
4149 TSI = AL.getTypeSourceInfo();
4151 case TemplateArgument::Template: {
4152 // We have a template type parameter but the template argument
4153 // is a template without any arguments.
4154 SourceRange SR = AL.getSourceRange();
4155 TemplateName Name = Arg.getAsTemplate();
4156 Diag(SR.getBegin(), diag::err_template_missing_args)
4157 << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
4158 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
4159 Diag(Decl->getLocation(), diag::note_template_decl_here);
4163 case TemplateArgument::Expression: {
4164 // We have a template type parameter but the template argument is an
4165 // expression; see if maybe it is missing the "typename" keyword.
4167 DeclarationNameInfo NameInfo;
4169 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
4170 SS.Adopt(ArgExpr->getQualifierLoc());
4171 NameInfo = ArgExpr->getNameInfo();
4172 } else if (DependentScopeDeclRefExpr *ArgExpr =
4173 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
4174 SS.Adopt(ArgExpr->getQualifierLoc());
4175 NameInfo = ArgExpr->getNameInfo();
4176 } else if (CXXDependentScopeMemberExpr *ArgExpr =
4177 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
4178 if (ArgExpr->isImplicitAccess()) {
4179 SS.Adopt(ArgExpr->getQualifierLoc());
4180 NameInfo = ArgExpr->getMemberNameInfo();
4184 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
4185 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
4186 LookupParsedName(Result, CurScope, &SS);
4188 if (Result.getAsSingle<TypeDecl>() ||
4189 Result.getResultKind() ==
4190 LookupResult::NotFoundInCurrentInstantiation) {
4191 // Suggest that the user add 'typename' before the NNS.
4192 SourceLocation Loc = AL.getSourceRange().getBegin();
4193 Diag(Loc, getLangOpts().MSVCCompat
4194 ? diag::ext_ms_template_type_arg_missing_typename
4195 : diag::err_template_arg_must_be_type_suggest)
4196 << FixItHint::CreateInsertion(Loc, "typename ");
4197 Diag(Param->getLocation(), diag::note_template_param_here);
4199 // Recover by synthesizing a type using the location information that we
4202 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4204 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4205 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4206 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4207 TL.setNameLoc(NameInfo.getLoc());
4208 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4210 // Overwrite our input TemplateArgumentLoc so that we can recover
4212 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4213 TemplateArgumentLocInfo(TSI));
4222 // We have a template type parameter but the template argument
4224 SourceRange SR = AL.getSourceRange();
4225 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4226 Diag(Param->getLocation(), diag::note_template_param_here);
4232 if (CheckTemplateArgument(Param, TSI))
4235 // Add the converted template type argument.
4236 ArgType = Context.getCanonicalType(ArgType);
4239 // If an explicitly-specified template argument type is a lifetime type
4240 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4241 if (getLangOpts().ObjCAutoRefCount &&
4242 ArgType->isObjCLifetimeType() &&
4243 !ArgType.getObjCLifetime()) {
4245 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4246 ArgType = Context.getQualifiedType(ArgType, Qs);
4249 Converted.push_back(TemplateArgument(ArgType));
4253 /// \brief Substitute template arguments into the default template argument for
4254 /// the given template type parameter.
4256 /// \param SemaRef the semantic analysis object for which we are performing
4257 /// the substitution.
4259 /// \param Template the template that we are synthesizing template arguments
4262 /// \param TemplateLoc the location of the template name that started the
4263 /// template-id we are checking.
4265 /// \param RAngleLoc the location of the right angle bracket ('>') that
4266 /// terminates the template-id.
4268 /// \param Param the template template parameter whose default we are
4269 /// substituting into.
4271 /// \param Converted the list of template arguments provided for template
4272 /// parameters that precede \p Param in the template parameter list.
4273 /// \returns the substituted template argument, or NULL if an error occurred.
4274 static TypeSourceInfo *
4275 SubstDefaultTemplateArgument(Sema &SemaRef,
4276 TemplateDecl *Template,
4277 SourceLocation TemplateLoc,
4278 SourceLocation RAngleLoc,
4279 TemplateTypeParmDecl *Param,
4280 SmallVectorImpl<TemplateArgument> &Converted) {
4281 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4283 // If the argument type is dependent, instantiate it now based
4284 // on the previously-computed template arguments.
4285 if (ArgType->getType()->isDependentType()) {
4286 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4287 Param, Template, Converted,
4288 SourceRange(TemplateLoc, RAngleLoc));
4289 if (Inst.isInvalid())
4292 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4294 // Only substitute for the innermost template argument list.
4295 MultiLevelTemplateArgumentList TemplateArgLists;
4296 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4297 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4298 TemplateArgLists.addOuterTemplateArguments(None);
4300 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4302 SemaRef.SubstType(ArgType, TemplateArgLists,
4303 Param->getDefaultArgumentLoc(), Param->getDeclName());
4309 /// \brief Substitute template arguments into the default template argument for
4310 /// the given non-type template parameter.
4312 /// \param SemaRef the semantic analysis object for which we are performing
4313 /// the substitution.
4315 /// \param Template the template that we are synthesizing template arguments
4318 /// \param TemplateLoc the location of the template name that started the
4319 /// template-id we are checking.
4321 /// \param RAngleLoc the location of the right angle bracket ('>') that
4322 /// terminates the template-id.
4324 /// \param Param the non-type template parameter whose default we are
4325 /// substituting into.
4327 /// \param Converted the list of template arguments provided for template
4328 /// parameters that precede \p Param in the template parameter list.
4330 /// \returns the substituted template argument, or NULL if an error occurred.
4332 SubstDefaultTemplateArgument(Sema &SemaRef,
4333 TemplateDecl *Template,
4334 SourceLocation TemplateLoc,
4335 SourceLocation RAngleLoc,
4336 NonTypeTemplateParmDecl *Param,
4337 SmallVectorImpl<TemplateArgument> &Converted) {
4338 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4339 Param, Template, Converted,
4340 SourceRange(TemplateLoc, RAngleLoc));
4341 if (Inst.isInvalid())
4344 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4346 // Only substitute for the innermost template argument list.
4347 MultiLevelTemplateArgumentList TemplateArgLists;
4348 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4349 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4350 TemplateArgLists.addOuterTemplateArguments(None);
4352 EnterExpressionEvaluationContext ConstantEvaluated(
4353 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4354 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4357 /// \brief Substitute template arguments into the default template argument for
4358 /// the given template template parameter.
4360 /// \param SemaRef the semantic analysis object for which we are performing
4361 /// the substitution.
4363 /// \param Template the template that we are synthesizing template arguments
4366 /// \param TemplateLoc the location of the template name that started the
4367 /// template-id we are checking.
4369 /// \param RAngleLoc the location of the right angle bracket ('>') that
4370 /// terminates the template-id.
4372 /// \param Param the template template parameter whose default we are
4373 /// substituting into.
4375 /// \param Converted the list of template arguments provided for template
4376 /// parameters that precede \p Param in the template parameter list.
4378 /// \param QualifierLoc Will be set to the nested-name-specifier (with
4379 /// source-location information) that precedes the template name.
4381 /// \returns the substituted template argument, or NULL if an error occurred.
4383 SubstDefaultTemplateArgument(Sema &SemaRef,
4384 TemplateDecl *Template,
4385 SourceLocation TemplateLoc,
4386 SourceLocation RAngleLoc,
4387 TemplateTemplateParmDecl *Param,
4388 SmallVectorImpl<TemplateArgument> &Converted,
4389 NestedNameSpecifierLoc &QualifierLoc) {
4390 Sema::InstantiatingTemplate Inst(
4391 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4392 SourceRange(TemplateLoc, RAngleLoc));
4393 if (Inst.isInvalid())
4394 return TemplateName();
4396 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4398 // Only substitute for the innermost template argument list.
4399 MultiLevelTemplateArgumentList TemplateArgLists;
4400 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4401 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4402 TemplateArgLists.addOuterTemplateArguments(None);
4404 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4405 // Substitute into the nested-name-specifier first,
4406 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4409 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4411 return TemplateName();
4414 return SemaRef.SubstTemplateName(
4416 Param->getDefaultArgument().getArgument().getAsTemplate(),
4417 Param->getDefaultArgument().getTemplateNameLoc(),
4421 /// \brief If the given template parameter has a default template
4422 /// argument, substitute into that default template argument and
4423 /// return the corresponding template argument.
4425 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4426 SourceLocation TemplateLoc,
4427 SourceLocation RAngleLoc,
4429 SmallVectorImpl<TemplateArgument>
4431 bool &HasDefaultArg) {
4432 HasDefaultArg = false;
4434 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4435 if (!hasVisibleDefaultArgument(TypeParm))
4436 return TemplateArgumentLoc();
4438 HasDefaultArg = true;
4439 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4445 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4447 return TemplateArgumentLoc();
4450 if (NonTypeTemplateParmDecl *NonTypeParm
4451 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4452 if (!hasVisibleDefaultArgument(NonTypeParm))
4453 return TemplateArgumentLoc();
4455 HasDefaultArg = true;
4456 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4461 if (Arg.isInvalid())
4462 return TemplateArgumentLoc();
4464 Expr *ArgE = Arg.getAs<Expr>();
4465 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4468 TemplateTemplateParmDecl *TempTempParm
4469 = cast<TemplateTemplateParmDecl>(Param);
4470 if (!hasVisibleDefaultArgument(TempTempParm))
4471 return TemplateArgumentLoc();
4473 HasDefaultArg = true;
4474 NestedNameSpecifierLoc QualifierLoc;
4475 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4482 return TemplateArgumentLoc();
4484 return TemplateArgumentLoc(TemplateArgument(TName),
4485 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4486 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4489 /// Convert a template-argument that we parsed as a type into a template, if
4490 /// possible. C++ permits injected-class-names to perform dual service as
4491 /// template template arguments and as template type arguments.
4492 static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4493 // Extract and step over any surrounding nested-name-specifier.
4494 NestedNameSpecifierLoc QualLoc;
4495 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4496 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4497 return TemplateArgumentLoc();
4499 QualLoc = ETLoc.getQualifierLoc();
4500 TLoc = ETLoc.getNamedTypeLoc();
4503 // If this type was written as an injected-class-name, it can be used as a
4504 // template template argument.
4505 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4506 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4507 QualLoc, InjLoc.getNameLoc());
4509 // If this type was written as an injected-class-name, it may have been
4510 // converted to a RecordType during instantiation. If the RecordType is
4511 // *not* wrapped in a TemplateSpecializationType and denotes a class
4512 // template specialization, it must have come from an injected-class-name.
4513 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4515 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4516 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4517 QualLoc, RecLoc.getNameLoc());
4519 return TemplateArgumentLoc();
4522 /// \brief Check that the given template argument corresponds to the given
4523 /// template parameter.
4525 /// \param Param The template parameter against which the argument will be
4528 /// \param Arg The template argument, which may be updated due to conversions.
4530 /// \param Template The template in which the template argument resides.
4532 /// \param TemplateLoc The location of the template name for the template
4533 /// whose argument list we're matching.
4535 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
4536 /// the template argument list.
4538 /// \param ArgumentPackIndex The index into the argument pack where this
4539 /// argument will be placed. Only valid if the parameter is a parameter pack.
4541 /// \param Converted The checked, converted argument will be added to the
4542 /// end of this small vector.
4544 /// \param CTAK Describes how we arrived at this particular template argument:
4545 /// explicitly written, deduced, etc.
4547 /// \returns true on error, false otherwise.
4548 bool Sema::CheckTemplateArgument(NamedDecl *Param,
4549 TemplateArgumentLoc &Arg,
4550 NamedDecl *Template,
4551 SourceLocation TemplateLoc,
4552 SourceLocation RAngleLoc,
4553 unsigned ArgumentPackIndex,
4554 SmallVectorImpl<TemplateArgument> &Converted,
4555 CheckTemplateArgumentKind CTAK) {
4556 // Check template type parameters.
4557 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4558 return CheckTemplateTypeArgument(TTP, Arg, Converted);
4560 // Check non-type template parameters.
4561 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4562 // Do substitution on the type of the non-type template parameter
4563 // with the template arguments we've seen thus far. But if the
4564 // template has a dependent context then we cannot substitute yet.
4565 QualType NTTPType = NTTP->getType();
4566 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4567 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
4569 if (NTTPType->isDependentType() &&
4570 !isa<TemplateTemplateParmDecl>(Template) &&
4571 !Template->getDeclContext()->isDependentContext()) {
4572 // Do substitution on the type of the non-type template parameter.
4573 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4575 SourceRange(TemplateLoc, RAngleLoc));
4576 if (Inst.isInvalid())
4579 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
4581 NTTPType = SubstType(NTTPType,
4582 MultiLevelTemplateArgumentList(TemplateArgs),
4583 NTTP->getLocation(),
4584 NTTP->getDeclName());
4585 // If that worked, check the non-type template parameter type
4587 if (!NTTPType.isNull())
4588 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4589 NTTP->getLocation());
4590 if (NTTPType.isNull())
4594 switch (Arg.getArgument().getKind()) {
4595 case TemplateArgument::Null:
4596 llvm_unreachable("Should never see a NULL template argument here");
4598 case TemplateArgument::Expression: {
4599 TemplateArgument Result;
4601 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4603 if (Res.isInvalid())
4606 // If the resulting expression is new, then use it in place of the
4607 // old expression in the template argument.
4608 if (Res.get() != Arg.getArgument().getAsExpr()) {
4609 TemplateArgument TA(Res.get());
4610 Arg = TemplateArgumentLoc(TA, Res.get());
4613 Converted.push_back(Result);
4617 case TemplateArgument::Declaration:
4618 case TemplateArgument::Integral:
4619 case TemplateArgument::NullPtr:
4620 // We've already checked this template argument, so just copy
4621 // it to the list of converted arguments.
4622 Converted.push_back(Arg.getArgument());
4625 case TemplateArgument::Template:
4626 case TemplateArgument::TemplateExpansion:
4627 // We were given a template template argument. It may not be ill-formed;
4629 if (DependentTemplateName *DTN
4630 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4631 .getAsDependentTemplateName()) {
4632 // We have a template argument such as \c T::template X, which we
4633 // parsed as a template template argument. However, since we now
4634 // know that we need a non-type template argument, convert this
4635 // template name into an expression.
4637 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4638 Arg.getTemplateNameLoc());
4641 SS.Adopt(Arg.getTemplateQualifierLoc());
4642 // FIXME: the template-template arg was a DependentTemplateName,
4643 // so it was provided with a template keyword. However, its source
4644 // location is not stored in the template argument structure.
4645 SourceLocation TemplateKWLoc;
4646 ExprResult E = DependentScopeDeclRefExpr::Create(
4647 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4650 // If we parsed the template argument as a pack expansion, create a
4651 // pack expansion expression.
4652 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
4653 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
4658 TemplateArgument Result;
4659 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
4663 Converted.push_back(Result);
4667 // We have a template argument that actually does refer to a class
4668 // template, alias template, or template template parameter, and
4669 // therefore cannot be a non-type template argument.
4670 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4671 << Arg.getSourceRange();
4673 Diag(Param->getLocation(), diag::note_template_param_here);
4676 case TemplateArgument::Type: {
4677 // We have a non-type template parameter but the template
4678 // argument is a type.
4680 // C++ [temp.arg]p2:
4681 // In a template-argument, an ambiguity between a type-id and
4682 // an expression is resolved to a type-id, regardless of the
4683 // form of the corresponding template-parameter.
4685 // We warn specifically about this case, since it can be rather
4686 // confusing for users.
4687 QualType T = Arg.getArgument().getAsType();
4688 SourceRange SR = Arg.getSourceRange();
4689 if (T->isFunctionType())
4690 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4692 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4693 Diag(Param->getLocation(), diag::note_template_param_here);
4697 case TemplateArgument::Pack:
4698 llvm_unreachable("Caller must expand template argument packs");
4705 // Check template template parameters.
4706 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
4708 // Substitute into the template parameter list of the template
4709 // template parameter, since previously-supplied template arguments
4710 // may appear within the template template parameter.
4712 // Set up a template instantiation context.
4713 LocalInstantiationScope Scope(*this);
4714 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4715 TempParm, Converted,
4716 SourceRange(TemplateLoc, RAngleLoc));
4717 if (Inst.isInvalid())
4720 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4721 TempParm = cast_or_null<TemplateTemplateParmDecl>(
4722 SubstDecl(TempParm, CurContext,
4723 MultiLevelTemplateArgumentList(TemplateArgs)));
4728 // C++1z [temp.local]p1: (DR1004)
4729 // When [the injected-class-name] is used [...] as a template-argument for
4730 // a template template-parameter [...] it refers to the class template
4732 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4733 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4734 Arg.getTypeSourceInfo()->getTypeLoc());
4735 if (!ConvertedArg.getArgument().isNull())
4739 switch (Arg.getArgument().getKind()) {
4740 case TemplateArgument::Null:
4741 llvm_unreachable("Should never see a NULL template argument here");
4743 case TemplateArgument::Template:
4744 case TemplateArgument::TemplateExpansion:
4745 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
4748 Converted.push_back(Arg.getArgument());
4751 case TemplateArgument::Expression:
4752 case TemplateArgument::Type:
4753 // We have a template template parameter but the template
4754 // argument does not refer to a template.
4755 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
4756 << getLangOpts().CPlusPlus11;
4759 case TemplateArgument::Declaration:
4760 llvm_unreachable("Declaration argument with template template parameter");
4761 case TemplateArgument::Integral:
4762 llvm_unreachable("Integral argument with template template parameter");
4763 case TemplateArgument::NullPtr:
4764 llvm_unreachable("Null pointer argument with template template parameter");
4766 case TemplateArgument::Pack:
4767 llvm_unreachable("Caller must expand template argument packs");
4773 /// \brief Diagnose an arity mismatch in the
4774 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4775 SourceLocation TemplateLoc,
4776 TemplateArgumentListInfo &TemplateArgs) {
4777 TemplateParameterList *Params = Template->getTemplateParameters();
4778 unsigned NumParams = Params->size();
4779 unsigned NumArgs = TemplateArgs.size();
4782 if (NumArgs > NumParams)
4783 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
4784 TemplateArgs.getRAngleLoc());
4785 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4786 << (NumArgs > NumParams)
4787 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
4788 << Template << Range;
4789 S.Diag(Template->getLocation(), diag::note_template_decl_here)
4790 << Params->getSourceRange();
4794 /// \brief Check whether the template parameter is a pack expansion, and if so,
4795 /// determine the number of parameters produced by that expansion. For instance:
4798 /// template<typename ...Ts> struct A {
4799 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4803 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4804 /// is not a pack expansion, so returns an empty Optional.
4805 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
4806 if (NonTypeTemplateParmDecl *NTTP
4807 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4808 if (NTTP->isExpandedParameterPack())
4809 return NTTP->getNumExpansionTypes();
4812 if (TemplateTemplateParmDecl *TTP
4813 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4814 if (TTP->isExpandedParameterPack())
4815 return TTP->getNumExpansionTemplateParameters();
4821 /// Diagnose a missing template argument.
4822 template<typename TemplateParmDecl>
4823 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4825 const TemplateParmDecl *D,
4826 TemplateArgumentListInfo &Args) {
4827 // Dig out the most recent declaration of the template parameter; there may be
4828 // declarations of the template that are more recent than TD.
4829 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4830 ->getTemplateParameters()
4831 ->getParam(D->getIndex()));
4833 // If there's a default argument that's not visible, diagnose that we're
4834 // missing a module import.
4835 llvm::SmallVector<Module*, 8> Modules;
4836 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4837 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4838 D->getDefaultArgumentLoc(), Modules,
4839 Sema::MissingImportKind::DefaultArgument,
4844 // FIXME: If there's a more recent default argument that *is* visible,
4845 // diagnose that it was declared too late.
4847 return diagnoseArityMismatch(S, TD, Loc, Args);
4850 /// \brief Check that the given template argument list is well-formed
4851 /// for specializing the given template.
4852 bool Sema::CheckTemplateArgumentList(
4853 TemplateDecl *Template, SourceLocation TemplateLoc,
4854 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4855 SmallVectorImpl<TemplateArgument> &Converted,
4856 bool UpdateArgsWithConversions) {
4857 // Make a copy of the template arguments for processing. Only make the
4858 // changes at the end when successful in matching the arguments to the
4860 TemplateArgumentListInfo NewArgs = TemplateArgs;
4862 // Make sure we get the template parameter list from the most
4863 // recentdeclaration, since that is the only one that has is guaranteed to
4864 // have all the default template argument information.
4865 TemplateParameterList *Params =
4866 cast<TemplateDecl>(Template->getMostRecentDecl())
4867 ->getTemplateParameters();
4869 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
4871 // C++ [temp.arg]p1:
4872 // [...] The type and form of each template-argument specified in
4873 // a template-id shall match the type and form specified for the
4874 // corresponding parameter declared by the template in its
4875 // template-parameter-list.
4876 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
4877 SmallVector<TemplateArgument, 2> ArgumentPack;
4878 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
4879 LocalInstantiationScope InstScope(*this, true);
4880 for (TemplateParameterList::iterator Param = Params->begin(),
4881 ParamEnd = Params->end();
4882 Param != ParamEnd; /* increment in loop */) {
4883 // If we have an expanded parameter pack, make sure we don't have too
4885 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
4886 if (*Expansions == ArgumentPack.size()) {
4887 // We're done with this parameter pack. Pack up its arguments and add
4888 // them to the list.
4889 Converted.push_back(
4890 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4891 ArgumentPack.clear();
4893 // This argument is assigned to the next parameter.
4896 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4897 // Not enough arguments for this parameter pack.
4898 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4900 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
4902 Diag(Template->getLocation(), diag::note_template_decl_here)
4903 << Params->getSourceRange();
4908 if (ArgIdx < NumArgs) {
4909 // Check the template argument we were given.
4910 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
4911 TemplateLoc, RAngleLoc,
4912 ArgumentPack.size(), Converted))
4915 bool PackExpansionIntoNonPack =
4916 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
4917 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4918 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
4919 // Core issue 1430: we have a pack expansion as an argument to an
4920 // alias template, and it's not part of a parameter pack. This
4921 // can't be canonicalized, so reject it now.
4922 Diag(NewArgs[ArgIdx].getLocation(),
4923 diag::err_alias_template_expansion_into_fixed_list)
4924 << NewArgs[ArgIdx].getSourceRange();
4925 Diag((*Param)->getLocation(), diag::note_template_param_here);
4929 // We're now done with this argument.
4932 if ((*Param)->isTemplateParameterPack()) {
4933 // The template parameter was a template parameter pack, so take the
4934 // deduced argument and place it on the argument pack. Note that we
4935 // stay on the same template parameter so that we can deduce more
4937 ArgumentPack.push_back(Converted.pop_back_val());
4939 // Move to the next template parameter.
4943 // If we just saw a pack expansion into a non-pack, then directly convert
4944 // the remaining arguments, because we don't know what parameters they'll
4946 if (PackExpansionIntoNonPack) {
4947 if (!ArgumentPack.empty()) {
4948 // If we were part way through filling in an expanded parameter pack,
4949 // fall back to just producing individual arguments.
4950 Converted.insert(Converted.end(),
4951 ArgumentPack.begin(), ArgumentPack.end());
4952 ArgumentPack.clear();
4955 while (ArgIdx < NumArgs) {
4956 Converted.push_back(NewArgs[ArgIdx].getArgument());
4966 // If we're checking a partial template argument list, we're done.
4967 if (PartialTemplateArgs) {
4968 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
4969 Converted.push_back(
4970 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4975 // If we have a template parameter pack with no more corresponding
4976 // arguments, just break out now and we'll fill in the argument pack below.
4977 if ((*Param)->isTemplateParameterPack()) {
4978 assert(!getExpandedPackSize(*Param) &&
4979 "Should have dealt with this already");
4981 // A non-expanded parameter pack before the end of the parameter list
4982 // only occurs for an ill-formed template parameter list, unless we've
4983 // got a partial argument list for a function template, so just bail out.
4984 if (Param + 1 != ParamEnd)
4987 Converted.push_back(
4988 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4989 ArgumentPack.clear();
4995 // Check whether we have a default argument.
4996 TemplateArgumentLoc Arg;
4998 // Retrieve the default template argument from the template
4999 // parameter. For each kind of template parameter, we substitute the
5000 // template arguments provided thus far and any "outer" template arguments
5001 // (when the template parameter was part of a nested template) into
5002 // the default argument.
5003 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
5004 if (!hasVisibleDefaultArgument(TTP))
5005 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5008 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
5017 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5019 } else if (NonTypeTemplateParmDecl *NTTP
5020 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
5021 if (!hasVisibleDefaultArgument(NTTP))
5022 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5025 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
5033 Expr *Ex = E.getAs<Expr>();
5034 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5036 TemplateTemplateParmDecl *TempParm
5037 = cast<TemplateTemplateParmDecl>(*Param);
5039 if (!hasVisibleDefaultArgument(TempParm))
5040 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5043 NestedNameSpecifierLoc QualifierLoc;
5044 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
5053 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
5054 TempParm->getDefaultArgument().getTemplateNameLoc());
5057 // Introduce an instantiation record that describes where we are using
5058 // the default template argument. We're not actually instantiating a
5059 // template here, we just create this object to put a note into the
5061 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5062 SourceRange(TemplateLoc, RAngleLoc));
5063 if (Inst.isInvalid())
5066 // Check the default template argument.
5067 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
5068 RAngleLoc, 0, Converted))
5071 // Core issue 150 (assumed resolution): if this is a template template
5072 // parameter, keep track of the default template arguments from the
5073 // template definition.
5074 if (isTemplateTemplateParameter)
5075 NewArgs.addArgument(Arg);
5077 // Move to the next template parameter and argument.
5082 // If we're performing a partial argument substitution, allow any trailing
5083 // pack expansions; they might be empty. This can happen even if
5084 // PartialTemplateArgs is false (the list of arguments is complete but
5085 // still dependent).
5086 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5087 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5088 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5089 Converted.push_back(NewArgs[ArgIdx++].getArgument());
5092 // If we have any leftover arguments, then there were too many arguments.
5093 // Complain and fail.
5094 if (ArgIdx < NumArgs)
5095 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
5097 // No problems found with the new argument list, propagate changes back
5099 if (UpdateArgsWithConversions)
5100 TemplateArgs = std::move(NewArgs);
5106 class UnnamedLocalNoLinkageFinder
5107 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
5112 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
5115 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
5117 bool Visit(QualType T) {
5118 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
5121 #define TYPE(Class, Parent) \
5122 bool Visit##Class##Type(const Class##Type *);
5123 #define ABSTRACT_TYPE(Class, Parent) \
5124 bool Visit##Class##Type(const Class##Type *) { return false; }
5125 #define NON_CANONICAL_TYPE(Class, Parent) \
5126 bool Visit##Class##Type(const Class##Type *) { return false; }
5127 #include "clang/AST/TypeNodes.def"
5129 bool VisitTagDecl(const TagDecl *Tag);
5130 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
5132 } // end anonymous namespace
5134 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
5138 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
5139 return Visit(T->getElementType());
5142 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
5143 return Visit(T->getPointeeType());
5146 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
5147 const BlockPointerType* T) {
5148 return Visit(T->getPointeeType());
5151 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
5152 const LValueReferenceType* T) {
5153 return Visit(T->getPointeeType());
5156 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
5157 const RValueReferenceType* T) {
5158 return Visit(T->getPointeeType());
5161 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
5162 const MemberPointerType* T) {
5163 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
5166 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
5167 const ConstantArrayType* T) {
5168 return Visit(T->getElementType());
5171 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
5172 const IncompleteArrayType* T) {
5173 return Visit(T->getElementType());
5176 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
5177 const VariableArrayType* T) {
5178 return Visit(T->getElementType());
5181 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
5182 const DependentSizedArrayType* T) {
5183 return Visit(T->getElementType());
5186 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
5187 const DependentSizedExtVectorType* T) {
5188 return Visit(T->getElementType());
5191 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
5192 const DependentAddressSpaceType *T) {
5193 return Visit(T->getPointeeType());
5196 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
5197 return Visit(T->getElementType());
5200 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
5201 return Visit(T->getElementType());
5204 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
5205 const FunctionProtoType* T) {
5206 for (const auto &A : T->param_types()) {
5211 return Visit(T->getReturnType());
5214 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5215 const FunctionNoProtoType* T) {
5216 return Visit(T->getReturnType());
5219 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5220 const UnresolvedUsingType*) {
5224 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5228 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5229 return Visit(T->getUnderlyingType());
5232 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5236 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5237 const UnaryTransformType*) {
5241 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5242 return Visit(T->getDeducedType());
5245 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5246 const DeducedTemplateSpecializationType *T) {
5247 return Visit(T->getDeducedType());
5250 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5251 return VisitTagDecl(T->getDecl());
5254 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5255 return VisitTagDecl(T->getDecl());
5258 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5259 const TemplateTypeParmType*) {
5263 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5264 const SubstTemplateTypeParmPackType *) {
5268 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5269 const TemplateSpecializationType*) {
5273 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5274 const InjectedClassNameType* T) {
5275 return VisitTagDecl(T->getDecl());
5278 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5279 const DependentNameType* T) {
5280 return VisitNestedNameSpecifier(T->getQualifier());
5283 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5284 const DependentTemplateSpecializationType* T) {
5285 return VisitNestedNameSpecifier(T->getQualifier());
5288 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5289 const PackExpansionType* T) {
5290 return Visit(T->getPattern());
5293 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5297 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5298 const ObjCInterfaceType *) {
5302 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5303 const ObjCObjectPointerType *) {
5307 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5308 return Visit(T->getValueType());
5311 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5315 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5316 if (Tag->getDeclContext()->isFunctionOrMethod()) {
5317 S.Diag(SR.getBegin(),
5318 S.getLangOpts().CPlusPlus11 ?
5319 diag::warn_cxx98_compat_template_arg_local_type :
5320 diag::ext_template_arg_local_type)
5321 << S.Context.getTypeDeclType(Tag) << SR;
5325 if (!Tag->hasNameForLinkage()) {
5326 S.Diag(SR.getBegin(),
5327 S.getLangOpts().CPlusPlus11 ?
5328 diag::warn_cxx98_compat_template_arg_unnamed_type :
5329 diag::ext_template_arg_unnamed_type) << SR;
5330 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5337 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5338 NestedNameSpecifier *NNS) {
5339 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5342 switch (NNS->getKind()) {
5343 case NestedNameSpecifier::Identifier:
5344 case NestedNameSpecifier::Namespace:
5345 case NestedNameSpecifier::NamespaceAlias:
5346 case NestedNameSpecifier::Global:
5347 case NestedNameSpecifier::Super:
5350 case NestedNameSpecifier::TypeSpec:
5351 case NestedNameSpecifier::TypeSpecWithTemplate:
5352 return Visit(QualType(NNS->getAsType(), 0));
5354 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5357 /// \brief Check a template argument against its corresponding
5358 /// template type parameter.
5360 /// This routine implements the semantics of C++ [temp.arg.type]. It
5361 /// returns true if an error occurred, and false otherwise.
5362 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
5363 TypeSourceInfo *ArgInfo) {
5364 assert(ArgInfo && "invalid TypeSourceInfo");
5365 QualType Arg = ArgInfo->getType();
5366 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5368 if (Arg->isVariablyModifiedType()) {
5369 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5370 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5371 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5374 // C++03 [temp.arg.type]p2:
5375 // A local type, a type with no linkage, an unnamed type or a type
5376 // compounded from any of these types shall not be used as a
5377 // template-argument for a template type-parameter.
5379 // C++11 allows these, and even in C++03 we allow them as an extension with
5381 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5382 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5383 (void)Finder.Visit(Context.getCanonicalType(Arg));
5389 enum NullPointerValueKind {
5395 /// \brief Determine whether the given template argument is a null pointer
5396 /// value of the appropriate type.
5397 static NullPointerValueKind
5398 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5399 QualType ParamType, Expr *Arg,
5400 Decl *Entity = nullptr) {
5401 if (Arg->isValueDependent() || Arg->isTypeDependent())
5402 return NPV_NotNullPointer;
5404 // dllimport'd entities aren't constant but are available inside of template
5406 if (Entity && Entity->hasAttr<DLLImportAttr>())
5407 return NPV_NotNullPointer;
5409 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5411 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
5413 if (!S.getLangOpts().CPlusPlus11)
5414 return NPV_NotNullPointer;
5416 // Determine whether we have a constant expression.
5417 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5418 if (ArgRV.isInvalid())
5422 Expr::EvalResult EvalResult;
5423 SmallVector<PartialDiagnosticAt, 8> Notes;
5424 EvalResult.Diag = &Notes;
5425 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5426 EvalResult.HasSideEffects) {
5427 SourceLocation DiagLoc = Arg->getExprLoc();
5429 // If our only note is the usual "invalid subexpression" note, just point
5430 // the caret at its location rather than producing an essentially
5432 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5433 diag::note_invalid_subexpr_in_const_expr) {
5434 DiagLoc = Notes[0].first;
5438 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5439 << Arg->getType() << Arg->getSourceRange();
5440 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5441 S.Diag(Notes[I].first, Notes[I].second);
5443 S.Diag(Param->getLocation(), diag::note_template_param_here);
5447 // C++11 [temp.arg.nontype]p1:
5448 // - an address constant expression of type std::nullptr_t
5449 if (Arg->getType()->isNullPtrType())
5450 return NPV_NullPointer;
5452 // - a constant expression that evaluates to a null pointer value (4.10); or
5453 // - a constant expression that evaluates to a null member pointer value
5455 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5456 (EvalResult.Val.isMemberPointer() &&
5457 !EvalResult.Val.getMemberPointerDecl())) {
5458 // If our expression has an appropriate type, we've succeeded.
5459 bool ObjCLifetimeConversion;
5460 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5461 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5462 ObjCLifetimeConversion))
5463 return NPV_NullPointer;
5465 // The types didn't match, but we know we got a null pointer; complain,
5466 // then recover as if the types were correct.
5467 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5468 << Arg->getType() << ParamType << Arg->getSourceRange();
5469 S.Diag(Param->getLocation(), diag::note_template_param_here);
5470 return NPV_NullPointer;
5473 // If we don't have a null pointer value, but we do have a NULL pointer
5474 // constant, suggest a cast to the appropriate type.
5475 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5476 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5477 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
5478 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5479 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
5481 S.Diag(Param->getLocation(), diag::note_template_param_here);
5482 return NPV_NullPointer;
5485 // FIXME: If we ever want to support general, address-constant expressions
5486 // as non-type template arguments, we should return the ExprResult here to
5487 // be interpreted by the caller.
5488 return NPV_NotNullPointer;
5491 /// \brief Checks whether the given template argument is compatible with its
5492 /// template parameter.
5493 static bool CheckTemplateArgumentIsCompatibleWithParameter(
5494 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5495 Expr *Arg, QualType ArgType) {
5496 bool ObjCLifetimeConversion;
5497 if (ParamType->isPointerType() &&
5498 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5499 S.IsQualificationConversion(ArgType, ParamType, false,
5500 ObjCLifetimeConversion)) {
5501 // For pointer-to-object types, qualification conversions are
5504 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5505 if (!ParamRef->getPointeeType()->isFunctionType()) {
5506 // C++ [temp.arg.nontype]p5b3:
5507 // For a non-type template-parameter of type reference to
5508 // object, no conversions apply. The type referred to by the
5509 // reference may be more cv-qualified than the (otherwise
5510 // identical) type of the template- argument. The
5511 // template-parameter is bound directly to the
5512 // template-argument, which shall be an lvalue.
5514 // FIXME: Other qualifiers?
5515 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5516 unsigned ArgQuals = ArgType.getCVRQualifiers();
5518 if ((ParamQuals | ArgQuals) != ParamQuals) {
5519 S.Diag(Arg->getLocStart(),
5520 diag::err_template_arg_ref_bind_ignores_quals)
5521 << ParamType << Arg->getType() << Arg->getSourceRange();
5522 S.Diag(Param->getLocation(), diag::note_template_param_here);
5528 // At this point, the template argument refers to an object or
5529 // function with external linkage. We now need to check whether the
5530 // argument and parameter types are compatible.
5531 if (!S.Context.hasSameUnqualifiedType(ArgType,
5532 ParamType.getNonReferenceType())) {
5533 // We can't perform this conversion or binding.
5534 if (ParamType->isReferenceType())
5535 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5536 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5538 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5539 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5540 S.Diag(Param->getLocation(), diag::note_template_param_here);
5548 /// \brief Checks whether the given template argument is the address
5549 /// of an object or function according to C++ [temp.arg.nontype]p1.
5551 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5552 NonTypeTemplateParmDecl *Param,
5555 TemplateArgument &Converted) {
5556 bool Invalid = false;
5558 QualType ArgType = Arg->getType();
5560 bool AddressTaken = false;
5561 SourceLocation AddrOpLoc;
5562 if (S.getLangOpts().MicrosoftExt) {
5563 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5564 // dereference and address-of operators.
5565 Arg = Arg->IgnoreParenCasts();
5567 bool ExtWarnMSTemplateArg = false;
5568 UnaryOperatorKind FirstOpKind;
5569 SourceLocation FirstOpLoc;
5570 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5571 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5572 if (UnOpKind == UO_Deref)
5573 ExtWarnMSTemplateArg = true;
5574 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5575 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5576 if (!AddrOpLoc.isValid()) {
5577 FirstOpKind = UnOpKind;
5578 FirstOpLoc = UnOp->getOperatorLoc();
5583 if (FirstOpLoc.isValid()) {
5584 if (ExtWarnMSTemplateArg)
5585 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5586 << ArgIn->getSourceRange();
5588 if (FirstOpKind == UO_AddrOf)
5589 AddressTaken = true;
5590 else if (Arg->getType()->isPointerType()) {
5591 // We cannot let pointers get dereferenced here, that is obviously not a
5592 // constant expression.
5593 assert(FirstOpKind == UO_Deref);
5594 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5595 << Arg->getSourceRange();
5599 // See through any implicit casts we added to fix the type.
5600 Arg = Arg->IgnoreImpCasts();
5602 // C++ [temp.arg.nontype]p1:
5604 // A template-argument for a non-type, non-template
5605 // template-parameter shall be one of: [...]
5607 // -- the address of an object or function with external
5608 // linkage, including function templates and function
5609 // template-ids but excluding non-static class members,
5610 // expressed as & id-expression where the & is optional if
5611 // the name refers to a function or array, or if the
5612 // corresponding template-parameter is a reference; or
5614 // In C++98/03 mode, give an extension warning on any extra parentheses.
5615 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5616 bool ExtraParens = false;
5617 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5618 if (!Invalid && !ExtraParens) {
5619 S.Diag(Arg->getLocStart(),
5620 S.getLangOpts().CPlusPlus11
5621 ? diag::warn_cxx98_compat_template_arg_extra_parens
5622 : diag::ext_template_arg_extra_parens)
5623 << Arg->getSourceRange();
5627 Arg = Parens->getSubExpr();
5630 while (SubstNonTypeTemplateParmExpr *subst =
5631 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5632 Arg = subst->getReplacement()->IgnoreImpCasts();
5634 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5635 if (UnOp->getOpcode() == UO_AddrOf) {
5636 Arg = UnOp->getSubExpr();
5637 AddressTaken = true;
5638 AddrOpLoc = UnOp->getOperatorLoc();
5642 while (SubstNonTypeTemplateParmExpr *subst =
5643 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5644 Arg = subst->getReplacement()->IgnoreImpCasts();
5647 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5648 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5650 // If our parameter has pointer type, check for a null template value.
5651 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5652 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
5654 case NPV_NullPointer:
5655 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5656 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5657 /*isNullPtr=*/true);
5663 case NPV_NotNullPointer:
5668 // Stop checking the precise nature of the argument if it is value dependent,
5669 // it should be checked when instantiated.
5670 if (Arg->isValueDependent()) {
5671 Converted = TemplateArgument(ArgIn);
5675 if (isa<CXXUuidofExpr>(Arg)) {
5676 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5677 ArgIn, Arg, ArgType))
5680 Converted = TemplateArgument(ArgIn);
5685 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5686 << Arg->getSourceRange();
5687 S.Diag(Param->getLocation(), diag::note_template_param_here);
5691 // Cannot refer to non-static data members
5692 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
5693 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
5694 << Entity << Arg->getSourceRange();
5695 S.Diag(Param->getLocation(), diag::note_template_param_here);
5699 // Cannot refer to non-static member functions
5700 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
5701 if (!Method->isStatic()) {
5702 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
5703 << Method << Arg->getSourceRange();
5704 S.Diag(Param->getLocation(), diag::note_template_param_here);
5709 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5710 VarDecl *Var = dyn_cast<VarDecl>(Entity);
5712 // A non-type template argument must refer to an object or function.
5713 if (!Func && !Var) {
5714 // We found something, but we don't know specifically what it is.
5715 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5716 << Arg->getSourceRange();
5717 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5721 // Address / reference template args must have external linkage in C++98.
5722 if (Entity->getFormalLinkage() == InternalLinkage) {
5723 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
5724 diag::warn_cxx98_compat_template_arg_object_internal :
5725 diag::ext_template_arg_object_internal)
5726 << !Func << Entity << Arg->getSourceRange();
5727 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5729 } else if (!Entity->hasLinkage()) {
5730 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5731 << !Func << Entity << Arg->getSourceRange();
5732 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5738 // If the template parameter has pointer type, the function decays.
5739 if (ParamType->isPointerType() && !AddressTaken)
5740 ArgType = S.Context.getPointerType(Func->getType());
5741 else if (AddressTaken && ParamType->isReferenceType()) {
5742 // If we originally had an address-of operator, but the
5743 // parameter has reference type, complain and (if things look
5744 // like they will work) drop the address-of operator.
5745 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5746 ParamType.getNonReferenceType())) {
5747 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5749 S.Diag(Param->getLocation(), diag::note_template_param_here);
5753 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5755 << FixItHint::CreateRemoval(AddrOpLoc);
5756 S.Diag(Param->getLocation(), diag::note_template_param_here);
5758 ArgType = Func->getType();
5761 // A value of reference type is not an object.
5762 if (Var->getType()->isReferenceType()) {
5763 S.Diag(Arg->getLocStart(),
5764 diag::err_template_arg_reference_var)
5765 << Var->getType() << Arg->getSourceRange();
5766 S.Diag(Param->getLocation(), diag::note_template_param_here);
5770 // A template argument must have static storage duration.
5771 if (Var->getTLSKind()) {
5772 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5773 << Arg->getSourceRange();
5774 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5778 // If the template parameter has pointer type, we must have taken
5779 // the address of this object.
5780 if (ParamType->isReferenceType()) {
5782 // If we originally had an address-of operator, but the
5783 // parameter has reference type, complain and (if things look
5784 // like they will work) drop the address-of operator.
5785 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5786 ParamType.getNonReferenceType())) {
5787 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5789 S.Diag(Param->getLocation(), diag::note_template_param_here);
5793 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5795 << FixItHint::CreateRemoval(AddrOpLoc);
5796 S.Diag(Param->getLocation(), diag::note_template_param_here);
5798 ArgType = Var->getType();
5800 } else if (!AddressTaken && ParamType->isPointerType()) {
5801 if (Var->getType()->isArrayType()) {
5802 // Array-to-pointer decay.
5803 ArgType = S.Context.getArrayDecayedType(Var->getType());
5805 // If the template parameter has pointer type but the address of
5806 // this object was not taken, complain and (possibly) recover by
5807 // taking the address of the entity.
5808 ArgType = S.Context.getPointerType(Var->getType());
5809 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5810 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5812 S.Diag(Param->getLocation(), diag::note_template_param_here);
5816 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5818 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5820 S.Diag(Param->getLocation(), diag::note_template_param_here);
5825 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5829 // Create the template argument.
5831 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
5832 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
5836 /// \brief Checks whether the given template argument is a pointer to
5837 /// member constant according to C++ [temp.arg.nontype]p1.
5838 static bool CheckTemplateArgumentPointerToMember(Sema &S,
5839 NonTypeTemplateParmDecl *Param,
5842 TemplateArgument &Converted) {
5843 bool Invalid = false;
5845 Expr *Arg = ResultArg;
5846 bool ObjCLifetimeConversion;
5848 // C++ [temp.arg.nontype]p1:
5850 // A template-argument for a non-type, non-template
5851 // template-parameter shall be one of: [...]
5853 // -- a pointer to member expressed as described in 5.3.1.
5854 DeclRefExpr *DRE = nullptr;
5856 // In C++98/03 mode, give an extension warning on any extra parentheses.
5857 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5858 bool ExtraParens = false;
5859 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5860 if (!Invalid && !ExtraParens) {
5861 S.Diag(Arg->getLocStart(),
5862 S.getLangOpts().CPlusPlus11 ?
5863 diag::warn_cxx98_compat_template_arg_extra_parens :
5864 diag::ext_template_arg_extra_parens)
5865 << Arg->getSourceRange();
5869 Arg = Parens->getSubExpr();
5872 while (SubstNonTypeTemplateParmExpr *subst =
5873 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5874 Arg = subst->getReplacement()->IgnoreImpCasts();
5876 // A pointer-to-member constant written &Class::member.
5877 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5878 if (UnOp->getOpcode() == UO_AddrOf) {
5879 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5880 if (DRE && !DRE->getQualifier())
5884 // A constant of pointer-to-member type.
5885 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5886 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5887 if (VD->getType()->isMemberPointerType()) {
5888 if (isa<NonTypeTemplateParmDecl>(VD)) {
5889 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5890 Converted = TemplateArgument(Arg);
5892 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5893 Converted = TemplateArgument(VD, ParamType);
5903 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5905 // Check for a null pointer value.
5906 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
5910 case NPV_NullPointer:
5911 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5912 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5915 case NPV_NotNullPointer:
5919 if (S.IsQualificationConversion(ResultArg->getType(),
5920 ParamType.getNonReferenceType(), false,
5921 ObjCLifetimeConversion)) {
5922 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,
5923 ResultArg->getValueKind())
5925 } else if (!S.Context.hasSameUnqualifiedType(
5926 ResultArg->getType(), ParamType.getNonReferenceType())) {
5927 // We can't perform this conversion.
5928 S.Diag(ResultArg->getLocStart(), diag::err_template_arg_not_convertible)
5929 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
5930 S.Diag(Param->getLocation(), diag::note_template_param_here);
5935 return S.Diag(Arg->getLocStart(),
5936 diag::err_template_arg_not_pointer_to_member_form)
5937 << Arg->getSourceRange();
5939 if (isa<FieldDecl>(DRE->getDecl()) ||
5940 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5941 isa<CXXMethodDecl>(DRE->getDecl())) {
5942 assert((isa<FieldDecl>(DRE->getDecl()) ||
5943 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5944 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5945 "Only non-static member pointers can make it here");
5947 // Okay: this is the address of a non-static member, and therefore
5948 // a member pointer constant.
5949 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5950 Converted = TemplateArgument(Arg);
5952 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
5953 Converted = TemplateArgument(D, ParamType);
5958 // We found something else, but we don't know specifically what it is.
5959 S.Diag(Arg->getLocStart(),
5960 diag::err_template_arg_not_pointer_to_member_form)
5961 << Arg->getSourceRange();
5962 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5966 /// \brief Check a template argument against its corresponding
5967 /// non-type template parameter.
5969 /// This routine implements the semantics of C++ [temp.arg.nontype].
5970 /// If an error occurred, it returns ExprError(); otherwise, it
5971 /// returns the converted template argument. \p ParamType is the
5972 /// type of the non-type template parameter after it has been instantiated.
5973 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5974 QualType ParamType, Expr *Arg,
5975 TemplateArgument &Converted,
5976 CheckTemplateArgumentKind CTAK) {
5977 SourceLocation StartLoc = Arg->getLocStart();
5979 // If the parameter type somehow involves auto, deduce the type now.
5980 if (getLangOpts().CPlusPlus17 && ParamType->isUndeducedType()) {
5981 // During template argument deduction, we allow 'decltype(auto)' to
5982 // match an arbitrary dependent argument.
5983 // FIXME: The language rules don't say what happens in this case.
5984 // FIXME: We get an opaque dependent type out of decltype(auto) if the
5985 // expression is merely instantiation-dependent; is this enough?
5986 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
5987 auto *AT = dyn_cast<AutoType>(ParamType);
5988 if (AT && AT->isDecltypeAuto()) {
5989 Converted = TemplateArgument(Arg);
5994 // When checking a deduced template argument, deduce from its type even if
5995 // the type is dependent, in order to check the types of non-type template
5996 // arguments line up properly in partial ordering.
5997 Optional<unsigned> Depth;
5998 if (CTAK != CTAK_Specified)
5999 Depth = Param->getDepth() + 1;
6001 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
6002 Arg, ParamType, Depth) == DAR_Failed) {
6003 Diag(Arg->getExprLoc(),
6004 diag::err_non_type_template_parm_type_deduction_failure)
6005 << Param->getDeclName() << Param->getType() << Arg->getType()
6006 << Arg->getSourceRange();
6007 Diag(Param->getLocation(), diag::note_template_param_here);
6010 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
6011 // an error. The error message normally references the parameter
6012 // declaration, but here we'll pass the argument location because that's
6013 // where the parameter type is deduced.
6014 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
6015 if (ParamType.isNull()) {
6016 Diag(Param->getLocation(), diag::note_template_param_here);
6021 // We should have already dropped all cv-qualifiers by now.
6022 assert(!ParamType.hasQualifiers() &&
6023 "non-type template parameter type cannot be qualified");
6025 if (CTAK == CTAK_Deduced &&
6026 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
6028 // FIXME: If either type is dependent, we skip the check. This isn't
6029 // correct, since during deduction we're supposed to have replaced each
6030 // template parameter with some unique (non-dependent) placeholder.
6031 // FIXME: If the argument type contains 'auto', we carry on and fail the
6032 // type check in order to force specific types to be more specialized than
6033 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
6035 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
6036 !Arg->getType()->getContainedAutoType()) {
6037 Converted = TemplateArgument(Arg);
6040 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
6041 // we should actually be checking the type of the template argument in P,
6042 // not the type of the template argument deduced from A, against the
6043 // template parameter type.
6044 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
6046 << ParamType.getUnqualifiedType();
6047 Diag(Param->getLocation(), diag::note_template_param_here);
6051 // If either the parameter has a dependent type or the argument is
6052 // type-dependent, there's nothing we can check now.
6053 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
6054 // FIXME: Produce a cloned, canonical expression?
6055 Converted = TemplateArgument(Arg);
6059 // The initialization of the parameter from the argument is
6060 // a constant-evaluated context.
6061 EnterExpressionEvaluationContext ConstantEvaluated(
6062 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6064 if (getLangOpts().CPlusPlus17) {
6065 // C++17 [temp.arg.nontype]p1:
6066 // A template-argument for a non-type template parameter shall be
6067 // a converted constant expression of the type of the template-parameter.
6069 ExprResult ArgResult = CheckConvertedConstantExpression(
6070 Arg, ParamType, Value, CCEK_TemplateArg);
6071 if (ArgResult.isInvalid())
6074 // For a value-dependent argument, CheckConvertedConstantExpression is
6075 // permitted (and expected) to be unable to determine a value.
6076 if (ArgResult.get()->isValueDependent()) {
6077 Converted = TemplateArgument(ArgResult.get());
6081 QualType CanonParamType = Context.getCanonicalType(ParamType);
6083 // Convert the APValue to a TemplateArgument.
6084 switch (Value.getKind()) {
6085 case APValue::Uninitialized:
6086 assert(ParamType->isNullPtrType());
6087 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
6090 assert(ParamType->isIntegralOrEnumerationType());
6091 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
6093 case APValue::MemberPointer: {
6094 assert(ParamType->isMemberPointerType());
6096 // FIXME: We need TemplateArgument representation and mangling for these.
6097 if (!Value.getMemberPointerPath().empty()) {
6098 Diag(Arg->getLocStart(),
6099 diag::err_template_arg_member_ptr_base_derived_not_supported)
6100 << Value.getMemberPointerDecl() << ParamType
6101 << Arg->getSourceRange();
6105 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
6106 Converted = VD ? TemplateArgument(VD, CanonParamType)
6107 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6110 case APValue::LValue: {
6111 // For a non-type template-parameter of pointer or reference type,
6112 // the value of the constant expression shall not refer to
6113 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
6114 ParamType->isNullPtrType());
6115 // -- a temporary object
6116 // -- a string literal
6117 // -- the result of a typeid expression, or
6118 // -- a predefined __func__ variable
6119 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
6120 if (isa<CXXUuidofExpr>(E)) {
6121 Converted = TemplateArgument(const_cast<Expr*>(E));
6124 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
6125 << Arg->getSourceRange();
6128 auto *VD = const_cast<ValueDecl *>(
6129 Value.getLValueBase().dyn_cast<const ValueDecl *>());
6131 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
6132 VD && VD->getType()->isArrayType() &&
6133 Value.getLValuePath()[0].ArrayIndex == 0 &&
6134 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
6135 // Per defect report (no number yet):
6136 // ... other than a pointer to the first element of a complete array
6138 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
6139 Value.isLValueOnePastTheEnd()) {
6140 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
6141 << Value.getAsString(Context, ParamType);
6144 assert((VD || !ParamType->isReferenceType()) &&
6145 "null reference should not be a constant expression");
6146 assert((!VD || !ParamType->isNullPtrType()) &&
6147 "non-null value of type nullptr_t?");
6148 Converted = VD ? TemplateArgument(VD, CanonParamType)
6149 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
6152 case APValue::AddrLabelDiff:
6153 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
6154 case APValue::Float:
6155 case APValue::ComplexInt:
6156 case APValue::ComplexFloat:
6157 case APValue::Vector:
6158 case APValue::Array:
6159 case APValue::Struct:
6160 case APValue::Union:
6161 llvm_unreachable("invalid kind for template argument");
6164 return ArgResult.get();
6167 // C++ [temp.arg.nontype]p5:
6168 // The following conversions are performed on each expression used
6169 // as a non-type template-argument. If a non-type
6170 // template-argument cannot be converted to the type of the
6171 // corresponding template-parameter then the program is
6173 if (ParamType->isIntegralOrEnumerationType()) {
6175 // -- for a non-type template-parameter of integral or
6176 // enumeration type, conversions permitted in a converted
6177 // constant expression are applied.
6180 // -- for a non-type template-parameter of integral or
6181 // enumeration type, integral promotions (4.5) and integral
6182 // conversions (4.7) are applied.
6184 if (getLangOpts().CPlusPlus11) {
6185 // C++ [temp.arg.nontype]p1:
6186 // A template-argument for a non-type, non-template template-parameter
6189 // -- for a non-type template-parameter of integral or enumeration
6190 // type, a converted constant expression of the type of the
6191 // template-parameter; or
6193 ExprResult ArgResult =
6194 CheckConvertedConstantExpression(Arg, ParamType, Value,
6196 if (ArgResult.isInvalid())
6199 // We can't check arbitrary value-dependent arguments.
6200 if (ArgResult.get()->isValueDependent()) {
6201 Converted = TemplateArgument(ArgResult.get());
6205 // Widen the argument value to sizeof(parameter type). This is almost
6206 // always a no-op, except when the parameter type is bool. In
6207 // that case, this may extend the argument from 1 bit to 8 bits.
6208 QualType IntegerType = ParamType;
6209 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6210 IntegerType = Enum->getDecl()->getIntegerType();
6211 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6213 Converted = TemplateArgument(Context, Value,
6214 Context.getCanonicalType(ParamType));
6218 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6219 if (ArgResult.isInvalid())
6221 Arg = ArgResult.get();
6223 QualType ArgType = Arg->getType();
6225 // C++ [temp.arg.nontype]p1:
6226 // A template-argument for a non-type, non-template
6227 // template-parameter shall be one of:
6229 // -- an integral constant-expression of integral or enumeration
6231 // -- the name of a non-type template-parameter; or
6233 if (!ArgType->isIntegralOrEnumerationType()) {
6234 Diag(Arg->getLocStart(),
6235 diag::err_template_arg_not_integral_or_enumeral)
6236 << ArgType << Arg->getSourceRange();
6237 Diag(Param->getLocation(), diag::note_template_param_here);
6239 } else if (!Arg->isValueDependent()) {
6240 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6244 TmplArgICEDiagnoser(QualType T) : T(T) { }
6246 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6247 SourceRange SR) override {
6248 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6250 } Diagnoser(ArgType);
6252 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
6258 // From here on out, all we care about is the unqualified form
6259 // of the argument type.
6260 ArgType = ArgType.getUnqualifiedType();
6262 // Try to convert the argument to the parameter's type.
6263 if (Context.hasSameType(ParamType, ArgType)) {
6264 // Okay: no conversion necessary
6265 } else if (ParamType->isBooleanType()) {
6266 // This is an integral-to-boolean conversion.
6267 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
6268 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6269 !ParamType->isEnumeralType()) {
6270 // This is an integral promotion or conversion.
6271 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
6273 // We can't perform this conversion.
6274 Diag(Arg->getLocStart(),
6275 diag::err_template_arg_not_convertible)
6276 << Arg->getType() << ParamType << Arg->getSourceRange();
6277 Diag(Param->getLocation(), diag::note_template_param_here);
6281 // Add the value of this argument to the list of converted
6282 // arguments. We use the bitwidth and signedness of the template
6284 if (Arg->isValueDependent()) {
6285 // The argument is value-dependent. Create a new
6286 // TemplateArgument with the converted expression.
6287 Converted = TemplateArgument(Arg);
6291 QualType IntegerType = Context.getCanonicalType(ParamType);
6292 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6293 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
6295 if (ParamType->isBooleanType()) {
6296 // Value must be zero or one.
6298 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6299 if (Value.getBitWidth() != AllowedBits)
6300 Value = Value.extOrTrunc(AllowedBits);
6301 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6303 llvm::APSInt OldValue = Value;
6305 // Coerce the template argument's value to the value it will have
6306 // based on the template parameter's type.
6307 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6308 if (Value.getBitWidth() != AllowedBits)
6309 Value = Value.extOrTrunc(AllowedBits);
6310 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6312 // Complain if an unsigned parameter received a negative value.
6313 if (IntegerType->isUnsignedIntegerOrEnumerationType()
6314 && (OldValue.isSigned() && OldValue.isNegative())) {
6315 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
6316 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6317 << Arg->getSourceRange();
6318 Diag(Param->getLocation(), diag::note_template_param_here);
6321 // Complain if we overflowed the template parameter's type.
6322 unsigned RequiredBits;
6323 if (IntegerType->isUnsignedIntegerOrEnumerationType())
6324 RequiredBits = OldValue.getActiveBits();
6325 else if (OldValue.isUnsigned())
6326 RequiredBits = OldValue.getActiveBits() + 1;
6328 RequiredBits = OldValue.getMinSignedBits();
6329 if (RequiredBits > AllowedBits) {
6330 Diag(Arg->getLocStart(),
6331 diag::warn_template_arg_too_large)
6332 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6333 << Arg->getSourceRange();
6334 Diag(Param->getLocation(), diag::note_template_param_here);
6338 Converted = TemplateArgument(Context, Value,
6339 ParamType->isEnumeralType()
6340 ? Context.getCanonicalType(ParamType)
6345 QualType ArgType = Arg->getType();
6346 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6348 // Handle pointer-to-function, reference-to-function, and
6349 // pointer-to-member-function all in (roughly) the same way.
6350 if (// -- For a non-type template-parameter of type pointer to
6351 // function, only the function-to-pointer conversion (4.3) is
6352 // applied. If the template-argument represents a set of
6353 // overloaded functions (or a pointer to such), the matching
6354 // function is selected from the set (13.4).
6355 (ParamType->isPointerType() &&
6356 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6357 // -- For a non-type template-parameter of type reference to
6358 // function, no conversions apply. If the template-argument
6359 // represents a set of overloaded functions, the matching
6360 // function is selected from the set (13.4).
6361 (ParamType->isReferenceType() &&
6362 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6363 // -- For a non-type template-parameter of type pointer to
6364 // member function, no conversions apply. If the
6365 // template-argument represents a set of overloaded member
6366 // functions, the matching member function is selected from
6368 (ParamType->isMemberPointerType() &&
6369 ParamType->getAs<MemberPointerType>()->getPointeeType()
6370 ->isFunctionType())) {
6372 if (Arg->getType() == Context.OverloadTy) {
6373 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6376 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6379 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6380 ArgType = Arg->getType();
6385 if (!ParamType->isMemberPointerType()) {
6386 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6393 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6399 if (ParamType->isPointerType()) {
6400 // -- for a non-type template-parameter of type pointer to
6401 // object, qualification conversions (4.4) and the
6402 // array-to-pointer conversion (4.2) are applied.
6403 // C++0x also allows a value of std::nullptr_t.
6404 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
6405 "Only object pointers allowed here");
6407 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6414 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
6415 // -- For a non-type template-parameter of type reference to
6416 // object, no conversions apply. The type referred to by the
6417 // reference may be more cv-qualified than the (otherwise
6418 // identical) type of the template-argument. The
6419 // template-parameter is bound directly to the
6420 // template-argument, which must be an lvalue.
6421 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
6422 "Only object references allowed here");
6424 if (Arg->getType() == Context.OverloadTy) {
6425 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6426 ParamRefType->getPointeeType(),
6429 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6432 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6433 ArgType = Arg->getType();
6438 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6445 // Deal with parameters of type std::nullptr_t.
6446 if (ParamType->isNullPtrType()) {
6447 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6448 Converted = TemplateArgument(Arg);
6452 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6453 case NPV_NotNullPointer:
6454 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6455 << Arg->getType() << ParamType;
6456 Diag(Param->getLocation(), diag::note_template_param_here);
6462 case NPV_NullPointer:
6463 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6464 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6470 // -- For a non-type template-parameter of type pointer to data
6471 // member, qualification conversions (4.4) are applied.
6472 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6474 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6480 static void DiagnoseTemplateParameterListArityMismatch(
6481 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6482 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6484 /// \brief Check a template argument against its corresponding
6485 /// template template parameter.
6487 /// This routine implements the semantics of C++ [temp.arg.template].
6488 /// It returns true if an error occurred, and false otherwise.
6489 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6490 TemplateArgumentLoc &Arg,
6491 unsigned ArgumentPackIndex) {
6492 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
6493 TemplateDecl *Template = Name.getAsTemplateDecl();
6495 // Any dependent template name is fine.
6496 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6500 if (Template->isInvalidDecl())
6503 // C++0x [temp.arg.template]p1:
6504 // A template-argument for a template template-parameter shall be
6505 // the name of a class template or an alias template, expressed as an
6506 // id-expression. When the template-argument names a class template, only
6507 // primary class templates are considered when matching the
6508 // template template argument with the corresponding parameter;
6509 // partial specializations are not considered even if their
6510 // parameter lists match that of the template template parameter.
6512 // Note that we also allow template template parameters here, which
6513 // will happen when we are dealing with, e.g., class template
6514 // partial specializations.
6515 if (!isa<ClassTemplateDecl>(Template) &&
6516 !isa<TemplateTemplateParmDecl>(Template) &&
6517 !isa<TypeAliasTemplateDecl>(Template) &&
6518 !isa<BuiltinTemplateDecl>(Template)) {
6519 assert(isa<FunctionTemplateDecl>(Template) &&
6520 "Only function templates are possible here");
6521 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
6522 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6526 TemplateParameterList *Params = Param->getTemplateParameters();
6527 if (Param->isExpandedParameterPack())
6528 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
6530 // C++1z [temp.arg.template]p3: (DR 150)
6531 // A template-argument matches a template template-parameter P when P
6532 // is at least as specialized as the template-argument A.
6533 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6534 // Quick check for the common case:
6535 // If P contains a parameter pack, then A [...] matches P if each of A's
6536 // template parameters matches the corresponding template parameter in
6537 // the template-parameter-list of P.
6538 if (TemplateParameterListsAreEqual(
6539 Template->getTemplateParameters(), Params, false,
6540 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6543 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6546 // FIXME: Produce better diagnostics for deduction failures.
6549 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
6552 TPL_TemplateTemplateArgumentMatch,
6556 /// \brief Given a non-type template argument that refers to a
6557 /// declaration and the type of its corresponding non-type template
6558 /// parameter, produce an expression that properly refers to that
6561 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6563 SourceLocation Loc) {
6564 // C++ [temp.param]p8:
6566 // A non-type template-parameter of type "array of T" or
6567 // "function returning T" is adjusted to be of type "pointer to
6568 // T" or "pointer to function returning T", respectively.
6569 if (ParamType->isArrayType())
6570 ParamType = Context.getArrayDecayedType(ParamType);
6571 else if (ParamType->isFunctionType())
6572 ParamType = Context.getPointerType(ParamType);
6574 // For a NULL non-type template argument, return nullptr casted to the
6575 // parameter's type.
6576 if (Arg.getKind() == TemplateArgument::NullPtr) {
6577 return ImpCastExprToType(
6578 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6580 ParamType->getAs<MemberPointerType>()
6581 ? CK_NullToMemberPointer
6582 : CK_NullToPointer);
6584 assert(Arg.getKind() == TemplateArgument::Declaration &&
6585 "Only declaration template arguments permitted here");
6587 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
6589 if (VD->getDeclContext()->isRecord() &&
6590 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6591 isa<IndirectFieldDecl>(VD))) {
6592 // If the value is a class member, we might have a pointer-to-member.
6593 // Determine whether the non-type template template parameter is of
6594 // pointer-to-member type. If so, we need to build an appropriate
6595 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6596 // would refer to the member itself.
6597 if (ParamType->isMemberPointerType()) {
6599 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6600 NestedNameSpecifier *Qualifier
6601 = NestedNameSpecifier::Create(Context, nullptr, false,
6602 ClassType.getTypePtr());
6604 SS.MakeTrivial(Context, Qualifier, Loc);
6606 // The actual value-ness of this is unimportant, but for
6607 // internal consistency's sake, references to instance methods
6609 ExprValueKind VK = VK_LValue;
6610 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6613 ExprResult RefExpr = BuildDeclRefExpr(VD,
6614 VD->getType().getNonReferenceType(),
6618 if (RefExpr.isInvalid())
6621 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6623 // We might need to perform a trailing qualification conversion, since
6624 // the element type on the parameter could be more qualified than the
6625 // element type in the expression we constructed.
6626 bool ObjCLifetimeConversion;
6627 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
6628 ParamType.getUnqualifiedType(), false,
6629 ObjCLifetimeConversion))
6630 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
6632 assert(!RefExpr.isInvalid() &&
6633 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
6634 ParamType.getUnqualifiedType()));
6639 QualType T = VD->getType().getNonReferenceType();
6641 if (ParamType->isPointerType()) {
6642 // When the non-type template parameter is a pointer, take the
6643 // address of the declaration.
6644 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
6645 if (RefExpr.isInvalid())
6648 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6649 (T->isFunctionType() || T->isArrayType())) {
6650 // Decay functions and arrays unless we're forming a pointer to array.
6651 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
6652 if (RefExpr.isInvalid())
6658 // Take the address of everything else
6659 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6662 ExprValueKind VK = VK_RValue;
6664 // If the non-type template parameter has reference type, qualify the
6665 // resulting declaration reference with the extra qualifiers on the
6666 // type that the reference refers to.
6667 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6669 T = Context.getQualifiedType(T,
6670 TargetRef->getPointeeType().getQualifiers());
6671 } else if (isa<FunctionDecl>(VD)) {
6672 // References to functions are always lvalues.
6676 return BuildDeclRefExpr(VD, T, VK, Loc);
6679 /// \brief Construct a new expression that refers to the given
6680 /// integral template argument with the given source-location
6683 /// This routine takes care of the mapping from an integral template
6684 /// argument (which may have any integral type) to the appropriate
6687 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6688 SourceLocation Loc) {
6689 assert(Arg.getKind() == TemplateArgument::Integral &&
6690 "Operation is only valid for integral template arguments");
6691 QualType OrigT = Arg.getIntegralType();
6693 // If this is an enum type that we're instantiating, we need to use an integer
6694 // type the same size as the enumerator. We don't want to build an
6695 // IntegerLiteral with enum type. The integer type of an enum type can be of
6696 // any integral type with C++11 enum classes, make sure we create the right
6697 // type of literal for it.
6699 if (const EnumType *ET = OrigT->getAs<EnumType>())
6700 T = ET->getDecl()->getIntegerType();
6703 if (T->isAnyCharacterType()) {
6704 // This does not need to handle u8 character literals because those are
6705 // of type char, and so can also be covered by an ASCII character literal.
6706 CharacterLiteral::CharacterKind Kind;
6707 if (T->isWideCharType())
6708 Kind = CharacterLiteral::Wide;
6709 else if (T->isChar16Type())
6710 Kind = CharacterLiteral::UTF16;
6711 else if (T->isChar32Type())
6712 Kind = CharacterLiteral::UTF32;
6714 Kind = CharacterLiteral::Ascii;
6716 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6718 } else if (T->isBooleanType()) {
6719 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6721 } else if (T->isNullPtrType()) {
6722 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6724 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
6727 if (OrigT->isEnumeralType()) {
6728 // FIXME: This is a hack. We need a better way to handle substituted
6729 // non-type template parameters.
6730 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6732 Context.getTrivialTypeSourceInfo(OrigT, Loc),
6739 /// \brief Match two template parameters within template parameter lists.
6740 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6742 Sema::TemplateParameterListEqualKind Kind,
6743 SourceLocation TemplateArgLoc) {
6744 // Check the actual kind (type, non-type, template).
6745 if (Old->getKind() != New->getKind()) {
6747 unsigned NextDiag = diag::err_template_param_different_kind;
6748 if (TemplateArgLoc.isValid()) {
6749 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6750 NextDiag = diag::note_template_param_different_kind;
6752 S.Diag(New->getLocation(), NextDiag)
6753 << (Kind != Sema::TPL_TemplateMatch);
6754 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6755 << (Kind != Sema::TPL_TemplateMatch);
6761 // Check that both are parameter packs or neither are parameter packs.
6762 // However, if we are matching a template template argument to a
6763 // template template parameter, the template template parameter can have
6764 // a parameter pack where the template template argument does not.
6765 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6766 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6767 Old->isTemplateParameterPack())) {
6769 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6770 if (TemplateArgLoc.isValid()) {
6771 S.Diag(TemplateArgLoc,
6772 diag::err_template_arg_template_params_mismatch);
6773 NextDiag = diag::note_template_parameter_pack_non_pack;
6776 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6777 : isa<NonTypeTemplateParmDecl>(New)? 1
6779 S.Diag(New->getLocation(), NextDiag)
6780 << ParamKind << New->isParameterPack();
6781 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6782 << ParamKind << Old->isParameterPack();
6788 // For non-type template parameters, check the type of the parameter.
6789 if (NonTypeTemplateParmDecl *OldNTTP
6790 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6791 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
6793 // If we are matching a template template argument to a template
6794 // template parameter and one of the non-type template parameter types
6795 // is dependent, then we must wait until template instantiation time
6796 // to actually compare the arguments.
6797 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6798 (OldNTTP->getType()->isDependentType() ||
6799 NewNTTP->getType()->isDependentType()))
6802 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6804 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6805 if (TemplateArgLoc.isValid()) {
6806 S.Diag(TemplateArgLoc,
6807 diag::err_template_arg_template_params_mismatch);
6808 NextDiag = diag::note_template_nontype_parm_different_type;
6810 S.Diag(NewNTTP->getLocation(), NextDiag)
6811 << NewNTTP->getType()
6812 << (Kind != Sema::TPL_TemplateMatch);
6813 S.Diag(OldNTTP->getLocation(),
6814 diag::note_template_nontype_parm_prev_declaration)
6815 << OldNTTP->getType();
6824 // For template template parameters, check the template parameter types.
6825 // The template parameter lists of template template
6826 // parameters must agree.
6827 if (TemplateTemplateParmDecl *OldTTP
6828 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
6829 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
6830 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6831 OldTTP->getTemplateParameters(),
6833 (Kind == Sema::TPL_TemplateMatch
6834 ? Sema::TPL_TemplateTemplateParmMatch
6842 /// \brief Diagnose a known arity mismatch when comparing template argument
6845 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
6846 TemplateParameterList *New,
6847 TemplateParameterList *Old,
6848 Sema::TemplateParameterListEqualKind Kind,
6849 SourceLocation TemplateArgLoc) {
6850 unsigned NextDiag = diag::err_template_param_list_different_arity;
6851 if (TemplateArgLoc.isValid()) {
6852 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6853 NextDiag = diag::note_template_param_list_different_arity;
6855 S.Diag(New->getTemplateLoc(), NextDiag)
6856 << (New->size() > Old->size())
6857 << (Kind != Sema::TPL_TemplateMatch)
6858 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6859 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6860 << (Kind != Sema::TPL_TemplateMatch)
6861 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6864 /// \brief Determine whether the given template parameter lists are
6867 /// \param New The new template parameter list, typically written in the
6868 /// source code as part of a new template declaration.
6870 /// \param Old The old template parameter list, typically found via
6871 /// name lookup of the template declared with this template parameter
6874 /// \param Complain If true, this routine will produce a diagnostic if
6875 /// the template parameter lists are not equivalent.
6877 /// \param Kind describes how we are to match the template parameter lists.
6879 /// \param TemplateArgLoc If this source location is valid, then we
6880 /// are actually checking the template parameter list of a template
6881 /// argument (New) against the template parameter list of its
6882 /// corresponding template template parameter (Old). We produce
6883 /// slightly different diagnostics in this scenario.
6885 /// \returns True if the template parameter lists are equal, false
6888 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
6889 TemplateParameterList *Old,
6891 TemplateParameterListEqualKind Kind,
6892 SourceLocation TemplateArgLoc) {
6893 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6895 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6901 // C++0x [temp.arg.template]p3:
6902 // A template-argument matches a template template-parameter (call it P)
6903 // when each of the template parameters in the template-parameter-list of
6904 // the template-argument's corresponding class template or alias template
6905 // (call it A) matches the corresponding template parameter in the
6906 // template-parameter-list of P. [...]
6907 TemplateParameterList::iterator NewParm = New->begin();
6908 TemplateParameterList::iterator NewParmEnd = New->end();
6909 for (TemplateParameterList::iterator OldParm = Old->begin(),
6910 OldParmEnd = Old->end();
6911 OldParm != OldParmEnd; ++OldParm) {
6912 if (Kind != TPL_TemplateTemplateArgumentMatch ||
6913 !(*OldParm)->isTemplateParameterPack()) {
6914 if (NewParm == NewParmEnd) {
6916 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6922 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6923 Kind, TemplateArgLoc))
6930 // C++0x [temp.arg.template]p3:
6931 // [...] When P's template- parameter-list contains a template parameter
6932 // pack (14.5.3), the template parameter pack will match zero or more
6933 // template parameters or template parameter packs in the
6934 // template-parameter-list of A with the same type and form as the
6935 // template parameter pack in P (ignoring whether those template
6936 // parameters are template parameter packs).
6937 for (; NewParm != NewParmEnd; ++NewParm) {
6938 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6939 Kind, TemplateArgLoc))
6944 // Make sure we exhausted all of the arguments.
6945 if (NewParm != NewParmEnd) {
6947 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6956 /// \brief Check whether a template can be declared within this scope.
6958 /// If the template declaration is valid in this scope, returns
6959 /// false. Otherwise, issues a diagnostic and returns true.
6961 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
6965 // Find the nearest enclosing declaration scope.
6966 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6967 (S->getFlags() & Scope::TemplateParamScope) != 0)
6971 // A template [...] shall not have C linkage.
6972 DeclContext *Ctx = S->getEntity();
6973 if (Ctx && Ctx->isExternCContext()) {
6974 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6975 << TemplateParams->getSourceRange();
6976 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6977 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6980 Ctx = Ctx->getRedeclContext();
6983 // A template-declaration can appear only as a namespace scope or
6984 // class scope declaration.
6986 if (Ctx->isFileContext())
6988 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6989 // C++ [temp.mem]p2:
6990 // A local class shall not have member templates.
6991 if (RD->isLocalClass())
6992 return Diag(TemplateParams->getTemplateLoc(),
6993 diag::err_template_inside_local_class)
6994 << TemplateParams->getSourceRange();
7000 return Diag(TemplateParams->getTemplateLoc(),
7001 diag::err_template_outside_namespace_or_class_scope)
7002 << TemplateParams->getSourceRange();
7005 /// \brief Determine what kind of template specialization the given declaration
7007 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
7009 return TSK_Undeclared;
7011 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
7012 return Record->getTemplateSpecializationKind();
7013 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
7014 return Function->getTemplateSpecializationKind();
7015 if (VarDecl *Var = dyn_cast<VarDecl>(D))
7016 return Var->getTemplateSpecializationKind();
7018 return TSK_Undeclared;
7021 /// \brief Check whether a specialization is well-formed in the current
7024 /// This routine determines whether a template specialization can be declared
7025 /// in the current context (C++ [temp.expl.spec]p2).
7027 /// \param S the semantic analysis object for which this check is being
7030 /// \param Specialized the entity being specialized or instantiated, which
7031 /// may be a kind of template (class template, function template, etc.) or
7032 /// a member of a class template (member function, static data member,
7035 /// \param PrevDecl the previous declaration of this entity, if any.
7037 /// \param Loc the location of the explicit specialization or instantiation of
7040 /// \param IsPartialSpecialization whether this is a partial specialization of
7041 /// a class template.
7043 /// \returns true if there was an error that we cannot recover from, false
7045 static bool CheckTemplateSpecializationScope(Sema &S,
7046 NamedDecl *Specialized,
7047 NamedDecl *PrevDecl,
7049 bool IsPartialSpecialization) {
7050 // Keep these "kind" numbers in sync with the %select statements in the
7051 // various diagnostics emitted by this routine.
7053 if (isa<ClassTemplateDecl>(Specialized))
7054 EntityKind = IsPartialSpecialization? 1 : 0;
7055 else if (isa<VarTemplateDecl>(Specialized))
7056 EntityKind = IsPartialSpecialization ? 3 : 2;
7057 else if (isa<FunctionTemplateDecl>(Specialized))
7059 else if (isa<CXXMethodDecl>(Specialized))
7061 else if (isa<VarDecl>(Specialized))
7063 else if (isa<RecordDecl>(Specialized))
7065 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
7068 S.Diag(Loc, diag::err_template_spec_unknown_kind)
7069 << S.getLangOpts().CPlusPlus11;
7070 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7074 // C++ [temp.expl.spec]p2:
7075 // An explicit specialization shall be declared in the namespace
7076 // of which the template is a member, or, for member templates, in
7077 // the namespace of which the enclosing class or enclosing class
7078 // template is a member. An explicit specialization of a member
7079 // function, member class or static data member of a class
7080 // template shall be declared in the namespace of which the class
7081 // template is a member. Such a declaration may also be a
7082 // definition. If the declaration is not a definition, the
7083 // specialization may be defined later in the name- space in which
7084 // the explicit specialization was declared, or in a namespace
7085 // that encloses the one in which the explicit specialization was
7087 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7088 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
7093 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
7094 if (S.getLangOpts().MicrosoftExt) {
7095 // Do not warn for class scope explicit specialization during
7096 // instantiation, warning was already emitted during pattern
7097 // semantic analysis.
7098 if (!S.inTemplateInstantiation())
7099 S.Diag(Loc, diag::ext_function_specialization_in_class)
7102 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
7108 if (S.CurContext->isRecord() &&
7109 !S.CurContext->Equals(Specialized->getDeclContext())) {
7110 // Make sure that we're specializing in the right record context.
7111 // Otherwise, things can go horribly wrong.
7112 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
7117 // C++ [temp.class.spec]p6:
7118 // A class template partial specialization may be declared or redeclared
7119 // in any namespace scope in which its definition may be defined (14.5.1
7121 DeclContext *SpecializedContext
7122 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
7123 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
7125 // Make sure that this redeclaration (or definition) occurs in an enclosing
7127 // Note that HandleDeclarator() performs this check for explicit
7128 // specializations of function templates, static data members, and member
7129 // functions, so we skip the check here for those kinds of entities.
7130 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
7131 // Should we refactor that check, so that it occurs later?
7132 if (!DC->Encloses(SpecializedContext) &&
7133 !(isa<FunctionTemplateDecl>(Specialized) ||
7134 isa<FunctionDecl>(Specialized) ||
7135 isa<VarTemplateDecl>(Specialized) ||
7136 isa<VarDecl>(Specialized))) {
7137 if (isa<TranslationUnitDecl>(SpecializedContext))
7138 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
7139 << EntityKind << Specialized;
7140 else if (isa<NamespaceDecl>(SpecializedContext)) {
7141 int Diag = diag::err_template_spec_redecl_out_of_scope;
7142 if (S.getLangOpts().MicrosoftExt)
7143 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
7144 S.Diag(Loc, Diag) << EntityKind << Specialized
7145 << cast<NamedDecl>(SpecializedContext);
7147 llvm_unreachable("unexpected namespace context for specialization");
7149 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7150 } else if ((!PrevDecl ||
7151 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
7152 getTemplateSpecializationKind(PrevDecl) ==
7153 TSK_ImplicitInstantiation)) {
7154 // C++ [temp.exp.spec]p2:
7155 // An explicit specialization shall be declared in the namespace of which
7156 // the template is a member, or, for member templates, in the namespace
7157 // of which the enclosing class or enclosing class template is a member.
7158 // An explicit specialization of a member function, member class or
7159 // static data member of a class template shall be declared in the
7160 // namespace of which the class template is a member.
7162 // C++11 [temp.expl.spec]p2:
7163 // An explicit specialization shall be declared in a namespace enclosing
7164 // the specialized template.
7165 // C++11 [temp.explicit]p3:
7166 // An explicit instantiation shall appear in an enclosing namespace of its
7168 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
7169 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
7170 if (isa<TranslationUnitDecl>(SpecializedContext)) {
7171 assert(!IsCPlusPlus11Extension &&
7172 "DC encloses TU but isn't in enclosing namespace set");
7173 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
7174 << EntityKind << Specialized;
7175 } else if (isa<NamespaceDecl>(SpecializedContext)) {
7177 if (!IsCPlusPlus11Extension)
7178 Diag = diag::err_template_spec_decl_out_of_scope;
7179 else if (!S.getLangOpts().CPlusPlus11)
7180 Diag = diag::ext_template_spec_decl_out_of_scope;
7182 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
7184 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
7187 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
7194 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
7195 if (!E->isTypeDependent())
7196 return SourceLocation();
7197 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7198 Checker.TraverseStmt(E);
7199 if (Checker.MatchLoc.isInvalid())
7200 return E->getSourceRange();
7201 return Checker.MatchLoc;
7204 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7205 if (!TL.getType()->isDependentType())
7206 return SourceLocation();
7207 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7208 Checker.TraverseTypeLoc(TL);
7209 if (Checker.MatchLoc.isInvalid())
7210 return TL.getSourceRange();
7211 return Checker.MatchLoc;
7214 /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
7215 /// that checks non-type template partial specialization arguments.
7216 static bool CheckNonTypeTemplatePartialSpecializationArgs(
7217 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7218 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
7219 for (unsigned I = 0; I != NumArgs; ++I) {
7220 if (Args[I].getKind() == TemplateArgument::Pack) {
7221 if (CheckNonTypeTemplatePartialSpecializationArgs(
7222 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7223 Args[I].pack_size(), IsDefaultArgument))
7229 if (Args[I].getKind() != TemplateArgument::Expression)
7232 Expr *ArgExpr = Args[I].getAsExpr();
7234 // We can have a pack expansion of any of the bullets below.
7235 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7236 ArgExpr = Expansion->getPattern();
7238 // Strip off any implicit casts we added as part of type checking.
7239 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7240 ArgExpr = ICE->getSubExpr();
7242 // C++ [temp.class.spec]p8:
7243 // A non-type argument is non-specialized if it is the name of a
7244 // non-type parameter. All other non-type arguments are
7247 // Below, we check the two conditions that only apply to
7248 // specialized non-type arguments, so skip any non-specialized
7250 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
7251 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
7254 // C++ [temp.class.spec]p9:
7255 // Within the argument list of a class template partial
7256 // specialization, the following restrictions apply:
7257 // -- A partially specialized non-type argument expression
7258 // shall not involve a template parameter of the partial
7259 // specialization except when the argument expression is a
7260 // simple identifier.
7261 // -- The type of a template parameter corresponding to a
7262 // specialized non-type argument shall not be dependent on a
7263 // parameter of the specialization.
7264 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7265 // We implement a compromise between the original rules and DR1315:
7266 // -- A specialized non-type template argument shall not be
7267 // type-dependent and the corresponding template parameter
7268 // shall have a non-dependent type.
7269 SourceRange ParamUseRange =
7270 findTemplateParameterInType(Param->getDepth(), ArgExpr);
7271 if (ParamUseRange.isValid()) {
7272 if (IsDefaultArgument) {
7273 S.Diag(TemplateNameLoc,
7274 diag::err_dependent_non_type_arg_in_partial_spec);
7275 S.Diag(ParamUseRange.getBegin(),
7276 diag::note_dependent_non_type_default_arg_in_partial_spec)
7279 S.Diag(ParamUseRange.getBegin(),
7280 diag::err_dependent_non_type_arg_in_partial_spec)
7286 ParamUseRange = findTemplateParameter(
7287 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
7288 if (ParamUseRange.isValid()) {
7289 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
7290 diag::err_dependent_typed_non_type_arg_in_partial_spec)
7291 << Param->getType();
7292 S.Diag(Param->getLocation(), diag::note_template_param_here)
7293 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7302 /// \brief Check the non-type template arguments of a class template
7303 /// partial specialization according to C++ [temp.class.spec]p9.
7305 /// \param TemplateNameLoc the location of the template name.
7306 /// \param PrimaryTemplate the template parameters of the primary class
7308 /// \param NumExplicit the number of explicitly-specified template arguments.
7309 /// \param TemplateArgs the template arguments of the class template
7310 /// partial specialization.
7312 /// \returns \c true if there was an error, \c false otherwise.
7313 bool Sema::CheckTemplatePartialSpecializationArgs(
7314 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7315 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7316 // We have to be conservative when checking a template in a dependent
7318 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7321 TemplateParameterList *TemplateParams =
7322 PrimaryTemplate->getTemplateParameters();
7323 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7324 NonTypeTemplateParmDecl *Param
7325 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7329 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7330 Param, &TemplateArgs[I],
7331 1, I >= NumExplicit))
7339 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
7341 SourceLocation KWLoc,
7342 SourceLocation ModulePrivateLoc,
7343 TemplateIdAnnotation &TemplateId,
7344 AttributeList *Attr,
7345 MultiTemplateParamsArg
7346 TemplateParameterLists,
7347 SkipBodyInfo *SkipBody) {
7348 assert(TUK != TUK_Reference && "References are not specializations");
7350 CXXScopeSpec &SS = TemplateId.SS;
7352 // NOTE: KWLoc is the location of the tag keyword. This will instead
7353 // store the location of the outermost template keyword in the declaration.
7354 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
7355 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7356 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7357 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7358 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
7360 // Find the class template we're specializing
7361 TemplateName Name = TemplateId.Template.get();
7362 ClassTemplateDecl *ClassTemplate
7363 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7365 if (!ClassTemplate) {
7366 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
7367 << (Name.getAsTemplateDecl() &&
7368 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7372 bool isMemberSpecialization = false;
7373 bool isPartialSpecialization = false;
7375 // Check the validity of the template headers that introduce this
7377 // FIXME: We probably shouldn't complain about these headers for
7378 // friend declarations.
7379 bool Invalid = false;
7380 TemplateParameterList *TemplateParams =
7381 MatchTemplateParametersToScopeSpecifier(
7382 KWLoc, TemplateNameLoc, SS, &TemplateId,
7383 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
7388 if (TemplateParams && TemplateParams->size() > 0) {
7389 isPartialSpecialization = true;
7391 if (TUK == TUK_Friend) {
7392 Diag(KWLoc, diag::err_partial_specialization_friend)
7393 << SourceRange(LAngleLoc, RAngleLoc);
7397 // C++ [temp.class.spec]p10:
7398 // The template parameter list of a specialization shall not
7399 // contain default template argument values.
7400 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7401 Decl *Param = TemplateParams->getParam(I);
7402 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7403 if (TTP->hasDefaultArgument()) {
7404 Diag(TTP->getDefaultArgumentLoc(),
7405 diag::err_default_arg_in_partial_spec);
7406 TTP->removeDefaultArgument();
7408 } else if (NonTypeTemplateParmDecl *NTTP
7409 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7410 if (Expr *DefArg = NTTP->getDefaultArgument()) {
7411 Diag(NTTP->getDefaultArgumentLoc(),
7412 diag::err_default_arg_in_partial_spec)
7413 << DefArg->getSourceRange();
7414 NTTP->removeDefaultArgument();
7417 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
7418 if (TTP->hasDefaultArgument()) {
7419 Diag(TTP->getDefaultArgument().getLocation(),
7420 diag::err_default_arg_in_partial_spec)
7421 << TTP->getDefaultArgument().getSourceRange();
7422 TTP->removeDefaultArgument();
7426 } else if (TemplateParams) {
7427 if (TUK == TUK_Friend)
7428 Diag(KWLoc, diag::err_template_spec_friend)
7429 << FixItHint::CreateRemoval(
7430 SourceRange(TemplateParams->getTemplateLoc(),
7431 TemplateParams->getRAngleLoc()))
7432 << SourceRange(LAngleLoc, RAngleLoc);
7434 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
7437 // Check that the specialization uses the same tag kind as the
7438 // original template.
7439 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7440 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
7441 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7442 Kind, TUK == TUK_Definition, KWLoc,
7443 ClassTemplate->getIdentifier())) {
7444 Diag(KWLoc, diag::err_use_with_wrong_tag)
7446 << FixItHint::CreateReplacement(KWLoc,
7447 ClassTemplate->getTemplatedDecl()->getKindName());
7448 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7449 diag::note_previous_use);
7450 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7453 // Translate the parser's template argument list in our AST format.
7454 TemplateArgumentListInfo TemplateArgs =
7455 makeTemplateArgumentListInfo(*this, TemplateId);
7457 // Check for unexpanded parameter packs in any of the template arguments.
7458 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7459 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
7460 UPPC_PartialSpecialization))
7463 // Check that the template argument list is well-formed for this
7465 SmallVector<TemplateArgument, 4> Converted;
7466 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7467 TemplateArgs, false, Converted))
7470 // Find the class template (partial) specialization declaration that
7471 // corresponds to these arguments.
7472 if (isPartialSpecialization) {
7473 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7474 TemplateArgs.size(), Converted))
7477 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7478 // also do it during instantiation.
7479 bool InstantiationDependent;
7480 if (!Name.isDependent() &&
7481 !TemplateSpecializationType::anyDependentTemplateArguments(
7482 TemplateArgs.arguments(), InstantiationDependent)) {
7483 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7484 << ClassTemplate->getDeclName();
7485 isPartialSpecialization = false;
7489 void *InsertPos = nullptr;
7490 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
7492 if (isPartialSpecialization)
7493 // FIXME: Template parameter list matters, too
7494 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
7496 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
7498 ClassTemplateSpecializationDecl *Specialization = nullptr;
7500 // Check whether we can declare a class template specialization in
7501 // the current scope.
7502 if (TUK != TUK_Friend &&
7503 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7505 isPartialSpecialization))
7508 // The canonical type
7510 if (isPartialSpecialization) {
7511 // Build the canonical type that describes the converted template
7512 // arguments of the class template partial specialization.
7513 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7514 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
7517 if (Context.hasSameType(CanonType,
7518 ClassTemplate->getInjectedClassNameSpecialization())) {
7519 // C++ [temp.class.spec]p9b3:
7521 // -- The argument list of the specialization shall not be identical
7522 // to the implicit argument list of the primary template.
7524 // This rule has since been removed, because it's redundant given DR1495,
7525 // but we keep it because it produces better diagnostics and recovery.
7526 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
7527 << /*class template*/0 << (TUK == TUK_Definition)
7528 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
7529 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7530 ClassTemplate->getIdentifier(),
7534 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
7535 /*FriendLoc*/SourceLocation(),
7536 TemplateParameterLists.size() - 1,
7537 TemplateParameterLists.data());
7540 // Create a new class template partial specialization declaration node.
7541 ClassTemplatePartialSpecializationDecl *PrevPartial
7542 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
7543 ClassTemplatePartialSpecializationDecl *Partial
7544 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
7545 ClassTemplate->getDeclContext(),
7546 KWLoc, TemplateNameLoc,
7553 SetNestedNameSpecifier(Partial, SS);
7554 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
7555 Partial->setTemplateParameterListsInfo(
7556 Context, TemplateParameterLists.drop_back(1));
7560 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
7561 Specialization = Partial;
7563 // If we are providing an explicit specialization of a member class
7564 // template specialization, make a note of that.
7565 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7566 PrevPartial->setMemberSpecialization();
7568 CheckTemplatePartialSpecialization(Partial);
7570 // Create a new class template specialization declaration node for
7571 // this explicit specialization or friend declaration.
7573 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7574 ClassTemplate->getDeclContext(),
7575 KWLoc, TemplateNameLoc,
7579 SetNestedNameSpecifier(Specialization, SS);
7580 if (TemplateParameterLists.size() > 0) {
7581 Specialization->setTemplateParameterListsInfo(Context,
7582 TemplateParameterLists);
7586 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7588 if (CurContext->isDependentContext()) {
7589 // -fms-extensions permits specialization of nested classes without
7590 // fully specializing the outer class(es).
7591 assert(getLangOpts().MicrosoftExt &&
7592 "Only possible with -fms-extensions!");
7593 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7594 CanonType = Context.getTemplateSpecializationType(
7595 CanonTemplate, Converted);
7597 CanonType = Context.getTypeDeclType(Specialization);
7601 // C++ [temp.expl.spec]p6:
7602 // If a template, a member template or the member of a class template is
7603 // explicitly specialized then that specialization shall be declared
7604 // before the first use of that specialization that would cause an implicit
7605 // instantiation to take place, in every translation unit in which such a
7606 // use occurs; no diagnostic is required.
7607 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
7609 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7610 // Is there any previous explicit specialization declaration?
7611 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7618 SourceRange Range(TemplateNameLoc, RAngleLoc);
7619 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7620 << Context.getTypeDeclType(Specialization) << Range;
7622 Diag(PrevDecl->getPointOfInstantiation(),
7623 diag::note_instantiation_required_here)
7624 << (PrevDecl->getTemplateSpecializationKind()
7625 != TSK_ImplicitInstantiation);
7630 // If this is not a friend, note that this is an explicit specialization.
7631 if (TUK != TUK_Friend)
7632 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
7634 // Check that this isn't a redefinition of this specialization.
7635 if (TUK == TUK_Definition) {
7636 RecordDecl *Def = Specialization->getDefinition();
7637 NamedDecl *Hidden = nullptr;
7638 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7639 SkipBody->ShouldSkip = true;
7640 makeMergedDefinitionVisible(Hidden);
7641 // From here on out, treat this as just a redeclaration.
7642 TUK = TUK_Declaration;
7644 SourceRange Range(TemplateNameLoc, RAngleLoc);
7645 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
7646 Diag(Def->getLocation(), diag::note_previous_definition);
7647 Specialization->setInvalidDecl();
7653 ProcessDeclAttributeList(S, Specialization, Attr);
7655 // Add alignment attributes if necessary; these attributes are checked when
7656 // the ASTContext lays out the structure.
7657 if (TUK == TUK_Definition) {
7658 AddAlignmentAttributesForRecord(Specialization);
7659 AddMsStructLayoutForRecord(Specialization);
7662 if (ModulePrivateLoc.isValid())
7663 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7664 << (isPartialSpecialization? 1 : 0)
7665 << FixItHint::CreateRemoval(ModulePrivateLoc);
7667 // Build the fully-sugared type for this class template
7668 // specialization as the user wrote in the specialization
7669 // itself. This means that we'll pretty-print the type retrieved
7670 // from the specialization's declaration the way that the user
7671 // actually wrote the specialization, rather than formatting the
7672 // name based on the "canonical" representation used to store the
7673 // template arguments in the specialization.
7674 TypeSourceInfo *WrittenTy
7675 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7676 TemplateArgs, CanonType);
7677 if (TUK != TUK_Friend) {
7678 Specialization->setTypeAsWritten(WrittenTy);
7679 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
7682 // C++ [temp.expl.spec]p9:
7683 // A template explicit specialization is in the scope of the
7684 // namespace in which the template was defined.
7686 // We actually implement this paragraph where we set the semantic
7687 // context (in the creation of the ClassTemplateSpecializationDecl),
7688 // but we also maintain the lexical context where the actual
7689 // definition occurs.
7690 Specialization->setLexicalDeclContext(CurContext);
7692 // We may be starting the definition of this specialization.
7693 if (TUK == TUK_Definition)
7694 Specialization->startDefinition();
7696 if (TUK == TUK_Friend) {
7697 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7701 Friend->setAccess(AS_public);
7702 CurContext->addDecl(Friend);
7704 // Add the specialization into its lexical context, so that it can
7705 // be seen when iterating through the list of declarations in that
7706 // context. However, specializations are not found by name lookup.
7707 CurContext->addDecl(Specialization);
7709 return Specialization;
7712 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
7713 MultiTemplateParamsArg TemplateParameterLists,
7715 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
7716 ActOnDocumentableDecl(NewDecl);
7720 /// \brief Strips various properties off an implicit instantiation
7721 /// that has just been explicitly specialized.
7722 static void StripImplicitInstantiation(NamedDecl *D) {
7723 D->dropAttr<DLLImportAttr>();
7724 D->dropAttr<DLLExportAttr>();
7726 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7727 FD->setInlineSpecified(false);
7730 /// \brief Compute the diagnostic location for an explicit instantiation
7731 // declaration or definition.
7732 static SourceLocation DiagLocForExplicitInstantiation(
7733 NamedDecl* D, SourceLocation PointOfInstantiation) {
7734 // Explicit instantiations following a specialization have no effect and
7735 // hence no PointOfInstantiation. In that case, walk decl backwards
7736 // until a valid name loc is found.
7737 SourceLocation PrevDiagLoc = PointOfInstantiation;
7738 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7739 Prev = Prev->getPreviousDecl()) {
7740 PrevDiagLoc = Prev->getLocation();
7742 assert(PrevDiagLoc.isValid() &&
7743 "Explicit instantiation without point of instantiation?");
7747 /// \brief Diagnose cases where we have an explicit template specialization
7748 /// before/after an explicit template instantiation, producing diagnostics
7749 /// for those cases where they are required and determining whether the
7750 /// new specialization/instantiation will have any effect.
7752 /// \param NewLoc the location of the new explicit specialization or
7755 /// \param NewTSK the kind of the new explicit specialization or instantiation.
7757 /// \param PrevDecl the previous declaration of the entity.
7759 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7761 /// \param PrevPointOfInstantiation if valid, indicates where the previus
7762 /// declaration was instantiated (either implicitly or explicitly).
7764 /// \param HasNoEffect will be set to true to indicate that the new
7765 /// specialization or instantiation has no effect and should be ignored.
7767 /// \returns true if there was an error that should prevent the introduction of
7768 /// the new declaration into the AST, false otherwise.
7770 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7771 TemplateSpecializationKind NewTSK,
7772 NamedDecl *PrevDecl,
7773 TemplateSpecializationKind PrevTSK,
7774 SourceLocation PrevPointOfInstantiation,
7775 bool &HasNoEffect) {
7776 HasNoEffect = false;
7779 case TSK_Undeclared:
7780 case TSK_ImplicitInstantiation:
7782 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7783 "previous declaration must be implicit!");
7786 case TSK_ExplicitSpecialization:
7788 case TSK_Undeclared:
7789 case TSK_ExplicitSpecialization:
7790 // Okay, we're just specializing something that is either already
7791 // explicitly specialized or has merely been mentioned without any
7795 case TSK_ImplicitInstantiation:
7796 if (PrevPointOfInstantiation.isInvalid()) {
7797 // The declaration itself has not actually been instantiated, so it is
7798 // still okay to specialize it.
7799 StripImplicitInstantiation(PrevDecl);
7805 case TSK_ExplicitInstantiationDeclaration:
7806 case TSK_ExplicitInstantiationDefinition:
7807 assert((PrevTSK == TSK_ImplicitInstantiation ||
7808 PrevPointOfInstantiation.isValid()) &&
7809 "Explicit instantiation without point of instantiation?");
7811 // C++ [temp.expl.spec]p6:
7812 // If a template, a member template or the member of a class template
7813 // is explicitly specialized then that specialization shall be declared
7814 // before the first use of that specialization that would cause an
7815 // implicit instantiation to take place, in every translation unit in
7816 // which such a use occurs; no diagnostic is required.
7817 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7818 // Is there any previous explicit specialization declaration?
7819 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7823 Diag(NewLoc, diag::err_specialization_after_instantiation)
7825 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
7826 << (PrevTSK != TSK_ImplicitInstantiation);
7830 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
7832 case TSK_ExplicitInstantiationDeclaration:
7834 case TSK_ExplicitInstantiationDeclaration:
7835 // This explicit instantiation declaration is redundant (that's okay).
7839 case TSK_Undeclared:
7840 case TSK_ImplicitInstantiation:
7841 // We're explicitly instantiating something that may have already been
7842 // implicitly instantiated; that's fine.
7845 case TSK_ExplicitSpecialization:
7846 // C++0x [temp.explicit]p4:
7847 // For a given set of template parameters, if an explicit instantiation
7848 // of a template appears after a declaration of an explicit
7849 // specialization for that template, the explicit instantiation has no
7854 case TSK_ExplicitInstantiationDefinition:
7855 // C++0x [temp.explicit]p10:
7856 // If an entity is the subject of both an explicit instantiation
7857 // declaration and an explicit instantiation definition in the same
7858 // translation unit, the definition shall follow the declaration.
7860 diag::err_explicit_instantiation_declaration_after_definition);
7862 // Explicit instantiations following a specialization have no effect and
7863 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7864 // until a valid name loc is found.
7865 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7866 diag::note_explicit_instantiation_definition_here);
7871 case TSK_ExplicitInstantiationDefinition:
7873 case TSK_Undeclared:
7874 case TSK_ImplicitInstantiation:
7875 // We're explicitly instantiating something that may have already been
7876 // implicitly instantiated; that's fine.
7879 case TSK_ExplicitSpecialization:
7880 // C++ DR 259, C++0x [temp.explicit]p4:
7881 // For a given set of template parameters, if an explicit
7882 // instantiation of a template appears after a declaration of
7883 // an explicit specialization for that template, the explicit
7884 // instantiation has no effect.
7885 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
7887 Diag(PrevDecl->getLocation(),
7888 diag::note_previous_template_specialization);
7892 case TSK_ExplicitInstantiationDeclaration:
7893 // We're explicity instantiating a definition for something for which we
7894 // were previously asked to suppress instantiations. That's fine.
7896 // C++0x [temp.explicit]p4:
7897 // For a given set of template parameters, if an explicit instantiation
7898 // of a template appears after a declaration of an explicit
7899 // specialization for that template, the explicit instantiation has no
7901 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7902 // Is there any previous explicit specialization declaration?
7903 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7911 case TSK_ExplicitInstantiationDefinition:
7912 // C++0x [temp.spec]p5:
7913 // For a given template and a given set of template-arguments,
7914 // - an explicit instantiation definition shall appear at most once
7917 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7918 Diag(NewLoc, (getLangOpts().MSVCCompat)
7919 ? diag::ext_explicit_instantiation_duplicate
7920 : diag::err_explicit_instantiation_duplicate)
7922 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7923 diag::note_previous_explicit_instantiation);
7929 llvm_unreachable("Missing specialization/instantiation case?");
7932 /// \brief Perform semantic analysis for the given dependent function
7933 /// template specialization.
7935 /// The only possible way to get a dependent function template specialization
7936 /// is with a friend declaration, like so:
7939 /// template \<class T> void foo(T);
7940 /// template \<class T> class A {
7941 /// friend void foo<>(T);
7945 /// There really isn't any useful analysis we can do here, so we
7946 /// just store the information.
7948 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7949 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7950 LookupResult &Previous) {
7951 // Remove anything from Previous that isn't a function template in
7952 // the correct context.
7953 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
7954 LookupResult::Filter F = Previous.makeFilter();
7955 while (F.hasNext()) {
7956 NamedDecl *D = F.next()->getUnderlyingDecl();
7957 if (!isa<FunctionTemplateDecl>(D) ||
7958 !FDLookupContext->InEnclosingNamespaceSetOf(
7959 D->getDeclContext()->getRedeclContext()))
7964 // Should this be diagnosed here?
7965 if (Previous.empty()) return true;
7967 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7968 ExplicitTemplateArgs);
7972 /// \brief Perform semantic analysis for the given function template
7975 /// This routine performs all of the semantic analysis required for an
7976 /// explicit function template specialization. On successful completion,
7977 /// the function declaration \p FD will become a function template
7980 /// \param FD the function declaration, which will be updated to become a
7981 /// function template specialization.
7983 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7984 /// if any. Note that this may be valid info even when 0 arguments are
7985 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7986 /// as it anyway contains info on the angle brackets locations.
7988 /// \param Previous the set of declarations that may be specialized by
7989 /// this function specialization.
7990 bool Sema::CheckFunctionTemplateSpecialization(
7991 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7992 LookupResult &Previous) {
7993 // The set of function template specializations that could match this
7994 // explicit function template specialization.
7995 UnresolvedSet<8> Candidates;
7996 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7997 /*ForTakingAddress=*/false);
7999 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
8000 ConvertedTemplateArgs;
8002 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
8003 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8005 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
8006 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
8007 // Only consider templates found within the same semantic lookup scope as
8009 if (!FDLookupContext->InEnclosingNamespaceSetOf(
8010 Ovl->getDeclContext()->getRedeclContext()))
8013 // When matching a constexpr member function template specialization
8014 // against the primary template, we don't yet know whether the
8015 // specialization has an implicit 'const' (because we don't know whether
8016 // it will be a static member function until we know which template it
8017 // specializes), so adjust it now assuming it specializes this template.
8018 QualType FT = FD->getType();
8019 if (FD->isConstexpr()) {
8020 CXXMethodDecl *OldMD =
8021 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
8022 if (OldMD && OldMD->isConst()) {
8023 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
8024 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8025 EPI.TypeQuals |= Qualifiers::Const;
8026 FT = Context.getFunctionType(FPT->getReturnType(),
8027 FPT->getParamTypes(), EPI);
8031 TemplateArgumentListInfo Args;
8032 if (ExplicitTemplateArgs)
8033 Args = *ExplicitTemplateArgs;
8035 // C++ [temp.expl.spec]p11:
8036 // A trailing template-argument can be left unspecified in the
8037 // template-id naming an explicit function template specialization
8038 // provided it can be deduced from the function argument type.
8039 // Perform template argument deduction to determine whether we may be
8040 // specializing this template.
8041 // FIXME: It is somewhat wasteful to build
8042 TemplateDeductionInfo Info(FailedCandidates.getLocation());
8043 FunctionDecl *Specialization = nullptr;
8044 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
8045 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
8046 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
8048 // Template argument deduction failed; record why it failed, so
8049 // that we can provide nifty diagnostics.
8050 FailedCandidates.addCandidate().set(
8051 I.getPair(), FunTmpl->getTemplatedDecl(),
8052 MakeDeductionFailureInfo(Context, TDK, Info));
8057 // Target attributes are part of the cuda function signature, so
8058 // the deduced template's cuda target must match that of the
8059 // specialization. Given that C++ template deduction does not
8060 // take target attributes into account, we reject candidates
8061 // here that have a different target.
8062 if (LangOpts.CUDA &&
8063 IdentifyCUDATarget(Specialization,
8064 /* IgnoreImplicitHDAttributes = */ true) !=
8065 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
8066 FailedCandidates.addCandidate().set(
8067 I.getPair(), FunTmpl->getTemplatedDecl(),
8068 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8072 // Record this candidate.
8073 if (ExplicitTemplateArgs)
8074 ConvertedTemplateArgs[Specialization] = std::move(Args);
8075 Candidates.addDecl(Specialization, I.getAccess());
8079 // Find the most specialized function template.
8080 UnresolvedSetIterator Result = getMostSpecialized(
8081 Candidates.begin(), Candidates.end(), FailedCandidates,
8083 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
8084 PDiag(diag::err_function_template_spec_ambiguous)
8085 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
8086 PDiag(diag::note_function_template_spec_matched));
8088 if (Result == Candidates.end())
8091 // Ignore access information; it doesn't figure into redeclaration checking.
8092 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8094 FunctionTemplateSpecializationInfo *SpecInfo
8095 = Specialization->getTemplateSpecializationInfo();
8096 assert(SpecInfo && "Function template specialization info missing?");
8098 // Note: do not overwrite location info if previous template
8099 // specialization kind was explicit.
8100 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
8101 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
8102 Specialization->setLocation(FD->getLocation());
8103 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
8104 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
8105 // function can differ from the template declaration with respect to
8106 // the constexpr specifier.
8107 // FIXME: We need an update record for this AST mutation.
8108 // FIXME: What if there are multiple such prior declarations (for instance,
8109 // from different modules)?
8110 Specialization->setConstexpr(FD->isConstexpr());
8113 // FIXME: Check if the prior specialization has a point of instantiation.
8114 // If so, we have run afoul of .
8116 // If this is a friend declaration, then we're not really declaring
8117 // an explicit specialization.
8118 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
8120 // Check the scope of this explicit specialization.
8122 CheckTemplateSpecializationScope(*this,
8123 Specialization->getPrimaryTemplate(),
8124 Specialization, FD->getLocation(),
8128 // C++ [temp.expl.spec]p6:
8129 // If a template, a member template or the member of a class template is
8130 // explicitly specialized then that specialization shall be declared
8131 // before the first use of that specialization that would cause an implicit
8132 // instantiation to take place, in every translation unit in which such a
8133 // use occurs; no diagnostic is required.
8134 bool HasNoEffect = false;
8136 CheckSpecializationInstantiationRedecl(FD->getLocation(),
8137 TSK_ExplicitSpecialization,
8139 SpecInfo->getTemplateSpecializationKind(),
8140 SpecInfo->getPointOfInstantiation(),
8144 // Mark the prior declaration as an explicit specialization, so that later
8145 // clients know that this is an explicit specialization.
8147 // Since explicit specializations do not inherit '=delete' from their
8148 // primary function template - check if the 'specialization' that was
8149 // implicitly generated (during template argument deduction for partial
8150 // ordering) from the most specialized of all the function templates that
8151 // 'FD' could have been specializing, has a 'deleted' definition. If so,
8152 // first check that it was implicitly generated during template argument
8153 // deduction by making sure it wasn't referenced, and then reset the deleted
8154 // flag to not-deleted, so that we can inherit that information from 'FD'.
8155 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
8156 !Specialization->getCanonicalDecl()->isReferenced()) {
8157 // FIXME: This assert will not hold in the presence of modules.
8159 Specialization->getCanonicalDecl() == Specialization &&
8160 "This must be the only existing declaration of this specialization");
8161 // FIXME: We need an update record for this AST mutation.
8162 Specialization->setDeletedAsWritten(false);
8164 // FIXME: We need an update record for this AST mutation.
8165 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8166 MarkUnusedFileScopedDecl(Specialization);
8169 // Turn the given function declaration into a function template
8170 // specialization, with the template arguments from the previous
8172 // Take copies of (semantic and syntactic) template argument lists.
8173 const TemplateArgumentList* TemplArgs = new (Context)
8174 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
8175 FD->setFunctionTemplateSpecialization(
8176 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
8177 SpecInfo->getTemplateSpecializationKind(),
8178 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
8180 // A function template specialization inherits the target attributes
8181 // of its template. (We require the attributes explicitly in the
8182 // code to match, but a template may have implicit attributes by
8183 // virtue e.g. of being constexpr, and it passes these implicit
8184 // attributes on to its specializations.)
8186 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
8188 // The "previous declaration" for this function template specialization is
8189 // the prior function template specialization.
8191 Previous.addDecl(Specialization);
8195 /// \brief Perform semantic analysis for the given non-template member
8198 /// This routine performs all of the semantic analysis required for an
8199 /// explicit member function specialization. On successful completion,
8200 /// the function declaration \p FD will become a member function
8203 /// \param Member the member declaration, which will be updated to become a
8206 /// \param Previous the set of declarations, one of which may be specialized
8207 /// by this function specialization; the set will be modified to contain the
8208 /// redeclared member.
8210 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
8211 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
8213 // Try to find the member we are instantiating.
8214 NamedDecl *FoundInstantiation = nullptr;
8215 NamedDecl *Instantiation = nullptr;
8216 NamedDecl *InstantiatedFrom = nullptr;
8217 MemberSpecializationInfo *MSInfo = nullptr;
8219 if (Previous.empty()) {
8220 // Nowhere to look anyway.
8221 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
8222 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8224 NamedDecl *D = (*I)->getUnderlyingDecl();
8225 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
8226 QualType Adjusted = Function->getType();
8227 if (!hasExplicitCallingConv(Adjusted))
8228 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
8229 if (Context.hasSameType(Adjusted, Method->getType())) {
8230 FoundInstantiation = *I;
8231 Instantiation = Method;
8232 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
8233 MSInfo = Method->getMemberSpecializationInfo();
8238 } else if (isa<VarDecl>(Member)) {
8240 if (Previous.isSingleResult() &&
8241 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
8242 if (PrevVar->isStaticDataMember()) {
8243 FoundInstantiation = Previous.getRepresentativeDecl();
8244 Instantiation = PrevVar;
8245 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
8246 MSInfo = PrevVar->getMemberSpecializationInfo();
8248 } else if (isa<RecordDecl>(Member)) {
8249 CXXRecordDecl *PrevRecord;
8250 if (Previous.isSingleResult() &&
8251 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
8252 FoundInstantiation = Previous.getRepresentativeDecl();
8253 Instantiation = PrevRecord;
8254 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
8255 MSInfo = PrevRecord->getMemberSpecializationInfo();
8257 } else if (isa<EnumDecl>(Member)) {
8259 if (Previous.isSingleResult() &&
8260 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
8261 FoundInstantiation = Previous.getRepresentativeDecl();
8262 Instantiation = PrevEnum;
8263 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8264 MSInfo = PrevEnum->getMemberSpecializationInfo();
8268 if (!Instantiation) {
8269 // There is no previous declaration that matches. Since member
8270 // specializations are always out-of-line, the caller will complain about
8271 // this mismatch later.
8275 // A member specialization in a friend declaration isn't really declaring
8276 // an explicit specialization, just identifying a specific (possibly implicit)
8277 // specialization. Don't change the template specialization kind.
8279 // FIXME: Is this really valid? Other compilers reject.
8280 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8281 // Preserve instantiation information.
8282 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8283 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8284 cast<CXXMethodDecl>(InstantiatedFrom),
8285 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8286 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8287 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8288 cast<CXXRecordDecl>(InstantiatedFrom),
8289 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8293 Previous.addDecl(FoundInstantiation);
8297 // Make sure that this is a specialization of a member.
8298 if (!InstantiatedFrom) {
8299 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8301 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8305 // C++ [temp.expl.spec]p6:
8306 // If a template, a member template or the member of a class template is
8307 // explicitly specialized then that specialization shall be declared
8308 // before the first use of that specialization that would cause an implicit
8309 // instantiation to take place, in every translation unit in which such a
8310 // use occurs; no diagnostic is required.
8311 assert(MSInfo && "Member specialization info missing?");
8313 bool HasNoEffect = false;
8314 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8315 TSK_ExplicitSpecialization,
8317 MSInfo->getTemplateSpecializationKind(),
8318 MSInfo->getPointOfInstantiation(),
8322 // Check the scope of this explicit specialization.
8323 if (CheckTemplateSpecializationScope(*this,
8325 Instantiation, Member->getLocation(),
8329 // Note that this member specialization is an "instantiation of" the
8330 // corresponding member of the original template.
8331 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
8332 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8333 if (InstantiationFunction->getTemplateSpecializationKind() ==
8334 TSK_ImplicitInstantiation) {
8335 // Explicit specializations of member functions of class templates do not
8336 // inherit '=delete' from the member function they are specializing.
8337 if (InstantiationFunction->isDeleted()) {
8338 // FIXME: This assert will not hold in the presence of modules.
8339 assert(InstantiationFunction->getCanonicalDecl() ==
8340 InstantiationFunction);
8341 // FIXME: We need an update record for this AST mutation.
8342 InstantiationFunction->setDeletedAsWritten(false);
8346 MemberFunction->setInstantiationOfMemberFunction(
8347 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8348 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8349 MemberVar->setInstantiationOfStaticDataMember(
8350 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8351 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8352 MemberClass->setInstantiationOfMemberClass(
8353 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8354 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8355 MemberEnum->setInstantiationOfMemberEnum(
8356 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8358 llvm_unreachable("unknown member specialization kind");
8361 // Save the caller the trouble of having to figure out which declaration
8362 // this specialization matches.
8364 Previous.addDecl(FoundInstantiation);
8368 /// Complete the explicit specialization of a member of a class template by
8369 /// updating the instantiated member to be marked as an explicit specialization.
8371 /// \param OrigD The member declaration instantiated from the template.
8372 /// \param Loc The location of the explicit specialization of the member.
8373 template<typename DeclT>
8374 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8375 SourceLocation Loc) {
8376 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8379 // FIXME: Inform AST mutation listeners of this AST mutation.
8380 // FIXME: If there are multiple in-class declarations of the member (from
8381 // multiple modules, or a declaration and later definition of a member type),
8382 // should we update all of them?
8383 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8384 OrigD->setLocation(Loc);
8387 void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8388 LookupResult &Previous) {
8389 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8390 if (Instantiation == Member)
8393 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8394 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8395 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8396 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8397 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8398 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8399 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8400 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8402 llvm_unreachable("unknown member specialization kind");
8405 /// \brief Check the scope of an explicit instantiation.
8407 /// \returns true if a serious error occurs, false otherwise.
8408 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
8409 SourceLocation InstLoc,
8410 bool WasQualifiedName) {
8411 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8412 DeclContext *CurContext = S.CurContext->getRedeclContext();
8414 if (CurContext->isRecord()) {
8415 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8420 // C++11 [temp.explicit]p3:
8421 // An explicit instantiation shall appear in an enclosing namespace of its
8422 // template. If the name declared in the explicit instantiation is an
8423 // unqualified name, the explicit instantiation shall appear in the
8424 // namespace where its template is declared or, if that namespace is inline
8425 // (7.3.1), any namespace from its enclosing namespace set.
8427 // This is DR275, which we do not retroactively apply to C++98/03.
8428 if (WasQualifiedName) {
8429 if (CurContext->Encloses(OrigContext))
8432 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8436 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8437 if (WasQualifiedName)
8439 S.getLangOpts().CPlusPlus11?
8440 diag::err_explicit_instantiation_out_of_scope :
8441 diag::warn_explicit_instantiation_out_of_scope_0x)
8445 S.getLangOpts().CPlusPlus11?
8446 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8447 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8451 S.getLangOpts().CPlusPlus11?
8452 diag::err_explicit_instantiation_must_be_global :
8453 diag::warn_explicit_instantiation_must_be_global_0x)
8455 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
8459 /// \brief Determine whether the given scope specifier has a template-id in it.
8460 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8464 // C++11 [temp.explicit]p3:
8465 // If the explicit instantiation is for a member function, a member class
8466 // or a static data member of a class template specialization, the name of
8467 // the class template specialization in the qualified-id for the member
8468 // name shall be a simple-template-id.
8470 // C++98 has the same restriction, just worded differently.
8471 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8472 NNS = NNS->getPrefix())
8473 if (const Type *T = NNS->getAsType())
8474 if (isa<TemplateSpecializationType>(T))
8480 /// Make a dllexport or dllimport attr on a class template specialization take
8482 static void dllExportImportClassTemplateSpecialization(
8483 Sema &S, ClassTemplateSpecializationDecl *Def) {
8484 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8485 assert(A && "dllExportImportClassTemplateSpecialization called "
8486 "on Def without dllexport or dllimport");
8488 // We reject explicit instantiations in class scope, so there should
8489 // never be any delayed exported classes to worry about.
8490 assert(S.DelayedDllExportClasses.empty() &&
8491 "delayed exports present at explicit instantiation");
8492 S.checkClassLevelDLLAttribute(Def);
8494 // Propagate attribute to base class templates.
8495 for (auto &B : Def->bases()) {
8496 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8497 B.getType()->getAsCXXRecordDecl()))
8498 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
8501 S.referenceDLLExportedClassMethods();
8504 // Explicit instantiation of a class template specialization
8506 Sema::ActOnExplicitInstantiation(Scope *S,
8507 SourceLocation ExternLoc,
8508 SourceLocation TemplateLoc,
8510 SourceLocation KWLoc,
8511 const CXXScopeSpec &SS,
8512 TemplateTy TemplateD,
8513 SourceLocation TemplateNameLoc,
8514 SourceLocation LAngleLoc,
8515 ASTTemplateArgsPtr TemplateArgsIn,
8516 SourceLocation RAngleLoc,
8517 AttributeList *Attr) {
8518 // Find the class template we're specializing
8519 TemplateName Name = TemplateD.get();
8520 TemplateDecl *TD = Name.getAsTemplateDecl();
8521 // Check that the specialization uses the same tag kind as the
8522 // original template.
8523 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8524 assert(Kind != TTK_Enum &&
8525 "Invalid enum tag in class template explicit instantiation!");
8527 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8529 if (!ClassTemplate) {
8530 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8531 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
8532 Diag(TD->getLocation(), diag::note_previous_use);
8536 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
8537 Kind, /*isDefinition*/false, KWLoc,
8538 ClassTemplate->getIdentifier())) {
8539 Diag(KWLoc, diag::err_use_with_wrong_tag)
8541 << FixItHint::CreateReplacement(KWLoc,
8542 ClassTemplate->getTemplatedDecl()->getKindName());
8543 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8544 diag::note_previous_use);
8545 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8548 // C++0x [temp.explicit]p2:
8549 // There are two forms of explicit instantiation: an explicit instantiation
8550 // definition and an explicit instantiation declaration. An explicit
8551 // instantiation declaration begins with the extern keyword. [...]
8552 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8553 ? TSK_ExplicitInstantiationDefinition
8554 : TSK_ExplicitInstantiationDeclaration;
8556 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8557 // Check for dllexport class template instantiation declarations.
8558 for (AttributeList *A = Attr; A; A = A->getNext()) {
8559 if (A->getKind() == AttributeList::AT_DLLExport) {
8561 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8562 Diag(A->getLoc(), diag::note_attribute);
8567 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8569 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8570 Diag(A->getLocation(), diag::note_attribute);
8574 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8575 // instantiation declarations for most purposes.
8576 bool DLLImportExplicitInstantiationDef = false;
8577 if (TSK == TSK_ExplicitInstantiationDefinition &&
8578 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8579 // Check for dllimport class template instantiation definitions.
8581 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
8582 for (AttributeList *A = Attr; A; A = A->getNext()) {
8583 if (A->getKind() == AttributeList::AT_DLLImport)
8585 if (A->getKind() == AttributeList::AT_DLLExport) {
8586 // dllexport trumps dllimport here.
8592 TSK = TSK_ExplicitInstantiationDeclaration;
8593 DLLImportExplicitInstantiationDef = true;
8597 // Translate the parser's template argument list in our AST format.
8598 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8599 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8601 // Check that the template argument list is well-formed for this
8603 SmallVector<TemplateArgument, 4> Converted;
8604 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8605 TemplateArgs, false, Converted))
8608 // Find the class template specialization declaration that
8609 // corresponds to these arguments.
8610 void *InsertPos = nullptr;
8611 ClassTemplateSpecializationDecl *PrevDecl
8612 = ClassTemplate->findSpecialization(Converted, InsertPos);
8614 TemplateSpecializationKind PrevDecl_TSK
8615 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8617 // C++0x [temp.explicit]p2:
8618 // [...] An explicit instantiation shall appear in an enclosing
8619 // namespace of its template. [...]
8621 // This is C++ DR 275.
8622 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8626 ClassTemplateSpecializationDecl *Specialization = nullptr;
8628 bool HasNoEffect = false;
8630 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
8631 PrevDecl, PrevDecl_TSK,
8632 PrevDecl->getPointOfInstantiation(),
8636 // Even though HasNoEffect == true means that this explicit instantiation
8637 // has no effect on semantics, we go on to put its syntax in the AST.
8639 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8640 PrevDecl_TSK == TSK_Undeclared) {
8641 // Since the only prior class template specialization with these
8642 // arguments was referenced but not declared, reuse that
8643 // declaration node as our own, updating the source location
8644 // for the template name to reflect our new declaration.
8645 // (Other source locations will be updated later.)
8646 Specialization = PrevDecl;
8647 Specialization->setLocation(TemplateNameLoc);
8651 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8652 DLLImportExplicitInstantiationDef) {
8653 // The new specialization might add a dllimport attribute.
8654 HasNoEffect = false;
8658 if (!Specialization) {
8659 // Create a new class template specialization declaration node for
8660 // this explicit specialization.
8662 = ClassTemplateSpecializationDecl::Create(Context, Kind,
8663 ClassTemplate->getDeclContext(),
8664 KWLoc, TemplateNameLoc,
8668 SetNestedNameSpecifier(Specialization, SS);
8670 if (!HasNoEffect && !PrevDecl) {
8671 // Insert the new specialization.
8672 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8676 // Build the fully-sugared type for this explicit instantiation as
8677 // the user wrote in the explicit instantiation itself. This means
8678 // that we'll pretty-print the type retrieved from the
8679 // specialization's declaration the way that the user actually wrote
8680 // the explicit instantiation, rather than formatting the name based
8681 // on the "canonical" representation used to store the template
8682 // arguments in the specialization.
8683 TypeSourceInfo *WrittenTy
8684 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8686 Context.getTypeDeclType(Specialization));
8687 Specialization->setTypeAsWritten(WrittenTy);
8689 // Set source locations for keywords.
8690 Specialization->setExternLoc(ExternLoc);
8691 Specialization->setTemplateKeywordLoc(TemplateLoc);
8692 Specialization->setBraceRange(SourceRange());
8694 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
8696 ProcessDeclAttributeList(S, Specialization, Attr);
8698 // Add the explicit instantiation into its lexical context. However,
8699 // since explicit instantiations are never found by name lookup, we
8700 // just put it into the declaration context directly.
8701 Specialization->setLexicalDeclContext(CurContext);
8702 CurContext->addDecl(Specialization);
8704 // Syntax is now OK, so return if it has no other effect on semantics.
8706 // Set the template specialization kind.
8707 Specialization->setTemplateSpecializationKind(TSK);
8708 return Specialization;
8711 // C++ [temp.explicit]p3:
8712 // A definition of a class template or class member template
8713 // shall be in scope at the point of the explicit instantiation of
8714 // the class template or class member template.
8716 // This check comes when we actually try to perform the
8718 ClassTemplateSpecializationDecl *Def
8719 = cast_or_null<ClassTemplateSpecializationDecl>(
8720 Specialization->getDefinition());
8722 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
8723 else if (TSK == TSK_ExplicitInstantiationDefinition) {
8724 MarkVTableUsed(TemplateNameLoc, Specialization, true);
8725 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8728 // Instantiate the members of this class template specialization.
8729 Def = cast_or_null<ClassTemplateSpecializationDecl>(
8730 Specialization->getDefinition());
8732 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
8733 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8734 // TSK_ExplicitInstantiationDefinition
8735 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
8736 (TSK == TSK_ExplicitInstantiationDefinition ||
8737 DLLImportExplicitInstantiationDef)) {
8738 // FIXME: Need to notify the ASTMutationListener that we did this.
8739 Def->setTemplateSpecializationKind(TSK);
8741 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
8742 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8743 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8744 // In the MS ABI, an explicit instantiation definition can add a dll
8745 // attribute to a template with a previous instantiation declaration.
8746 // MinGW doesn't allow this.
8747 auto *A = cast<InheritableAttr>(
8748 getDLLAttr(Specialization)->clone(getASTContext()));
8749 A->setInherited(true);
8751 dllExportImportClassTemplateSpecialization(*this, Def);
8755 // Fix a TSK_ImplicitInstantiation followed by a
8756 // TSK_ExplicitInstantiationDefinition
8757 bool NewlyDLLExported =
8758 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8759 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
8760 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8761 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8762 // In the MS ABI, an explicit instantiation definition can add a dll
8763 // attribute to a template with a previous implicit instantiation.
8764 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8765 // avoid potentially strange codegen behavior. For example, if we extend
8766 // this conditional to dllimport, and we have a source file calling a
8767 // method on an implicitly instantiated template class instance and then
8768 // declaring a dllimport explicit instantiation definition for the same
8769 // template class, the codegen for the method call will not respect the
8770 // dllimport, while it will with cl. The Def will already have the DLL
8771 // attribute, since the Def and Specialization will be the same in the
8772 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8773 // attribute to the Specialization; we just need to make it take effect.
8774 assert(Def == Specialization &&
8775 "Def and Specialization should match for implicit instantiation");
8776 dllExportImportClassTemplateSpecialization(*this, Def);
8779 // Set the template specialization kind. Make sure it is set before
8780 // instantiating the members which will trigger ASTConsumer callbacks.
8781 Specialization->setTemplateSpecializationKind(TSK);
8782 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
8785 // Set the template specialization kind.
8786 Specialization->setTemplateSpecializationKind(TSK);
8789 return Specialization;
8792 // Explicit instantiation of a member class of a class template.
8794 Sema::ActOnExplicitInstantiation(Scope *S,
8795 SourceLocation ExternLoc,
8796 SourceLocation TemplateLoc,
8798 SourceLocation KWLoc,
8800 IdentifierInfo *Name,
8801 SourceLocation NameLoc,
8802 AttributeList *Attr) {
8805 bool IsDependent = false;
8806 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
8807 KWLoc, SS, Name, NameLoc, Attr, AS_none,
8808 /*ModulePrivateLoc=*/SourceLocation(),
8809 MultiTemplateParamsArg(), Owned, IsDependent,
8810 SourceLocation(), false, TypeResult(),
8811 /*IsTypeSpecifier*/false,
8812 /*IsTemplateParamOrArg*/false);
8813 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8818 TagDecl *Tag = cast<TagDecl>(TagD);
8819 assert(!Tag->isEnum() && "shouldn't see enumerations here");
8821 if (Tag->isInvalidDecl())
8824 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8825 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8827 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8828 << Context.getTypeDeclType(Record);
8829 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8833 // C++0x [temp.explicit]p2:
8834 // If the explicit instantiation is for a class or member class, the
8835 // elaborated-type-specifier in the declaration shall include a
8836 // simple-template-id.
8838 // C++98 has the same restriction, just worded differently.
8839 if (!ScopeSpecifierHasTemplateId(SS))
8840 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
8841 << Record << SS.getRange();
8843 // C++0x [temp.explicit]p2:
8844 // There are two forms of explicit instantiation: an explicit instantiation
8845 // definition and an explicit instantiation declaration. An explicit
8846 // instantiation declaration begins with the extern keyword. [...]
8847 TemplateSpecializationKind TSK
8848 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8849 : TSK_ExplicitInstantiationDeclaration;
8851 // C++0x [temp.explicit]p2:
8852 // [...] An explicit instantiation shall appear in an enclosing
8853 // namespace of its template. [...]
8855 // This is C++ DR 275.
8856 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
8858 // Verify that it is okay to explicitly instantiate here.
8859 CXXRecordDecl *PrevDecl
8860 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
8861 if (!PrevDecl && Record->getDefinition())
8864 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
8865 bool HasNoEffect = false;
8866 assert(MSInfo && "No member specialization information?");
8867 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
8869 MSInfo->getTemplateSpecializationKind(),
8870 MSInfo->getPointOfInstantiation(),
8877 CXXRecordDecl *RecordDef
8878 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8880 // C++ [temp.explicit]p3:
8881 // A definition of a member class of a class template shall be in scope
8882 // at the point of an explicit instantiation of the member class.
8884 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
8886 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8887 << 0 << Record->getDeclName() << Record->getDeclContext();
8888 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8892 if (InstantiateClass(NameLoc, Record, Def,
8893 getTemplateInstantiationArgs(Record),
8897 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8903 // Instantiate all of the members of the class.
8904 InstantiateClassMembers(NameLoc, RecordDef,
8905 getTemplateInstantiationArgs(Record), TSK);
8907 if (TSK == TSK_ExplicitInstantiationDefinition)
8908 MarkVTableUsed(NameLoc, RecordDef, true);
8910 // FIXME: We don't have any representation for explicit instantiations of
8911 // member classes. Such a representation is not needed for compilation, but it
8912 // should be available for clients that want to see all of the declarations in
8917 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8918 SourceLocation ExternLoc,
8919 SourceLocation TemplateLoc,
8921 // Explicit instantiations always require a name.
8922 // TODO: check if/when DNInfo should replace Name.
8923 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8924 DeclarationName Name = NameInfo.getName();
8926 if (!D.isInvalidType())
8927 Diag(D.getDeclSpec().getLocStart(),
8928 diag::err_explicit_instantiation_requires_name)
8929 << D.getDeclSpec().getSourceRange()
8930 << D.getSourceRange();
8935 // The scope passed in may not be a decl scope. Zip up the scope tree until
8936 // we find one that is.
8937 while ((S->getFlags() & Scope::DeclScope) == 0 ||
8938 (S->getFlags() & Scope::TemplateParamScope) != 0)
8941 // Determine the type of the declaration.
8942 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8943 QualType R = T->getType();
8948 // A storage-class-specifier shall not be specified in [...] an explicit
8949 // instantiation (14.7.2) directive.
8950 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
8951 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8954 } else if (D.getDeclSpec().getStorageClassSpec()
8955 != DeclSpec::SCS_unspecified) {
8956 // Complain about then remove the storage class specifier.
8957 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8958 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8960 D.getMutableDeclSpec().ClearStorageClassSpecs();
8963 // C++0x [temp.explicit]p1:
8964 // [...] An explicit instantiation of a function template shall not use the
8965 // inline or constexpr specifiers.
8966 // Presumably, this also applies to member functions of class templates as
8968 if (D.getDeclSpec().isInlineSpecified())
8969 Diag(D.getDeclSpec().getInlineSpecLoc(),
8970 getLangOpts().CPlusPlus11 ?
8971 diag::err_explicit_instantiation_inline :
8972 diag::warn_explicit_instantiation_inline_0x)
8973 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8974 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
8975 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8976 // not already specified.
8977 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8978 diag::err_explicit_instantiation_constexpr);
8980 // A deduction guide is not on the list of entities that can be explicitly
8982 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8983 Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
8984 << /*explicit instantiation*/ 0;
8988 // C++0x [temp.explicit]p2:
8989 // There are two forms of explicit instantiation: an explicit instantiation
8990 // definition and an explicit instantiation declaration. An explicit
8991 // instantiation declaration begins with the extern keyword. [...]
8992 TemplateSpecializationKind TSK
8993 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8994 : TSK_ExplicitInstantiationDeclaration;
8996 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
8997 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
8999 if (!R->isFunctionType()) {
9000 // C++ [temp.explicit]p1:
9001 // A [...] static data member of a class template can be explicitly
9002 // instantiated from the member definition associated with its class
9004 // C++1y [temp.explicit]p1:
9005 // A [...] variable [...] template specialization can be explicitly
9006 // instantiated from its template.
9007 if (Previous.isAmbiguous())
9010 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
9011 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
9013 if (!PrevTemplate) {
9014 if (!Prev || !Prev->isStaticDataMember()) {
9015 // We expect to see a data data member here.
9016 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
9018 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9020 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
9024 if (!Prev->getInstantiatedFromStaticDataMember()) {
9025 // FIXME: Check for explicit specialization?
9026 Diag(D.getIdentifierLoc(),
9027 diag::err_explicit_instantiation_data_member_not_instantiated)
9029 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
9030 // FIXME: Can we provide a note showing where this was declared?
9034 // Explicitly instantiate a variable template.
9036 // C++1y [dcl.spec.auto]p6:
9037 // ... A program that uses auto or decltype(auto) in a context not
9038 // explicitly allowed in this section is ill-formed.
9040 // This includes auto-typed variable template instantiations.
9041 if (R->isUndeducedType()) {
9042 Diag(T->getTypeLoc().getLocStart(),
9043 diag::err_auto_not_allowed_var_inst);
9047 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9048 // C++1y [temp.explicit]p3:
9049 // If the explicit instantiation is for a variable, the unqualified-id
9050 // in the declaration shall be a template-id.
9051 Diag(D.getIdentifierLoc(),
9052 diag::err_explicit_instantiation_without_template_id)
9054 Diag(PrevTemplate->getLocation(),
9055 diag::note_explicit_instantiation_here);
9059 // Translate the parser's template argument list into our AST format.
9060 TemplateArgumentListInfo TemplateArgs =
9061 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9063 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
9064 D.getIdentifierLoc(), TemplateArgs);
9065 if (Res.isInvalid())
9068 // Ignore access control bits, we don't need them for redeclaration
9070 Prev = cast<VarDecl>(Res.get());
9073 // C++0x [temp.explicit]p2:
9074 // If the explicit instantiation is for a member function, a member class
9075 // or a static data member of a class template specialization, the name of
9076 // the class template specialization in the qualified-id for the member
9077 // name shall be a simple-template-id.
9079 // C++98 has the same restriction, just worded differently.
9081 // This does not apply to variable template specializations, where the
9082 // template-id is in the unqualified-id instead.
9083 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
9084 Diag(D.getIdentifierLoc(),
9085 diag::ext_explicit_instantiation_without_qualified_id)
9086 << Prev << D.getCXXScopeSpec().getRange();
9088 // Check the scope of this explicit instantiation.
9089 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
9091 // Verify that it is okay to explicitly instantiate here.
9092 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
9093 SourceLocation POI = Prev->getPointOfInstantiation();
9094 bool HasNoEffect = false;
9095 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
9096 PrevTSK, POI, HasNoEffect))
9100 // Instantiate static data member or variable template.
9101 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9103 // Merge attributes.
9104 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
9105 ProcessDeclAttributeList(S, Prev, Attr);
9107 if (TSK == TSK_ExplicitInstantiationDefinition)
9108 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
9111 // Check the new variable specialization against the parsed input.
9112 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
9113 Diag(T->getTypeLoc().getLocStart(),
9114 diag::err_invalid_var_template_spec_type)
9115 << 0 << PrevTemplate << R << Prev->getType();
9116 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
9117 << 2 << PrevTemplate->getDeclName();
9121 // FIXME: Create an ExplicitInstantiation node?
9122 return (Decl*) nullptr;
9125 // If the declarator is a template-id, translate the parser's template
9126 // argument list into our AST format.
9127 bool HasExplicitTemplateArgs = false;
9128 TemplateArgumentListInfo TemplateArgs;
9129 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9130 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
9131 HasExplicitTemplateArgs = true;
9134 // C++ [temp.explicit]p1:
9135 // A [...] function [...] can be explicitly instantiated from its template.
9136 // A member function [...] of a class template can be explicitly
9137 // instantiated from the member definition associated with its class
9139 UnresolvedSet<8> TemplateMatches;
9140 FunctionDecl *NonTemplateMatch = nullptr;
9141 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
9142 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
9143 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
9145 NamedDecl *Prev = *P;
9146 if (!HasExplicitTemplateArgs) {
9147 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
9148 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
9149 /*AdjustExceptionSpec*/true);
9150 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
9151 if (Method->getPrimaryTemplate()) {
9152 TemplateMatches.addDecl(Method, P.getAccess());
9154 // FIXME: Can this assert ever happen? Needs a test.
9155 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
9156 NonTemplateMatch = Method;
9162 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
9166 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9167 FunctionDecl *Specialization = nullptr;
9168 if (TemplateDeductionResult TDK
9169 = DeduceTemplateArguments(FunTmpl,
9170 (HasExplicitTemplateArgs ? &TemplateArgs
9172 R, Specialization, Info)) {
9173 // Keep track of almost-matches.
9174 FailedCandidates.addCandidate()
9175 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
9176 MakeDeductionFailureInfo(Context, TDK, Info));
9181 // Target attributes are part of the cuda function signature, so
9182 // the cuda target of the instantiated function must match that of its
9183 // template. Given that C++ template deduction does not take
9184 // target attributes into account, we reject candidates here that
9185 // have a different target.
9186 if (LangOpts.CUDA &&
9187 IdentifyCUDATarget(Specialization,
9188 /* IgnoreImplicitHDAttributes = */ true) !=
9189 IdentifyCUDATarget(Attr)) {
9190 FailedCandidates.addCandidate().set(
9191 P.getPair(), FunTmpl->getTemplatedDecl(),
9192 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9196 TemplateMatches.addDecl(Specialization, P.getAccess());
9199 FunctionDecl *Specialization = NonTemplateMatch;
9200 if (!Specialization) {
9201 // Find the most specialized function template specialization.
9202 UnresolvedSetIterator Result = getMostSpecialized(
9203 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9204 D.getIdentifierLoc(),
9205 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9206 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9207 PDiag(diag::note_explicit_instantiation_candidate));
9209 if (Result == TemplateMatches.end())
9212 // Ignore access control bits, we don't need them for redeclaration checking.
9213 Specialization = cast<FunctionDecl>(*Result);
9216 // C++11 [except.spec]p4
9217 // In an explicit instantiation an exception-specification may be specified,
9218 // but is not required.
9219 // If an exception-specification is specified in an explicit instantiation
9220 // directive, it shall be compatible with the exception-specifications of
9221 // other declarations of that function.
9222 if (auto *FPT = R->getAs<FunctionProtoType>())
9223 if (FPT->hasExceptionSpec()) {
9225 diag::err_mismatched_exception_spec_explicit_instantiation;
9226 if (getLangOpts().MicrosoftExt)
9227 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9228 bool Result = CheckEquivalentExceptionSpec(
9229 PDiag(DiagID) << Specialization->getType(),
9230 PDiag(diag::note_explicit_instantiation_here),
9231 Specialization->getType()->getAs<FunctionProtoType>(),
9232 Specialization->getLocation(), FPT, D.getLocStart());
9233 // In Microsoft mode, mismatching exception specifications just cause a
9235 if (!getLangOpts().MicrosoftExt && Result)
9239 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
9240 Diag(D.getIdentifierLoc(),
9241 diag::err_explicit_instantiation_member_function_not_instantiated)
9243 << (Specialization->getTemplateSpecializationKind() ==
9244 TSK_ExplicitSpecialization);
9245 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9249 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
9250 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9251 PrevDecl = Specialization;
9254 bool HasNoEffect = false;
9255 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
9257 PrevDecl->getTemplateSpecializationKind(),
9258 PrevDecl->getPointOfInstantiation(),
9262 // FIXME: We may still want to build some representation of this
9263 // explicit specialization.
9265 return (Decl*) nullptr;
9269 ProcessDeclAttributeList(S, Specialization, Attr);
9271 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9272 // instantiation declarations.
9273 if (TSK == TSK_ExplicitInstantiationDefinition &&
9274 Specialization->hasAttr<DLLImportAttr>() &&
9275 Context.getTargetInfo().getCXXABI().isMicrosoft())
9276 TSK = TSK_ExplicitInstantiationDeclaration;
9278 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9280 if (Specialization->isDefined()) {
9281 // Let the ASTConsumer know that this function has been explicitly
9282 // instantiated now, and its linkage might have changed.
9283 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9284 } else if (TSK == TSK_ExplicitInstantiationDefinition)
9285 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
9287 // C++0x [temp.explicit]p2:
9288 // If the explicit instantiation is for a member function, a member class
9289 // or a static data member of a class template specialization, the name of
9290 // the class template specialization in the qualified-id for the member
9291 // name shall be a simple-template-id.
9293 // C++98 has the same restriction, just worded differently.
9294 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
9295 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
9296 D.getCXXScopeSpec().isSet() &&
9297 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
9298 Diag(D.getIdentifierLoc(),
9299 diag::ext_explicit_instantiation_without_qualified_id)
9300 << Specialization << D.getCXXScopeSpec().getRange();
9302 CheckExplicitInstantiationScope(*this,
9303 FunTmpl? (NamedDecl *)FunTmpl
9304 : Specialization->getInstantiatedFromMemberFunction(),
9305 D.getIdentifierLoc(),
9306 D.getCXXScopeSpec().isSet());
9308 // FIXME: Create some kind of ExplicitInstantiationDecl here.
9309 return (Decl*) nullptr;
9313 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9314 const CXXScopeSpec &SS, IdentifierInfo *Name,
9315 SourceLocation TagLoc, SourceLocation NameLoc) {
9316 // This has to hold, because SS is expected to be defined.
9317 assert(Name && "Expected a name in a dependent tag");
9319 NestedNameSpecifier *NNS = SS.getScopeRep();
9323 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9325 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9326 Diag(NameLoc, diag::err_dependent_tag_decl)
9327 << (TUK == TUK_Definition) << Kind << SS.getRange();
9331 // Create the resulting type.
9332 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9333 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
9335 // Create type-source location information for this type.
9337 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
9338 TL.setElaboratedKeywordLoc(TagLoc);
9339 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9340 TL.setNameLoc(NameLoc);
9341 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
9345 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9346 const CXXScopeSpec &SS, const IdentifierInfo &II,
9347 SourceLocation IdLoc) {
9351 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9353 getLangOpts().CPlusPlus11 ?
9354 diag::warn_cxx98_compat_typename_outside_of_template :
9355 diag::ext_typename_outside_of_template)
9356 << FixItHint::CreateRemoval(TypenameLoc);
9358 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9359 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9360 TypenameLoc, QualifierLoc, II, IdLoc);
9364 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9365 if (isa<DependentNameType>(T)) {
9366 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
9367 TL.setElaboratedKeywordLoc(TypenameLoc);
9368 TL.setQualifierLoc(QualifierLoc);
9369 TL.setNameLoc(IdLoc);
9371 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
9372 TL.setElaboratedKeywordLoc(TypenameLoc);
9373 TL.setQualifierLoc(QualifierLoc);
9374 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
9377 return CreateParsedType(T, TSI);
9381 Sema::ActOnTypenameType(Scope *S,
9382 SourceLocation TypenameLoc,
9383 const CXXScopeSpec &SS,
9384 SourceLocation TemplateKWLoc,
9385 TemplateTy TemplateIn,
9386 IdentifierInfo *TemplateII,
9387 SourceLocation TemplateIILoc,
9388 SourceLocation LAngleLoc,
9389 ASTTemplateArgsPtr TemplateArgsIn,
9390 SourceLocation RAngleLoc) {
9391 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9393 getLangOpts().CPlusPlus11 ?
9394 diag::warn_cxx98_compat_typename_outside_of_template :
9395 diag::ext_typename_outside_of_template)
9396 << FixItHint::CreateRemoval(TypenameLoc);
9398 // Strangely, non-type results are not ignored by this lookup, so the
9399 // program is ill-formed if it finds an injected-class-name.
9400 if (TypenameLoc.isValid()) {
9402 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9403 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9405 diag::ext_out_of_line_qualified_id_type_names_constructor)
9406 << TemplateII << 0 /*injected-class-name used as template name*/
9407 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9411 // Translate the parser's template argument list in our AST format.
9412 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9413 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9415 TemplateName Template = TemplateIn.get();
9416 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9417 // Construct a dependent template specialization type.
9418 assert(DTN && "dependent template has non-dependent name?");
9419 assert(DTN->getQualifier() == SS.getScopeRep());
9420 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9421 DTN->getQualifier(),
9422 DTN->getIdentifier(),
9425 // Create source-location information for this type.
9426 TypeLocBuilder Builder;
9427 DependentTemplateSpecializationTypeLoc SpecTL
9428 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
9429 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9430 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
9431 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9432 SpecTL.setTemplateNameLoc(TemplateIILoc);
9433 SpecTL.setLAngleLoc(LAngleLoc);
9434 SpecTL.setRAngleLoc(RAngleLoc);
9435 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9436 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9437 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
9440 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
9444 // Provide source-location information for the template specialization type.
9445 TypeLocBuilder Builder;
9446 TemplateSpecializationTypeLoc SpecTL
9447 = Builder.push<TemplateSpecializationTypeLoc>(T);
9448 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9449 SpecTL.setTemplateNameLoc(TemplateIILoc);
9450 SpecTL.setLAngleLoc(LAngleLoc);
9451 SpecTL.setRAngleLoc(RAngleLoc);
9452 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9453 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9455 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9456 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
9457 TL.setElaboratedKeywordLoc(TypenameLoc);
9458 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9460 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9461 return CreateParsedType(T, TSI);
9465 /// Determine whether this failed name lookup should be treated as being
9466 /// disabled by a usage of std::enable_if.
9467 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
9468 SourceRange &CondRange, Expr *&Cond) {
9469 // We must be looking for a ::type...
9470 if (!II.isStr("type"))
9473 // ... within an explicitly-written template specialization...
9474 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9476 TypeLoc EnableIfTy = NNS.getTypeLoc();
9477 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9478 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9479 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
9481 const TemplateSpecializationType *EnableIfTST =
9482 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
9484 // ... which names a complete class template declaration...
9485 const TemplateDecl *EnableIfDecl =
9486 EnableIfTST->getTemplateName().getAsTemplateDecl();
9487 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9490 // ... called "enable_if".
9491 const IdentifierInfo *EnableIfII =
9492 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9493 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9496 // Assume the first template argument is the condition.
9497 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
9499 // Dig out the condition.
9501 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()
9502 != TemplateArgument::Expression)
9505 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();
9507 // Ignore Boolean literals; they add no value.
9508 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))
9514 /// \brief Build the type that describes a C++ typename specifier,
9515 /// e.g., "typename T::type".
9517 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
9518 SourceLocation KeywordLoc,
9519 NestedNameSpecifierLoc QualifierLoc,
9520 const IdentifierInfo &II,
9521 SourceLocation IILoc) {
9523 SS.Adopt(QualifierLoc);
9525 DeclContext *Ctx = computeDeclContext(SS);
9527 // If the nested-name-specifier is dependent and couldn't be
9528 // resolved to a type, build a typename type.
9529 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
9530 return Context.getDependentNameType(Keyword,
9531 QualifierLoc.getNestedNameSpecifier(),
9535 // If the nested-name-specifier refers to the current instantiation,
9536 // the "typename" keyword itself is superfluous. In C++03, the
9537 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9538 // allows such extraneous "typename" keywords, and we retroactively
9539 // apply this DR to C++03 code with only a warning. In any case we continue.
9541 if (RequireCompleteDeclContext(SS, Ctx))
9544 DeclarationName Name(&II);
9545 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
9546 LookupQualifiedName(Result, Ctx, SS);
9547 unsigned DiagID = 0;
9548 Decl *Referenced = nullptr;
9549 switch (Result.getResultKind()) {
9550 case LookupResult::NotFound: {
9551 // If we're looking up 'type' within a template named 'enable_if', produce
9552 // a more specific diagnostic.
9553 SourceRange CondRange;
9554 Expr *Cond = nullptr;
9555 if (isEnableIf(QualifierLoc, II, CondRange, Cond)) {
9556 // If we have a condition, narrow it down to the specific failed
9560 std::string FailedDescription;
9561 std::tie(FailedCond, FailedDescription) =
9562 findFailedBooleanCondition(Cond, /*AllowTopLevelCond=*/true);
9564 Diag(FailedCond->getExprLoc(),
9565 diag::err_typename_nested_not_found_requirement)
9566 << FailedDescription
9567 << FailedCond->getSourceRange();
9571 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
9572 << Ctx << CondRange;
9576 DiagID = diag::err_typename_nested_not_found;
9580 case LookupResult::FoundUnresolvedValue: {
9581 // We found a using declaration that is a value. Most likely, the using
9582 // declaration itself is meant to have the 'typename' keyword.
9583 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9585 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9586 << Name << Ctx << FullRange;
9587 if (UnresolvedUsingValueDecl *Using
9588 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
9589 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
9590 Diag(Loc, diag::note_using_value_decl_missing_typename)
9591 << FixItHint::CreateInsertion(Loc, "typename ");
9594 // Fall through to create a dependent typename type, from which we can recover
9598 case LookupResult::NotFoundInCurrentInstantiation:
9599 // Okay, it's a member of an unknown instantiation.
9600 return Context.getDependentNameType(Keyword,
9601 QualifierLoc.getNestedNameSpecifier(),
9604 case LookupResult::Found:
9605 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
9606 // C++ [class.qual]p2:
9607 // In a lookup in which function names are not ignored and the
9608 // nested-name-specifier nominates a class C, if the name specified
9609 // after the nested-name-specifier, when looked up in C, is the
9610 // injected-class-name of C [...] then the name is instead considered
9611 // to name the constructor of class C.
9613 // Unlike in an elaborated-type-specifier, function names are not ignored
9614 // in typename-specifier lookup. However, they are ignored in all the
9615 // contexts where we form a typename type with no keyword (that is, in
9616 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9618 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9619 // ignore functions, but that appears to be an oversight.
9620 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9621 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9622 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9623 FoundRD->isInjectedClassName() &&
9624 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9625 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9626 << &II << 1 << 0 /*'typename' keyword used*/;
9628 // We found a type. Build an ElaboratedType, since the
9629 // typename-specifier was just sugar.
9630 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
9631 return Context.getElaboratedType(Keyword,
9632 QualifierLoc.getNestedNameSpecifier(),
9633 Context.getTypeDeclType(Type));
9636 // C++ [dcl.type.simple]p2:
9637 // A type-specifier of the form
9638 // typename[opt] nested-name-specifier[opt] template-name
9639 // is a placeholder for a deduced class type [...].
9640 if (getLangOpts().CPlusPlus17) {
9641 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9642 return Context.getElaboratedType(
9643 Keyword, QualifierLoc.getNestedNameSpecifier(),
9644 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9645 QualType(), false));
9649 DiagID = diag::err_typename_nested_not_type;
9650 Referenced = Result.getFoundDecl();
9653 case LookupResult::FoundOverloaded:
9654 DiagID = diag::err_typename_nested_not_type;
9655 Referenced = *Result.begin();
9658 case LookupResult::Ambiguous:
9662 // If we get here, it's because name lookup did not find a
9663 // type. Emit an appropriate diagnostic and return an error.
9664 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9666 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
9668 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9674 // See Sema::RebuildTypeInCurrentInstantiation
9675 class CurrentInstantiationRebuilder
9676 : public TreeTransform<CurrentInstantiationRebuilder> {
9678 DeclarationName Entity;
9681 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
9683 CurrentInstantiationRebuilder(Sema &SemaRef,
9685 DeclarationName Entity)
9686 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
9687 Loc(Loc), Entity(Entity) { }
9689 /// \brief Determine whether the given type \p T has already been
9692 /// For the purposes of type reconstruction, a type has already been
9693 /// transformed if it is NULL or if it is not dependent.
9694 bool AlreadyTransformed(QualType T) {
9695 return T.isNull() || !T->isDependentType();
9698 /// \brief Returns the location of the entity whose type is being
9700 SourceLocation getBaseLocation() { return Loc; }
9702 /// \brief Returns the name of the entity whose type is being rebuilt.
9703 DeclarationName getBaseEntity() { return Entity; }
9705 /// \brief Sets the "base" location and entity when that
9706 /// information is known based on another transformation.
9707 void setBase(SourceLocation Loc, DeclarationName Entity) {
9709 this->Entity = Entity;
9712 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9713 // Lambdas never need to be transformed.
9717 } // end anonymous namespace
9719 /// \brief Rebuilds a type within the context of the current instantiation.
9721 /// The type \p T is part of the type of an out-of-line member definition of
9722 /// a class template (or class template partial specialization) that was parsed
9723 /// and constructed before we entered the scope of the class template (or
9724 /// partial specialization thereof). This routine will rebuild that type now
9725 /// that we have entered the declarator's scope, which may produce different
9726 /// canonical types, e.g.,
9729 /// template<typename T>
9731 /// typedef T* pointer;
9735 /// template<typename T>
9736 /// typename X<T>::pointer X<T>::data() { ... }
9739 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
9740 /// since we do not know that we can look into X<T> when we parsed the type.
9741 /// This function will rebuild the type, performing the lookup of "pointer"
9742 /// in X<T> and returning an ElaboratedType whose canonical type is the same
9743 /// as the canonical type of T*, allowing the return types of the out-of-line
9744 /// definition and the declaration to match.
9745 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9747 DeclarationName Name) {
9748 if (!T || !T->getType()->isDependentType())
9751 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9752 return Rebuilder.TransformType(T);
9755 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
9756 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9758 return Rebuilder.TransformExpr(E);
9761 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
9765 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9766 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9768 NestedNameSpecifierLoc Rebuilt
9769 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
9777 /// \brief Rebuild the template parameters now that we know we're in a current
9779 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9780 TemplateParameterList *Params) {
9781 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9782 Decl *Param = Params->getParam(I);
9784 // There is nothing to rebuild in a type parameter.
9785 if (isa<TemplateTypeParmDecl>(Param))
9788 // Rebuild the template parameter list of a template template parameter.
9789 if (TemplateTemplateParmDecl *TTP
9790 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9791 if (RebuildTemplateParamsInCurrentInstantiation(
9792 TTP->getTemplateParameters()))
9798 // Rebuild the type of a non-type template parameter.
9799 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
9800 TypeSourceInfo *NewTSI
9801 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9802 NTTP->getLocation(),
9803 NTTP->getDeclName());
9807 if (NewTSI != NTTP->getTypeSourceInfo()) {
9808 NTTP->setTypeSourceInfo(NewTSI);
9809 NTTP->setType(NewTSI->getType());
9816 /// \brief Produces a formatted string that describes the binding of
9817 /// template parameters to template arguments.
9819 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9820 const TemplateArgumentList &Args) {
9821 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
9825 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9826 const TemplateArgument *Args,
9828 SmallString<128> Str;
9829 llvm::raw_svector_ostream Out(Str);
9831 if (!Params || Params->size() == 0 || NumArgs == 0)
9832 return std::string();
9834 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9843 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
9844 Out << Id->getName();
9850 Args[I].print(getPrintingPolicy(), Out);
9857 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9858 CachedTokens &Toks) {
9862 auto LPT = llvm::make_unique<LateParsedTemplate>();
9864 // Take tokens to avoid allocations
9865 LPT->Toks.swap(Toks);
9867 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
9869 FD->setLateTemplateParsed(true);
9872 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9875 FD->setLateTemplateParsed(false);
9878 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9879 DeclContext *DC = CurContext;
9882 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9883 const FunctionDecl *FD = RD->isLocalClass();
9884 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9885 } else if (DC->isTranslationUnit() || DC->isNamespace())
9888 DC = DC->getParent();
9894 /// \brief Walk the path from which a declaration was instantiated, and check
9895 /// that every explicit specialization along that path is visible. This enforces
9896 /// C++ [temp.expl.spec]/6:
9898 /// If a template, a member template or a member of a class template is
9899 /// explicitly specialized then that specialization shall be declared before
9900 /// the first use of that specialization that would cause an implicit
9901 /// instantiation to take place, in every translation unit in which such a
9902 /// use occurs; no diagnostic is required.
9904 /// and also C++ [temp.class.spec]/1:
9906 /// A partial specialization shall be declared before the first use of a
9907 /// class template specialization that would make use of the partial
9908 /// specialization as the result of an implicit or explicit instantiation
9909 /// in every translation unit in which such a use occurs; no diagnostic is
9911 class ExplicitSpecializationVisibilityChecker {
9914 llvm::SmallVector<Module *, 8> Modules;
9917 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9920 void check(NamedDecl *ND) {
9921 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9922 return checkImpl(FD);
9923 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9924 return checkImpl(RD);
9925 if (auto *VD = dyn_cast<VarDecl>(ND))
9926 return checkImpl(VD);
9927 if (auto *ED = dyn_cast<EnumDecl>(ND))
9928 return checkImpl(ED);
9932 void diagnose(NamedDecl *D, bool IsPartialSpec) {
9933 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9934 : Sema::MissingImportKind::ExplicitSpecialization;
9935 const bool Recover = true;
9937 // If we got a custom set of modules (because only a subset of the
9938 // declarations are interesting), use them, otherwise let
9939 // diagnoseMissingImport intelligently pick some.
9940 if (Modules.empty())
9941 S.diagnoseMissingImport(Loc, D, Kind, Recover);
9943 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9946 // Check a specific declaration. There are three problematic cases:
9948 // 1) The declaration is an explicit specialization of a template
9950 // 2) The declaration is an explicit specialization of a member of an
9952 // 3) The declaration is an instantiation of a template, and that template
9953 // is an explicit specialization of a member of a templated class.
9955 // We don't need to go any deeper than that, as the instantiation of the
9956 // surrounding class / etc is not triggered by whatever triggered this
9957 // instantiation, and thus should be checked elsewhere.
9958 template<typename SpecDecl>
9959 void checkImpl(SpecDecl *Spec) {
9960 bool IsHiddenExplicitSpecialization = false;
9961 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
9962 IsHiddenExplicitSpecialization =
9963 Spec->getMemberSpecializationInfo()
9964 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
9965 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
9967 checkInstantiated(Spec);
9970 if (IsHiddenExplicitSpecialization)
9971 diagnose(Spec->getMostRecentDecl(), false);
9974 void checkInstantiated(FunctionDecl *FD) {
9975 if (auto *TD = FD->getPrimaryTemplate())
9979 void checkInstantiated(CXXRecordDecl *RD) {
9980 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
9984 auto From = SD->getSpecializedTemplateOrPartial();
9985 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
9988 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
9989 if (!S.hasVisibleDeclaration(TD))
9995 void checkInstantiated(VarDecl *RD) {
9996 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
10000 auto From = SD->getSpecializedTemplateOrPartial();
10001 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
10003 else if (auto *TD =
10004 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
10005 if (!S.hasVisibleDeclaration(TD))
10006 diagnose(TD, true);
10011 void checkInstantiated(EnumDecl *FD) {}
10013 template<typename TemplDecl>
10014 void checkTemplate(TemplDecl *TD) {
10015 if (TD->isMemberSpecialization()) {
10016 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
10017 diagnose(TD->getMostRecentDecl(), false);
10021 } // end anonymous namespace
10023 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
10024 if (!getLangOpts().Modules)
10027 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
10030 /// \brief Check whether a template partial specialization that we've discovered
10031 /// is hidden, and produce suitable diagnostics if so.
10032 void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
10034 llvm::SmallVector<Module *, 8> Modules;
10035 if (!hasVisibleDeclaration(Spec, &Modules))
10036 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
10037 MissingImportKind::PartialSpecialization,