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 UnqualifiedId::IK_Identifier:
173 TName = DeclarationName(Name.Identifier);
176 case UnqualifiedId::IK_OperatorFunctionId:
177 TName = Context.DeclarationNames.getCXXOperatorName(
178 Name.OperatorFunctionId.Operator);
181 case UnqualifiedId::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 /// ActOnDependentIdExpression - Handle a dependent id-expression that
459 /// was just parsed. This is only possible with an explicit scope
460 /// specifier naming a dependent type.
462 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
463 SourceLocation TemplateKWLoc,
464 const DeclarationNameInfo &NameInfo,
465 bool isAddressOfOperand,
466 const TemplateArgumentListInfo *TemplateArgs) {
467 DeclContext *DC = getFunctionLevelDeclContext();
469 // C++11 [expr.prim.general]p12:
470 // An id-expression that denotes a non-static data member or non-static
471 // member function of a class can only be used:
473 // - if that id-expression denotes a non-static data member and it
474 // appears in an unevaluated operand.
476 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
477 // CXXDependentScopeMemberExpr. The former can instantiate to either
478 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
479 // always a MemberExpr.
480 bool MightBeCxx11UnevalField =
481 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
483 // Check if the nested name specifier is an enum type.
485 if (NestedNameSpecifier *NNS = SS.getScopeRep())
486 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
488 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
489 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
490 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
492 // Since the 'this' expression is synthesized, we don't need to
493 // perform the double-lookup check.
494 NamedDecl *FirstQualifierInScope = nullptr;
496 return CXXDependentScopeMemberExpr::Create(
497 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
498 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
499 FirstQualifierInScope, NameInfo, TemplateArgs);
502 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
506 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
507 SourceLocation TemplateKWLoc,
508 const DeclarationNameInfo &NameInfo,
509 const TemplateArgumentListInfo *TemplateArgs) {
510 return DependentScopeDeclRefExpr::Create(
511 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
516 /// Determine whether we would be unable to instantiate this template (because
517 /// it either has no definition, or is in the process of being instantiated).
518 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
519 NamedDecl *Instantiation,
520 bool InstantiatedFromMember,
521 const NamedDecl *Pattern,
522 const NamedDecl *PatternDef,
523 TemplateSpecializationKind TSK,
524 bool Complain /*= true*/) {
525 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
526 isa<VarDecl>(Instantiation));
528 bool IsEntityBeingDefined = false;
529 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
530 IsEntityBeingDefined = TD->isBeingDefined();
532 if (PatternDef && !IsEntityBeingDefined) {
533 NamedDecl *SuggestedDef = nullptr;
534 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
535 /*OnlyNeedComplete*/false)) {
536 // If we're allowed to diagnose this and recover, do so.
537 bool Recover = Complain && !isSFINAEContext();
539 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
540 Sema::MissingImportKind::Definition, Recover);
546 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
549 llvm::Optional<unsigned> Note;
550 QualType InstantiationTy;
551 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
552 InstantiationTy = Context.getTypeDeclType(TD);
554 Diag(PointOfInstantiation,
555 diag::err_template_instantiate_within_definition)
556 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
558 // Not much point in noting the template declaration here, since
559 // we're lexically inside it.
560 Instantiation->setInvalidDecl();
561 } else if (InstantiatedFromMember) {
562 if (isa<FunctionDecl>(Instantiation)) {
563 Diag(PointOfInstantiation,
564 diag::err_explicit_instantiation_undefined_member)
565 << /*member function*/ 1 << Instantiation->getDeclName()
566 << Instantiation->getDeclContext();
567 Note = diag::note_explicit_instantiation_here;
569 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
570 Diag(PointOfInstantiation,
571 diag::err_implicit_instantiate_member_undefined)
573 Note = diag::note_member_declared_at;
576 if (isa<FunctionDecl>(Instantiation)) {
577 Diag(PointOfInstantiation,
578 diag::err_explicit_instantiation_undefined_func_template)
580 Note = diag::note_explicit_instantiation_here;
581 } else if (isa<TagDecl>(Instantiation)) {
582 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
583 << (TSK != TSK_ImplicitInstantiation)
585 Note = diag::note_template_decl_here;
587 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
588 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
589 Diag(PointOfInstantiation,
590 diag::err_explicit_instantiation_undefined_var_template)
592 Instantiation->setInvalidDecl();
594 Diag(PointOfInstantiation,
595 diag::err_explicit_instantiation_undefined_member)
596 << /*static data member*/ 2 << Instantiation->getDeclName()
597 << Instantiation->getDeclContext();
598 Note = diag::note_explicit_instantiation_here;
601 if (Note) // Diagnostics were emitted.
602 Diag(Pattern->getLocation(), Note.getValue());
604 // In general, Instantiation isn't marked invalid to get more than one
605 // error for multiple undefined instantiations. But the code that does
606 // explicit declaration -> explicit definition conversion can't handle
607 // invalid declarations, so mark as invalid in that case.
608 if (TSK == TSK_ExplicitInstantiationDeclaration)
609 Instantiation->setInvalidDecl();
613 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
614 /// that the template parameter 'PrevDecl' is being shadowed by a new
615 /// declaration at location Loc. Returns true to indicate that this is
616 /// an error, and false otherwise.
617 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
618 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
620 // Microsoft Visual C++ permits template parameters to be shadowed.
621 if (getLangOpts().MicrosoftExt)
624 // C++ [temp.local]p4:
625 // A template-parameter shall not be redeclared within its
626 // scope (including nested scopes).
627 Diag(Loc, diag::err_template_param_shadow)
628 << cast<NamedDecl>(PrevDecl)->getDeclName();
629 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
632 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
633 /// the parameter D to reference the templated declaration and return a pointer
634 /// to the template declaration. Otherwise, do nothing to D and return null.
635 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
636 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
637 D = Temp->getTemplatedDecl();
643 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
644 SourceLocation EllipsisLoc) const {
645 assert(Kind == Template &&
646 "Only template template arguments can be pack expansions here");
647 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
648 "Template template argument pack expansion without packs");
649 ParsedTemplateArgument Result(*this);
650 Result.EllipsisLoc = EllipsisLoc;
654 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
655 const ParsedTemplateArgument &Arg) {
657 switch (Arg.getKind()) {
658 case ParsedTemplateArgument::Type: {
660 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
662 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
663 return TemplateArgumentLoc(TemplateArgument(T), DI);
666 case ParsedTemplateArgument::NonType: {
667 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
668 return TemplateArgumentLoc(TemplateArgument(E), E);
671 case ParsedTemplateArgument::Template: {
672 TemplateName Template = Arg.getAsTemplate().get();
673 TemplateArgument TArg;
674 if (Arg.getEllipsisLoc().isValid())
675 TArg = TemplateArgument(Template, Optional<unsigned int>());
678 return TemplateArgumentLoc(TArg,
679 Arg.getScopeSpec().getWithLocInContext(
682 Arg.getEllipsisLoc());
686 llvm_unreachable("Unhandled parsed template argument");
689 /// \brief Translates template arguments as provided by the parser
690 /// into template arguments used by semantic analysis.
691 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
692 TemplateArgumentListInfo &TemplateArgs) {
693 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
694 TemplateArgs.addArgument(translateTemplateArgument(*this,
698 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
700 IdentifierInfo *Name) {
701 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
702 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
703 if (PrevDecl && PrevDecl->isTemplateParameter())
704 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
707 /// ActOnTypeParameter - Called when a C++ template type parameter
708 /// (e.g., "typename T") has been parsed. Typename specifies whether
709 /// the keyword "typename" was used to declare the type parameter
710 /// (otherwise, "class" was used), and KeyLoc is the location of the
711 /// "class" or "typename" keyword. ParamName is the name of the
712 /// parameter (NULL indicates an unnamed template parameter) and
713 /// ParamNameLoc is the location of the parameter name (if any).
714 /// If the type parameter has a default argument, it will be added
715 /// later via ActOnTypeParameterDefault.
716 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
717 SourceLocation EllipsisLoc,
718 SourceLocation KeyLoc,
719 IdentifierInfo *ParamName,
720 SourceLocation ParamNameLoc,
721 unsigned Depth, unsigned Position,
722 SourceLocation EqualLoc,
723 ParsedType DefaultArg) {
724 assert(S->isTemplateParamScope() &&
725 "Template type parameter not in template parameter scope!");
727 SourceLocation Loc = ParamNameLoc;
731 bool IsParameterPack = EllipsisLoc.isValid();
732 TemplateTypeParmDecl *Param
733 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
734 KeyLoc, Loc, Depth, Position, ParamName,
735 Typename, IsParameterPack);
736 Param->setAccess(AS_public);
739 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
741 // Add the template parameter into the current scope.
743 IdResolver.AddDecl(Param);
746 // C++0x [temp.param]p9:
747 // A default template-argument may be specified for any kind of
748 // template-parameter that is not a template parameter pack.
749 if (DefaultArg && IsParameterPack) {
750 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
751 DefaultArg = nullptr;
754 // Handle the default argument, if provided.
756 TypeSourceInfo *DefaultTInfo;
757 GetTypeFromParser(DefaultArg, &DefaultTInfo);
759 assert(DefaultTInfo && "expected source information for type");
761 // Check for unexpanded parameter packs.
762 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
763 UPPC_DefaultArgument))
766 // Check the template argument itself.
767 if (CheckTemplateArgument(Param, DefaultTInfo)) {
768 Param->setInvalidDecl();
772 Param->setDefaultArgument(DefaultTInfo);
778 /// \brief Check that the type of a non-type template parameter is
781 /// \returns the (possibly-promoted) parameter type if valid;
782 /// otherwise, produces a diagnostic and returns a NULL type.
783 QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
784 SourceLocation Loc) {
785 if (TSI->getType()->isUndeducedType()) {
786 // C++1z [temp.dep.expr]p3:
787 // An id-expression is type-dependent if it contains
788 // - an identifier associated by name lookup with a non-type
789 // template-parameter declared with a type that contains a
790 // placeholder type (7.1.7.4),
791 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
794 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
797 QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
798 SourceLocation Loc) {
799 // We don't allow variably-modified types as the type of non-type template
801 if (T->isVariablyModifiedType()) {
802 Diag(Loc, diag::err_variably_modified_nontype_template_param)
807 // C++ [temp.param]p4:
809 // A non-type template-parameter shall have one of the following
810 // (optionally cv-qualified) types:
812 // -- integral or enumeration type,
813 if (T->isIntegralOrEnumerationType() ||
814 // -- pointer to object or pointer to function,
815 T->isPointerType() ||
816 // -- reference to object or reference to function,
817 T->isReferenceType() ||
818 // -- pointer to member,
819 T->isMemberPointerType() ||
820 // -- std::nullptr_t.
821 T->isNullPtrType() ||
822 // If T is a dependent type, we can't do the check now, so we
823 // assume that it is well-formed.
824 T->isDependentType() ||
825 // Allow use of auto in template parameter declarations.
826 T->isUndeducedType()) {
827 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
828 // are ignored when determining its type.
829 return T.getUnqualifiedType();
832 // C++ [temp.param]p8:
834 // A non-type template-parameter of type "array of T" or
835 // "function returning T" is adjusted to be of type "pointer to
836 // T" or "pointer to function returning T", respectively.
837 else if (T->isArrayType() || T->isFunctionType())
838 return Context.getDecayedType(T);
840 Diag(Loc, diag::err_template_nontype_parm_bad_type)
846 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
849 SourceLocation EqualLoc,
851 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
853 if (TInfo->getType()->isUndeducedType()) {
854 Diag(D.getIdentifierLoc(),
855 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
856 << QualType(TInfo->getType()->getContainedAutoType(), 0);
859 assert(S->isTemplateParamScope() &&
860 "Non-type template parameter not in template parameter scope!");
861 bool Invalid = false;
863 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
865 T = Context.IntTy; // Recover with an 'int' type.
869 IdentifierInfo *ParamName = D.getIdentifier();
870 bool IsParameterPack = D.hasEllipsis();
871 NonTypeTemplateParmDecl *Param
872 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
874 D.getIdentifierLoc(),
875 Depth, Position, ParamName, T,
876 IsParameterPack, TInfo);
877 Param->setAccess(AS_public);
880 Param->setInvalidDecl();
883 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
886 // Add the template parameter into the current scope.
888 IdResolver.AddDecl(Param);
891 // C++0x [temp.param]p9:
892 // A default template-argument may be specified for any kind of
893 // template-parameter that is not a template parameter pack.
894 if (Default && IsParameterPack) {
895 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
899 // Check the well-formedness of the default template argument, if provided.
901 // Check for unexpanded parameter packs.
902 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
905 TemplateArgument Converted;
906 ExprResult DefaultRes =
907 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
908 if (DefaultRes.isInvalid()) {
909 Param->setInvalidDecl();
912 Default = DefaultRes.get();
914 Param->setDefaultArgument(Default);
920 /// ActOnTemplateTemplateParameter - Called when a C++ template template
921 /// parameter (e.g. T in template <template \<typename> class T> class array)
922 /// has been parsed. S is the current scope.
923 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
924 SourceLocation TmpLoc,
925 TemplateParameterList *Params,
926 SourceLocation EllipsisLoc,
927 IdentifierInfo *Name,
928 SourceLocation NameLoc,
931 SourceLocation EqualLoc,
932 ParsedTemplateArgument Default) {
933 assert(S->isTemplateParamScope() &&
934 "Template template parameter not in template parameter scope!");
936 // Construct the parameter object.
937 bool IsParameterPack = EllipsisLoc.isValid();
938 TemplateTemplateParmDecl *Param =
939 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
940 NameLoc.isInvalid()? TmpLoc : NameLoc,
941 Depth, Position, IsParameterPack,
943 Param->setAccess(AS_public);
945 // If the template template parameter has a name, then link the identifier
946 // into the scope and lookup mechanisms.
948 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
951 IdResolver.AddDecl(Param);
954 if (Params->size() == 0) {
955 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
956 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
957 Param->setInvalidDecl();
960 // C++0x [temp.param]p9:
961 // A default template-argument may be specified for any kind of
962 // template-parameter that is not a template parameter pack.
963 if (IsParameterPack && !Default.isInvalid()) {
964 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
965 Default = ParsedTemplateArgument();
968 if (!Default.isInvalid()) {
969 // Check only that we have a template template argument. We don't want to
970 // try to check well-formedness now, because our template template parameter
971 // might have dependent types in its template parameters, which we wouldn't
972 // be able to match now.
974 // If none of the template template parameter's template arguments mention
975 // other template parameters, we could actually perform more checking here.
976 // However, it isn't worth doing.
977 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
978 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
979 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
980 << DefaultArg.getSourceRange();
984 // Check for unexpanded parameter packs.
985 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
986 DefaultArg.getArgument().getAsTemplate(),
987 UPPC_DefaultArgument))
990 Param->setDefaultArgument(Context, DefaultArg);
996 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
997 /// constrained by RequiresClause, that contains the template parameters in
999 TemplateParameterList *
1000 Sema::ActOnTemplateParameterList(unsigned Depth,
1001 SourceLocation ExportLoc,
1002 SourceLocation TemplateLoc,
1003 SourceLocation LAngleLoc,
1004 ArrayRef<Decl *> Params,
1005 SourceLocation RAngleLoc,
1006 Expr *RequiresClause) {
1007 if (ExportLoc.isValid())
1008 Diag(ExportLoc, diag::warn_template_export_unsupported);
1010 return TemplateParameterList::Create(
1011 Context, TemplateLoc, LAngleLoc,
1012 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
1013 RAngleLoc, RequiresClause);
1016 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1018 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
1022 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
1023 SourceLocation KWLoc, CXXScopeSpec &SS,
1024 IdentifierInfo *Name, SourceLocation NameLoc,
1025 AttributeList *Attr,
1026 TemplateParameterList *TemplateParams,
1027 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1028 SourceLocation FriendLoc,
1029 unsigned NumOuterTemplateParamLists,
1030 TemplateParameterList** OuterTemplateParamLists,
1031 SkipBodyInfo *SkipBody) {
1032 assert(TemplateParams && TemplateParams->size() > 0 &&
1033 "No template parameters");
1034 assert(TUK != TUK_Reference && "Can only declare or define class templates");
1035 bool Invalid = false;
1037 // Check that we can declare a template here.
1038 if (CheckTemplateDeclScope(S, TemplateParams))
1041 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1042 assert(Kind != TTK_Enum && "can't build template of enumerated type");
1044 // There is no such thing as an unnamed class template.
1046 Diag(KWLoc, diag::err_template_unnamed_class);
1050 // Find any previous declaration with this name. For a friend with no
1051 // scope explicitly specified, we only look for tag declarations (per
1052 // C++11 [basic.lookup.elab]p2).
1053 DeclContext *SemanticContext;
1054 LookupResult Previous(*this, Name, NameLoc,
1055 (SS.isEmpty() && TUK == TUK_Friend)
1056 ? LookupTagName : LookupOrdinaryName,
1058 if (SS.isNotEmpty() && !SS.isInvalid()) {
1059 SemanticContext = computeDeclContext(SS, true);
1060 if (!SemanticContext) {
1061 // FIXME: Horrible, horrible hack! We can't currently represent this
1062 // in the AST, and historically we have just ignored such friend
1063 // class templates, so don't complain here.
1064 Diag(NameLoc, TUK == TUK_Friend
1065 ? diag::warn_template_qualified_friend_ignored
1066 : diag::err_template_qualified_declarator_no_match)
1067 << SS.getScopeRep() << SS.getRange();
1068 return TUK != TUK_Friend;
1071 if (RequireCompleteDeclContext(SS, SemanticContext))
1074 // If we're adding a template to a dependent context, we may need to
1075 // rebuilding some of the types used within the template parameter list,
1076 // now that we know what the current instantiation is.
1077 if (SemanticContext->isDependentContext()) {
1078 ContextRAII SavedContext(*this, SemanticContext);
1079 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1081 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1082 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
1084 LookupQualifiedName(Previous, SemanticContext);
1086 SemanticContext = CurContext;
1088 // C++14 [class.mem]p14:
1089 // If T is the name of a class, then each of the following shall have a
1090 // name different from T:
1091 // -- every member template of class T
1092 if (TUK != TUK_Friend &&
1093 DiagnoseClassNameShadow(SemanticContext,
1094 DeclarationNameInfo(Name, NameLoc)))
1097 LookupName(Previous, S);
1100 if (Previous.isAmbiguous())
1103 NamedDecl *PrevDecl = nullptr;
1104 if (Previous.begin() != Previous.end())
1105 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1107 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1108 // Maybe we will complain about the shadowed template parameter.
1109 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1110 // Just pretend that we didn't see the previous declaration.
1114 // If there is a previous declaration with the same name, check
1115 // whether this is a valid redeclaration.
1116 ClassTemplateDecl *PrevClassTemplate
1117 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1119 // We may have found the injected-class-name of a class template,
1120 // class template partial specialization, or class template specialization.
1121 // In these cases, grab the template that is being defined or specialized.
1122 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1123 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1124 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1126 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1127 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1129 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1130 ->getSpecializedTemplate();
1134 if (TUK == TUK_Friend) {
1135 // C++ [namespace.memdef]p3:
1136 // [...] When looking for a prior declaration of a class or a function
1137 // declared as a friend, and when the name of the friend class or
1138 // function is neither a qualified name nor a template-id, scopes outside
1139 // the innermost enclosing namespace scope are not considered.
1141 DeclContext *OutermostContext = CurContext;
1142 while (!OutermostContext->isFileContext())
1143 OutermostContext = OutermostContext->getLookupParent();
1146 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1147 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1148 SemanticContext = PrevDecl->getDeclContext();
1150 // Declarations in outer scopes don't matter. However, the outermost
1151 // context we computed is the semantic context for our new
1153 PrevDecl = PrevClassTemplate = nullptr;
1154 SemanticContext = OutermostContext;
1156 // Check that the chosen semantic context doesn't already contain a
1157 // declaration of this name as a non-tag type.
1158 Previous.clear(LookupOrdinaryName);
1159 DeclContext *LookupContext = SemanticContext;
1160 while (LookupContext->isTransparentContext())
1161 LookupContext = LookupContext->getLookupParent();
1162 LookupQualifiedName(Previous, LookupContext);
1164 if (Previous.isAmbiguous())
1167 if (Previous.begin() != Previous.end())
1168 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1171 } else if (PrevDecl &&
1172 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1174 PrevDecl = PrevClassTemplate = nullptr;
1176 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1177 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1179 !(PrevClassTemplate &&
1180 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1181 SemanticContext->getRedeclContext()))) {
1182 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1183 Diag(Shadow->getTargetDecl()->getLocation(),
1184 diag::note_using_decl_target);
1185 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1186 // Recover by ignoring the old declaration.
1187 PrevDecl = PrevClassTemplate = nullptr;
1191 // TODO Memory management; associated constraints are not always stored.
1192 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1194 if (PrevClassTemplate) {
1195 // Ensure that the template parameter lists are compatible. Skip this check
1196 // for a friend in a dependent context: the template parameter list itself
1197 // could be dependent.
1198 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1199 !TemplateParameterListsAreEqual(TemplateParams,
1200 PrevClassTemplate->getTemplateParameters(),
1205 // Check for matching associated constraints on redeclarations.
1206 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1207 const bool RedeclACMismatch = [&] {
1208 if (!(CurAC || PrevAC))
1209 return false; // Nothing to check; no mismatch.
1210 if (CurAC && PrevAC) {
1211 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1212 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1213 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1214 if (CurACInfo == PrevACInfo)
1215 return false; // All good; no mismatch.
1220 if (RedeclACMismatch) {
1221 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1222 diag::err_template_different_associated_constraints);
1223 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1224 diag::note_template_prev_declaration) << /*declaration*/0;
1228 // C++ [temp.class]p4:
1229 // In a redeclaration, partial specialization, explicit
1230 // specialization or explicit instantiation of a class template,
1231 // the class-key shall agree in kind with the original class
1232 // template declaration (7.1.5.3).
1233 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1234 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1235 TUK == TUK_Definition, KWLoc, Name)) {
1236 Diag(KWLoc, diag::err_use_with_wrong_tag)
1238 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1239 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1240 Kind = PrevRecordDecl->getTagKind();
1243 // Check for redefinition of this class template.
1244 if (TUK == TUK_Definition) {
1245 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1246 // If we have a prior definition that is not visible, treat this as
1247 // simply making that previous definition visible.
1248 NamedDecl *Hidden = nullptr;
1249 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1250 SkipBody->ShouldSkip = true;
1251 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1252 assert(Tmpl && "original definition of a class template is not a "
1254 makeMergedDefinitionVisible(Hidden, KWLoc);
1255 makeMergedDefinitionVisible(Tmpl, KWLoc);
1259 Diag(NameLoc, diag::err_redefinition) << Name;
1260 Diag(Def->getLocation(), diag::note_previous_definition);
1261 // FIXME: Would it make sense to try to "forget" the previous
1262 // definition, as part of error recovery?
1266 } else if (PrevDecl) {
1268 // A class template shall not have the same name as any other
1269 // template, class, function, object, enumeration, enumerator,
1270 // namespace, or type in the same scope (3.3), except as specified
1272 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1273 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1277 // Check the template parameter list of this declaration, possibly
1278 // merging in the template parameter list from the previous class
1279 // template declaration. Skip this check for a friend in a dependent
1280 // context, because the template parameter list might be dependent.
1281 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1282 CheckTemplateParameterList(
1284 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1286 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1287 SemanticContext->isDependentContext())
1288 ? TPC_ClassTemplateMember
1289 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1290 : TPC_ClassTemplate))
1294 // If the name of the template was qualified, we must be defining the
1295 // template out-of-line.
1296 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1297 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1298 : diag::err_member_decl_does_not_match)
1299 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1304 // If this is a templated friend in a dependent context we should not put it
1305 // on the redecl chain. In some cases, the templated friend can be the most
1306 // recent declaration tricking the template instantiator to make substitutions
1308 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1309 bool ShouldAddRedecl
1310 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1312 CXXRecordDecl *NewClass =
1313 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1314 PrevClassTemplate && ShouldAddRedecl ?
1315 PrevClassTemplate->getTemplatedDecl() : nullptr,
1316 /*DelayTypeCreation=*/true);
1317 SetNestedNameSpecifier(NewClass, SS);
1318 if (NumOuterTemplateParamLists > 0)
1319 NewClass->setTemplateParameterListsInfo(
1320 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1321 NumOuterTemplateParamLists));
1323 // Add alignment attributes if necessary; these attributes are checked when
1324 // the ASTContext lays out the structure.
1325 if (TUK == TUK_Definition) {
1326 AddAlignmentAttributesForRecord(NewClass);
1327 AddMsStructLayoutForRecord(NewClass);
1330 // Attach the associated constraints when the declaration will not be part of
1332 Expr *const ACtoAttach =
1333 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1335 ClassTemplateDecl *NewTemplate
1336 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1337 DeclarationName(Name), TemplateParams,
1338 NewClass, ACtoAttach);
1340 if (ShouldAddRedecl)
1341 NewTemplate->setPreviousDecl(PrevClassTemplate);
1343 NewClass->setDescribedClassTemplate(NewTemplate);
1345 if (ModulePrivateLoc.isValid())
1346 NewTemplate->setModulePrivate();
1348 // Build the type for the class template declaration now.
1349 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1350 T = Context.getInjectedClassNameType(NewClass, T);
1351 assert(T->isDependentType() && "Class template type is not dependent?");
1354 // If we are providing an explicit specialization of a member that is a
1355 // class template, make a note of that.
1356 if (PrevClassTemplate &&
1357 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1358 PrevClassTemplate->setMemberSpecialization();
1360 // Set the access specifier.
1361 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1362 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1364 // Set the lexical context of these templates
1365 NewClass->setLexicalDeclContext(CurContext);
1366 NewTemplate->setLexicalDeclContext(CurContext);
1368 if (TUK == TUK_Definition)
1369 NewClass->startDefinition();
1372 ProcessDeclAttributeList(S, NewClass, Attr);
1374 if (PrevClassTemplate)
1375 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1377 AddPushedVisibilityAttribute(NewClass);
1379 if (TUK != TUK_Friend) {
1380 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1382 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1383 Outer = Outer->getParent();
1384 PushOnScopeChains(NewTemplate, Outer);
1386 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1387 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1388 NewClass->setAccess(PrevClassTemplate->getAccess());
1391 NewTemplate->setObjectOfFriendDecl();
1393 // Friend templates are visible in fairly strange ways.
1394 if (!CurContext->isDependentContext()) {
1395 DeclContext *DC = SemanticContext->getRedeclContext();
1396 DC->makeDeclVisibleInContext(NewTemplate);
1397 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1398 PushOnScopeChains(NewTemplate, EnclosingScope,
1399 /* AddToContext = */ false);
1402 FriendDecl *Friend = FriendDecl::Create(
1403 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1404 Friend->setAccess(AS_public);
1405 CurContext->addDecl(Friend);
1409 NewTemplate->setInvalidDecl();
1410 NewClass->setInvalidDecl();
1413 ActOnDocumentableDecl(NewTemplate);
1419 /// Transform to convert portions of a constructor declaration into the
1420 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1421 struct ConvertConstructorToDeductionGuideTransform {
1422 ConvertConstructorToDeductionGuideTransform(Sema &S,
1423 ClassTemplateDecl *Template)
1424 : SemaRef(S), Template(Template) {}
1427 ClassTemplateDecl *Template;
1429 DeclContext *DC = Template->getDeclContext();
1430 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1431 DeclarationName DeductionGuideName =
1432 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1434 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1436 // Index adjustment to apply to convert depth-1 template parameters into
1437 // depth-0 template parameters.
1438 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1440 /// Transform a constructor declaration into a deduction guide.
1441 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1442 CXXConstructorDecl *CD) {
1443 SmallVector<TemplateArgument, 16> SubstArgs;
1445 LocalInstantiationScope Scope(SemaRef);
1447 // C++ [over.match.class.deduct]p1:
1448 // -- For each constructor of the class template designated by the
1449 // template-name, a function template with the following properties:
1451 // -- The template parameters are the template parameters of the class
1452 // template followed by the template parameters (including default
1453 // template arguments) of the constructor, if any.
1454 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1456 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1457 SmallVector<NamedDecl *, 16> AllParams;
1458 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1459 AllParams.insert(AllParams.begin(),
1460 TemplateParams->begin(), TemplateParams->end());
1461 SubstArgs.reserve(InnerParams->size());
1463 // Later template parameters could refer to earlier ones, so build up
1464 // a list of substituted template arguments as we go.
1465 for (NamedDecl *Param : *InnerParams) {
1466 MultiLevelTemplateArgumentList Args;
1467 Args.addOuterTemplateArguments(SubstArgs);
1468 Args.addOuterRetainedLevel();
1469 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1472 AllParams.push_back(NewParam);
1473 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1474 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1476 TemplateParams = TemplateParameterList::Create(
1477 SemaRef.Context, InnerParams->getTemplateLoc(),
1478 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1479 /*FIXME: RequiresClause*/ nullptr);
1482 // If we built a new template-parameter-list, track that we need to
1483 // substitute references to the old parameters into references to the
1485 MultiLevelTemplateArgumentList Args;
1487 Args.addOuterTemplateArguments(SubstArgs);
1488 Args.addOuterRetainedLevel();
1491 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
1492 .getAsAdjusted<FunctionProtoTypeLoc>();
1493 assert(FPTL && "no prototype for constructor declaration");
1495 // Transform the type of the function, adjusting the return type and
1496 // replacing references to the old parameters with references to the
1499 SmallVector<ParmVarDecl*, 8> Params;
1500 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1501 if (NewType.isNull())
1503 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1505 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1506 CD->getLocStart(), CD->getLocation(),
1510 /// Build a deduction guide with the specified parameter types.
1511 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1512 SourceLocation Loc = Template->getLocation();
1514 // Build the requested type.
1515 FunctionProtoType::ExtProtoInfo EPI;
1516 EPI.HasTrailingReturn = true;
1517 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1518 DeductionGuideName, EPI);
1519 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1521 FunctionProtoTypeLoc FPTL =
1522 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1524 // Build the parameters, needed during deduction / substitution.
1525 SmallVector<ParmVarDecl*, 4> Params;
1526 for (auto T : ParamTypes) {
1527 ParmVarDecl *NewParam = ParmVarDecl::Create(
1528 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1529 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1530 NewParam->setScopeInfo(0, Params.size());
1531 FPTL.setParam(Params.size(), NewParam);
1532 Params.push_back(NewParam);
1535 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1540 /// Transform a constructor template parameter into a deduction guide template
1541 /// parameter, rebuilding any internal references to earlier parameters and
1542 /// renumbering as we go.
1543 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1544 MultiLevelTemplateArgumentList &Args) {
1545 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1546 // TemplateTypeParmDecl's index cannot be changed after creation, so
1547 // substitute it directly.
1548 auto *NewTTP = TemplateTypeParmDecl::Create(
1549 SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1550 /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1551 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1552 TTP->isParameterPack());
1553 if (TTP->hasDefaultArgument()) {
1554 TypeSourceInfo *InstantiatedDefaultArg =
1555 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1556 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1557 if (InstantiatedDefaultArg)
1558 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1560 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1565 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1566 return transformTemplateParameterImpl(TTP, Args);
1568 return transformTemplateParameterImpl(
1569 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1571 template<typename TemplateParmDecl>
1573 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1574 MultiLevelTemplateArgumentList &Args) {
1575 // Ask the template instantiator to do the heavy lifting for us, then adjust
1576 // the index of the parameter once it's done.
1578 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1579 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1580 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1584 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1585 FunctionProtoTypeLoc TL,
1586 SmallVectorImpl<ParmVarDecl*> &Params,
1587 MultiLevelTemplateArgumentList &Args) {
1588 SmallVector<QualType, 4> ParamTypes;
1589 const FunctionProtoType *T = TL.getTypePtr();
1591 // -- The types of the function parameters are those of the constructor.
1592 for (auto *OldParam : TL.getParams()) {
1593 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
1596 ParamTypes.push_back(NewParam->getType());
1597 Params.push_back(NewParam);
1600 // -- The return type is the class template specialization designated by
1601 // the template-name and template arguments corresponding to the
1602 // template parameters obtained from the class template.
1604 // We use the injected-class-name type of the primary template instead.
1605 // This has the convenient property that it is different from any type that
1606 // the user can write in a deduction-guide (because they cannot enter the
1607 // context of the template), so implicit deduction guides can never collide
1608 // with explicit ones.
1609 QualType ReturnType = DeducedType;
1610 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1612 // Resolving a wording defect, we also inherit the variadicness of the
1614 FunctionProtoType::ExtProtoInfo EPI;
1615 EPI.Variadic = T->isVariadic();
1616 EPI.HasTrailingReturn = true;
1618 QualType Result = SemaRef.BuildFunctionType(
1619 ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1620 if (Result.isNull())
1623 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1624 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1625 NewTL.setLParenLoc(TL.getLParenLoc());
1626 NewTL.setRParenLoc(TL.getRParenLoc());
1627 NewTL.setExceptionSpecRange(SourceRange());
1628 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1629 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1630 NewTL.setParam(I, Params[I]);
1636 transformFunctionTypeParam(ParmVarDecl *OldParam,
1637 MultiLevelTemplateArgumentList &Args) {
1638 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
1639 TypeSourceInfo *NewDI =
1641 ? SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1642 OldParam->getDeclName())
1647 // Canonicalize the type. This (for instance) replaces references to
1648 // typedef members of the current instantiations with the definitions of
1649 // those typedefs, avoiding triggering instantiation of the deduced type
1650 // during deduction.
1651 // FIXME: It would be preferable to retain type sugar and source
1652 // information here (and handle this in substitution instead).
1653 NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
1654 SemaRef.Context.getCanonicalType(NewDI->getType()),
1655 OldParam->getLocation());
1657 // Resolving a wording defect, we also inherit default arguments from the
1659 ExprResult NewDefArg;
1660 if (OldParam->hasDefaultArg()) {
1661 NewDefArg = Args.getNumLevels()
1662 ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
1663 : OldParam->getDefaultArg();
1664 if (NewDefArg.isInvalid())
1668 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1669 OldParam->getInnerLocStart(),
1670 OldParam->getLocation(),
1671 OldParam->getIdentifier(),
1674 OldParam->getStorageClass(),
1676 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1677 OldParam->getFunctionScopeIndex());
1681 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1682 bool Explicit, TypeSourceInfo *TInfo,
1683 SourceLocation LocStart, SourceLocation Loc,
1684 SourceLocation LocEnd) {
1685 DeclarationNameInfo Name(DeductionGuideName, Loc);
1686 ArrayRef<ParmVarDecl *> Params =
1687 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1689 // Build the implicit deduction guide template.
1691 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1692 Name, TInfo->getType(), TInfo, LocEnd);
1693 Guide->setImplicit();
1694 Guide->setParams(Params);
1696 for (auto *Param : Params)
1697 Param->setDeclContext(Guide);
1699 auto *GuideTemplate = FunctionTemplateDecl::Create(
1700 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1701 GuideTemplate->setImplicit();
1702 Guide->setDescribedFunctionTemplate(GuideTemplate);
1704 if (isa<CXXRecordDecl>(DC)) {
1705 Guide->setAccess(AS_public);
1706 GuideTemplate->setAccess(AS_public);
1709 DC->addDecl(GuideTemplate);
1710 return GuideTemplate;
1715 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1716 SourceLocation Loc) {
1717 DeclContext *DC = Template->getDeclContext();
1718 if (DC->isDependentContext())
1721 ConvertConstructorToDeductionGuideTransform Transform(
1722 *this, cast<ClassTemplateDecl>(Template));
1723 if (!isCompleteType(Loc, Transform.DeducedType))
1726 // Check whether we've already declared deduction guides for this template.
1727 // FIXME: Consider storing a flag on the template to indicate this.
1728 auto Existing = DC->lookup(Transform.DeductionGuideName);
1729 for (auto *D : Existing)
1730 if (D->isImplicit())
1733 // In case we were expanding a pack when we attempted to declare deduction
1734 // guides, turn off pack expansion for everything we're about to do.
1735 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1736 // Create a template instantiation record to track the "instantiation" of
1737 // constructors into deduction guides.
1738 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1739 // this substitution process actually fail?
1740 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1742 // Convert declared constructors into deduction guide templates.
1743 // FIXME: Skip constructors for which deduction must necessarily fail (those
1744 // for which some class template parameter without a default argument never
1745 // appears in a deduced context).
1746 bool AddedAny = false;
1747 bool AddedCopyOrMove = false;
1748 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1749 D = D->getUnderlyingDecl();
1750 if (D->isInvalidDecl() || D->isImplicit())
1752 D = cast<NamedDecl>(D->getCanonicalDecl());
1754 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
1756 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
1757 // Class-scope explicit specializations (MS extension) do not result in
1758 // deduction guides.
1759 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
1762 Transform.transformConstructor(FTD, CD);
1765 AddedCopyOrMove |= CD->isCopyOrMoveConstructor();
1768 // Synthesize an X() -> X<...> guide if there were no declared constructors.
1769 // FIXME: The standard doesn't say (how) to do this.
1771 Transform.buildSimpleDeductionGuide(None);
1773 // Synthesize an X(X<...>) -> X<...> guide if there was no declared constructor
1774 // resembling a copy or move constructor.
1775 // FIXME: The standard doesn't say (how) to do this.
1776 if (!AddedCopyOrMove)
1777 Transform.buildSimpleDeductionGuide(Transform.DeducedType);
1780 /// \brief Diagnose the presence of a default template argument on a
1781 /// template parameter, which is ill-formed in certain contexts.
1783 /// \returns true if the default template argument should be dropped.
1784 static bool DiagnoseDefaultTemplateArgument(Sema &S,
1785 Sema::TemplateParamListContext TPC,
1786 SourceLocation ParamLoc,
1787 SourceRange DefArgRange) {
1789 case Sema::TPC_ClassTemplate:
1790 case Sema::TPC_VarTemplate:
1791 case Sema::TPC_TypeAliasTemplate:
1794 case Sema::TPC_FunctionTemplate:
1795 case Sema::TPC_FriendFunctionTemplateDefinition:
1796 // C++ [temp.param]p9:
1797 // A default template-argument shall not be specified in a
1798 // function template declaration or a function template
1800 // If a friend function template declaration specifies a default
1801 // template-argument, that declaration shall be a definition and shall be
1802 // the only declaration of the function template in the translation unit.
1803 // (C++98/03 doesn't have this wording; see DR226).
1804 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1805 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1806 : diag::ext_template_parameter_default_in_function_template)
1810 case Sema::TPC_ClassTemplateMember:
1811 // C++0x [temp.param]p9:
1812 // A default template-argument shall not be specified in the
1813 // template-parameter-lists of the definition of a member of a
1814 // class template that appears outside of the member's class.
1815 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1819 case Sema::TPC_FriendClassTemplate:
1820 case Sema::TPC_FriendFunctionTemplate:
1821 // C++ [temp.param]p9:
1822 // A default template-argument shall not be specified in a
1823 // friend template declaration.
1824 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1828 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1829 // for friend function templates if there is only a single
1830 // declaration (and it is a definition). Strange!
1833 llvm_unreachable("Invalid TemplateParamListContext!");
1836 /// \brief Check for unexpanded parameter packs within the template parameters
1837 /// of a template template parameter, recursively.
1838 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1839 TemplateTemplateParmDecl *TTP) {
1840 // A template template parameter which is a parameter pack is also a pack
1842 if (TTP->isParameterPack())
1845 TemplateParameterList *Params = TTP->getTemplateParameters();
1846 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1847 NamedDecl *P = Params->getParam(I);
1848 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1849 if (!NTTP->isParameterPack() &&
1850 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1851 NTTP->getTypeSourceInfo(),
1852 Sema::UPPC_NonTypeTemplateParameterType))
1858 if (TemplateTemplateParmDecl *InnerTTP
1859 = dyn_cast<TemplateTemplateParmDecl>(P))
1860 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1867 /// \brief Checks the validity of a template parameter list, possibly
1868 /// considering the template parameter list from a previous
1871 /// If an "old" template parameter list is provided, it must be
1872 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1873 /// template parameter list.
1875 /// \param NewParams Template parameter list for a new template
1876 /// declaration. This template parameter list will be updated with any
1877 /// default arguments that are carried through from the previous
1878 /// template parameter list.
1880 /// \param OldParams If provided, template parameter list from a
1881 /// previous declaration of the same template. Default template
1882 /// arguments will be merged from the old template parameter list to
1883 /// the new template parameter list.
1885 /// \param TPC Describes the context in which we are checking the given
1886 /// template parameter list.
1888 /// \returns true if an error occurred, false otherwise.
1889 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1890 TemplateParameterList *OldParams,
1891 TemplateParamListContext TPC) {
1892 bool Invalid = false;
1894 // C++ [temp.param]p10:
1895 // The set of default template-arguments available for use with a
1896 // template declaration or definition is obtained by merging the
1897 // default arguments from the definition (if in scope) and all
1898 // declarations in scope in the same way default function
1899 // arguments are (8.3.6).
1900 bool SawDefaultArgument = false;
1901 SourceLocation PreviousDefaultArgLoc;
1903 // Dummy initialization to avoid warnings.
1904 TemplateParameterList::iterator OldParam = NewParams->end();
1906 OldParam = OldParams->begin();
1908 bool RemoveDefaultArguments = false;
1909 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1910 NewParamEnd = NewParams->end();
1911 NewParam != NewParamEnd; ++NewParam) {
1912 // Variables used to diagnose redundant default arguments
1913 bool RedundantDefaultArg = false;
1914 SourceLocation OldDefaultLoc;
1915 SourceLocation NewDefaultLoc;
1917 // Variable used to diagnose missing default arguments
1918 bool MissingDefaultArg = false;
1920 // Variable used to diagnose non-final parameter packs
1921 bool SawParameterPack = false;
1923 if (TemplateTypeParmDecl *NewTypeParm
1924 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1925 // Check the presence of a default argument here.
1926 if (NewTypeParm->hasDefaultArgument() &&
1927 DiagnoseDefaultTemplateArgument(*this, TPC,
1928 NewTypeParm->getLocation(),
1929 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1931 NewTypeParm->removeDefaultArgument();
1933 // Merge default arguments for template type parameters.
1934 TemplateTypeParmDecl *OldTypeParm
1935 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
1936 if (NewTypeParm->isParameterPack()) {
1937 assert(!NewTypeParm->hasDefaultArgument() &&
1938 "Parameter packs can't have a default argument!");
1939 SawParameterPack = true;
1940 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
1941 NewTypeParm->hasDefaultArgument()) {
1942 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1943 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1944 SawDefaultArgument = true;
1945 RedundantDefaultArg = true;
1946 PreviousDefaultArgLoc = NewDefaultLoc;
1947 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1948 // Merge the default argument from the old declaration to the
1950 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
1951 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1952 } else if (NewTypeParm->hasDefaultArgument()) {
1953 SawDefaultArgument = true;
1954 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1955 } else if (SawDefaultArgument)
1956 MissingDefaultArg = true;
1957 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1958 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1959 // Check for unexpanded parameter packs.
1960 if (!NewNonTypeParm->isParameterPack() &&
1961 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1962 NewNonTypeParm->getTypeSourceInfo(),
1963 UPPC_NonTypeTemplateParameterType)) {
1968 // Check the presence of a default argument here.
1969 if (NewNonTypeParm->hasDefaultArgument() &&
1970 DiagnoseDefaultTemplateArgument(*this, TPC,
1971 NewNonTypeParm->getLocation(),
1972 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1973 NewNonTypeParm->removeDefaultArgument();
1976 // Merge default arguments for non-type template parameters
1977 NonTypeTemplateParmDecl *OldNonTypeParm
1978 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
1979 if (NewNonTypeParm->isParameterPack()) {
1980 assert(!NewNonTypeParm->hasDefaultArgument() &&
1981 "Parameter packs can't have a default argument!");
1982 if (!NewNonTypeParm->isPackExpansion())
1983 SawParameterPack = true;
1984 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
1985 NewNonTypeParm->hasDefaultArgument()) {
1986 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1987 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1988 SawDefaultArgument = true;
1989 RedundantDefaultArg = true;
1990 PreviousDefaultArgLoc = NewDefaultLoc;
1991 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1992 // Merge the default argument from the old declaration to the
1994 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
1995 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1996 } else if (NewNonTypeParm->hasDefaultArgument()) {
1997 SawDefaultArgument = true;
1998 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1999 } else if (SawDefaultArgument)
2000 MissingDefaultArg = true;
2002 TemplateTemplateParmDecl *NewTemplateParm
2003 = cast<TemplateTemplateParmDecl>(*NewParam);
2005 // Check for unexpanded parameter packs, recursively.
2006 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2011 // Check the presence of a default argument here.
2012 if (NewTemplateParm->hasDefaultArgument() &&
2013 DiagnoseDefaultTemplateArgument(*this, TPC,
2014 NewTemplateParm->getLocation(),
2015 NewTemplateParm->getDefaultArgument().getSourceRange()))
2016 NewTemplateParm->removeDefaultArgument();
2018 // Merge default arguments for template template parameters
2019 TemplateTemplateParmDecl *OldTemplateParm
2020 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2021 if (NewTemplateParm->isParameterPack()) {
2022 assert(!NewTemplateParm->hasDefaultArgument() &&
2023 "Parameter packs can't have a default argument!");
2024 if (!NewTemplateParm->isPackExpansion())
2025 SawParameterPack = true;
2026 } else if (OldTemplateParm &&
2027 hasVisibleDefaultArgument(OldTemplateParm) &&
2028 NewTemplateParm->hasDefaultArgument()) {
2029 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2030 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2031 SawDefaultArgument = true;
2032 RedundantDefaultArg = true;
2033 PreviousDefaultArgLoc = NewDefaultLoc;
2034 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2035 // Merge the default argument from the old declaration to the
2037 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2038 PreviousDefaultArgLoc
2039 = OldTemplateParm->getDefaultArgument().getLocation();
2040 } else if (NewTemplateParm->hasDefaultArgument()) {
2041 SawDefaultArgument = true;
2042 PreviousDefaultArgLoc
2043 = NewTemplateParm->getDefaultArgument().getLocation();
2044 } else if (SawDefaultArgument)
2045 MissingDefaultArg = true;
2048 // C++11 [temp.param]p11:
2049 // If a template parameter of a primary class template or alias template
2050 // is a template parameter pack, it shall be the last template parameter.
2051 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2052 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2053 TPC == TPC_TypeAliasTemplate)) {
2054 Diag((*NewParam)->getLocation(),
2055 diag::err_template_param_pack_must_be_last_template_parameter);
2059 if (RedundantDefaultArg) {
2060 // C++ [temp.param]p12:
2061 // A template-parameter shall not be given default arguments
2062 // by two different declarations in the same scope.
2063 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2064 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2066 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2067 // C++ [temp.param]p11:
2068 // If a template-parameter of a class template has a default
2069 // template-argument, each subsequent template-parameter shall either
2070 // have a default template-argument supplied or be a template parameter
2072 Diag((*NewParam)->getLocation(),
2073 diag::err_template_param_default_arg_missing);
2074 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2076 RemoveDefaultArguments = true;
2079 // If we have an old template parameter list that we're merging
2080 // in, move on to the next parameter.
2085 // We were missing some default arguments at the end of the list, so remove
2086 // all of the default arguments.
2087 if (RemoveDefaultArguments) {
2088 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2089 NewParamEnd = NewParams->end();
2090 NewParam != NewParamEnd; ++NewParam) {
2091 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2092 TTP->removeDefaultArgument();
2093 else if (NonTypeTemplateParmDecl *NTTP
2094 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2095 NTTP->removeDefaultArgument();
2097 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2106 /// A class which looks for a use of a certain level of template
2108 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2109 typedef RecursiveASTVisitor<DependencyChecker> super;
2113 // Whether we're looking for a use of a template parameter that makes the
2114 // overall construct type-dependent / a dependent type. This is strictly
2115 // best-effort for now; we may fail to match at all for a dependent type
2116 // in some cases if this is set.
2117 bool IgnoreNonTypeDependent;
2120 SourceLocation MatchLoc;
2122 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2123 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2126 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2127 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2128 NamedDecl *ND = Params->getParam(0);
2129 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2130 Depth = PD->getDepth();
2131 } else if (NonTypeTemplateParmDecl *PD =
2132 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2133 Depth = PD->getDepth();
2135 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2139 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2140 if (ParmDepth >= Depth) {
2148 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2149 // Prune out non-type-dependent expressions if requested. This can
2150 // sometimes result in us failing to find a template parameter reference
2151 // (if a value-dependent expression creates a dependent type), but this
2152 // mode is best-effort only.
2153 if (auto *E = dyn_cast_or_null<Expr>(S))
2154 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2156 return super::TraverseStmt(S, Q);
2159 bool TraverseTypeLoc(TypeLoc TL) {
2160 if (IgnoreNonTypeDependent && !TL.isNull() &&
2161 !TL.getType()->isDependentType())
2163 return super::TraverseTypeLoc(TL);
2166 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2167 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2170 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2171 // For a best-effort search, keep looking until we find a location.
2172 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2175 bool TraverseTemplateName(TemplateName N) {
2176 if (TemplateTemplateParmDecl *PD =
2177 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2178 if (Matches(PD->getDepth()))
2180 return super::TraverseTemplateName(N);
2183 bool VisitDeclRefExpr(DeclRefExpr *E) {
2184 if (NonTypeTemplateParmDecl *PD =
2185 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2186 if (Matches(PD->getDepth(), E->getExprLoc()))
2188 return super::VisitDeclRefExpr(E);
2191 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2192 return TraverseType(T->getReplacementType());
2196 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2197 return TraverseTemplateArgument(T->getArgumentPack());
2200 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2201 return TraverseType(T->getInjectedSpecializationType());
2204 } // end anonymous namespace
2206 /// Determines whether a given type depends on the given parameter
2209 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2210 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2211 Checker.TraverseType(T);
2212 return Checker.Match;
2215 // Find the source range corresponding to the named type in the given
2216 // nested-name-specifier, if any.
2217 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2219 const CXXScopeSpec &SS) {
2220 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2221 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2222 if (const Type *CurType = NNS->getAsType()) {
2223 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2224 return NNSLoc.getTypeLoc().getSourceRange();
2228 NNSLoc = NNSLoc.getPrefix();
2231 return SourceRange();
2234 /// \brief Match the given template parameter lists to the given scope
2235 /// specifier, returning the template parameter list that applies to the
2238 /// \param DeclStartLoc the start of the declaration that has a scope
2239 /// specifier or a template parameter list.
2241 /// \param DeclLoc The location of the declaration itself.
2243 /// \param SS the scope specifier that will be matched to the given template
2244 /// parameter lists. This scope specifier precedes a qualified name that is
2247 /// \param TemplateId The template-id following the scope specifier, if there
2248 /// is one. Used to check for a missing 'template<>'.
2250 /// \param ParamLists the template parameter lists, from the outermost to the
2251 /// innermost template parameter lists.
2253 /// \param IsFriend Whether to apply the slightly different rules for
2254 /// matching template parameters to scope specifiers in friend
2257 /// \param IsMemberSpecialization will be set true if the scope specifier
2258 /// denotes a fully-specialized type, and therefore this is a declaration of
2259 /// a member specialization.
2261 /// \returns the template parameter list, if any, that corresponds to the
2262 /// name that is preceded by the scope specifier @p SS. This template
2263 /// parameter list may have template parameters (if we're declaring a
2264 /// template) or may have no template parameters (if we're declaring a
2265 /// template specialization), or may be NULL (if what we're declaring isn't
2266 /// itself a template).
2267 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2268 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2269 TemplateIdAnnotation *TemplateId,
2270 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2271 bool &IsMemberSpecialization, bool &Invalid) {
2272 IsMemberSpecialization = false;
2275 // The sequence of nested types to which we will match up the template
2276 // parameter lists. We first build this list by starting with the type named
2277 // by the nested-name-specifier and walking out until we run out of types.
2278 SmallVector<QualType, 4> NestedTypes;
2280 if (SS.getScopeRep()) {
2281 if (CXXRecordDecl *Record
2282 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2283 T = Context.getTypeDeclType(Record);
2285 T = QualType(SS.getScopeRep()->getAsType(), 0);
2288 // If we found an explicit specialization that prevents us from needing
2289 // 'template<>' headers, this will be set to the location of that
2290 // explicit specialization.
2291 SourceLocation ExplicitSpecLoc;
2293 while (!T.isNull()) {
2294 NestedTypes.push_back(T);
2296 // Retrieve the parent of a record type.
2297 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2298 // If this type is an explicit specialization, we're done.
2299 if (ClassTemplateSpecializationDecl *Spec
2300 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2301 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2302 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2303 ExplicitSpecLoc = Spec->getLocation();
2306 } else if (Record->getTemplateSpecializationKind()
2307 == TSK_ExplicitSpecialization) {
2308 ExplicitSpecLoc = Record->getLocation();
2312 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2313 T = Context.getTypeDeclType(Parent);
2319 if (const TemplateSpecializationType *TST
2320 = T->getAs<TemplateSpecializationType>()) {
2321 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2322 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2323 T = Context.getTypeDeclType(Parent);
2330 // Look one step prior in a dependent template specialization type.
2331 if (const DependentTemplateSpecializationType *DependentTST
2332 = T->getAs<DependentTemplateSpecializationType>()) {
2333 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2334 T = QualType(NNS->getAsType(), 0);
2340 // Look one step prior in a dependent name type.
2341 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2342 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2343 T = QualType(NNS->getAsType(), 0);
2349 // Retrieve the parent of an enumeration type.
2350 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2351 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2353 EnumDecl *Enum = EnumT->getDecl();
2355 // Get to the parent type.
2356 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2357 T = Context.getTypeDeclType(Parent);
2365 // Reverse the nested types list, since we want to traverse from the outermost
2366 // to the innermost while checking template-parameter-lists.
2367 std::reverse(NestedTypes.begin(), NestedTypes.end());
2369 // C++0x [temp.expl.spec]p17:
2370 // A member or a member template may be nested within many
2371 // enclosing class templates. In an explicit specialization for
2372 // such a member, the member declaration shall be preceded by a
2373 // template<> for each enclosing class template that is
2374 // explicitly specialized.
2375 bool SawNonEmptyTemplateParameterList = false;
2377 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2378 if (SawNonEmptyTemplateParameterList) {
2379 Diag(DeclLoc, diag::err_specialize_member_of_template)
2380 << !Recovery << Range;
2382 IsMemberSpecialization = false;
2389 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2390 // Check that we can have an explicit specialization here.
2391 if (CheckExplicitSpecialization(Range, true))
2394 // We don't have a template header, but we should.
2395 SourceLocation ExpectedTemplateLoc;
2396 if (!ParamLists.empty())
2397 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2399 ExpectedTemplateLoc = DeclStartLoc;
2401 Diag(DeclLoc, diag::err_template_spec_needs_header)
2403 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2407 unsigned ParamIdx = 0;
2408 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2410 T = NestedTypes[TypeIdx];
2412 // Whether we expect a 'template<>' header.
2413 bool NeedEmptyTemplateHeader = false;
2415 // Whether we expect a template header with parameters.
2416 bool NeedNonemptyTemplateHeader = false;
2418 // For a dependent type, the set of template parameters that we
2420 TemplateParameterList *ExpectedTemplateParams = nullptr;
2422 // C++0x [temp.expl.spec]p15:
2423 // A member or a member template may be nested within many enclosing
2424 // class templates. In an explicit specialization for such a member, the
2425 // member declaration shall be preceded by a template<> for each
2426 // enclosing class template that is explicitly specialized.
2427 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2428 if (ClassTemplatePartialSpecializationDecl *Partial
2429 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2430 ExpectedTemplateParams = Partial->getTemplateParameters();
2431 NeedNonemptyTemplateHeader = true;
2432 } else if (Record->isDependentType()) {
2433 if (Record->getDescribedClassTemplate()) {
2434 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2435 ->getTemplateParameters();
2436 NeedNonemptyTemplateHeader = true;
2438 } else if (ClassTemplateSpecializationDecl *Spec
2439 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2440 // C++0x [temp.expl.spec]p4:
2441 // Members of an explicitly specialized class template are defined
2442 // in the same manner as members of normal classes, and not using
2443 // the template<> syntax.
2444 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2445 NeedEmptyTemplateHeader = true;
2448 } else if (Record->getTemplateSpecializationKind()) {
2449 if (Record->getTemplateSpecializationKind()
2450 != TSK_ExplicitSpecialization &&
2451 TypeIdx == NumTypes - 1)
2452 IsMemberSpecialization = true;
2456 } else if (const TemplateSpecializationType *TST
2457 = T->getAs<TemplateSpecializationType>()) {
2458 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2459 ExpectedTemplateParams = Template->getTemplateParameters();
2460 NeedNonemptyTemplateHeader = true;
2462 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2463 // FIXME: We actually could/should check the template arguments here
2464 // against the corresponding template parameter list.
2465 NeedNonemptyTemplateHeader = false;
2468 // C++ [temp.expl.spec]p16:
2469 // In an explicit specialization declaration for a member of a class
2470 // template or a member template that ap- pears in namespace scope, the
2471 // member template and some of its enclosing class templates may remain
2472 // unspecialized, except that the declaration shall not explicitly
2473 // specialize a class member template if its en- closing class templates
2474 // are not explicitly specialized as well.
2475 if (ParamIdx < ParamLists.size()) {
2476 if (ParamLists[ParamIdx]->size() == 0) {
2477 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2481 SawNonEmptyTemplateParameterList = true;
2484 if (NeedEmptyTemplateHeader) {
2485 // If we're on the last of the types, and we need a 'template<>' header
2486 // here, then it's a member specialization.
2487 if (TypeIdx == NumTypes - 1)
2488 IsMemberSpecialization = true;
2490 if (ParamIdx < ParamLists.size()) {
2491 if (ParamLists[ParamIdx]->size() > 0) {
2492 // The header has template parameters when it shouldn't. Complain.
2493 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2494 diag::err_template_param_list_matches_nontemplate)
2496 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2497 ParamLists[ParamIdx]->getRAngleLoc())
2498 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2503 // Consume this template header.
2509 if (DiagnoseMissingExplicitSpecialization(
2510 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2516 if (NeedNonemptyTemplateHeader) {
2517 // In friend declarations we can have template-ids which don't
2518 // depend on the corresponding template parameter lists. But
2519 // assume that empty parameter lists are supposed to match this
2521 if (IsFriend && T->isDependentType()) {
2522 if (ParamIdx < ParamLists.size() &&
2523 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2524 ExpectedTemplateParams = nullptr;
2529 if (ParamIdx < ParamLists.size()) {
2530 // Check the template parameter list, if we can.
2531 if (ExpectedTemplateParams &&
2532 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2533 ExpectedTemplateParams,
2534 true, TPL_TemplateMatch))
2538 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2539 TPC_ClassTemplateMember))
2546 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2548 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2554 // If there were at least as many template-ids as there were template
2555 // parameter lists, then there are no template parameter lists remaining for
2556 // the declaration itself.
2557 if (ParamIdx >= ParamLists.size()) {
2558 if (TemplateId && !IsFriend) {
2559 // We don't have a template header for the declaration itself, but we
2561 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2562 TemplateId->RAngleLoc));
2564 // Fabricate an empty template parameter list for the invented header.
2565 return TemplateParameterList::Create(Context, SourceLocation(),
2566 SourceLocation(), None,
2567 SourceLocation(), nullptr);
2573 // If there were too many template parameter lists, complain about that now.
2574 if (ParamIdx < ParamLists.size() - 1) {
2575 bool HasAnyExplicitSpecHeader = false;
2576 bool AllExplicitSpecHeaders = true;
2577 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2578 if (ParamLists[I]->size() == 0)
2579 HasAnyExplicitSpecHeader = true;
2581 AllExplicitSpecHeaders = false;
2584 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2585 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2586 : diag::err_template_spec_extra_headers)
2587 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2588 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
2590 // If there was a specialization somewhere, such that 'template<>' is
2591 // not required, and there were any 'template<>' headers, note where the
2592 // specialization occurred.
2593 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2594 Diag(ExplicitSpecLoc,
2595 diag::note_explicit_template_spec_does_not_need_header)
2596 << NestedTypes.back();
2598 // We have a template parameter list with no corresponding scope, which
2599 // means that the resulting template declaration can't be instantiated
2600 // properly (we'll end up with dependent nodes when we shouldn't).
2601 if (!AllExplicitSpecHeaders)
2605 // C++ [temp.expl.spec]p16:
2606 // In an explicit specialization declaration for a member of a class
2607 // template or a member template that ap- pears in namespace scope, the
2608 // member template and some of its enclosing class templates may remain
2609 // unspecialized, except that the declaration shall not explicitly
2610 // specialize a class member template if its en- closing class templates
2611 // are not explicitly specialized as well.
2612 if (ParamLists.back()->size() == 0 &&
2613 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2617 // Return the last template parameter list, which corresponds to the
2618 // entity being declared.
2619 return ParamLists.back();
2622 void Sema::NoteAllFoundTemplates(TemplateName Name) {
2623 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2624 Diag(Template->getLocation(), diag::note_template_declared_here)
2625 << (isa<FunctionTemplateDecl>(Template)
2627 : isa<ClassTemplateDecl>(Template)
2629 : isa<VarTemplateDecl>(Template)
2631 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2632 << Template->getDeclName();
2636 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2637 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2640 Diag((*I)->getLocation(), diag::note_template_declared_here)
2641 << 0 << (*I)->getDeclName();
2648 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2649 const SmallVectorImpl<TemplateArgument> &Converted,
2650 SourceLocation TemplateLoc,
2651 TemplateArgumentListInfo &TemplateArgs) {
2652 ASTContext &Context = SemaRef.getASTContext();
2653 switch (BTD->getBuiltinTemplateKind()) {
2654 case BTK__make_integer_seq: {
2655 // Specializations of __make_integer_seq<S, T, N> are treated like
2656 // S<T, 0, ..., N-1>.
2658 // C++14 [inteseq.intseq]p1:
2659 // T shall be an integer type.
2660 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2661 SemaRef.Diag(TemplateArgs[1].getLocation(),
2662 diag::err_integer_sequence_integral_element_type);
2666 // C++14 [inteseq.make]p1:
2667 // If N is negative the program is ill-formed.
2668 TemplateArgument NumArgsArg = Converted[2];
2669 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2671 SemaRef.Diag(TemplateArgs[2].getLocation(),
2672 diag::err_integer_sequence_negative_length);
2676 QualType ArgTy = NumArgsArg.getIntegralType();
2677 TemplateArgumentListInfo SyntheticTemplateArgs;
2678 // The type argument gets reused as the first template argument in the
2679 // synthetic template argument list.
2680 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2681 // Expand N into 0 ... N-1.
2682 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2684 TemplateArgument TA(Context, I, ArgTy);
2685 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2686 TA, ArgTy, TemplateArgs[2].getLocation()));
2688 // The first template argument will be reused as the template decl that
2689 // our synthetic template arguments will be applied to.
2690 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2691 TemplateLoc, SyntheticTemplateArgs);
2694 case BTK__type_pack_element:
2695 // Specializations of
2696 // __type_pack_element<Index, T_1, ..., T_N>
2697 // are treated like T_Index.
2698 assert(Converted.size() == 2 &&
2699 "__type_pack_element should be given an index and a parameter pack");
2701 // If the Index is out of bounds, the program is ill-formed.
2702 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2703 llvm::APSInt Index = IndexArg.getAsIntegral();
2704 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2705 "type std::size_t, and hence be non-negative");
2706 if (Index >= Ts.pack_size()) {
2707 SemaRef.Diag(TemplateArgs[0].getLocation(),
2708 diag::err_type_pack_element_out_of_bounds);
2712 // We simply return the type at index `Index`.
2713 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2714 return Nth->getAsType();
2716 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2719 QualType Sema::CheckTemplateIdType(TemplateName Name,
2720 SourceLocation TemplateLoc,
2721 TemplateArgumentListInfo &TemplateArgs) {
2722 DependentTemplateName *DTN
2723 = Name.getUnderlying().getAsDependentTemplateName();
2724 if (DTN && DTN->isIdentifier())
2725 // When building a template-id where the template-name is dependent,
2726 // assume the template is a type template. Either our assumption is
2727 // correct, or the code is ill-formed and will be diagnosed when the
2728 // dependent name is substituted.
2729 return Context.getDependentTemplateSpecializationType(ETK_None,
2730 DTN->getQualifier(),
2731 DTN->getIdentifier(),
2734 TemplateDecl *Template = Name.getAsTemplateDecl();
2735 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2736 isa<VarTemplateDecl>(Template)) {
2737 // We might have a substituted template template parameter pack. If so,
2738 // build a template specialization type for it.
2739 if (Name.getAsSubstTemplateTemplateParmPack())
2740 return Context.getTemplateSpecializationType(Name, TemplateArgs);
2742 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2744 NoteAllFoundTemplates(Name);
2748 // Check that the template argument list is well-formed for this
2750 SmallVector<TemplateArgument, 4> Converted;
2751 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2757 bool InstantiationDependent = false;
2758 if (TypeAliasTemplateDecl *AliasTemplate =
2759 dyn_cast<TypeAliasTemplateDecl>(Template)) {
2760 // Find the canonical type for this type alias template specialization.
2761 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2762 if (Pattern->isInvalidDecl())
2765 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2768 // Only substitute for the innermost template argument list.
2769 MultiLevelTemplateArgumentList TemplateArgLists;
2770 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
2771 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2772 for (unsigned I = 0; I < Depth; ++I)
2773 TemplateArgLists.addOuterTemplateArguments(None);
2775 LocalInstantiationScope Scope(*this);
2776 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2777 if (Inst.isInvalid())
2780 CanonType = SubstType(Pattern->getUnderlyingType(),
2781 TemplateArgLists, AliasTemplate->getLocation(),
2782 AliasTemplate->getDeclName());
2783 if (CanonType.isNull())
2785 } else if (Name.isDependent() ||
2786 TemplateSpecializationType::anyDependentTemplateArguments(
2787 TemplateArgs, InstantiationDependent)) {
2788 // This class template specialization is a dependent
2789 // type. Therefore, its canonical type is another class template
2790 // specialization type that contains all of the converted
2791 // arguments in canonical form. This ensures that, e.g., A<T> and
2792 // A<T, T> have identical types when A is declared as:
2794 // template<typename T, typename U = T> struct A;
2795 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
2797 // This might work out to be a current instantiation, in which
2798 // case the canonical type needs to be the InjectedClassNameType.
2800 // TODO: in theory this could be a simple hashtable lookup; most
2801 // changes to CurContext don't change the set of current
2803 if (isa<ClassTemplateDecl>(Template)) {
2804 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2805 // If we get out to a namespace, we're done.
2806 if (Ctx->isFileContext()) break;
2808 // If this isn't a record, keep looking.
2809 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2810 if (!Record) continue;
2812 // Look for one of the two cases with InjectedClassNameTypes
2813 // and check whether it's the same template.
2814 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2815 !Record->getDescribedClassTemplate())
2818 // Fetch the injected class name type and check whether its
2819 // injected type is equal to the type we just built.
2820 QualType ICNT = Context.getTypeDeclType(Record);
2821 QualType Injected = cast<InjectedClassNameType>(ICNT)
2822 ->getInjectedSpecializationType();
2824 if (CanonType != Injected->getCanonicalTypeInternal())
2827 // If so, the canonical type of this TST is the injected
2828 // class name type of the record we just found.
2829 assert(ICNT.isCanonical());
2834 } else if (ClassTemplateDecl *ClassTemplate
2835 = dyn_cast<ClassTemplateDecl>(Template)) {
2836 // Find the class template specialization declaration that
2837 // corresponds to these arguments.
2838 void *InsertPos = nullptr;
2839 ClassTemplateSpecializationDecl *Decl
2840 = ClassTemplate->findSpecialization(Converted, InsertPos);
2842 // This is the first time we have referenced this class template
2843 // specialization. Create the canonical declaration and add it to
2844 // the set of specializations.
2845 Decl = ClassTemplateSpecializationDecl::Create(Context,
2846 ClassTemplate->getTemplatedDecl()->getTagKind(),
2847 ClassTemplate->getDeclContext(),
2848 ClassTemplate->getTemplatedDecl()->getLocStart(),
2849 ClassTemplate->getLocation(),
2851 Converted, nullptr);
2852 ClassTemplate->AddSpecialization(Decl, InsertPos);
2853 if (ClassTemplate->isOutOfLine())
2854 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2857 if (Decl->getSpecializationKind() == TSK_Undeclared) {
2858 MultiLevelTemplateArgumentList TemplateArgLists;
2859 TemplateArgLists.addOuterTemplateArguments(Converted);
2860 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
2864 // Diagnose uses of this specialization.
2865 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2867 CanonType = Context.getTypeDeclType(Decl);
2868 assert(isa<RecordType>(CanonType) &&
2869 "type of non-dependent specialization is not a RecordType");
2870 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2871 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2875 // Build the fully-sugared type for this class template
2876 // specialization, which refers back to the class template
2877 // specialization we created or found.
2878 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2882 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2883 TemplateTy TemplateD, IdentifierInfo *TemplateII,
2884 SourceLocation TemplateIILoc,
2885 SourceLocation LAngleLoc,
2886 ASTTemplateArgsPtr TemplateArgsIn,
2887 SourceLocation RAngleLoc,
2888 bool IsCtorOrDtorName, bool IsClassName) {
2892 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
2893 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
2895 // C++ [temp.res]p3:
2896 // A qualified-id that refers to a type and in which the
2897 // nested-name-specifier depends on a template-parameter (14.6.2)
2898 // shall be prefixed by the keyword typename to indicate that the
2899 // qualified-id denotes a type, forming an
2900 // elaborated-type-specifier (7.1.5.3).
2901 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
2902 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
2903 << SS.getScopeRep() << TemplateII->getName();
2904 // Recover as if 'typename' were specified.
2905 // FIXME: This is not quite correct recovery as we don't transform SS
2906 // into the corresponding dependent form (and we don't diagnose missing
2907 // 'template' keywords within SS as a result).
2908 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
2909 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
2910 TemplateArgsIn, RAngleLoc);
2913 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
2914 // it's not actually allowed to be used as a type in most cases. Because
2915 // we annotate it before we know whether it's valid, we have to check for
2917 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
2918 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
2920 TemplateKWLoc.isInvalid()
2921 ? diag::err_out_of_line_qualified_id_type_names_constructor
2922 : diag::ext_out_of_line_qualified_id_type_names_constructor)
2923 << TemplateII << 0 /*injected-class-name used as template name*/
2924 << 1 /*if any keyword was present, it was 'template'*/;
2928 TemplateName Template = TemplateD.get();
2930 // Translate the parser's template argument list in our AST format.
2931 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2932 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2934 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2936 = Context.getDependentTemplateSpecializationType(ETK_None,
2937 DTN->getQualifier(),
2938 DTN->getIdentifier(),
2940 // Build type-source information.
2942 DependentTemplateSpecializationTypeLoc SpecTL
2943 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2944 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2945 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2946 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2947 SpecTL.setTemplateNameLoc(TemplateIILoc);
2948 SpecTL.setLAngleLoc(LAngleLoc);
2949 SpecTL.setRAngleLoc(RAngleLoc);
2950 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2951 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2952 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2955 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
2956 if (Result.isNull())
2959 // Build type-source information.
2961 TemplateSpecializationTypeLoc SpecTL
2962 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2963 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2964 SpecTL.setTemplateNameLoc(TemplateIILoc);
2965 SpecTL.setLAngleLoc(LAngleLoc);
2966 SpecTL.setRAngleLoc(RAngleLoc);
2967 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2968 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2970 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2971 // constructor or destructor name (in such a case, the scope specifier
2972 // will be attached to the enclosing Decl or Expr node).
2973 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
2974 // Create an elaborated-type-specifier containing the nested-name-specifier.
2975 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2976 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2977 ElabTL.setElaboratedKeywordLoc(SourceLocation());
2978 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2981 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2984 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
2985 TypeSpecifierType TagSpec,
2986 SourceLocation TagLoc,
2988 SourceLocation TemplateKWLoc,
2989 TemplateTy TemplateD,
2990 SourceLocation TemplateLoc,
2991 SourceLocation LAngleLoc,
2992 ASTTemplateArgsPtr TemplateArgsIn,
2993 SourceLocation RAngleLoc) {
2994 TemplateName Template = TemplateD.get();
2996 // Translate the parser's template argument list in our AST format.
2997 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2998 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3000 // Determine the tag kind
3001 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3002 ElaboratedTypeKeyword Keyword
3003 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3005 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3006 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
3007 DTN->getQualifier(),
3008 DTN->getIdentifier(),
3011 // Build type-source information.
3013 DependentTemplateSpecializationTypeLoc SpecTL
3014 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3015 SpecTL.setElaboratedKeywordLoc(TagLoc);
3016 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3017 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3018 SpecTL.setTemplateNameLoc(TemplateLoc);
3019 SpecTL.setLAngleLoc(LAngleLoc);
3020 SpecTL.setRAngleLoc(RAngleLoc);
3021 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3022 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3023 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3026 if (TypeAliasTemplateDecl *TAT =
3027 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3028 // C++0x [dcl.type.elab]p2:
3029 // If the identifier resolves to a typedef-name or the simple-template-id
3030 // resolves to an alias template specialization, the
3031 // elaborated-type-specifier is ill-formed.
3032 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3033 << TAT << NTK_TypeAliasTemplate << TagKind;
3034 Diag(TAT->getLocation(), diag::note_declared_at);
3037 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3038 if (Result.isNull())
3039 return TypeResult(true);
3041 // Check the tag kind
3042 if (const RecordType *RT = Result->getAs<RecordType>()) {
3043 RecordDecl *D = RT->getDecl();
3045 IdentifierInfo *Id = D->getIdentifier();
3046 assert(Id && "templated class must have an identifier");
3048 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3050 Diag(TagLoc, diag::err_use_with_wrong_tag)
3052 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3053 Diag(D->getLocation(), diag::note_previous_use);
3057 // Provide source-location information for the template specialization.
3059 TemplateSpecializationTypeLoc SpecTL
3060 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3061 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3062 SpecTL.setTemplateNameLoc(TemplateLoc);
3063 SpecTL.setLAngleLoc(LAngleLoc);
3064 SpecTL.setRAngleLoc(RAngleLoc);
3065 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3066 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3068 // Construct an elaborated type containing the nested-name-specifier (if any)
3070 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3071 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3072 ElabTL.setElaboratedKeywordLoc(TagLoc);
3073 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3074 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3077 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3078 NamedDecl *PrevDecl,
3080 bool IsPartialSpecialization);
3082 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
3084 static bool isTemplateArgumentTemplateParameter(
3085 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3086 switch (Arg.getKind()) {
3087 case TemplateArgument::Null:
3088 case TemplateArgument::NullPtr:
3089 case TemplateArgument::Integral:
3090 case TemplateArgument::Declaration:
3091 case TemplateArgument::Pack:
3092 case TemplateArgument::TemplateExpansion:
3095 case TemplateArgument::Type: {
3096 QualType Type = Arg.getAsType();
3097 const TemplateTypeParmType *TPT =
3098 Arg.getAsType()->getAs<TemplateTypeParmType>();
3099 return TPT && !Type.hasQualifiers() &&
3100 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3103 case TemplateArgument::Expression: {
3104 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3105 if (!DRE || !DRE->getDecl())
3107 const NonTypeTemplateParmDecl *NTTP =
3108 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3109 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3112 case TemplateArgument::Template:
3113 const TemplateTemplateParmDecl *TTP =
3114 dyn_cast_or_null<TemplateTemplateParmDecl>(
3115 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3116 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3118 llvm_unreachable("unexpected kind of template argument");
3121 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3122 ArrayRef<TemplateArgument> Args) {
3123 if (Params->size() != Args.size())
3126 unsigned Depth = Params->getDepth();
3128 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3129 TemplateArgument Arg = Args[I];
3131 // If the parameter is a pack expansion, the argument must be a pack
3132 // whose only element is a pack expansion.
3133 if (Params->getParam(I)->isParameterPack()) {
3134 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3135 !Arg.pack_begin()->isPackExpansion())
3137 Arg = Arg.pack_begin()->getPackExpansionPattern();
3140 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3147 /// Convert the parser's template argument list representation into our form.
3148 static TemplateArgumentListInfo
3149 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3150 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3151 TemplateId.RAngleLoc);
3152 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3153 TemplateId.NumArgs);
3154 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3155 return TemplateArgs;
3158 template<typename PartialSpecDecl>
3159 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3160 if (Partial->getDeclContext()->isDependentContext())
3163 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3164 // for non-substitution-failure issues?
3165 TemplateDeductionInfo Info(Partial->getLocation());
3166 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3169 auto *Template = Partial->getSpecializedTemplate();
3170 S.Diag(Partial->getLocation(),
3171 diag::ext_partial_spec_not_more_specialized_than_primary)
3172 << isa<VarTemplateDecl>(Template);
3174 if (Info.hasSFINAEDiagnostic()) {
3175 PartialDiagnosticAt Diag = {SourceLocation(),
3176 PartialDiagnostic::NullDiagnostic()};
3177 Info.takeSFINAEDiagnostic(Diag);
3178 SmallString<128> SFINAEArgString;
3179 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3181 diag::note_partial_spec_not_more_specialized_than_primary)
3185 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3189 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3190 const llvm::SmallBitVector &DeducibleParams) {
3191 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3192 if (!DeducibleParams[I]) {
3193 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3194 if (Param->getDeclName())
3195 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3196 << Param->getDeclName();
3198 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3205 template<typename PartialSpecDecl>
3206 static void checkTemplatePartialSpecialization(Sema &S,
3207 PartialSpecDecl *Partial) {
3208 // C++1z [temp.class.spec]p8: (DR1495)
3209 // - The specialization shall be more specialized than the primary
3210 // template (14.5.5.2).
3211 checkMoreSpecializedThanPrimary(S, Partial);
3213 // C++ [temp.class.spec]p8: (DR1315)
3214 // - Each template-parameter shall appear at least once in the
3215 // template-id outside a non-deduced context.
3216 // C++1z [temp.class.spec.match]p3 (P0127R2)
3217 // If the template arguments of a partial specialization cannot be
3218 // deduced because of the structure of its template-parameter-list
3219 // and the template-id, the program is ill-formed.
3220 auto *TemplateParams = Partial->getTemplateParameters();
3221 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3222 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3223 TemplateParams->getDepth(), DeducibleParams);
3225 if (!DeducibleParams.all()) {
3226 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3227 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3228 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3229 << (NumNonDeducible > 1)
3230 << SourceRange(Partial->getLocation(),
3231 Partial->getTemplateArgsAsWritten()->RAngleLoc);
3232 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3236 void Sema::CheckTemplatePartialSpecialization(
3237 ClassTemplatePartialSpecializationDecl *Partial) {
3238 checkTemplatePartialSpecialization(*this, Partial);
3241 void Sema::CheckTemplatePartialSpecialization(
3242 VarTemplatePartialSpecializationDecl *Partial) {
3243 checkTemplatePartialSpecialization(*this, Partial);
3246 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3247 // C++1z [temp.param]p11:
3248 // A template parameter of a deduction guide template that does not have a
3249 // default-argument shall be deducible from the parameter-type-list of the
3250 // deduction guide template.
3251 auto *TemplateParams = TD->getTemplateParameters();
3252 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3253 MarkDeducedTemplateParameters(TD, DeducibleParams);
3254 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3255 // A parameter pack is deducible (to an empty pack).
3256 auto *Param = TemplateParams->getParam(I);
3257 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3258 DeducibleParams[I] = true;
3261 if (!DeducibleParams.all()) {
3262 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3263 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3264 << (NumNonDeducible > 1);
3265 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3269 DeclResult Sema::ActOnVarTemplateSpecialization(
3270 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3271 TemplateParameterList *TemplateParams, StorageClass SC,
3272 bool IsPartialSpecialization) {
3273 // D must be variable template id.
3274 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
3275 "Variable template specialization is declared with a template it.");
3277 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3278 TemplateArgumentListInfo TemplateArgs =
3279 makeTemplateArgumentListInfo(*this, *TemplateId);
3280 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3281 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3282 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3284 TemplateName Name = TemplateId->Template.get();
3286 // The template-id must name a variable template.
3287 VarTemplateDecl *VarTemplate =
3288 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3290 NamedDecl *FnTemplate;
3291 if (auto *OTS = Name.getAsOverloadedTemplate())
3292 FnTemplate = *OTS->begin();
3294 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3296 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3297 << FnTemplate->getDeclName();
3298 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3299 << IsPartialSpecialization;
3302 // Check for unexpanded parameter packs in any of the template arguments.
3303 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3304 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3305 UPPC_PartialSpecialization))
3308 // Check that the template argument list is well-formed for this
3310 SmallVector<TemplateArgument, 4> Converted;
3311 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3315 // Find the variable template (partial) specialization declaration that
3316 // corresponds to these arguments.
3317 if (IsPartialSpecialization) {
3318 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3319 TemplateArgs.size(), Converted))
3322 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3323 // also do them during instantiation.
3324 bool InstantiationDependent;
3325 if (!Name.isDependent() &&
3326 !TemplateSpecializationType::anyDependentTemplateArguments(
3327 TemplateArgs.arguments(),
3328 InstantiationDependent)) {
3329 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3330 << VarTemplate->getDeclName();
3331 IsPartialSpecialization = false;
3334 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3336 // C++ [temp.class.spec]p9b3:
3338 // -- The argument list of the specialization shall not be identical
3339 // to the implicit argument list of the primary template.
3340 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3341 << /*variable template*/ 1
3342 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3343 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3344 // FIXME: Recover from this by treating the declaration as a redeclaration
3345 // of the primary template.
3350 void *InsertPos = nullptr;
3351 VarTemplateSpecializationDecl *PrevDecl = nullptr;
3353 if (IsPartialSpecialization)
3354 // FIXME: Template parameter list matters too
3355 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
3357 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
3359 VarTemplateSpecializationDecl *Specialization = nullptr;
3361 // Check whether we can declare a variable template specialization in
3362 // the current scope.
3363 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3365 IsPartialSpecialization))
3368 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3369 // Since the only prior variable template specialization with these
3370 // arguments was referenced but not declared, reuse that
3371 // declaration node as our own, updating its source location and
3372 // the list of outer template parameters to reflect our new declaration.
3373 Specialization = PrevDecl;
3374 Specialization->setLocation(TemplateNameLoc);
3376 } else if (IsPartialSpecialization) {
3377 // Create a new class template partial specialization declaration node.
3378 VarTemplatePartialSpecializationDecl *PrevPartial =
3379 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
3380 VarTemplatePartialSpecializationDecl *Partial =
3381 VarTemplatePartialSpecializationDecl::Create(
3382 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3383 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
3384 Converted, TemplateArgs);
3387 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3388 Specialization = Partial;
3390 // If we are providing an explicit specialization of a member variable
3391 // template specialization, make a note of that.
3392 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3393 PrevPartial->setMemberSpecialization();
3395 CheckTemplatePartialSpecialization(Partial);
3397 // Create a new class template specialization declaration node for
3398 // this explicit specialization or friend declaration.
3399 Specialization = VarTemplateSpecializationDecl::Create(
3400 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
3401 VarTemplate, DI->getType(), DI, SC, Converted);
3402 Specialization->setTemplateArgsInfo(TemplateArgs);
3405 VarTemplate->AddSpecialization(Specialization, InsertPos);
3408 // C++ [temp.expl.spec]p6:
3409 // If a template, a member template or the member of a class template is
3410 // explicitly specialized then that specialization shall be declared
3411 // before the first use of that specialization that would cause an implicit
3412 // instantiation to take place, in every translation unit in which such a
3413 // use occurs; no diagnostic is required.
3414 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3416 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3417 // Is there any previous explicit specialization declaration?
3418 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3425 SourceRange Range(TemplateNameLoc, RAngleLoc);
3426 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3429 Diag(PrevDecl->getPointOfInstantiation(),
3430 diag::note_instantiation_required_here)
3431 << (PrevDecl->getTemplateSpecializationKind() !=
3432 TSK_ImplicitInstantiation);
3437 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3438 Specialization->setLexicalDeclContext(CurContext);
3440 // Add the specialization into its lexical context, so that it can
3441 // be seen when iterating through the list of declarations in that
3442 // context. However, specializations are not found by name lookup.
3443 CurContext->addDecl(Specialization);
3445 // Note that this is an explicit specialization.
3446 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3449 // Check that this isn't a redefinition of this specialization,
3450 // merging with previous declarations.
3451 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3453 PrevSpec.addDecl(PrevDecl);
3454 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
3455 } else if (Specialization->isStaticDataMember() &&
3456 Specialization->isOutOfLine()) {
3457 Specialization->setAccess(VarTemplate->getAccess());
3460 // Link instantiations of static data members back to the template from
3461 // which they were instantiated.
3462 if (Specialization->isStaticDataMember())
3463 Specialization->setInstantiationOfStaticDataMember(
3464 VarTemplate->getTemplatedDecl(),
3465 Specialization->getSpecializationKind());
3467 return Specialization;
3471 /// \brief A partial specialization whose template arguments have matched
3472 /// a given template-id.
3473 struct PartialSpecMatchResult {
3474 VarTemplatePartialSpecializationDecl *Partial;
3475 TemplateArgumentList *Args;
3477 } // end anonymous namespace
3480 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3481 SourceLocation TemplateNameLoc,
3482 const TemplateArgumentListInfo &TemplateArgs) {
3483 assert(Template && "A variable template id without template?");
3485 // Check that the template argument list is well-formed for this template.
3486 SmallVector<TemplateArgument, 4> Converted;
3487 if (CheckTemplateArgumentList(
3488 Template, TemplateNameLoc,
3489 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
3493 // Find the variable template specialization declaration that
3494 // corresponds to these arguments.
3495 void *InsertPos = nullptr;
3496 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
3497 Converted, InsertPos)) {
3498 checkSpecializationVisibility(TemplateNameLoc, Spec);
3499 // If we already have a variable template specialization, return it.
3503 // This is the first time we have referenced this variable template
3504 // specialization. Create the canonical declaration and add it to
3505 // the set of specializations, based on the closest partial specialization
3506 // that it represents. That is,
3507 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3508 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
3510 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3511 bool AmbiguousPartialSpec = false;
3512 typedef PartialSpecMatchResult MatchResult;
3513 SmallVector<MatchResult, 4> Matched;
3514 SourceLocation PointOfInstantiation = TemplateNameLoc;
3515 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3516 /*ForTakingAddress=*/false);
3518 // 1. Attempt to find the closest partial specialization that this
3519 // specializes, if any.
3520 // If any of the template arguments is dependent, then this is probably
3521 // a placeholder for an incomplete declarative context; which must be
3522 // complete by instantiation time. Thus, do not search through the partial
3523 // specializations yet.
3524 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3525 // Perhaps better after unification of DeduceTemplateArguments() and
3526 // getMoreSpecializedPartialSpecialization().
3527 bool InstantiationDependent = false;
3528 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3529 TemplateArgs, InstantiationDependent)) {
3531 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3532 Template->getPartialSpecializations(PartialSpecs);
3534 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3535 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3536 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3538 if (TemplateDeductionResult Result =
3539 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3540 // Store the failed-deduction information for use in diagnostics, later.
3541 // TODO: Actually use the failed-deduction info?
3542 FailedCandidates.addCandidate().set(
3543 DeclAccessPair::make(Template, AS_public), Partial,
3544 MakeDeductionFailureInfo(Context, Result, Info));
3547 Matched.push_back(PartialSpecMatchResult());
3548 Matched.back().Partial = Partial;
3549 Matched.back().Args = Info.take();
3553 if (Matched.size() >= 1) {
3554 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3555 if (Matched.size() == 1) {
3556 // -- If exactly one matching specialization is found, the
3557 // instantiation is generated from that specialization.
3558 // We don't need to do anything for this.
3560 // -- If more than one matching specialization is found, the
3561 // partial order rules (14.5.4.2) are used to determine
3562 // whether one of the specializations is more specialized
3563 // than the others. If none of the specializations is more
3564 // specialized than all of the other matching
3565 // specializations, then the use of the variable template is
3566 // ambiguous and the program is ill-formed.
3567 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3568 PEnd = Matched.end();
3570 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3571 PointOfInstantiation) ==
3576 // Determine if the best partial specialization is more specialized than
3578 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3579 PEnd = Matched.end();
3581 if (P != Best && getMoreSpecializedPartialSpecialization(
3582 P->Partial, Best->Partial,
3583 PointOfInstantiation) != Best->Partial) {
3584 AmbiguousPartialSpec = true;
3590 // Instantiate using the best variable template partial specialization.
3591 InstantiationPattern = Best->Partial;
3592 InstantiationArgs = Best->Args;
3594 // -- If no match is found, the instantiation is generated
3595 // from the primary template.
3596 // InstantiationPattern = Template->getTemplatedDecl();
3600 // 2. Create the canonical declaration.
3601 // Note that we do not instantiate a definition until we see an odr-use
3602 // in DoMarkVarDeclReferenced().
3603 // FIXME: LateAttrs et al.?
3604 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3605 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3606 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3610 if (AmbiguousPartialSpec) {
3611 // Partial ordering did not produce a clear winner. Complain.
3612 Decl->setInvalidDecl();
3613 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3616 // Print the matching partial specializations.
3617 for (MatchResult P : Matched)
3618 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3619 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3624 if (VarTemplatePartialSpecializationDecl *D =
3625 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3626 Decl->setInstantiationOf(D, InstantiationArgs);
3628 checkSpecializationVisibility(TemplateNameLoc, Decl);
3630 assert(Decl && "No variable template specialization?");
3635 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3636 const DeclarationNameInfo &NameInfo,
3637 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3638 const TemplateArgumentListInfo *TemplateArgs) {
3640 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3642 if (Decl.isInvalid())
3645 VarDecl *Var = cast<VarDecl>(Decl.get());
3646 if (!Var->getTemplateSpecializationKind())
3647 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3650 // Build an ordinary singleton decl ref.
3651 return BuildDeclarationNameExpr(SS, NameInfo, Var,
3652 /*FoundD=*/nullptr, TemplateArgs);
3655 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
3656 SourceLocation TemplateKWLoc,
3659 const TemplateArgumentListInfo *TemplateArgs) {
3660 // FIXME: Can we do any checking at this point? I guess we could check the
3661 // template arguments that we have against the template name, if the template
3662 // name refers to a single template. That's not a terribly common case,
3664 // foo<int> could identify a single function unambiguously
3665 // This approach does NOT work, since f<int>(1);
3666 // gets resolved prior to resorting to overload resolution
3667 // i.e., template<class T> void f(double);
3668 // vs template<class T, class U> void f(U);
3670 // These should be filtered out by our callers.
3671 assert(!R.empty() && "empty lookup results when building templateid");
3672 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3674 // In C++1y, check variable template ids.
3675 bool InstantiationDependent;
3676 if (R.getAsSingle<VarTemplateDecl>() &&
3677 !TemplateSpecializationType::anyDependentTemplateArguments(
3678 *TemplateArgs, InstantiationDependent)) {
3679 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3680 R.getAsSingle<VarTemplateDecl>(),
3681 TemplateKWLoc, TemplateArgs);
3684 // We don't want lookup warnings at this point.
3685 R.suppressDiagnostics();
3687 UnresolvedLookupExpr *ULE
3688 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3689 SS.getWithLocInContext(Context),
3691 R.getLookupNameInfo(),
3692 RequiresADL, TemplateArgs,
3693 R.begin(), R.end());
3698 // We actually only call this from template instantiation.
3700 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
3701 SourceLocation TemplateKWLoc,
3702 const DeclarationNameInfo &NameInfo,
3703 const TemplateArgumentListInfo *TemplateArgs) {
3705 assert(TemplateArgs || TemplateKWLoc.isValid());
3707 if (!(DC = computeDeclContext(SS, false)) ||
3708 DC->isDependentContext() ||
3709 RequireCompleteDeclContext(SS, DC))
3710 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
3712 bool MemberOfUnknownSpecialization;
3713 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3714 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
3715 MemberOfUnknownSpecialization);
3717 if (R.isAmbiguous())
3721 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3722 << NameInfo.getName() << SS.getRange();
3726 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
3727 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
3729 << NameInfo.getName().getAsString() << SS.getRange();
3730 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3734 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
3737 /// \brief Form a dependent template name.
3739 /// This action forms a dependent template name given the template
3740 /// name and its (presumably dependent) scope specifier. For
3741 /// example, given "MetaFun::template apply", the scope specifier \p
3742 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3743 /// of the "template" keyword, and "apply" is the \p Name.
3744 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
3746 SourceLocation TemplateKWLoc,
3747 UnqualifiedId &Name,
3748 ParsedType ObjectType,
3749 bool EnteringContext,
3751 bool AllowInjectedClassName) {
3752 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3754 getLangOpts().CPlusPlus11 ?
3755 diag::warn_cxx98_compat_template_outside_of_template :
3756 diag::ext_template_outside_of_template)
3757 << FixItHint::CreateRemoval(TemplateKWLoc);
3759 DeclContext *LookupCtx = nullptr;
3761 LookupCtx = computeDeclContext(SS, EnteringContext);
3762 if (!LookupCtx && ObjectType)
3763 LookupCtx = computeDeclContext(ObjectType.get());
3765 // C++0x [temp.names]p5:
3766 // If a name prefixed by the keyword template is not the name of
3767 // a template, the program is ill-formed. [Note: the keyword
3768 // template may not be applied to non-template members of class
3769 // templates. -end note ] [ Note: as is the case with the
3770 // typename prefix, the template prefix is allowed in cases
3771 // where it is not strictly necessary; i.e., when the
3772 // nested-name-specifier or the expression on the left of the ->
3773 // or . is not dependent on a template-parameter, or the use
3774 // does not appear in the scope of a template. -end note]
3776 // Note: C++03 was more strict here, because it banned the use of
3777 // the "template" keyword prior to a template-name that was not a
3778 // dependent name. C++ DR468 relaxed this requirement (the
3779 // "template" keyword is now permitted). We follow the C++0x
3780 // rules, even in C++03 mode with a warning, retroactively applying the DR.
3781 bool MemberOfUnknownSpecialization;
3782 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
3783 ObjectType, EnteringContext, Result,
3784 MemberOfUnknownSpecialization);
3785 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3786 isa<CXXRecordDecl>(LookupCtx) &&
3787 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3788 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
3789 // This is a dependent template. Handle it below.
3790 } else if (TNK == TNK_Non_template) {
3791 Diag(Name.getLocStart(),
3792 diag::err_template_kw_refers_to_non_template)
3793 << GetNameFromUnqualifiedId(Name).getName()
3794 << Name.getSourceRange()
3796 return TNK_Non_template;
3798 // We found something; return it.
3799 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
3800 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
3801 Name.getKind() == UnqualifiedId::IK_Identifier && Name.Identifier &&
3802 LookupRD->getIdentifier() == Name.Identifier) {
3803 // C++14 [class.qual]p2:
3804 // In a lookup in which function names are not ignored and the
3805 // nested-name-specifier nominates a class C, if the name specified
3806 // [...] is the injected-class-name of C, [...] the name is instead
3807 // considered to name the constructor
3809 // We don't get here if naming the constructor would be valid, so we
3810 // just reject immediately and recover by treating the
3811 // injected-class-name as naming the template.
3812 Diag(Name.getLocStart(),
3813 diag::ext_out_of_line_qualified_id_type_names_constructor)
3814 << Name.Identifier << 0 /*injected-class-name used as template name*/
3815 << 1 /*'template' keyword was used*/;
3821 NestedNameSpecifier *Qualifier = SS.getScopeRep();
3823 switch (Name.getKind()) {
3824 case UnqualifiedId::IK_Identifier:
3825 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
3827 return TNK_Dependent_template_name;
3829 case UnqualifiedId::IK_OperatorFunctionId:
3830 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
3831 Name.OperatorFunctionId.Operator));
3832 return TNK_Function_template;
3834 case UnqualifiedId::IK_LiteralOperatorId:
3835 llvm_unreachable("literal operator id cannot have a dependent scope");
3841 Diag(Name.getLocStart(),
3842 diag::err_template_kw_refers_to_non_template)
3843 << GetNameFromUnqualifiedId(Name).getName()
3844 << Name.getSourceRange()
3846 return TNK_Non_template;
3849 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
3850 TemplateArgumentLoc &AL,
3851 SmallVectorImpl<TemplateArgument> &Converted) {
3852 const TemplateArgument &Arg = AL.getArgument();
3854 TypeSourceInfo *TSI = nullptr;
3856 // Check template type parameter.
3857 switch(Arg.getKind()) {
3858 case TemplateArgument::Type:
3859 // C++ [temp.arg.type]p1:
3860 // A template-argument for a template-parameter which is a
3861 // type shall be a type-id.
3862 ArgType = Arg.getAsType();
3863 TSI = AL.getTypeSourceInfo();
3865 case TemplateArgument::Template: {
3866 // We have a template type parameter but the template argument
3867 // is a template without any arguments.
3868 SourceRange SR = AL.getSourceRange();
3869 TemplateName Name = Arg.getAsTemplate();
3870 Diag(SR.getBegin(), diag::err_template_missing_args)
3871 << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
3872 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3873 Diag(Decl->getLocation(), diag::note_template_decl_here);
3877 case TemplateArgument::Expression: {
3878 // We have a template type parameter but the template argument is an
3879 // expression; see if maybe it is missing the "typename" keyword.
3881 DeclarationNameInfo NameInfo;
3883 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3884 SS.Adopt(ArgExpr->getQualifierLoc());
3885 NameInfo = ArgExpr->getNameInfo();
3886 } else if (DependentScopeDeclRefExpr *ArgExpr =
3887 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3888 SS.Adopt(ArgExpr->getQualifierLoc());
3889 NameInfo = ArgExpr->getNameInfo();
3890 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3891 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
3892 if (ArgExpr->isImplicitAccess()) {
3893 SS.Adopt(ArgExpr->getQualifierLoc());
3894 NameInfo = ArgExpr->getMemberNameInfo();
3898 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
3899 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3900 LookupParsedName(Result, CurScope, &SS);
3902 if (Result.getAsSingle<TypeDecl>() ||
3903 Result.getResultKind() ==
3904 LookupResult::NotFoundInCurrentInstantiation) {
3905 // Suggest that the user add 'typename' before the NNS.
3906 SourceLocation Loc = AL.getSourceRange().getBegin();
3907 Diag(Loc, getLangOpts().MSVCCompat
3908 ? diag::ext_ms_template_type_arg_missing_typename
3909 : diag::err_template_arg_must_be_type_suggest)
3910 << FixItHint::CreateInsertion(Loc, "typename ");
3911 Diag(Param->getLocation(), diag::note_template_param_here);
3913 // Recover by synthesizing a type using the location information that we
3916 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3918 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3919 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3920 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3921 TL.setNameLoc(NameInfo.getLoc());
3922 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3924 // Overwrite our input TemplateArgumentLoc so that we can recover
3926 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3927 TemplateArgumentLocInfo(TSI));
3935 // We have a template type parameter but the template argument
3937 SourceRange SR = AL.getSourceRange();
3938 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
3939 Diag(Param->getLocation(), diag::note_template_param_here);
3945 if (CheckTemplateArgument(Param, TSI))
3948 // Add the converted template type argument.
3949 ArgType = Context.getCanonicalType(ArgType);
3952 // If an explicitly-specified template argument type is a lifetime type
3953 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
3954 if (getLangOpts().ObjCAutoRefCount &&
3955 ArgType->isObjCLifetimeType() &&
3956 !ArgType.getObjCLifetime()) {
3958 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3959 ArgType = Context.getQualifiedType(ArgType, Qs);
3962 Converted.push_back(TemplateArgument(ArgType));
3966 /// \brief Substitute template arguments into the default template argument for
3967 /// the given template type parameter.
3969 /// \param SemaRef the semantic analysis object for which we are performing
3970 /// the substitution.
3972 /// \param Template the template that we are synthesizing template arguments
3975 /// \param TemplateLoc the location of the template name that started the
3976 /// template-id we are checking.
3978 /// \param RAngleLoc the location of the right angle bracket ('>') that
3979 /// terminates the template-id.
3981 /// \param Param the template template parameter whose default we are
3982 /// substituting into.
3984 /// \param Converted the list of template arguments provided for template
3985 /// parameters that precede \p Param in the template parameter list.
3986 /// \returns the substituted template argument, or NULL if an error occurred.
3987 static TypeSourceInfo *
3988 SubstDefaultTemplateArgument(Sema &SemaRef,
3989 TemplateDecl *Template,
3990 SourceLocation TemplateLoc,
3991 SourceLocation RAngleLoc,
3992 TemplateTypeParmDecl *Param,
3993 SmallVectorImpl<TemplateArgument> &Converted) {
3994 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
3996 // If the argument type is dependent, instantiate it now based
3997 // on the previously-computed template arguments.
3998 if (ArgType->getType()->isDependentType()) {
3999 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4000 Param, Template, Converted,
4001 SourceRange(TemplateLoc, RAngleLoc));
4002 if (Inst.isInvalid())
4005 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4007 // Only substitute for the innermost template argument list.
4008 MultiLevelTemplateArgumentList TemplateArgLists;
4009 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4010 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4011 TemplateArgLists.addOuterTemplateArguments(None);
4013 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4015 SemaRef.SubstType(ArgType, TemplateArgLists,
4016 Param->getDefaultArgumentLoc(), Param->getDeclName());
4022 /// \brief Substitute template arguments into the default template argument for
4023 /// the given non-type template parameter.
4025 /// \param SemaRef the semantic analysis object for which we are performing
4026 /// the substitution.
4028 /// \param Template the template that we are synthesizing template arguments
4031 /// \param TemplateLoc the location of the template name that started the
4032 /// template-id we are checking.
4034 /// \param RAngleLoc the location of the right angle bracket ('>') that
4035 /// terminates the template-id.
4037 /// \param Param the non-type template parameter whose default we are
4038 /// substituting into.
4040 /// \param Converted the list of template arguments provided for template
4041 /// parameters that precede \p Param in the template parameter list.
4043 /// \returns the substituted template argument, or NULL if an error occurred.
4045 SubstDefaultTemplateArgument(Sema &SemaRef,
4046 TemplateDecl *Template,
4047 SourceLocation TemplateLoc,
4048 SourceLocation RAngleLoc,
4049 NonTypeTemplateParmDecl *Param,
4050 SmallVectorImpl<TemplateArgument> &Converted) {
4051 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4052 Param, Template, Converted,
4053 SourceRange(TemplateLoc, RAngleLoc));
4054 if (Inst.isInvalid())
4057 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4059 // Only substitute for the innermost template argument list.
4060 MultiLevelTemplateArgumentList TemplateArgLists;
4061 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4062 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4063 TemplateArgLists.addOuterTemplateArguments(None);
4065 EnterExpressionEvaluationContext ConstantEvaluated(
4066 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4067 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4070 /// \brief Substitute template arguments into the default template argument for
4071 /// the given template template parameter.
4073 /// \param SemaRef the semantic analysis object for which we are performing
4074 /// the substitution.
4076 /// \param Template the template that we are synthesizing template arguments
4079 /// \param TemplateLoc the location of the template name that started the
4080 /// template-id we are checking.
4082 /// \param RAngleLoc the location of the right angle bracket ('>') that
4083 /// terminates the template-id.
4085 /// \param Param the template template parameter whose default we are
4086 /// substituting into.
4088 /// \param Converted the list of template arguments provided for template
4089 /// parameters that precede \p Param in the template parameter list.
4091 /// \param QualifierLoc Will be set to the nested-name-specifier (with
4092 /// source-location information) that precedes the template name.
4094 /// \returns the substituted template argument, or NULL if an error occurred.
4096 SubstDefaultTemplateArgument(Sema &SemaRef,
4097 TemplateDecl *Template,
4098 SourceLocation TemplateLoc,
4099 SourceLocation RAngleLoc,
4100 TemplateTemplateParmDecl *Param,
4101 SmallVectorImpl<TemplateArgument> &Converted,
4102 NestedNameSpecifierLoc &QualifierLoc) {
4103 Sema::InstantiatingTemplate Inst(
4104 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4105 SourceRange(TemplateLoc, RAngleLoc));
4106 if (Inst.isInvalid())
4107 return TemplateName();
4109 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4111 // Only substitute for the innermost template argument list.
4112 MultiLevelTemplateArgumentList TemplateArgLists;
4113 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4114 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4115 TemplateArgLists.addOuterTemplateArguments(None);
4117 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4118 // Substitute into the nested-name-specifier first,
4119 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4122 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4124 return TemplateName();
4127 return SemaRef.SubstTemplateName(
4129 Param->getDefaultArgument().getArgument().getAsTemplate(),
4130 Param->getDefaultArgument().getTemplateNameLoc(),
4134 /// \brief If the given template parameter has a default template
4135 /// argument, substitute into that default template argument and
4136 /// return the corresponding template argument.
4138 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4139 SourceLocation TemplateLoc,
4140 SourceLocation RAngleLoc,
4142 SmallVectorImpl<TemplateArgument>
4144 bool &HasDefaultArg) {
4145 HasDefaultArg = false;
4147 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4148 if (!hasVisibleDefaultArgument(TypeParm))
4149 return TemplateArgumentLoc();
4151 HasDefaultArg = true;
4152 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4158 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4160 return TemplateArgumentLoc();
4163 if (NonTypeTemplateParmDecl *NonTypeParm
4164 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4165 if (!hasVisibleDefaultArgument(NonTypeParm))
4166 return TemplateArgumentLoc();
4168 HasDefaultArg = true;
4169 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4174 if (Arg.isInvalid())
4175 return TemplateArgumentLoc();
4177 Expr *ArgE = Arg.getAs<Expr>();
4178 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4181 TemplateTemplateParmDecl *TempTempParm
4182 = cast<TemplateTemplateParmDecl>(Param);
4183 if (!hasVisibleDefaultArgument(TempTempParm))
4184 return TemplateArgumentLoc();
4186 HasDefaultArg = true;
4187 NestedNameSpecifierLoc QualifierLoc;
4188 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4195 return TemplateArgumentLoc();
4197 return TemplateArgumentLoc(TemplateArgument(TName),
4198 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4199 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4202 /// Convert a template-argument that we parsed as a type into a template, if
4203 /// possible. C++ permits injected-class-names to perform dual service as
4204 /// template template arguments and as template type arguments.
4205 static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4206 // Extract and step over any surrounding nested-name-specifier.
4207 NestedNameSpecifierLoc QualLoc;
4208 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4209 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4210 return TemplateArgumentLoc();
4212 QualLoc = ETLoc.getQualifierLoc();
4213 TLoc = ETLoc.getNamedTypeLoc();
4216 // If this type was written as an injected-class-name, it can be used as a
4217 // template template argument.
4218 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4219 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4220 QualLoc, InjLoc.getNameLoc());
4222 // If this type was written as an injected-class-name, it may have been
4223 // converted to a RecordType during instantiation. If the RecordType is
4224 // *not* wrapped in a TemplateSpecializationType and denotes a class
4225 // template specialization, it must have come from an injected-class-name.
4226 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4228 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4229 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4230 QualLoc, RecLoc.getNameLoc());
4232 return TemplateArgumentLoc();
4235 /// \brief Check that the given template argument corresponds to the given
4236 /// template parameter.
4238 /// \param Param The template parameter against which the argument will be
4241 /// \param Arg The template argument, which may be updated due to conversions.
4243 /// \param Template The template in which the template argument resides.
4245 /// \param TemplateLoc The location of the template name for the template
4246 /// whose argument list we're matching.
4248 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
4249 /// the template argument list.
4251 /// \param ArgumentPackIndex The index into the argument pack where this
4252 /// argument will be placed. Only valid if the parameter is a parameter pack.
4254 /// \param Converted The checked, converted argument will be added to the
4255 /// end of this small vector.
4257 /// \param CTAK Describes how we arrived at this particular template argument:
4258 /// explicitly written, deduced, etc.
4260 /// \returns true on error, false otherwise.
4261 bool Sema::CheckTemplateArgument(NamedDecl *Param,
4262 TemplateArgumentLoc &Arg,
4263 NamedDecl *Template,
4264 SourceLocation TemplateLoc,
4265 SourceLocation RAngleLoc,
4266 unsigned ArgumentPackIndex,
4267 SmallVectorImpl<TemplateArgument> &Converted,
4268 CheckTemplateArgumentKind CTAK) {
4269 // Check template type parameters.
4270 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4271 return CheckTemplateTypeArgument(TTP, Arg, Converted);
4273 // Check non-type template parameters.
4274 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4275 // Do substitution on the type of the non-type template parameter
4276 // with the template arguments we've seen thus far. But if the
4277 // template has a dependent context then we cannot substitute yet.
4278 QualType NTTPType = NTTP->getType();
4279 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4280 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
4282 if (NTTPType->isDependentType() &&
4283 !isa<TemplateTemplateParmDecl>(Template) &&
4284 !Template->getDeclContext()->isDependentContext()) {
4285 // Do substitution on the type of the non-type template parameter.
4286 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4288 SourceRange(TemplateLoc, RAngleLoc));
4289 if (Inst.isInvalid())
4292 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
4294 NTTPType = SubstType(NTTPType,
4295 MultiLevelTemplateArgumentList(TemplateArgs),
4296 NTTP->getLocation(),
4297 NTTP->getDeclName());
4298 // If that worked, check the non-type template parameter type
4300 if (!NTTPType.isNull())
4301 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4302 NTTP->getLocation());
4303 if (NTTPType.isNull())
4307 switch (Arg.getArgument().getKind()) {
4308 case TemplateArgument::Null:
4309 llvm_unreachable("Should never see a NULL template argument here");
4311 case TemplateArgument::Expression: {
4312 TemplateArgument Result;
4314 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4316 if (Res.isInvalid())
4319 // If the resulting expression is new, then use it in place of the
4320 // old expression in the template argument.
4321 if (Res.get() != Arg.getArgument().getAsExpr()) {
4322 TemplateArgument TA(Res.get());
4323 Arg = TemplateArgumentLoc(TA, Res.get());
4326 Converted.push_back(Result);
4330 case TemplateArgument::Declaration:
4331 case TemplateArgument::Integral:
4332 case TemplateArgument::NullPtr:
4333 // We've already checked this template argument, so just copy
4334 // it to the list of converted arguments.
4335 Converted.push_back(Arg.getArgument());
4338 case TemplateArgument::Template:
4339 case TemplateArgument::TemplateExpansion:
4340 // We were given a template template argument. It may not be ill-formed;
4342 if (DependentTemplateName *DTN
4343 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4344 .getAsDependentTemplateName()) {
4345 // We have a template argument such as \c T::template X, which we
4346 // parsed as a template template argument. However, since we now
4347 // know that we need a non-type template argument, convert this
4348 // template name into an expression.
4350 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4351 Arg.getTemplateNameLoc());
4354 SS.Adopt(Arg.getTemplateQualifierLoc());
4355 // FIXME: the template-template arg was a DependentTemplateName,
4356 // so it was provided with a template keyword. However, its source
4357 // location is not stored in the template argument structure.
4358 SourceLocation TemplateKWLoc;
4359 ExprResult E = DependentScopeDeclRefExpr::Create(
4360 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4363 // If we parsed the template argument as a pack expansion, create a
4364 // pack expansion expression.
4365 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
4366 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
4371 TemplateArgument Result;
4372 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
4376 Converted.push_back(Result);
4380 // We have a template argument that actually does refer to a class
4381 // template, alias template, or template template parameter, and
4382 // therefore cannot be a non-type template argument.
4383 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4384 << Arg.getSourceRange();
4386 Diag(Param->getLocation(), diag::note_template_param_here);
4389 case TemplateArgument::Type: {
4390 // We have a non-type template parameter but the template
4391 // argument is a type.
4393 // C++ [temp.arg]p2:
4394 // In a template-argument, an ambiguity between a type-id and
4395 // an expression is resolved to a type-id, regardless of the
4396 // form of the corresponding template-parameter.
4398 // We warn specifically about this case, since it can be rather
4399 // confusing for users.
4400 QualType T = Arg.getArgument().getAsType();
4401 SourceRange SR = Arg.getSourceRange();
4402 if (T->isFunctionType())
4403 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4405 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4406 Diag(Param->getLocation(), diag::note_template_param_here);
4410 case TemplateArgument::Pack:
4411 llvm_unreachable("Caller must expand template argument packs");
4418 // Check template template parameters.
4419 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
4421 // Substitute into the template parameter list of the template
4422 // template parameter, since previously-supplied template arguments
4423 // may appear within the template template parameter.
4425 // Set up a template instantiation context.
4426 LocalInstantiationScope Scope(*this);
4427 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4428 TempParm, Converted,
4429 SourceRange(TemplateLoc, RAngleLoc));
4430 if (Inst.isInvalid())
4433 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4434 TempParm = cast_or_null<TemplateTemplateParmDecl>(
4435 SubstDecl(TempParm, CurContext,
4436 MultiLevelTemplateArgumentList(TemplateArgs)));
4441 // C++1z [temp.local]p1: (DR1004)
4442 // When [the injected-class-name] is used [...] as a template-argument for
4443 // a template template-parameter [...] it refers to the class template
4445 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4446 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4447 Arg.getTypeSourceInfo()->getTypeLoc());
4448 if (!ConvertedArg.getArgument().isNull())
4452 switch (Arg.getArgument().getKind()) {
4453 case TemplateArgument::Null:
4454 llvm_unreachable("Should never see a NULL template argument here");
4456 case TemplateArgument::Template:
4457 case TemplateArgument::TemplateExpansion:
4458 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
4461 Converted.push_back(Arg.getArgument());
4464 case TemplateArgument::Expression:
4465 case TemplateArgument::Type:
4466 // We have a template template parameter but the template
4467 // argument does not refer to a template.
4468 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
4469 << getLangOpts().CPlusPlus11;
4472 case TemplateArgument::Declaration:
4473 llvm_unreachable("Declaration argument with template template parameter");
4474 case TemplateArgument::Integral:
4475 llvm_unreachable("Integral argument with template template parameter");
4476 case TemplateArgument::NullPtr:
4477 llvm_unreachable("Null pointer argument with template template parameter");
4479 case TemplateArgument::Pack:
4480 llvm_unreachable("Caller must expand template argument packs");
4486 /// \brief Diagnose an arity mismatch in the
4487 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4488 SourceLocation TemplateLoc,
4489 TemplateArgumentListInfo &TemplateArgs) {
4490 TemplateParameterList *Params = Template->getTemplateParameters();
4491 unsigned NumParams = Params->size();
4492 unsigned NumArgs = TemplateArgs.size();
4495 if (NumArgs > NumParams)
4496 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
4497 TemplateArgs.getRAngleLoc());
4498 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4499 << (NumArgs > NumParams)
4500 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
4501 << Template << Range;
4502 S.Diag(Template->getLocation(), diag::note_template_decl_here)
4503 << Params->getSourceRange();
4507 /// \brief Check whether the template parameter is a pack expansion, and if so,
4508 /// determine the number of parameters produced by that expansion. For instance:
4511 /// template<typename ...Ts> struct A {
4512 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4516 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4517 /// is not a pack expansion, so returns an empty Optional.
4518 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
4519 if (NonTypeTemplateParmDecl *NTTP
4520 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4521 if (NTTP->isExpandedParameterPack())
4522 return NTTP->getNumExpansionTypes();
4525 if (TemplateTemplateParmDecl *TTP
4526 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4527 if (TTP->isExpandedParameterPack())
4528 return TTP->getNumExpansionTemplateParameters();
4534 /// Diagnose a missing template argument.
4535 template<typename TemplateParmDecl>
4536 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4538 const TemplateParmDecl *D,
4539 TemplateArgumentListInfo &Args) {
4540 // Dig out the most recent declaration of the template parameter; there may be
4541 // declarations of the template that are more recent than TD.
4542 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4543 ->getTemplateParameters()
4544 ->getParam(D->getIndex()));
4546 // If there's a default argument that's not visible, diagnose that we're
4547 // missing a module import.
4548 llvm::SmallVector<Module*, 8> Modules;
4549 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4550 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4551 D->getDefaultArgumentLoc(), Modules,
4552 Sema::MissingImportKind::DefaultArgument,
4557 // FIXME: If there's a more recent default argument that *is* visible,
4558 // diagnose that it was declared too late.
4560 return diagnoseArityMismatch(S, TD, Loc, Args);
4563 /// \brief Check that the given template argument list is well-formed
4564 /// for specializing the given template.
4565 bool Sema::CheckTemplateArgumentList(
4566 TemplateDecl *Template, SourceLocation TemplateLoc,
4567 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4568 SmallVectorImpl<TemplateArgument> &Converted,
4569 bool UpdateArgsWithConversions) {
4570 // Make a copy of the template arguments for processing. Only make the
4571 // changes at the end when successful in matching the arguments to the
4573 TemplateArgumentListInfo NewArgs = TemplateArgs;
4575 TemplateParameterList *Params = Template->getTemplateParameters();
4577 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
4579 // C++ [temp.arg]p1:
4580 // [...] The type and form of each template-argument specified in
4581 // a template-id shall match the type and form specified for the
4582 // corresponding parameter declared by the template in its
4583 // template-parameter-list.
4584 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
4585 SmallVector<TemplateArgument, 2> ArgumentPack;
4586 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
4587 LocalInstantiationScope InstScope(*this, true);
4588 for (TemplateParameterList::iterator Param = Params->begin(),
4589 ParamEnd = Params->end();
4590 Param != ParamEnd; /* increment in loop */) {
4591 // If we have an expanded parameter pack, make sure we don't have too
4593 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
4594 if (*Expansions == ArgumentPack.size()) {
4595 // We're done with this parameter pack. Pack up its arguments and add
4596 // them to the list.
4597 Converted.push_back(
4598 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4599 ArgumentPack.clear();
4601 // This argument is assigned to the next parameter.
4604 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4605 // Not enough arguments for this parameter pack.
4606 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4608 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
4610 Diag(Template->getLocation(), diag::note_template_decl_here)
4611 << Params->getSourceRange();
4616 if (ArgIdx < NumArgs) {
4617 // Check the template argument we were given.
4618 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
4619 TemplateLoc, RAngleLoc,
4620 ArgumentPack.size(), Converted))
4623 bool PackExpansionIntoNonPack =
4624 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
4625 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4626 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
4627 // Core issue 1430: we have a pack expansion as an argument to an
4628 // alias template, and it's not part of a parameter pack. This
4629 // can't be canonicalized, so reject it now.
4630 Diag(NewArgs[ArgIdx].getLocation(),
4631 diag::err_alias_template_expansion_into_fixed_list)
4632 << NewArgs[ArgIdx].getSourceRange();
4633 Diag((*Param)->getLocation(), diag::note_template_param_here);
4637 // We're now done with this argument.
4640 if ((*Param)->isTemplateParameterPack()) {
4641 // The template parameter was a template parameter pack, so take the
4642 // deduced argument and place it on the argument pack. Note that we
4643 // stay on the same template parameter so that we can deduce more
4645 ArgumentPack.push_back(Converted.pop_back_val());
4647 // Move to the next template parameter.
4651 // If we just saw a pack expansion into a non-pack, then directly convert
4652 // the remaining arguments, because we don't know what parameters they'll
4654 if (PackExpansionIntoNonPack) {
4655 if (!ArgumentPack.empty()) {
4656 // If we were part way through filling in an expanded parameter pack,
4657 // fall back to just producing individual arguments.
4658 Converted.insert(Converted.end(),
4659 ArgumentPack.begin(), ArgumentPack.end());
4660 ArgumentPack.clear();
4663 while (ArgIdx < NumArgs) {
4664 Converted.push_back(NewArgs[ArgIdx].getArgument());
4674 // If we're checking a partial template argument list, we're done.
4675 if (PartialTemplateArgs) {
4676 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
4677 Converted.push_back(
4678 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4683 // If we have a template parameter pack with no more corresponding
4684 // arguments, just break out now and we'll fill in the argument pack below.
4685 if ((*Param)->isTemplateParameterPack()) {
4686 assert(!getExpandedPackSize(*Param) &&
4687 "Should have dealt with this already");
4689 // A non-expanded parameter pack before the end of the parameter list
4690 // only occurs for an ill-formed template parameter list, unless we've
4691 // got a partial argument list for a function template, so just bail out.
4692 if (Param + 1 != ParamEnd)
4695 Converted.push_back(
4696 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4697 ArgumentPack.clear();
4703 // Check whether we have a default argument.
4704 TemplateArgumentLoc Arg;
4706 // Retrieve the default template argument from the template
4707 // parameter. For each kind of template parameter, we substitute the
4708 // template arguments provided thus far and any "outer" template arguments
4709 // (when the template parameter was part of a nested template) into
4710 // the default argument.
4711 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
4712 if (!hasVisibleDefaultArgument(TTP))
4713 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4716 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
4725 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4727 } else if (NonTypeTemplateParmDecl *NTTP
4728 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
4729 if (!hasVisibleDefaultArgument(NTTP))
4730 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4733 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
4741 Expr *Ex = E.getAs<Expr>();
4742 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4744 TemplateTemplateParmDecl *TempParm
4745 = cast<TemplateTemplateParmDecl>(*Param);
4747 if (!hasVisibleDefaultArgument(TempParm))
4748 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4751 NestedNameSpecifierLoc QualifierLoc;
4752 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
4761 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4762 TempParm->getDefaultArgument().getTemplateNameLoc());
4765 // Introduce an instantiation record that describes where we are using
4766 // the default template argument. We're not actually instantiating a
4767 // template here, we just create this object to put a note into the
4769 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4770 SourceRange(TemplateLoc, RAngleLoc));
4771 if (Inst.isInvalid())
4774 // Check the default template argument.
4775 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
4776 RAngleLoc, 0, Converted))
4779 // Core issue 150 (assumed resolution): if this is a template template
4780 // parameter, keep track of the default template arguments from the
4781 // template definition.
4782 if (isTemplateTemplateParameter)
4783 NewArgs.addArgument(Arg);
4785 // Move to the next template parameter and argument.
4790 // If we're performing a partial argument substitution, allow any trailing
4791 // pack expansions; they might be empty. This can happen even if
4792 // PartialTemplateArgs is false (the list of arguments is complete but
4793 // still dependent).
4794 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4795 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
4796 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4797 Converted.push_back(NewArgs[ArgIdx++].getArgument());
4800 // If we have any leftover arguments, then there were too many arguments.
4801 // Complain and fail.
4802 if (ArgIdx < NumArgs)
4803 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4805 // No problems found with the new argument list, propagate changes back
4807 if (UpdateArgsWithConversions)
4808 TemplateArgs = std::move(NewArgs);
4814 class UnnamedLocalNoLinkageFinder
4815 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
4820 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
4823 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4825 bool Visit(QualType T) {
4826 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
4829 #define TYPE(Class, Parent) \
4830 bool Visit##Class##Type(const Class##Type *);
4831 #define ABSTRACT_TYPE(Class, Parent) \
4832 bool Visit##Class##Type(const Class##Type *) { return false; }
4833 #define NON_CANONICAL_TYPE(Class, Parent) \
4834 bool Visit##Class##Type(const Class##Type *) { return false; }
4835 #include "clang/AST/TypeNodes.def"
4837 bool VisitTagDecl(const TagDecl *Tag);
4838 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4840 } // end anonymous namespace
4842 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
4846 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4847 return Visit(T->getElementType());
4850 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
4851 return Visit(T->getPointeeType());
4854 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
4855 const BlockPointerType* T) {
4856 return Visit(T->getPointeeType());
4859 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
4860 const LValueReferenceType* T) {
4861 return Visit(T->getPointeeType());
4864 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
4865 const RValueReferenceType* T) {
4866 return Visit(T->getPointeeType());
4869 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
4870 const MemberPointerType* T) {
4871 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4874 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
4875 const ConstantArrayType* T) {
4876 return Visit(T->getElementType());
4879 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
4880 const IncompleteArrayType* T) {
4881 return Visit(T->getElementType());
4884 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
4885 const VariableArrayType* T) {
4886 return Visit(T->getElementType());
4889 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
4890 const DependentSizedArrayType* T) {
4891 return Visit(T->getElementType());
4894 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
4895 const DependentSizedExtVectorType* T) {
4896 return Visit(T->getElementType());
4899 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4900 return Visit(T->getElementType());
4903 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4904 return Visit(T->getElementType());
4907 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4908 const FunctionProtoType* T) {
4909 for (const auto &A : T->param_types()) {
4914 return Visit(T->getReturnType());
4917 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4918 const FunctionNoProtoType* T) {
4919 return Visit(T->getReturnType());
4922 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4923 const UnresolvedUsingType*) {
4927 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4931 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4932 return Visit(T->getUnderlyingType());
4935 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4939 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4940 const UnaryTransformType*) {
4944 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4945 return Visit(T->getDeducedType());
4948 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
4949 const DeducedTemplateSpecializationType *T) {
4950 return Visit(T->getDeducedType());
4953 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4954 return VisitTagDecl(T->getDecl());
4957 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4958 return VisitTagDecl(T->getDecl());
4961 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4962 const TemplateTypeParmType*) {
4966 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4967 const SubstTemplateTypeParmPackType *) {
4971 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4972 const TemplateSpecializationType*) {
4976 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4977 const InjectedClassNameType* T) {
4978 return VisitTagDecl(T->getDecl());
4981 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4982 const DependentNameType* T) {
4983 return VisitNestedNameSpecifier(T->getQualifier());
4986 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4987 const DependentTemplateSpecializationType* T) {
4988 return VisitNestedNameSpecifier(T->getQualifier());
4991 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4992 const PackExpansionType* T) {
4993 return Visit(T->getPattern());
4996 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5000 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5001 const ObjCInterfaceType *) {
5005 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5006 const ObjCObjectPointerType *) {
5010 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5011 return Visit(T->getValueType());
5014 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5018 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5019 if (Tag->getDeclContext()->isFunctionOrMethod()) {
5020 S.Diag(SR.getBegin(),
5021 S.getLangOpts().CPlusPlus11 ?
5022 diag::warn_cxx98_compat_template_arg_local_type :
5023 diag::ext_template_arg_local_type)
5024 << S.Context.getTypeDeclType(Tag) << SR;
5028 if (!Tag->hasNameForLinkage()) {
5029 S.Diag(SR.getBegin(),
5030 S.getLangOpts().CPlusPlus11 ?
5031 diag::warn_cxx98_compat_template_arg_unnamed_type :
5032 diag::ext_template_arg_unnamed_type) << SR;
5033 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5040 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5041 NestedNameSpecifier *NNS) {
5042 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5045 switch (NNS->getKind()) {
5046 case NestedNameSpecifier::Identifier:
5047 case NestedNameSpecifier::Namespace:
5048 case NestedNameSpecifier::NamespaceAlias:
5049 case NestedNameSpecifier::Global:
5050 case NestedNameSpecifier::Super:
5053 case NestedNameSpecifier::TypeSpec:
5054 case NestedNameSpecifier::TypeSpecWithTemplate:
5055 return Visit(QualType(NNS->getAsType(), 0));
5057 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5060 /// \brief Check a template argument against its corresponding
5061 /// template type parameter.
5063 /// This routine implements the semantics of C++ [temp.arg.type]. It
5064 /// returns true if an error occurred, and false otherwise.
5065 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
5066 TypeSourceInfo *ArgInfo) {
5067 assert(ArgInfo && "invalid TypeSourceInfo");
5068 QualType Arg = ArgInfo->getType();
5069 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5071 if (Arg->isVariablyModifiedType()) {
5072 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5073 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5074 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5077 // C++03 [temp.arg.type]p2:
5078 // A local type, a type with no linkage, an unnamed type or a type
5079 // compounded from any of these types shall not be used as a
5080 // template-argument for a template type-parameter.
5082 // C++11 allows these, and even in C++03 we allow them as an extension with
5084 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5085 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5086 (void)Finder.Visit(Context.getCanonicalType(Arg));
5092 enum NullPointerValueKind {
5098 /// \brief Determine whether the given template argument is a null pointer
5099 /// value of the appropriate type.
5100 static NullPointerValueKind
5101 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5102 QualType ParamType, Expr *Arg) {
5103 if (Arg->isValueDependent() || Arg->isTypeDependent())
5104 return NPV_NotNullPointer;
5106 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5108 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
5110 if (!S.getLangOpts().CPlusPlus11)
5111 return NPV_NotNullPointer;
5113 // Determine whether we have a constant expression.
5114 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5115 if (ArgRV.isInvalid())
5119 Expr::EvalResult EvalResult;
5120 SmallVector<PartialDiagnosticAt, 8> Notes;
5121 EvalResult.Diag = &Notes;
5122 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5123 EvalResult.HasSideEffects) {
5124 SourceLocation DiagLoc = Arg->getExprLoc();
5126 // If our only note is the usual "invalid subexpression" note, just point
5127 // the caret at its location rather than producing an essentially
5129 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5130 diag::note_invalid_subexpr_in_const_expr) {
5131 DiagLoc = Notes[0].first;
5135 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5136 << Arg->getType() << Arg->getSourceRange();
5137 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5138 S.Diag(Notes[I].first, Notes[I].second);
5140 S.Diag(Param->getLocation(), diag::note_template_param_here);
5144 // C++11 [temp.arg.nontype]p1:
5145 // - an address constant expression of type std::nullptr_t
5146 if (Arg->getType()->isNullPtrType())
5147 return NPV_NullPointer;
5149 // - a constant expression that evaluates to a null pointer value (4.10); or
5150 // - a constant expression that evaluates to a null member pointer value
5152 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5153 (EvalResult.Val.isMemberPointer() &&
5154 !EvalResult.Val.getMemberPointerDecl())) {
5155 // If our expression has an appropriate type, we've succeeded.
5156 bool ObjCLifetimeConversion;
5157 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5158 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5159 ObjCLifetimeConversion))
5160 return NPV_NullPointer;
5162 // The types didn't match, but we know we got a null pointer; complain,
5163 // then recover as if the types were correct.
5164 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5165 << Arg->getType() << ParamType << Arg->getSourceRange();
5166 S.Diag(Param->getLocation(), diag::note_template_param_here);
5167 return NPV_NullPointer;
5170 // If we don't have a null pointer value, but we do have a NULL pointer
5171 // constant, suggest a cast to the appropriate type.
5172 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5173 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5174 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
5175 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5176 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
5178 S.Diag(Param->getLocation(), diag::note_template_param_here);
5179 return NPV_NullPointer;
5182 // FIXME: If we ever want to support general, address-constant expressions
5183 // as non-type template arguments, we should return the ExprResult here to
5184 // be interpreted by the caller.
5185 return NPV_NotNullPointer;
5188 /// \brief Checks whether the given template argument is compatible with its
5189 /// template parameter.
5190 static bool CheckTemplateArgumentIsCompatibleWithParameter(
5191 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5192 Expr *Arg, QualType ArgType) {
5193 bool ObjCLifetimeConversion;
5194 if (ParamType->isPointerType() &&
5195 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5196 S.IsQualificationConversion(ArgType, ParamType, false,
5197 ObjCLifetimeConversion)) {
5198 // For pointer-to-object types, qualification conversions are
5201 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5202 if (!ParamRef->getPointeeType()->isFunctionType()) {
5203 // C++ [temp.arg.nontype]p5b3:
5204 // For a non-type template-parameter of type reference to
5205 // object, no conversions apply. The type referred to by the
5206 // reference may be more cv-qualified than the (otherwise
5207 // identical) type of the template- argument. The
5208 // template-parameter is bound directly to the
5209 // template-argument, which shall be an lvalue.
5211 // FIXME: Other qualifiers?
5212 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5213 unsigned ArgQuals = ArgType.getCVRQualifiers();
5215 if ((ParamQuals | ArgQuals) != ParamQuals) {
5216 S.Diag(Arg->getLocStart(),
5217 diag::err_template_arg_ref_bind_ignores_quals)
5218 << ParamType << Arg->getType() << Arg->getSourceRange();
5219 S.Diag(Param->getLocation(), diag::note_template_param_here);
5225 // At this point, the template argument refers to an object or
5226 // function with external linkage. We now need to check whether the
5227 // argument and parameter types are compatible.
5228 if (!S.Context.hasSameUnqualifiedType(ArgType,
5229 ParamType.getNonReferenceType())) {
5230 // We can't perform this conversion or binding.
5231 if (ParamType->isReferenceType())
5232 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5233 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5235 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5236 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5237 S.Diag(Param->getLocation(), diag::note_template_param_here);
5245 /// \brief Checks whether the given template argument is the address
5246 /// of an object or function according to C++ [temp.arg.nontype]p1.
5248 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5249 NonTypeTemplateParmDecl *Param,
5252 TemplateArgument &Converted) {
5253 bool Invalid = false;
5255 QualType ArgType = Arg->getType();
5257 bool AddressTaken = false;
5258 SourceLocation AddrOpLoc;
5259 if (S.getLangOpts().MicrosoftExt) {
5260 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5261 // dereference and address-of operators.
5262 Arg = Arg->IgnoreParenCasts();
5264 bool ExtWarnMSTemplateArg = false;
5265 UnaryOperatorKind FirstOpKind;
5266 SourceLocation FirstOpLoc;
5267 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5268 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5269 if (UnOpKind == UO_Deref)
5270 ExtWarnMSTemplateArg = true;
5271 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5272 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5273 if (!AddrOpLoc.isValid()) {
5274 FirstOpKind = UnOpKind;
5275 FirstOpLoc = UnOp->getOperatorLoc();
5280 if (FirstOpLoc.isValid()) {
5281 if (ExtWarnMSTemplateArg)
5282 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5283 << ArgIn->getSourceRange();
5285 if (FirstOpKind == UO_AddrOf)
5286 AddressTaken = true;
5287 else if (Arg->getType()->isPointerType()) {
5288 // We cannot let pointers get dereferenced here, that is obviously not a
5289 // constant expression.
5290 assert(FirstOpKind == UO_Deref);
5291 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5292 << Arg->getSourceRange();
5296 // See through any implicit casts we added to fix the type.
5297 Arg = Arg->IgnoreImpCasts();
5299 // C++ [temp.arg.nontype]p1:
5301 // A template-argument for a non-type, non-template
5302 // template-parameter shall be one of: [...]
5304 // -- the address of an object or function with external
5305 // linkage, including function templates and function
5306 // template-ids but excluding non-static class members,
5307 // expressed as & id-expression where the & is optional if
5308 // the name refers to a function or array, or if the
5309 // corresponding template-parameter is a reference; or
5311 // In C++98/03 mode, give an extension warning on any extra parentheses.
5312 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5313 bool ExtraParens = false;
5314 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5315 if (!Invalid && !ExtraParens) {
5316 S.Diag(Arg->getLocStart(),
5317 S.getLangOpts().CPlusPlus11
5318 ? diag::warn_cxx98_compat_template_arg_extra_parens
5319 : diag::ext_template_arg_extra_parens)
5320 << Arg->getSourceRange();
5324 Arg = Parens->getSubExpr();
5327 while (SubstNonTypeTemplateParmExpr *subst =
5328 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5329 Arg = subst->getReplacement()->IgnoreImpCasts();
5331 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5332 if (UnOp->getOpcode() == UO_AddrOf) {
5333 Arg = UnOp->getSubExpr();
5334 AddressTaken = true;
5335 AddrOpLoc = UnOp->getOperatorLoc();
5339 while (SubstNonTypeTemplateParmExpr *subst =
5340 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5341 Arg = subst->getReplacement()->IgnoreImpCasts();
5344 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5345 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5347 // If our parameter has pointer type, check for a null template value.
5348 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5349 NullPointerValueKind NPV;
5350 // dllimport'd entities aren't constant but are available inside of template
5352 if (Entity && Entity->hasAttr<DLLImportAttr>())
5353 NPV = NPV_NotNullPointer;
5355 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
5357 case NPV_NullPointer:
5358 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5359 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5360 /*isNullPtr=*/true);
5366 case NPV_NotNullPointer:
5371 // Stop checking the precise nature of the argument if it is value dependent,
5372 // it should be checked when instantiated.
5373 if (Arg->isValueDependent()) {
5374 Converted = TemplateArgument(ArgIn);
5378 if (isa<CXXUuidofExpr>(Arg)) {
5379 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5380 ArgIn, Arg, ArgType))
5383 Converted = TemplateArgument(ArgIn);
5388 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5389 << Arg->getSourceRange();
5390 S.Diag(Param->getLocation(), diag::note_template_param_here);
5394 // Cannot refer to non-static data members
5395 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
5396 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
5397 << Entity << Arg->getSourceRange();
5398 S.Diag(Param->getLocation(), diag::note_template_param_here);
5402 // Cannot refer to non-static member functions
5403 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
5404 if (!Method->isStatic()) {
5405 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
5406 << Method << Arg->getSourceRange();
5407 S.Diag(Param->getLocation(), diag::note_template_param_here);
5412 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5413 VarDecl *Var = dyn_cast<VarDecl>(Entity);
5415 // A non-type template argument must refer to an object or function.
5416 if (!Func && !Var) {
5417 // We found something, but we don't know specifically what it is.
5418 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5419 << Arg->getSourceRange();
5420 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5424 // Address / reference template args must have external linkage in C++98.
5425 if (Entity->getFormalLinkage() == InternalLinkage) {
5426 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
5427 diag::warn_cxx98_compat_template_arg_object_internal :
5428 diag::ext_template_arg_object_internal)
5429 << !Func << Entity << Arg->getSourceRange();
5430 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5432 } else if (!Entity->hasLinkage()) {
5433 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5434 << !Func << Entity << Arg->getSourceRange();
5435 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5441 // If the template parameter has pointer type, the function decays.
5442 if (ParamType->isPointerType() && !AddressTaken)
5443 ArgType = S.Context.getPointerType(Func->getType());
5444 else if (AddressTaken && ParamType->isReferenceType()) {
5445 // If we originally had an address-of operator, but the
5446 // parameter has reference type, complain and (if things look
5447 // like they will work) drop the address-of operator.
5448 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5449 ParamType.getNonReferenceType())) {
5450 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5452 S.Diag(Param->getLocation(), diag::note_template_param_here);
5456 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5458 << FixItHint::CreateRemoval(AddrOpLoc);
5459 S.Diag(Param->getLocation(), diag::note_template_param_here);
5461 ArgType = Func->getType();
5464 // A value of reference type is not an object.
5465 if (Var->getType()->isReferenceType()) {
5466 S.Diag(Arg->getLocStart(),
5467 diag::err_template_arg_reference_var)
5468 << Var->getType() << Arg->getSourceRange();
5469 S.Diag(Param->getLocation(), diag::note_template_param_here);
5473 // A template argument must have static storage duration.
5474 if (Var->getTLSKind()) {
5475 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5476 << Arg->getSourceRange();
5477 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5481 // If the template parameter has pointer type, we must have taken
5482 // the address of this object.
5483 if (ParamType->isReferenceType()) {
5485 // If we originally had an address-of operator, but the
5486 // parameter has reference type, complain and (if things look
5487 // like they will work) drop the address-of operator.
5488 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5489 ParamType.getNonReferenceType())) {
5490 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5492 S.Diag(Param->getLocation(), diag::note_template_param_here);
5496 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5498 << FixItHint::CreateRemoval(AddrOpLoc);
5499 S.Diag(Param->getLocation(), diag::note_template_param_here);
5501 ArgType = Var->getType();
5503 } else if (!AddressTaken && ParamType->isPointerType()) {
5504 if (Var->getType()->isArrayType()) {
5505 // Array-to-pointer decay.
5506 ArgType = S.Context.getArrayDecayedType(Var->getType());
5508 // If the template parameter has pointer type but the address of
5509 // this object was not taken, complain and (possibly) recover by
5510 // taking the address of the entity.
5511 ArgType = S.Context.getPointerType(Var->getType());
5512 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5513 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5515 S.Diag(Param->getLocation(), diag::note_template_param_here);
5519 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5521 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5523 S.Diag(Param->getLocation(), diag::note_template_param_here);
5528 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5532 // Create the template argument.
5534 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
5535 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
5539 /// \brief Checks whether the given template argument is a pointer to
5540 /// member constant according to C++ [temp.arg.nontype]p1.
5541 static bool CheckTemplateArgumentPointerToMember(Sema &S,
5542 NonTypeTemplateParmDecl *Param,
5545 TemplateArgument &Converted) {
5546 bool Invalid = false;
5548 // Check for a null pointer value.
5549 Expr *Arg = ResultArg;
5550 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
5553 case NPV_NullPointer:
5554 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5555 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5558 case NPV_NotNullPointer:
5562 bool ObjCLifetimeConversion;
5563 if (S.IsQualificationConversion(Arg->getType(),
5564 ParamType.getNonReferenceType(),
5565 false, ObjCLifetimeConversion)) {
5566 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
5567 Arg->getValueKind()).get();
5569 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
5570 ParamType.getNonReferenceType())) {
5571 // We can't perform this conversion.
5572 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5573 << Arg->getType() << ParamType << Arg->getSourceRange();
5574 S.Diag(Param->getLocation(), diag::note_template_param_here);
5578 // See through any implicit casts we added to fix the type.
5579 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
5580 Arg = Cast->getSubExpr();
5582 // C++ [temp.arg.nontype]p1:
5584 // A template-argument for a non-type, non-template
5585 // template-parameter shall be one of: [...]
5587 // -- a pointer to member expressed as described in 5.3.1.
5588 DeclRefExpr *DRE = nullptr;
5590 // In C++98/03 mode, give an extension warning on any extra parentheses.
5591 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5592 bool ExtraParens = false;
5593 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5594 if (!Invalid && !ExtraParens) {
5595 S.Diag(Arg->getLocStart(),
5596 S.getLangOpts().CPlusPlus11 ?
5597 diag::warn_cxx98_compat_template_arg_extra_parens :
5598 diag::ext_template_arg_extra_parens)
5599 << Arg->getSourceRange();
5603 Arg = Parens->getSubExpr();
5606 while (SubstNonTypeTemplateParmExpr *subst =
5607 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5608 Arg = subst->getReplacement()->IgnoreImpCasts();
5610 // A pointer-to-member constant written &Class::member.
5611 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5612 if (UnOp->getOpcode() == UO_AddrOf) {
5613 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5614 if (DRE && !DRE->getQualifier())
5618 // A constant of pointer-to-member type.
5619 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5620 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5621 if (VD->getType()->isMemberPointerType()) {
5622 if (isa<NonTypeTemplateParmDecl>(VD)) {
5623 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5624 Converted = TemplateArgument(Arg);
5626 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5627 Converted = TemplateArgument(VD, ParamType);
5638 return S.Diag(Arg->getLocStart(),
5639 diag::err_template_arg_not_pointer_to_member_form)
5640 << Arg->getSourceRange();
5642 if (isa<FieldDecl>(DRE->getDecl()) ||
5643 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5644 isa<CXXMethodDecl>(DRE->getDecl())) {
5645 assert((isa<FieldDecl>(DRE->getDecl()) ||
5646 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5647 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5648 "Only non-static member pointers can make it here");
5650 // Okay: this is the address of a non-static member, and therefore
5651 // a member pointer constant.
5652 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5653 Converted = TemplateArgument(Arg);
5655 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
5656 Converted = TemplateArgument(D, ParamType);
5661 // We found something else, but we don't know specifically what it is.
5662 S.Diag(Arg->getLocStart(),
5663 diag::err_template_arg_not_pointer_to_member_form)
5664 << Arg->getSourceRange();
5665 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5669 /// \brief Check a template argument against its corresponding
5670 /// non-type template parameter.
5672 /// This routine implements the semantics of C++ [temp.arg.nontype].
5673 /// If an error occurred, it returns ExprError(); otherwise, it
5674 /// returns the converted template argument. \p ParamType is the
5675 /// type of the non-type template parameter after it has been instantiated.
5676 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5677 QualType ParamType, Expr *Arg,
5678 TemplateArgument &Converted,
5679 CheckTemplateArgumentKind CTAK) {
5680 SourceLocation StartLoc = Arg->getLocStart();
5682 // If the parameter type somehow involves auto, deduce the type now.
5683 if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
5684 // During template argument deduction, we allow 'decltype(auto)' to
5685 // match an arbitrary dependent argument.
5686 // FIXME: The language rules don't say what happens in this case.
5687 // FIXME: We get an opaque dependent type out of decltype(auto) if the
5688 // expression is merely instantiation-dependent; is this enough?
5689 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
5690 auto *AT = dyn_cast<AutoType>(ParamType);
5691 if (AT && AT->isDecltypeAuto()) {
5692 Converted = TemplateArgument(Arg);
5697 // When checking a deduced template argument, deduce from its type even if
5698 // the type is dependent, in order to check the types of non-type template
5699 // arguments line up properly in partial ordering.
5700 Optional<unsigned> Depth;
5701 if (CTAK != CTAK_Specified)
5702 Depth = Param->getDepth() + 1;
5704 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
5705 Arg, ParamType, Depth) == DAR_Failed) {
5706 Diag(Arg->getExprLoc(),
5707 diag::err_non_type_template_parm_type_deduction_failure)
5708 << Param->getDeclName() << Param->getType() << Arg->getType()
5709 << Arg->getSourceRange();
5710 Diag(Param->getLocation(), diag::note_template_param_here);
5713 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5714 // an error. The error message normally references the parameter
5715 // declaration, but here we'll pass the argument location because that's
5716 // where the parameter type is deduced.
5717 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5718 if (ParamType.isNull()) {
5719 Diag(Param->getLocation(), diag::note_template_param_here);
5724 // We should have already dropped all cv-qualifiers by now.
5725 assert(!ParamType.hasQualifiers() &&
5726 "non-type template parameter type cannot be qualified");
5728 if (CTAK == CTAK_Deduced &&
5729 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
5731 // FIXME: If either type is dependent, we skip the check. This isn't
5732 // correct, since during deduction we're supposed to have replaced each
5733 // template parameter with some unique (non-dependent) placeholder.
5734 // FIXME: If the argument type contains 'auto', we carry on and fail the
5735 // type check in order to force specific types to be more specialized than
5736 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
5738 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
5739 !Arg->getType()->getContainedAutoType()) {
5740 Converted = TemplateArgument(Arg);
5743 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
5744 // we should actually be checking the type of the template argument in P,
5745 // not the type of the template argument deduced from A, against the
5746 // template parameter type.
5747 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
5749 << ParamType.getUnqualifiedType();
5750 Diag(Param->getLocation(), diag::note_template_param_here);
5754 // If either the parameter has a dependent type or the argument is
5755 // type-dependent, there's nothing we can check now.
5756 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
5757 // FIXME: Produce a cloned, canonical expression?
5758 Converted = TemplateArgument(Arg);
5762 // The initialization of the parameter from the argument is
5763 // a constant-evaluated context.
5764 EnterExpressionEvaluationContext ConstantEvaluated(
5765 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5767 if (getLangOpts().CPlusPlus1z) {
5768 // C++1z [temp.arg.nontype]p1:
5769 // A template-argument for a non-type template parameter shall be
5770 // a converted constant expression of the type of the template-parameter.
5772 ExprResult ArgResult = CheckConvertedConstantExpression(
5773 Arg, ParamType, Value, CCEK_TemplateArg);
5774 if (ArgResult.isInvalid())
5777 // For a value-dependent argument, CheckConvertedConstantExpression is
5778 // permitted (and expected) to be unable to determine a value.
5779 if (ArgResult.get()->isValueDependent()) {
5780 Converted = TemplateArgument(ArgResult.get());
5784 QualType CanonParamType = Context.getCanonicalType(ParamType);
5786 // Convert the APValue to a TemplateArgument.
5787 switch (Value.getKind()) {
5788 case APValue::Uninitialized:
5789 assert(ParamType->isNullPtrType());
5790 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
5793 assert(ParamType->isIntegralOrEnumerationType());
5794 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
5796 case APValue::MemberPointer: {
5797 assert(ParamType->isMemberPointerType());
5799 // FIXME: We need TemplateArgument representation and mangling for these.
5800 if (!Value.getMemberPointerPath().empty()) {
5801 Diag(Arg->getLocStart(),
5802 diag::err_template_arg_member_ptr_base_derived_not_supported)
5803 << Value.getMemberPointerDecl() << ParamType
5804 << Arg->getSourceRange();
5808 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
5809 Converted = VD ? TemplateArgument(VD, CanonParamType)
5810 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
5813 case APValue::LValue: {
5814 // For a non-type template-parameter of pointer or reference type,
5815 // the value of the constant expression shall not refer to
5816 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
5817 ParamType->isNullPtrType());
5818 // -- a temporary object
5819 // -- a string literal
5820 // -- the result of a typeid expression, or
5821 // -- a predefined __func__ variable
5822 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
5823 if (isa<CXXUuidofExpr>(E)) {
5824 Converted = TemplateArgument(const_cast<Expr*>(E));
5827 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5828 << Arg->getSourceRange();
5831 auto *VD = const_cast<ValueDecl *>(
5832 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5834 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5835 VD && VD->getType()->isArrayType() &&
5836 Value.getLValuePath()[0].ArrayIndex == 0 &&
5837 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5838 // Per defect report (no number yet):
5839 // ... other than a pointer to the first element of a complete array
5841 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5842 Value.isLValueOnePastTheEnd()) {
5843 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5844 << Value.getAsString(Context, ParamType);
5847 assert((VD || !ParamType->isReferenceType()) &&
5848 "null reference should not be a constant expression");
5849 assert((!VD || !ParamType->isNullPtrType()) &&
5850 "non-null value of type nullptr_t?");
5851 Converted = VD ? TemplateArgument(VD, CanonParamType)
5852 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
5855 case APValue::AddrLabelDiff:
5856 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5857 case APValue::Float:
5858 case APValue::ComplexInt:
5859 case APValue::ComplexFloat:
5860 case APValue::Vector:
5861 case APValue::Array:
5862 case APValue::Struct:
5863 case APValue::Union:
5864 llvm_unreachable("invalid kind for template argument");
5867 return ArgResult.get();
5870 // C++ [temp.arg.nontype]p5:
5871 // The following conversions are performed on each expression used
5872 // as a non-type template-argument. If a non-type
5873 // template-argument cannot be converted to the type of the
5874 // corresponding template-parameter then the program is
5876 if (ParamType->isIntegralOrEnumerationType()) {
5878 // -- for a non-type template-parameter of integral or
5879 // enumeration type, conversions permitted in a converted
5880 // constant expression are applied.
5883 // -- for a non-type template-parameter of integral or
5884 // enumeration type, integral promotions (4.5) and integral
5885 // conversions (4.7) are applied.
5887 if (getLangOpts().CPlusPlus11) {
5888 // C++ [temp.arg.nontype]p1:
5889 // A template-argument for a non-type, non-template template-parameter
5892 // -- for a non-type template-parameter of integral or enumeration
5893 // type, a converted constant expression of the type of the
5894 // template-parameter; or
5896 ExprResult ArgResult =
5897 CheckConvertedConstantExpression(Arg, ParamType, Value,
5899 if (ArgResult.isInvalid())
5902 // We can't check arbitrary value-dependent arguments.
5903 if (ArgResult.get()->isValueDependent()) {
5904 Converted = TemplateArgument(ArgResult.get());
5908 // Widen the argument value to sizeof(parameter type). This is almost
5909 // always a no-op, except when the parameter type is bool. In
5910 // that case, this may extend the argument from 1 bit to 8 bits.
5911 QualType IntegerType = ParamType;
5912 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5913 IntegerType = Enum->getDecl()->getIntegerType();
5914 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
5916 Converted = TemplateArgument(Context, Value,
5917 Context.getCanonicalType(ParamType));
5921 ExprResult ArgResult = DefaultLvalueConversion(Arg);
5922 if (ArgResult.isInvalid())
5924 Arg = ArgResult.get();
5926 QualType ArgType = Arg->getType();
5928 // C++ [temp.arg.nontype]p1:
5929 // A template-argument for a non-type, non-template
5930 // template-parameter shall be one of:
5932 // -- an integral constant-expression of integral or enumeration
5934 // -- the name of a non-type template-parameter; or
5935 SourceLocation NonConstantLoc;
5937 if (!ArgType->isIntegralOrEnumerationType()) {
5938 Diag(Arg->getLocStart(),
5939 diag::err_template_arg_not_integral_or_enumeral)
5940 << ArgType << Arg->getSourceRange();
5941 Diag(Param->getLocation(), diag::note_template_param_here);
5943 } else if (!Arg->isValueDependent()) {
5944 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5948 TmplArgICEDiagnoser(QualType T) : T(T) { }
5950 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5951 SourceRange SR) override {
5952 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5954 } Diagnoser(ArgType);
5956 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
5962 // From here on out, all we care about is the unqualified form
5963 // of the argument type.
5964 ArgType = ArgType.getUnqualifiedType();
5966 // Try to convert the argument to the parameter's type.
5967 if (Context.hasSameType(ParamType, ArgType)) {
5968 // Okay: no conversion necessary
5969 } else if (ParamType->isBooleanType()) {
5970 // This is an integral-to-boolean conversion.
5971 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
5972 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5973 !ParamType->isEnumeralType()) {
5974 // This is an integral promotion or conversion.
5975 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
5977 // We can't perform this conversion.
5978 Diag(Arg->getLocStart(),
5979 diag::err_template_arg_not_convertible)
5980 << Arg->getType() << ParamType << Arg->getSourceRange();
5981 Diag(Param->getLocation(), diag::note_template_param_here);
5985 // Add the value of this argument to the list of converted
5986 // arguments. We use the bitwidth and signedness of the template
5988 if (Arg->isValueDependent()) {
5989 // The argument is value-dependent. Create a new
5990 // TemplateArgument with the converted expression.
5991 Converted = TemplateArgument(Arg);
5995 QualType IntegerType = Context.getCanonicalType(ParamType);
5996 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5997 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
5999 if (ParamType->isBooleanType()) {
6000 // Value must be zero or one.
6002 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6003 if (Value.getBitWidth() != AllowedBits)
6004 Value = Value.extOrTrunc(AllowedBits);
6005 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6007 llvm::APSInt OldValue = Value;
6009 // Coerce the template argument's value to the value it will have
6010 // based on the template parameter's type.
6011 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6012 if (Value.getBitWidth() != AllowedBits)
6013 Value = Value.extOrTrunc(AllowedBits);
6014 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6016 // Complain if an unsigned parameter received a negative value.
6017 if (IntegerType->isUnsignedIntegerOrEnumerationType()
6018 && (OldValue.isSigned() && OldValue.isNegative())) {
6019 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
6020 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6021 << Arg->getSourceRange();
6022 Diag(Param->getLocation(), diag::note_template_param_here);
6025 // Complain if we overflowed the template parameter's type.
6026 unsigned RequiredBits;
6027 if (IntegerType->isUnsignedIntegerOrEnumerationType())
6028 RequiredBits = OldValue.getActiveBits();
6029 else if (OldValue.isUnsigned())
6030 RequiredBits = OldValue.getActiveBits() + 1;
6032 RequiredBits = OldValue.getMinSignedBits();
6033 if (RequiredBits > AllowedBits) {
6034 Diag(Arg->getLocStart(),
6035 diag::warn_template_arg_too_large)
6036 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6037 << Arg->getSourceRange();
6038 Diag(Param->getLocation(), diag::note_template_param_here);
6042 Converted = TemplateArgument(Context, Value,
6043 ParamType->isEnumeralType()
6044 ? Context.getCanonicalType(ParamType)
6049 QualType ArgType = Arg->getType();
6050 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6052 // Handle pointer-to-function, reference-to-function, and
6053 // pointer-to-member-function all in (roughly) the same way.
6054 if (// -- For a non-type template-parameter of type pointer to
6055 // function, only the function-to-pointer conversion (4.3) is
6056 // applied. If the template-argument represents a set of
6057 // overloaded functions (or a pointer to such), the matching
6058 // function is selected from the set (13.4).
6059 (ParamType->isPointerType() &&
6060 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6061 // -- For a non-type template-parameter of type reference to
6062 // function, no conversions apply. If the template-argument
6063 // represents a set of overloaded functions, the matching
6064 // function is selected from the set (13.4).
6065 (ParamType->isReferenceType() &&
6066 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6067 // -- For a non-type template-parameter of type pointer to
6068 // member function, no conversions apply. If the
6069 // template-argument represents a set of overloaded member
6070 // functions, the matching member function is selected from
6072 (ParamType->isMemberPointerType() &&
6073 ParamType->getAs<MemberPointerType>()->getPointeeType()
6074 ->isFunctionType())) {
6076 if (Arg->getType() == Context.OverloadTy) {
6077 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6080 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6083 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6084 ArgType = Arg->getType();
6089 if (!ParamType->isMemberPointerType()) {
6090 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6097 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6103 if (ParamType->isPointerType()) {
6104 // -- for a non-type template-parameter of type pointer to
6105 // object, qualification conversions (4.4) and the
6106 // array-to-pointer conversion (4.2) are applied.
6107 // C++0x also allows a value of std::nullptr_t.
6108 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
6109 "Only object pointers allowed here");
6111 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6118 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
6119 // -- For a non-type template-parameter of type reference to
6120 // object, no conversions apply. The type referred to by the
6121 // reference may be more cv-qualified than the (otherwise
6122 // identical) type of the template-argument. The
6123 // template-parameter is bound directly to the
6124 // template-argument, which must be an lvalue.
6125 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
6126 "Only object references allowed here");
6128 if (Arg->getType() == Context.OverloadTy) {
6129 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6130 ParamRefType->getPointeeType(),
6133 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6136 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6137 ArgType = Arg->getType();
6142 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6149 // Deal with parameters of type std::nullptr_t.
6150 if (ParamType->isNullPtrType()) {
6151 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6152 Converted = TemplateArgument(Arg);
6156 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6157 case NPV_NotNullPointer:
6158 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6159 << Arg->getType() << ParamType;
6160 Diag(Param->getLocation(), diag::note_template_param_here);
6166 case NPV_NullPointer:
6167 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6168 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6174 // -- For a non-type template-parameter of type pointer to data
6175 // member, qualification conversions (4.4) are applied.
6176 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6178 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6184 static void DiagnoseTemplateParameterListArityMismatch(
6185 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6186 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6188 /// \brief Check a template argument against its corresponding
6189 /// template template parameter.
6191 /// This routine implements the semantics of C++ [temp.arg.template].
6192 /// It returns true if an error occurred, and false otherwise.
6193 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6194 TemplateArgumentLoc &Arg,
6195 unsigned ArgumentPackIndex) {
6196 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
6197 TemplateDecl *Template = Name.getAsTemplateDecl();
6199 // Any dependent template name is fine.
6200 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6204 if (Template->isInvalidDecl())
6207 // C++0x [temp.arg.template]p1:
6208 // A template-argument for a template template-parameter shall be
6209 // the name of a class template or an alias template, expressed as an
6210 // id-expression. When the template-argument names a class template, only
6211 // primary class templates are considered when matching the
6212 // template template argument with the corresponding parameter;
6213 // partial specializations are not considered even if their
6214 // parameter lists match that of the template template parameter.
6216 // Note that we also allow template template parameters here, which
6217 // will happen when we are dealing with, e.g., class template
6218 // partial specializations.
6219 if (!isa<ClassTemplateDecl>(Template) &&
6220 !isa<TemplateTemplateParmDecl>(Template) &&
6221 !isa<TypeAliasTemplateDecl>(Template) &&
6222 !isa<BuiltinTemplateDecl>(Template)) {
6223 assert(isa<FunctionTemplateDecl>(Template) &&
6224 "Only function templates are possible here");
6225 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
6226 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6230 TemplateParameterList *Params = Param->getTemplateParameters();
6231 if (Param->isExpandedParameterPack())
6232 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
6234 // C++1z [temp.arg.template]p3: (DR 150)
6235 // A template-argument matches a template template-parameter P when P
6236 // is at least as specialized as the template-argument A.
6237 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6238 // Quick check for the common case:
6239 // If P contains a parameter pack, then A [...] matches P if each of A's
6240 // template parameters matches the corresponding template parameter in
6241 // the template-parameter-list of P.
6242 if (TemplateParameterListsAreEqual(
6243 Template->getTemplateParameters(), Params, false,
6244 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6247 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6250 // FIXME: Produce better diagnostics for deduction failures.
6253 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
6256 TPL_TemplateTemplateArgumentMatch,
6260 /// \brief Given a non-type template argument that refers to a
6261 /// declaration and the type of its corresponding non-type template
6262 /// parameter, produce an expression that properly refers to that
6265 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6267 SourceLocation Loc) {
6268 // C++ [temp.param]p8:
6270 // A non-type template-parameter of type "array of T" or
6271 // "function returning T" is adjusted to be of type "pointer to
6272 // T" or "pointer to function returning T", respectively.
6273 if (ParamType->isArrayType())
6274 ParamType = Context.getArrayDecayedType(ParamType);
6275 else if (ParamType->isFunctionType())
6276 ParamType = Context.getPointerType(ParamType);
6278 // For a NULL non-type template argument, return nullptr casted to the
6279 // parameter's type.
6280 if (Arg.getKind() == TemplateArgument::NullPtr) {
6281 return ImpCastExprToType(
6282 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6284 ParamType->getAs<MemberPointerType>()
6285 ? CK_NullToMemberPointer
6286 : CK_NullToPointer);
6288 assert(Arg.getKind() == TemplateArgument::Declaration &&
6289 "Only declaration template arguments permitted here");
6291 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
6293 if (VD->getDeclContext()->isRecord() &&
6294 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6295 isa<IndirectFieldDecl>(VD))) {
6296 // If the value is a class member, we might have a pointer-to-member.
6297 // Determine whether the non-type template template parameter is of
6298 // pointer-to-member type. If so, we need to build an appropriate
6299 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6300 // would refer to the member itself.
6301 if (ParamType->isMemberPointerType()) {
6303 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6304 NestedNameSpecifier *Qualifier
6305 = NestedNameSpecifier::Create(Context, nullptr, false,
6306 ClassType.getTypePtr());
6308 SS.MakeTrivial(Context, Qualifier, Loc);
6310 // The actual value-ness of this is unimportant, but for
6311 // internal consistency's sake, references to instance methods
6313 ExprValueKind VK = VK_LValue;
6314 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6317 ExprResult RefExpr = BuildDeclRefExpr(VD,
6318 VD->getType().getNonReferenceType(),
6322 if (RefExpr.isInvalid())
6325 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6327 // We might need to perform a trailing qualification conversion, since
6328 // the element type on the parameter could be more qualified than the
6329 // element type in the expression we constructed.
6330 bool ObjCLifetimeConversion;
6331 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
6332 ParamType.getUnqualifiedType(), false,
6333 ObjCLifetimeConversion))
6334 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
6336 assert(!RefExpr.isInvalid() &&
6337 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
6338 ParamType.getUnqualifiedType()));
6343 QualType T = VD->getType().getNonReferenceType();
6345 if (ParamType->isPointerType()) {
6346 // When the non-type template parameter is a pointer, take the
6347 // address of the declaration.
6348 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
6349 if (RefExpr.isInvalid())
6352 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6353 (T->isFunctionType() || T->isArrayType())) {
6354 // Decay functions and arrays unless we're forming a pointer to array.
6355 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
6356 if (RefExpr.isInvalid())
6362 // Take the address of everything else
6363 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6366 ExprValueKind VK = VK_RValue;
6368 // If the non-type template parameter has reference type, qualify the
6369 // resulting declaration reference with the extra qualifiers on the
6370 // type that the reference refers to.
6371 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6373 T = Context.getQualifiedType(T,
6374 TargetRef->getPointeeType().getQualifiers());
6375 } else if (isa<FunctionDecl>(VD)) {
6376 // References to functions are always lvalues.
6380 return BuildDeclRefExpr(VD, T, VK, Loc);
6383 /// \brief Construct a new expression that refers to the given
6384 /// integral template argument with the given source-location
6387 /// This routine takes care of the mapping from an integral template
6388 /// argument (which may have any integral type) to the appropriate
6391 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6392 SourceLocation Loc) {
6393 assert(Arg.getKind() == TemplateArgument::Integral &&
6394 "Operation is only valid for integral template arguments");
6395 QualType OrigT = Arg.getIntegralType();
6397 // If this is an enum type that we're instantiating, we need to use an integer
6398 // type the same size as the enumerator. We don't want to build an
6399 // IntegerLiteral with enum type. The integer type of an enum type can be of
6400 // any integral type with C++11 enum classes, make sure we create the right
6401 // type of literal for it.
6403 if (const EnumType *ET = OrigT->getAs<EnumType>())
6404 T = ET->getDecl()->getIntegerType();
6407 if (T->isAnyCharacterType()) {
6408 // This does not need to handle u8 character literals because those are
6409 // of type char, and so can also be covered by an ASCII character literal.
6410 CharacterLiteral::CharacterKind Kind;
6411 if (T->isWideCharType())
6412 Kind = CharacterLiteral::Wide;
6413 else if (T->isChar16Type())
6414 Kind = CharacterLiteral::UTF16;
6415 else if (T->isChar32Type())
6416 Kind = CharacterLiteral::UTF32;
6418 Kind = CharacterLiteral::Ascii;
6420 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6422 } else if (T->isBooleanType()) {
6423 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6425 } else if (T->isNullPtrType()) {
6426 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6428 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
6431 if (OrigT->isEnumeralType()) {
6432 // FIXME: This is a hack. We need a better way to handle substituted
6433 // non-type template parameters.
6434 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6436 Context.getTrivialTypeSourceInfo(OrigT, Loc),
6443 /// \brief Match two template parameters within template parameter lists.
6444 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6446 Sema::TemplateParameterListEqualKind Kind,
6447 SourceLocation TemplateArgLoc) {
6448 // Check the actual kind (type, non-type, template).
6449 if (Old->getKind() != New->getKind()) {
6451 unsigned NextDiag = diag::err_template_param_different_kind;
6452 if (TemplateArgLoc.isValid()) {
6453 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6454 NextDiag = diag::note_template_param_different_kind;
6456 S.Diag(New->getLocation(), NextDiag)
6457 << (Kind != Sema::TPL_TemplateMatch);
6458 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6459 << (Kind != Sema::TPL_TemplateMatch);
6465 // Check that both are parameter packs or neither are parameter packs.
6466 // However, if we are matching a template template argument to a
6467 // template template parameter, the template template parameter can have
6468 // a parameter pack where the template template argument does not.
6469 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6470 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6471 Old->isTemplateParameterPack())) {
6473 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6474 if (TemplateArgLoc.isValid()) {
6475 S.Diag(TemplateArgLoc,
6476 diag::err_template_arg_template_params_mismatch);
6477 NextDiag = diag::note_template_parameter_pack_non_pack;
6480 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6481 : isa<NonTypeTemplateParmDecl>(New)? 1
6483 S.Diag(New->getLocation(), NextDiag)
6484 << ParamKind << New->isParameterPack();
6485 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6486 << ParamKind << Old->isParameterPack();
6492 // For non-type template parameters, check the type of the parameter.
6493 if (NonTypeTemplateParmDecl *OldNTTP
6494 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6495 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
6497 // If we are matching a template template argument to a template
6498 // template parameter and one of the non-type template parameter types
6499 // is dependent, then we must wait until template instantiation time
6500 // to actually compare the arguments.
6501 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6502 (OldNTTP->getType()->isDependentType() ||
6503 NewNTTP->getType()->isDependentType()))
6506 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6508 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6509 if (TemplateArgLoc.isValid()) {
6510 S.Diag(TemplateArgLoc,
6511 diag::err_template_arg_template_params_mismatch);
6512 NextDiag = diag::note_template_nontype_parm_different_type;
6514 S.Diag(NewNTTP->getLocation(), NextDiag)
6515 << NewNTTP->getType()
6516 << (Kind != Sema::TPL_TemplateMatch);
6517 S.Diag(OldNTTP->getLocation(),
6518 diag::note_template_nontype_parm_prev_declaration)
6519 << OldNTTP->getType();
6528 // For template template parameters, check the template parameter types.
6529 // The template parameter lists of template template
6530 // parameters must agree.
6531 if (TemplateTemplateParmDecl *OldTTP
6532 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
6533 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
6534 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6535 OldTTP->getTemplateParameters(),
6537 (Kind == Sema::TPL_TemplateMatch
6538 ? Sema::TPL_TemplateTemplateParmMatch
6546 /// \brief Diagnose a known arity mismatch when comparing template argument
6549 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
6550 TemplateParameterList *New,
6551 TemplateParameterList *Old,
6552 Sema::TemplateParameterListEqualKind Kind,
6553 SourceLocation TemplateArgLoc) {
6554 unsigned NextDiag = diag::err_template_param_list_different_arity;
6555 if (TemplateArgLoc.isValid()) {
6556 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6557 NextDiag = diag::note_template_param_list_different_arity;
6559 S.Diag(New->getTemplateLoc(), NextDiag)
6560 << (New->size() > Old->size())
6561 << (Kind != Sema::TPL_TemplateMatch)
6562 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6563 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6564 << (Kind != Sema::TPL_TemplateMatch)
6565 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6568 /// \brief Determine whether the given template parameter lists are
6571 /// \param New The new template parameter list, typically written in the
6572 /// source code as part of a new template declaration.
6574 /// \param Old The old template parameter list, typically found via
6575 /// name lookup of the template declared with this template parameter
6578 /// \param Complain If true, this routine will produce a diagnostic if
6579 /// the template parameter lists are not equivalent.
6581 /// \param Kind describes how we are to match the template parameter lists.
6583 /// \param TemplateArgLoc If this source location is valid, then we
6584 /// are actually checking the template parameter list of a template
6585 /// argument (New) against the template parameter list of its
6586 /// corresponding template template parameter (Old). We produce
6587 /// slightly different diagnostics in this scenario.
6589 /// \returns True if the template parameter lists are equal, false
6592 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
6593 TemplateParameterList *Old,
6595 TemplateParameterListEqualKind Kind,
6596 SourceLocation TemplateArgLoc) {
6597 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6599 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6605 // C++0x [temp.arg.template]p3:
6606 // A template-argument matches a template template-parameter (call it P)
6607 // when each of the template parameters in the template-parameter-list of
6608 // the template-argument's corresponding class template or alias template
6609 // (call it A) matches the corresponding template parameter in the
6610 // template-parameter-list of P. [...]
6611 TemplateParameterList::iterator NewParm = New->begin();
6612 TemplateParameterList::iterator NewParmEnd = New->end();
6613 for (TemplateParameterList::iterator OldParm = Old->begin(),
6614 OldParmEnd = Old->end();
6615 OldParm != OldParmEnd; ++OldParm) {
6616 if (Kind != TPL_TemplateTemplateArgumentMatch ||
6617 !(*OldParm)->isTemplateParameterPack()) {
6618 if (NewParm == NewParmEnd) {
6620 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6626 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6627 Kind, TemplateArgLoc))
6634 // C++0x [temp.arg.template]p3:
6635 // [...] When P's template- parameter-list contains a template parameter
6636 // pack (14.5.3), the template parameter pack will match zero or more
6637 // template parameters or template parameter packs in the
6638 // template-parameter-list of A with the same type and form as the
6639 // template parameter pack in P (ignoring whether those template
6640 // parameters are template parameter packs).
6641 for (; NewParm != NewParmEnd; ++NewParm) {
6642 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6643 Kind, TemplateArgLoc))
6648 // Make sure we exhausted all of the arguments.
6649 if (NewParm != NewParmEnd) {
6651 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6660 /// \brief Check whether a template can be declared within this scope.
6662 /// If the template declaration is valid in this scope, returns
6663 /// false. Otherwise, issues a diagnostic and returns true.
6665 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
6669 // Find the nearest enclosing declaration scope.
6670 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6671 (S->getFlags() & Scope::TemplateParamScope) != 0)
6675 // A template [...] shall not have C linkage.
6676 DeclContext *Ctx = S->getEntity();
6677 if (Ctx && Ctx->isExternCContext()) {
6678 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6679 << TemplateParams->getSourceRange();
6680 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6681 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6684 Ctx = Ctx->getRedeclContext();
6687 // A template-declaration can appear only as a namespace scope or
6688 // class scope declaration.
6690 if (Ctx->isFileContext())
6692 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6693 // C++ [temp.mem]p2:
6694 // A local class shall not have member templates.
6695 if (RD->isLocalClass())
6696 return Diag(TemplateParams->getTemplateLoc(),
6697 diag::err_template_inside_local_class)
6698 << TemplateParams->getSourceRange();
6704 return Diag(TemplateParams->getTemplateLoc(),
6705 diag::err_template_outside_namespace_or_class_scope)
6706 << TemplateParams->getSourceRange();
6709 /// \brief Determine what kind of template specialization the given declaration
6711 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
6713 return TSK_Undeclared;
6715 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
6716 return Record->getTemplateSpecializationKind();
6717 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
6718 return Function->getTemplateSpecializationKind();
6719 if (VarDecl *Var = dyn_cast<VarDecl>(D))
6720 return Var->getTemplateSpecializationKind();
6722 return TSK_Undeclared;
6725 /// \brief Check whether a specialization is well-formed in the current
6728 /// This routine determines whether a template specialization can be declared
6729 /// in the current context (C++ [temp.expl.spec]p2).
6731 /// \param S the semantic analysis object for which this check is being
6734 /// \param Specialized the entity being specialized or instantiated, which
6735 /// may be a kind of template (class template, function template, etc.) or
6736 /// a member of a class template (member function, static data member,
6739 /// \param PrevDecl the previous declaration of this entity, if any.
6741 /// \param Loc the location of the explicit specialization or instantiation of
6744 /// \param IsPartialSpecialization whether this is a partial specialization of
6745 /// a class template.
6747 /// \returns true if there was an error that we cannot recover from, false
6749 static bool CheckTemplateSpecializationScope(Sema &S,
6750 NamedDecl *Specialized,
6751 NamedDecl *PrevDecl,
6753 bool IsPartialSpecialization) {
6754 // Keep these "kind" numbers in sync with the %select statements in the
6755 // various diagnostics emitted by this routine.
6757 if (isa<ClassTemplateDecl>(Specialized))
6758 EntityKind = IsPartialSpecialization? 1 : 0;
6759 else if (isa<VarTemplateDecl>(Specialized))
6760 EntityKind = IsPartialSpecialization ? 3 : 2;
6761 else if (isa<FunctionTemplateDecl>(Specialized))
6763 else if (isa<CXXMethodDecl>(Specialized))
6765 else if (isa<VarDecl>(Specialized))
6767 else if (isa<RecordDecl>(Specialized))
6769 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
6772 S.Diag(Loc, diag::err_template_spec_unknown_kind)
6773 << S.getLangOpts().CPlusPlus11;
6774 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6778 // C++ [temp.expl.spec]p2:
6779 // An explicit specialization shall be declared in the namespace
6780 // of which the template is a member, or, for member templates, in
6781 // the namespace of which the enclosing class or enclosing class
6782 // template is a member. An explicit specialization of a member
6783 // function, member class or static data member of a class
6784 // template shall be declared in the namespace of which the class
6785 // template is a member. Such a declaration may also be a
6786 // definition. If the declaration is not a definition, the
6787 // specialization may be defined later in the name- space in which
6788 // the explicit specialization was declared, or in a namespace
6789 // that encloses the one in which the explicit specialization was
6791 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6792 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
6797 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
6798 if (S.getLangOpts().MicrosoftExt) {
6799 // Do not warn for class scope explicit specialization during
6800 // instantiation, warning was already emitted during pattern
6801 // semantic analysis.
6802 if (!S.inTemplateInstantiation())
6803 S.Diag(Loc, diag::ext_function_specialization_in_class)
6806 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6812 if (S.CurContext->isRecord() &&
6813 !S.CurContext->Equals(Specialized->getDeclContext())) {
6814 // Make sure that we're specializing in the right record context.
6815 // Otherwise, things can go horribly wrong.
6816 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6821 // C++ [temp.class.spec]p6:
6822 // A class template partial specialization may be declared or redeclared
6823 // in any namespace scope in which its definition may be defined (14.5.1
6825 DeclContext *SpecializedContext
6826 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
6827 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
6829 // Make sure that this redeclaration (or definition) occurs in an enclosing
6831 // Note that HandleDeclarator() performs this check for explicit
6832 // specializations of function templates, static data members, and member
6833 // functions, so we skip the check here for those kinds of entities.
6834 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
6835 // Should we refactor that check, so that it occurs later?
6836 if (!DC->Encloses(SpecializedContext) &&
6837 !(isa<FunctionTemplateDecl>(Specialized) ||
6838 isa<FunctionDecl>(Specialized) ||
6839 isa<VarTemplateDecl>(Specialized) ||
6840 isa<VarDecl>(Specialized))) {
6841 if (isa<TranslationUnitDecl>(SpecializedContext))
6842 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
6843 << EntityKind << Specialized;
6844 else if (isa<NamespaceDecl>(SpecializedContext)) {
6845 int Diag = diag::err_template_spec_redecl_out_of_scope;
6846 if (S.getLangOpts().MicrosoftExt)
6847 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
6848 S.Diag(Loc, Diag) << EntityKind << Specialized
6849 << cast<NamedDecl>(SpecializedContext);
6851 llvm_unreachable("unexpected namespace context for specialization");
6853 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6854 } else if ((!PrevDecl ||
6855 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
6856 getTemplateSpecializationKind(PrevDecl) ==
6857 TSK_ImplicitInstantiation)) {
6858 // C++ [temp.exp.spec]p2:
6859 // An explicit specialization shall be declared in the namespace of which
6860 // the template is a member, or, for member templates, in the namespace
6861 // of which the enclosing class or enclosing class template is a member.
6862 // An explicit specialization of a member function, member class or
6863 // static data member of a class template shall be declared in the
6864 // namespace of which the class template is a member.
6866 // C++11 [temp.expl.spec]p2:
6867 // An explicit specialization shall be declared in a namespace enclosing
6868 // the specialized template.
6869 // C++11 [temp.explicit]p3:
6870 // An explicit instantiation shall appear in an enclosing namespace of its
6872 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
6873 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
6874 if (isa<TranslationUnitDecl>(SpecializedContext)) {
6875 assert(!IsCPlusPlus11Extension &&
6876 "DC encloses TU but isn't in enclosing namespace set");
6877 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
6878 << EntityKind << Specialized;
6879 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6881 if (!IsCPlusPlus11Extension)
6882 Diag = diag::err_template_spec_decl_out_of_scope;
6883 else if (!S.getLangOpts().CPlusPlus11)
6884 Diag = diag::ext_template_spec_decl_out_of_scope;
6886 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6888 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6891 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6898 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
6899 if (!E->isTypeDependent())
6900 return SourceLocation();
6901 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
6902 Checker.TraverseStmt(E);
6903 if (Checker.MatchLoc.isInvalid())
6904 return E->getSourceRange();
6905 return Checker.MatchLoc;
6908 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
6909 if (!TL.getType()->isDependentType())
6910 return SourceLocation();
6911 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
6912 Checker.TraverseTypeLoc(TL);
6913 if (Checker.MatchLoc.isInvalid())
6914 return TL.getSourceRange();
6915 return Checker.MatchLoc;
6918 /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
6919 /// that checks non-type template partial specialization arguments.
6920 static bool CheckNonTypeTemplatePartialSpecializationArgs(
6921 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
6922 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
6923 for (unsigned I = 0; I != NumArgs; ++I) {
6924 if (Args[I].getKind() == TemplateArgument::Pack) {
6925 if (CheckNonTypeTemplatePartialSpecializationArgs(
6926 S, TemplateNameLoc, Param, Args[I].pack_begin(),
6927 Args[I].pack_size(), IsDefaultArgument))
6933 if (Args[I].getKind() != TemplateArgument::Expression)
6936 Expr *ArgExpr = Args[I].getAsExpr();
6938 // We can have a pack expansion of any of the bullets below.
6939 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
6940 ArgExpr = Expansion->getPattern();
6942 // Strip off any implicit casts we added as part of type checking.
6943 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
6944 ArgExpr = ICE->getSubExpr();
6946 // C++ [temp.class.spec]p8:
6947 // A non-type argument is non-specialized if it is the name of a
6948 // non-type parameter. All other non-type arguments are
6951 // Below, we check the two conditions that only apply to
6952 // specialized non-type arguments, so skip any non-specialized
6954 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
6955 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
6958 // C++ [temp.class.spec]p9:
6959 // Within the argument list of a class template partial
6960 // specialization, the following restrictions apply:
6961 // -- A partially specialized non-type argument expression
6962 // shall not involve a template parameter of the partial
6963 // specialization except when the argument expression is a
6964 // simple identifier.
6965 // -- The type of a template parameter corresponding to a
6966 // specialized non-type argument shall not be dependent on a
6967 // parameter of the specialization.
6968 // DR1315 removes the first bullet, leaving an incoherent set of rules.
6969 // We implement a compromise between the original rules and DR1315:
6970 // -- A specialized non-type template argument shall not be
6971 // type-dependent and the corresponding template parameter
6972 // shall have a non-dependent type.
6973 SourceRange ParamUseRange =
6974 findTemplateParameterInType(Param->getDepth(), ArgExpr);
6975 if (ParamUseRange.isValid()) {
6976 if (IsDefaultArgument) {
6977 S.Diag(TemplateNameLoc,
6978 diag::err_dependent_non_type_arg_in_partial_spec);
6979 S.Diag(ParamUseRange.getBegin(),
6980 diag::note_dependent_non_type_default_arg_in_partial_spec)
6983 S.Diag(ParamUseRange.getBegin(),
6984 diag::err_dependent_non_type_arg_in_partial_spec)
6990 ParamUseRange = findTemplateParameter(
6991 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6992 if (ParamUseRange.isValid()) {
6993 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6994 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6995 << Param->getType();
6996 S.Diag(Param->getLocation(), diag::note_template_param_here)
6997 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7006 /// \brief Check the non-type template arguments of a class template
7007 /// partial specialization according to C++ [temp.class.spec]p9.
7009 /// \param TemplateNameLoc the location of the template name.
7010 /// \param PrimaryTemplate the template parameters of the primary class
7012 /// \param NumExplicit the number of explicitly-specified template arguments.
7013 /// \param TemplateArgs the template arguments of the class template
7014 /// partial specialization.
7016 /// \returns \c true if there was an error, \c false otherwise.
7017 bool Sema::CheckTemplatePartialSpecializationArgs(
7018 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7019 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7020 // We have to be conservative when checking a template in a dependent
7022 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7025 TemplateParameterList *TemplateParams =
7026 PrimaryTemplate->getTemplateParameters();
7027 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7028 NonTypeTemplateParmDecl *Param
7029 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7033 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7034 Param, &TemplateArgs[I],
7035 1, I >= NumExplicit))
7043 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
7045 SourceLocation KWLoc,
7046 SourceLocation ModulePrivateLoc,
7047 TemplateIdAnnotation &TemplateId,
7048 AttributeList *Attr,
7049 MultiTemplateParamsArg
7050 TemplateParameterLists,
7051 SkipBodyInfo *SkipBody) {
7052 assert(TUK != TUK_Reference && "References are not specializations");
7054 CXXScopeSpec &SS = TemplateId.SS;
7056 // NOTE: KWLoc is the location of the tag keyword. This will instead
7057 // store the location of the outermost template keyword in the declaration.
7058 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
7059 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7060 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7061 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7062 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
7064 // Find the class template we're specializing
7065 TemplateName Name = TemplateId.Template.get();
7066 ClassTemplateDecl *ClassTemplate
7067 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7069 if (!ClassTemplate) {
7070 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
7071 << (Name.getAsTemplateDecl() &&
7072 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7076 bool isMemberSpecialization = false;
7077 bool isPartialSpecialization = false;
7079 // Check the validity of the template headers that introduce this
7081 // FIXME: We probably shouldn't complain about these headers for
7082 // friend declarations.
7083 bool Invalid = false;
7084 TemplateParameterList *TemplateParams =
7085 MatchTemplateParametersToScopeSpecifier(
7086 KWLoc, TemplateNameLoc, SS, &TemplateId,
7087 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
7092 if (TemplateParams && TemplateParams->size() > 0) {
7093 isPartialSpecialization = true;
7095 if (TUK == TUK_Friend) {
7096 Diag(KWLoc, diag::err_partial_specialization_friend)
7097 << SourceRange(LAngleLoc, RAngleLoc);
7101 // C++ [temp.class.spec]p10:
7102 // The template parameter list of a specialization shall not
7103 // contain default template argument values.
7104 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7105 Decl *Param = TemplateParams->getParam(I);
7106 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7107 if (TTP->hasDefaultArgument()) {
7108 Diag(TTP->getDefaultArgumentLoc(),
7109 diag::err_default_arg_in_partial_spec);
7110 TTP->removeDefaultArgument();
7112 } else if (NonTypeTemplateParmDecl *NTTP
7113 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7114 if (Expr *DefArg = NTTP->getDefaultArgument()) {
7115 Diag(NTTP->getDefaultArgumentLoc(),
7116 diag::err_default_arg_in_partial_spec)
7117 << DefArg->getSourceRange();
7118 NTTP->removeDefaultArgument();
7121 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
7122 if (TTP->hasDefaultArgument()) {
7123 Diag(TTP->getDefaultArgument().getLocation(),
7124 diag::err_default_arg_in_partial_spec)
7125 << TTP->getDefaultArgument().getSourceRange();
7126 TTP->removeDefaultArgument();
7130 } else if (TemplateParams) {
7131 if (TUK == TUK_Friend)
7132 Diag(KWLoc, diag::err_template_spec_friend)
7133 << FixItHint::CreateRemoval(
7134 SourceRange(TemplateParams->getTemplateLoc(),
7135 TemplateParams->getRAngleLoc()))
7136 << SourceRange(LAngleLoc, RAngleLoc);
7138 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
7141 // Check that the specialization uses the same tag kind as the
7142 // original template.
7143 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7144 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
7145 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7146 Kind, TUK == TUK_Definition, KWLoc,
7147 ClassTemplate->getIdentifier())) {
7148 Diag(KWLoc, diag::err_use_with_wrong_tag)
7150 << FixItHint::CreateReplacement(KWLoc,
7151 ClassTemplate->getTemplatedDecl()->getKindName());
7152 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7153 diag::note_previous_use);
7154 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7157 // Translate the parser's template argument list in our AST format.
7158 TemplateArgumentListInfo TemplateArgs =
7159 makeTemplateArgumentListInfo(*this, TemplateId);
7161 // Check for unexpanded parameter packs in any of the template arguments.
7162 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7163 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
7164 UPPC_PartialSpecialization))
7167 // Check that the template argument list is well-formed for this
7169 SmallVector<TemplateArgument, 4> Converted;
7170 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7171 TemplateArgs, false, Converted))
7174 // Find the class template (partial) specialization declaration that
7175 // corresponds to these arguments.
7176 if (isPartialSpecialization) {
7177 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7178 TemplateArgs.size(), Converted))
7181 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7182 // also do it during instantiation.
7183 bool InstantiationDependent;
7184 if (!Name.isDependent() &&
7185 !TemplateSpecializationType::anyDependentTemplateArguments(
7186 TemplateArgs.arguments(), InstantiationDependent)) {
7187 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7188 << ClassTemplate->getDeclName();
7189 isPartialSpecialization = false;
7193 void *InsertPos = nullptr;
7194 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
7196 if (isPartialSpecialization)
7197 // FIXME: Template parameter list matters, too
7198 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
7200 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
7202 ClassTemplateSpecializationDecl *Specialization = nullptr;
7204 // Check whether we can declare a class template specialization in
7205 // the current scope.
7206 if (TUK != TUK_Friend &&
7207 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7209 isPartialSpecialization))
7212 // The canonical type
7214 if (isPartialSpecialization) {
7215 // Build the canonical type that describes the converted template
7216 // arguments of the class template partial specialization.
7217 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7218 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
7221 if (Context.hasSameType(CanonType,
7222 ClassTemplate->getInjectedClassNameSpecialization())) {
7223 // C++ [temp.class.spec]p9b3:
7225 // -- The argument list of the specialization shall not be identical
7226 // to the implicit argument list of the primary template.
7228 // This rule has since been removed, because it's redundant given DR1495,
7229 // but we keep it because it produces better diagnostics and recovery.
7230 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
7231 << /*class template*/0 << (TUK == TUK_Definition)
7232 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
7233 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7234 ClassTemplate->getIdentifier(),
7238 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
7239 /*FriendLoc*/SourceLocation(),
7240 TemplateParameterLists.size() - 1,
7241 TemplateParameterLists.data());
7244 // Create a new class template partial specialization declaration node.
7245 ClassTemplatePartialSpecializationDecl *PrevPartial
7246 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
7247 ClassTemplatePartialSpecializationDecl *Partial
7248 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
7249 ClassTemplate->getDeclContext(),
7250 KWLoc, TemplateNameLoc,
7257 SetNestedNameSpecifier(Partial, SS);
7258 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
7259 Partial->setTemplateParameterListsInfo(
7260 Context, TemplateParameterLists.drop_back(1));
7264 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
7265 Specialization = Partial;
7267 // If we are providing an explicit specialization of a member class
7268 // template specialization, make a note of that.
7269 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7270 PrevPartial->setMemberSpecialization();
7272 CheckTemplatePartialSpecialization(Partial);
7274 // Create a new class template specialization declaration node for
7275 // this explicit specialization or friend declaration.
7277 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7278 ClassTemplate->getDeclContext(),
7279 KWLoc, TemplateNameLoc,
7283 SetNestedNameSpecifier(Specialization, SS);
7284 if (TemplateParameterLists.size() > 0) {
7285 Specialization->setTemplateParameterListsInfo(Context,
7286 TemplateParameterLists);
7290 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7292 if (CurContext->isDependentContext()) {
7293 // -fms-extensions permits specialization of nested classes without
7294 // fully specializing the outer class(es).
7295 assert(getLangOpts().MicrosoftExt &&
7296 "Only possible with -fms-extensions!");
7297 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7298 CanonType = Context.getTemplateSpecializationType(
7299 CanonTemplate, Converted);
7301 CanonType = Context.getTypeDeclType(Specialization);
7305 // C++ [temp.expl.spec]p6:
7306 // If a template, a member template or the member of a class template is
7307 // explicitly specialized then that specialization shall be declared
7308 // before the first use of that specialization that would cause an implicit
7309 // instantiation to take place, in every translation unit in which such a
7310 // use occurs; no diagnostic is required.
7311 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
7313 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7314 // Is there any previous explicit specialization declaration?
7315 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7322 SourceRange Range(TemplateNameLoc, RAngleLoc);
7323 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7324 << Context.getTypeDeclType(Specialization) << Range;
7326 Diag(PrevDecl->getPointOfInstantiation(),
7327 diag::note_instantiation_required_here)
7328 << (PrevDecl->getTemplateSpecializationKind()
7329 != TSK_ImplicitInstantiation);
7334 // If this is not a friend, note that this is an explicit specialization.
7335 if (TUK != TUK_Friend)
7336 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
7338 // Check that this isn't a redefinition of this specialization.
7339 if (TUK == TUK_Definition) {
7340 RecordDecl *Def = Specialization->getDefinition();
7341 NamedDecl *Hidden = nullptr;
7342 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7343 SkipBody->ShouldSkip = true;
7344 makeMergedDefinitionVisible(Hidden, KWLoc);
7345 // From here on out, treat this as just a redeclaration.
7346 TUK = TUK_Declaration;
7348 SourceRange Range(TemplateNameLoc, RAngleLoc);
7349 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
7350 Diag(Def->getLocation(), diag::note_previous_definition);
7351 Specialization->setInvalidDecl();
7357 ProcessDeclAttributeList(S, Specialization, Attr);
7359 // Add alignment attributes if necessary; these attributes are checked when
7360 // the ASTContext lays out the structure.
7361 if (TUK == TUK_Definition) {
7362 AddAlignmentAttributesForRecord(Specialization);
7363 AddMsStructLayoutForRecord(Specialization);
7366 if (ModulePrivateLoc.isValid())
7367 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7368 << (isPartialSpecialization? 1 : 0)
7369 << FixItHint::CreateRemoval(ModulePrivateLoc);
7371 // Build the fully-sugared type for this class template
7372 // specialization as the user wrote in the specialization
7373 // itself. This means that we'll pretty-print the type retrieved
7374 // from the specialization's declaration the way that the user
7375 // actually wrote the specialization, rather than formatting the
7376 // name based on the "canonical" representation used to store the
7377 // template arguments in the specialization.
7378 TypeSourceInfo *WrittenTy
7379 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7380 TemplateArgs, CanonType);
7381 if (TUK != TUK_Friend) {
7382 Specialization->setTypeAsWritten(WrittenTy);
7383 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
7386 // C++ [temp.expl.spec]p9:
7387 // A template explicit specialization is in the scope of the
7388 // namespace in which the template was defined.
7390 // We actually implement this paragraph where we set the semantic
7391 // context (in the creation of the ClassTemplateSpecializationDecl),
7392 // but we also maintain the lexical context where the actual
7393 // definition occurs.
7394 Specialization->setLexicalDeclContext(CurContext);
7396 // We may be starting the definition of this specialization.
7397 if (TUK == TUK_Definition)
7398 Specialization->startDefinition();
7400 if (TUK == TUK_Friend) {
7401 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7405 Friend->setAccess(AS_public);
7406 CurContext->addDecl(Friend);
7408 // Add the specialization into its lexical context, so that it can
7409 // be seen when iterating through the list of declarations in that
7410 // context. However, specializations are not found by name lookup.
7411 CurContext->addDecl(Specialization);
7413 return Specialization;
7416 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
7417 MultiTemplateParamsArg TemplateParameterLists,
7419 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
7420 ActOnDocumentableDecl(NewDecl);
7424 /// \brief Strips various properties off an implicit instantiation
7425 /// that has just been explicitly specialized.
7426 static void StripImplicitInstantiation(NamedDecl *D) {
7427 D->dropAttr<DLLImportAttr>();
7428 D->dropAttr<DLLExportAttr>();
7430 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7431 FD->setInlineSpecified(false);
7434 /// \brief Compute the diagnostic location for an explicit instantiation
7435 // declaration or definition.
7436 static SourceLocation DiagLocForExplicitInstantiation(
7437 NamedDecl* D, SourceLocation PointOfInstantiation) {
7438 // Explicit instantiations following a specialization have no effect and
7439 // hence no PointOfInstantiation. In that case, walk decl backwards
7440 // until a valid name loc is found.
7441 SourceLocation PrevDiagLoc = PointOfInstantiation;
7442 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7443 Prev = Prev->getPreviousDecl()) {
7444 PrevDiagLoc = Prev->getLocation();
7446 assert(PrevDiagLoc.isValid() &&
7447 "Explicit instantiation without point of instantiation?");
7451 /// \brief Diagnose cases where we have an explicit template specialization
7452 /// before/after an explicit template instantiation, producing diagnostics
7453 /// for those cases where they are required and determining whether the
7454 /// new specialization/instantiation will have any effect.
7456 /// \param NewLoc the location of the new explicit specialization or
7459 /// \param NewTSK the kind of the new explicit specialization or instantiation.
7461 /// \param PrevDecl the previous declaration of the entity.
7463 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7465 /// \param PrevPointOfInstantiation if valid, indicates where the previus
7466 /// declaration was instantiated (either implicitly or explicitly).
7468 /// \param HasNoEffect will be set to true to indicate that the new
7469 /// specialization or instantiation has no effect and should be ignored.
7471 /// \returns true if there was an error that should prevent the introduction of
7472 /// the new declaration into the AST, false otherwise.
7474 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7475 TemplateSpecializationKind NewTSK,
7476 NamedDecl *PrevDecl,
7477 TemplateSpecializationKind PrevTSK,
7478 SourceLocation PrevPointOfInstantiation,
7479 bool &HasNoEffect) {
7480 HasNoEffect = false;
7483 case TSK_Undeclared:
7484 case TSK_ImplicitInstantiation:
7486 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7487 "previous declaration must be implicit!");
7490 case TSK_ExplicitSpecialization:
7492 case TSK_Undeclared:
7493 case TSK_ExplicitSpecialization:
7494 // Okay, we're just specializing something that is either already
7495 // explicitly specialized or has merely been mentioned without any
7499 case TSK_ImplicitInstantiation:
7500 if (PrevPointOfInstantiation.isInvalid()) {
7501 // The declaration itself has not actually been instantiated, so it is
7502 // still okay to specialize it.
7503 StripImplicitInstantiation(PrevDecl);
7508 case TSK_ExplicitInstantiationDeclaration:
7509 case TSK_ExplicitInstantiationDefinition:
7510 assert((PrevTSK == TSK_ImplicitInstantiation ||
7511 PrevPointOfInstantiation.isValid()) &&
7512 "Explicit instantiation without point of instantiation?");
7514 // C++ [temp.expl.spec]p6:
7515 // If a template, a member template or the member of a class template
7516 // is explicitly specialized then that specialization shall be declared
7517 // before the first use of that specialization that would cause an
7518 // implicit instantiation to take place, in every translation unit in
7519 // which such a use occurs; no diagnostic is required.
7520 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7521 // Is there any previous explicit specialization declaration?
7522 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7526 Diag(NewLoc, diag::err_specialization_after_instantiation)
7528 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
7529 << (PrevTSK != TSK_ImplicitInstantiation);
7534 case TSK_ExplicitInstantiationDeclaration:
7536 case TSK_ExplicitInstantiationDeclaration:
7537 // This explicit instantiation declaration is redundant (that's okay).
7541 case TSK_Undeclared:
7542 case TSK_ImplicitInstantiation:
7543 // We're explicitly instantiating something that may have already been
7544 // implicitly instantiated; that's fine.
7547 case TSK_ExplicitSpecialization:
7548 // C++0x [temp.explicit]p4:
7549 // For a given set of template parameters, if an explicit instantiation
7550 // of a template appears after a declaration of an explicit
7551 // specialization for that template, the explicit instantiation has no
7556 case TSK_ExplicitInstantiationDefinition:
7557 // C++0x [temp.explicit]p10:
7558 // If an entity is the subject of both an explicit instantiation
7559 // declaration and an explicit instantiation definition in the same
7560 // translation unit, the definition shall follow the declaration.
7562 diag::err_explicit_instantiation_declaration_after_definition);
7564 // Explicit instantiations following a specialization have no effect and
7565 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7566 // until a valid name loc is found.
7567 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7568 diag::note_explicit_instantiation_definition_here);
7573 case TSK_ExplicitInstantiationDefinition:
7575 case TSK_Undeclared:
7576 case TSK_ImplicitInstantiation:
7577 // We're explicitly instantiating something that may have already been
7578 // implicitly instantiated; that's fine.
7581 case TSK_ExplicitSpecialization:
7582 // C++ DR 259, C++0x [temp.explicit]p4:
7583 // For a given set of template parameters, if an explicit
7584 // instantiation of a template appears after a declaration of
7585 // an explicit specialization for that template, the explicit
7586 // instantiation has no effect.
7587 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
7589 Diag(PrevDecl->getLocation(),
7590 diag::note_previous_template_specialization);
7594 case TSK_ExplicitInstantiationDeclaration:
7595 // We're explicity instantiating a definition for something for which we
7596 // were previously asked to suppress instantiations. That's fine.
7598 // C++0x [temp.explicit]p4:
7599 // For a given set of template parameters, if an explicit instantiation
7600 // of a template appears after a declaration of an explicit
7601 // specialization for that template, the explicit instantiation has no
7603 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7604 // Is there any previous explicit specialization declaration?
7605 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7613 case TSK_ExplicitInstantiationDefinition:
7614 // C++0x [temp.spec]p5:
7615 // For a given template and a given set of template-arguments,
7616 // - an explicit instantiation definition shall appear at most once
7619 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7620 Diag(NewLoc, (getLangOpts().MSVCCompat)
7621 ? diag::ext_explicit_instantiation_duplicate
7622 : diag::err_explicit_instantiation_duplicate)
7624 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7625 diag::note_previous_explicit_instantiation);
7631 llvm_unreachable("Missing specialization/instantiation case?");
7634 /// \brief Perform semantic analysis for the given dependent function
7635 /// template specialization.
7637 /// The only possible way to get a dependent function template specialization
7638 /// is with a friend declaration, like so:
7641 /// template \<class T> void foo(T);
7642 /// template \<class T> class A {
7643 /// friend void foo<>(T);
7647 /// There really isn't any useful analysis we can do here, so we
7648 /// just store the information.
7650 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7651 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7652 LookupResult &Previous) {
7653 // Remove anything from Previous that isn't a function template in
7654 // the correct context.
7655 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
7656 LookupResult::Filter F = Previous.makeFilter();
7657 while (F.hasNext()) {
7658 NamedDecl *D = F.next()->getUnderlyingDecl();
7659 if (!isa<FunctionTemplateDecl>(D) ||
7660 !FDLookupContext->InEnclosingNamespaceSetOf(
7661 D->getDeclContext()->getRedeclContext()))
7666 // Should this be diagnosed here?
7667 if (Previous.empty()) return true;
7669 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7670 ExplicitTemplateArgs);
7674 /// \brief Perform semantic analysis for the given function template
7677 /// This routine performs all of the semantic analysis required for an
7678 /// explicit function template specialization. On successful completion,
7679 /// the function declaration \p FD will become a function template
7682 /// \param FD the function declaration, which will be updated to become a
7683 /// function template specialization.
7685 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7686 /// if any. Note that this may be valid info even when 0 arguments are
7687 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7688 /// as it anyway contains info on the angle brackets locations.
7690 /// \param Previous the set of declarations that may be specialized by
7691 /// this function specialization.
7692 bool Sema::CheckFunctionTemplateSpecialization(
7693 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7694 LookupResult &Previous) {
7695 // The set of function template specializations that could match this
7696 // explicit function template specialization.
7697 UnresolvedSet<8> Candidates;
7698 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7699 /*ForTakingAddress=*/false);
7701 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
7702 ConvertedTemplateArgs;
7704 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
7705 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7707 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7708 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
7709 // Only consider templates found within the same semantic lookup scope as
7711 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7712 Ovl->getDeclContext()->getRedeclContext()))
7715 // When matching a constexpr member function template specialization
7716 // against the primary template, we don't yet know whether the
7717 // specialization has an implicit 'const' (because we don't know whether
7718 // it will be a static member function until we know which template it
7719 // specializes), so adjust it now assuming it specializes this template.
7720 QualType FT = FD->getType();
7721 if (FD->isConstexpr()) {
7722 CXXMethodDecl *OldMD =
7723 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
7724 if (OldMD && OldMD->isConst()) {
7725 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
7726 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7727 EPI.TypeQuals |= Qualifiers::Const;
7728 FT = Context.getFunctionType(FPT->getReturnType(),
7729 FPT->getParamTypes(), EPI);
7733 TemplateArgumentListInfo Args;
7734 if (ExplicitTemplateArgs)
7735 Args = *ExplicitTemplateArgs;
7737 // C++ [temp.expl.spec]p11:
7738 // A trailing template-argument can be left unspecified in the
7739 // template-id naming an explicit function template specialization
7740 // provided it can be deduced from the function argument type.
7741 // Perform template argument deduction to determine whether we may be
7742 // specializing this template.
7743 // FIXME: It is somewhat wasteful to build
7744 TemplateDeductionInfo Info(FailedCandidates.getLocation());
7745 FunctionDecl *Specialization = nullptr;
7746 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
7747 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
7748 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7750 // Template argument deduction failed; record why it failed, so
7751 // that we can provide nifty diagnostics.
7752 FailedCandidates.addCandidate().set(
7753 I.getPair(), FunTmpl->getTemplatedDecl(),
7754 MakeDeductionFailureInfo(Context, TDK, Info));
7759 // Target attributes are part of the cuda function signature, so
7760 // the deduced template's cuda target must match that of the
7761 // specialization. Given that C++ template deduction does not
7762 // take target attributes into account, we reject candidates
7763 // here that have a different target.
7764 if (LangOpts.CUDA &&
7765 IdentifyCUDATarget(Specialization,
7766 /* IgnoreImplicitHDAttributes = */ true) !=
7767 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
7768 FailedCandidates.addCandidate().set(
7769 I.getPair(), FunTmpl->getTemplatedDecl(),
7770 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
7774 // Record this candidate.
7775 if (ExplicitTemplateArgs)
7776 ConvertedTemplateArgs[Specialization] = std::move(Args);
7777 Candidates.addDecl(Specialization, I.getAccess());
7781 // Find the most specialized function template.
7782 UnresolvedSetIterator Result = getMostSpecialized(
7783 Candidates.begin(), Candidates.end(), FailedCandidates,
7785 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
7786 PDiag(diag::err_function_template_spec_ambiguous)
7787 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
7788 PDiag(diag::note_function_template_spec_matched));
7790 if (Result == Candidates.end())
7793 // Ignore access information; it doesn't figure into redeclaration checking.
7794 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
7796 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
7797 // an explicit specialization (14.8.3) [...] of a concept definition.
7798 if (Specialization->getPrimaryTemplate()->isConcept()) {
7799 Diag(FD->getLocation(), diag::err_concept_specialized)
7800 << 0 /*function*/ << 1 /*explicitly specialized*/;
7801 Diag(Specialization->getLocation(), diag::note_previous_declaration);
7805 FunctionTemplateSpecializationInfo *SpecInfo
7806 = Specialization->getTemplateSpecializationInfo();
7807 assert(SpecInfo && "Function template specialization info missing?");
7809 // Note: do not overwrite location info if previous template
7810 // specialization kind was explicit.
7811 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
7812 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
7813 Specialization->setLocation(FD->getLocation());
7814 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
7815 // function can differ from the template declaration with respect to
7816 // the constexpr specifier.
7817 Specialization->setConstexpr(FD->isConstexpr());
7820 // FIXME: Check if the prior specialization has a point of instantiation.
7821 // If so, we have run afoul of .
7823 // If this is a friend declaration, then we're not really declaring
7824 // an explicit specialization.
7825 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
7827 // Check the scope of this explicit specialization.
7829 CheckTemplateSpecializationScope(*this,
7830 Specialization->getPrimaryTemplate(),
7831 Specialization, FD->getLocation(),
7835 // C++ [temp.expl.spec]p6:
7836 // If a template, a member template or the member of a class template is
7837 // explicitly specialized then that specialization shall be declared
7838 // before the first use of that specialization that would cause an implicit
7839 // instantiation to take place, in every translation unit in which such a
7840 // use occurs; no diagnostic is required.
7841 bool HasNoEffect = false;
7843 CheckSpecializationInstantiationRedecl(FD->getLocation(),
7844 TSK_ExplicitSpecialization,
7846 SpecInfo->getTemplateSpecializationKind(),
7847 SpecInfo->getPointOfInstantiation(),
7851 // Mark the prior declaration as an explicit specialization, so that later
7852 // clients know that this is an explicit specialization.
7854 // Since explicit specializations do not inherit '=delete' from their
7855 // primary function template - check if the 'specialization' that was
7856 // implicitly generated (during template argument deduction for partial
7857 // ordering) from the most specialized of all the function templates that
7858 // 'FD' could have been specializing, has a 'deleted' definition. If so,
7859 // first check that it was implicitly generated during template argument
7860 // deduction by making sure it wasn't referenced, and then reset the deleted
7861 // flag to not-deleted, so that we can inherit that information from 'FD'.
7862 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7863 !Specialization->getCanonicalDecl()->isReferenced()) {
7865 Specialization->getCanonicalDecl() == Specialization &&
7866 "This must be the only existing declaration of this specialization");
7867 Specialization->setDeletedAsWritten(false);
7869 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
7870 MarkUnusedFileScopedDecl(Specialization);
7873 // Turn the given function declaration into a function template
7874 // specialization, with the template arguments from the previous
7876 // Take copies of (semantic and syntactic) template argument lists.
7877 const TemplateArgumentList* TemplArgs = new (Context)
7878 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
7879 FD->setFunctionTemplateSpecialization(
7880 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7881 SpecInfo->getTemplateSpecializationKind(),
7882 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
7884 // A function template specialization inherits the target attributes
7885 // of its template. (We require the attributes explicitly in the
7886 // code to match, but a template may have implicit attributes by
7887 // virtue e.g. of being constexpr, and it passes these implicit
7888 // attributes on to its specializations.)
7890 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
7892 // The "previous declaration" for this function template specialization is
7893 // the prior function template specialization.
7895 Previous.addDecl(Specialization);
7899 /// \brief Perform semantic analysis for the given non-template member
7902 /// This routine performs all of the semantic analysis required for an
7903 /// explicit member function specialization. On successful completion,
7904 /// the function declaration \p FD will become a member function
7907 /// \param Member the member declaration, which will be updated to become a
7910 /// \param Previous the set of declarations, one of which may be specialized
7911 /// by this function specialization; the set will be modified to contain the
7912 /// redeclared member.
7914 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
7915 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
7917 // Try to find the member we are instantiating.
7918 NamedDecl *FoundInstantiation = nullptr;
7919 NamedDecl *Instantiation = nullptr;
7920 NamedDecl *InstantiatedFrom = nullptr;
7921 MemberSpecializationInfo *MSInfo = nullptr;
7923 if (Previous.empty()) {
7924 // Nowhere to look anyway.
7925 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
7926 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7928 NamedDecl *D = (*I)->getUnderlyingDecl();
7929 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
7930 QualType Adjusted = Function->getType();
7931 if (!hasExplicitCallingConv(Adjusted))
7932 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
7933 if (Context.hasSameType(Adjusted, Method->getType())) {
7934 FoundInstantiation = *I;
7935 Instantiation = Method;
7936 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
7937 MSInfo = Method->getMemberSpecializationInfo();
7942 } else if (isa<VarDecl>(Member)) {
7944 if (Previous.isSingleResult() &&
7945 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
7946 if (PrevVar->isStaticDataMember()) {
7947 FoundInstantiation = Previous.getRepresentativeDecl();
7948 Instantiation = PrevVar;
7949 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
7950 MSInfo = PrevVar->getMemberSpecializationInfo();
7952 } else if (isa<RecordDecl>(Member)) {
7953 CXXRecordDecl *PrevRecord;
7954 if (Previous.isSingleResult() &&
7955 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
7956 FoundInstantiation = Previous.getRepresentativeDecl();
7957 Instantiation = PrevRecord;
7958 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
7959 MSInfo = PrevRecord->getMemberSpecializationInfo();
7961 } else if (isa<EnumDecl>(Member)) {
7963 if (Previous.isSingleResult() &&
7964 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
7965 FoundInstantiation = Previous.getRepresentativeDecl();
7966 Instantiation = PrevEnum;
7967 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
7968 MSInfo = PrevEnum->getMemberSpecializationInfo();
7972 if (!Instantiation) {
7973 // There is no previous declaration that matches. Since member
7974 // specializations are always out-of-line, the caller will complain about
7975 // this mismatch later.
7979 // If this is a friend, just bail out here before we start turning
7980 // things into explicit specializations.
7981 if (Member->getFriendObjectKind() != Decl::FOK_None) {
7982 // Preserve instantiation information.
7983 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
7984 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
7985 cast<CXXMethodDecl>(InstantiatedFrom),
7986 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
7987 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7988 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7989 cast<CXXRecordDecl>(InstantiatedFrom),
7990 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7994 Previous.addDecl(FoundInstantiation);
7998 // Make sure that this is a specialization of a member.
7999 if (!InstantiatedFrom) {
8000 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8002 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8006 // C++ [temp.expl.spec]p6:
8007 // If a template, a member template or the member of a class template is
8008 // explicitly specialized then that specialization shall be declared
8009 // before the first use of that specialization that would cause an implicit
8010 // instantiation to take place, in every translation unit in which such a
8011 // use occurs; no diagnostic is required.
8012 assert(MSInfo && "Member specialization info missing?");
8014 bool HasNoEffect = false;
8015 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8016 TSK_ExplicitSpecialization,
8018 MSInfo->getTemplateSpecializationKind(),
8019 MSInfo->getPointOfInstantiation(),
8023 // Check the scope of this explicit specialization.
8024 if (CheckTemplateSpecializationScope(*this,
8026 Instantiation, Member->getLocation(),
8030 // Note that this is an explicit instantiation of a member.
8031 // the original declaration to note that it is an explicit specialization
8032 // (if it was previously an implicit instantiation). This latter step
8033 // makes bookkeeping easier.
8034 if (isa<FunctionDecl>(Member)) {
8035 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8036 if (InstantiationFunction->getTemplateSpecializationKind() ==
8037 TSK_ImplicitInstantiation) {
8038 InstantiationFunction->setTemplateSpecializationKind(
8039 TSK_ExplicitSpecialization);
8040 InstantiationFunction->setLocation(Member->getLocation());
8041 // Explicit specializations of member functions of class templates do not
8042 // inherit '=delete' from the member function they are specializing.
8043 if (InstantiationFunction->isDeleted()) {
8044 assert(InstantiationFunction->getCanonicalDecl() ==
8045 InstantiationFunction);
8046 InstantiationFunction->setDeletedAsWritten(false);
8050 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
8051 cast<CXXMethodDecl>(InstantiatedFrom),
8052 TSK_ExplicitSpecialization);
8053 MarkUnusedFileScopedDecl(InstantiationFunction);
8054 } else if (isa<VarDecl>(Member)) {
8055 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
8056 if (InstantiationVar->getTemplateSpecializationKind() ==
8057 TSK_ImplicitInstantiation) {
8058 InstantiationVar->setTemplateSpecializationKind(
8059 TSK_ExplicitSpecialization);
8060 InstantiationVar->setLocation(Member->getLocation());
8063 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
8064 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8065 MarkUnusedFileScopedDecl(InstantiationVar);
8066 } else if (isa<CXXRecordDecl>(Member)) {
8067 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
8068 if (InstantiationClass->getTemplateSpecializationKind() ==
8069 TSK_ImplicitInstantiation) {
8070 InstantiationClass->setTemplateSpecializationKind(
8071 TSK_ExplicitSpecialization);
8072 InstantiationClass->setLocation(Member->getLocation());
8075 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8076 cast<CXXRecordDecl>(InstantiatedFrom),
8077 TSK_ExplicitSpecialization);
8079 assert(isa<EnumDecl>(Member) && "Only member enums remain");
8080 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
8081 if (InstantiationEnum->getTemplateSpecializationKind() ==
8082 TSK_ImplicitInstantiation) {
8083 InstantiationEnum->setTemplateSpecializationKind(
8084 TSK_ExplicitSpecialization);
8085 InstantiationEnum->setLocation(Member->getLocation());
8088 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
8089 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8092 // Save the caller the trouble of having to figure out which declaration
8093 // this specialization matches.
8095 Previous.addDecl(FoundInstantiation);
8099 /// \brief Check the scope of an explicit instantiation.
8101 /// \returns true if a serious error occurs, false otherwise.
8102 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
8103 SourceLocation InstLoc,
8104 bool WasQualifiedName) {
8105 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8106 DeclContext *CurContext = S.CurContext->getRedeclContext();
8108 if (CurContext->isRecord()) {
8109 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8114 // C++11 [temp.explicit]p3:
8115 // An explicit instantiation shall appear in an enclosing namespace of its
8116 // template. If the name declared in the explicit instantiation is an
8117 // unqualified name, the explicit instantiation shall appear in the
8118 // namespace where its template is declared or, if that namespace is inline
8119 // (7.3.1), any namespace from its enclosing namespace set.
8121 // This is DR275, which we do not retroactively apply to C++98/03.
8122 if (WasQualifiedName) {
8123 if (CurContext->Encloses(OrigContext))
8126 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8130 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8131 if (WasQualifiedName)
8133 S.getLangOpts().CPlusPlus11?
8134 diag::err_explicit_instantiation_out_of_scope :
8135 diag::warn_explicit_instantiation_out_of_scope_0x)
8139 S.getLangOpts().CPlusPlus11?
8140 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8141 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8145 S.getLangOpts().CPlusPlus11?
8146 diag::err_explicit_instantiation_must_be_global :
8147 diag::warn_explicit_instantiation_must_be_global_0x)
8149 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
8153 /// \brief Determine whether the given scope specifier has a template-id in it.
8154 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8158 // C++11 [temp.explicit]p3:
8159 // If the explicit instantiation is for a member function, a member class
8160 // or a static data member of a class template specialization, the name of
8161 // the class template specialization in the qualified-id for the member
8162 // name shall be a simple-template-id.
8164 // C++98 has the same restriction, just worded differently.
8165 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8166 NNS = NNS->getPrefix())
8167 if (const Type *T = NNS->getAsType())
8168 if (isa<TemplateSpecializationType>(T))
8174 /// Make a dllexport or dllimport attr on a class template specialization take
8176 static void dllExportImportClassTemplateSpecialization(
8177 Sema &S, ClassTemplateSpecializationDecl *Def) {
8178 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8179 assert(A && "dllExportImportClassTemplateSpecialization called "
8180 "on Def without dllexport or dllimport");
8182 // We reject explicit instantiations in class scope, so there should
8183 // never be any delayed exported classes to worry about.
8184 assert(S.DelayedDllExportClasses.empty() &&
8185 "delayed exports present at explicit instantiation");
8186 S.checkClassLevelDLLAttribute(Def);
8188 // Propagate attribute to base class templates.
8189 for (auto &B : Def->bases()) {
8190 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8191 B.getType()->getAsCXXRecordDecl()))
8192 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
8195 S.referenceDLLExportedClassMethods();
8198 // Explicit instantiation of a class template specialization
8200 Sema::ActOnExplicitInstantiation(Scope *S,
8201 SourceLocation ExternLoc,
8202 SourceLocation TemplateLoc,
8204 SourceLocation KWLoc,
8205 const CXXScopeSpec &SS,
8206 TemplateTy TemplateD,
8207 SourceLocation TemplateNameLoc,
8208 SourceLocation LAngleLoc,
8209 ASTTemplateArgsPtr TemplateArgsIn,
8210 SourceLocation RAngleLoc,
8211 AttributeList *Attr) {
8212 // Find the class template we're specializing
8213 TemplateName Name = TemplateD.get();
8214 TemplateDecl *TD = Name.getAsTemplateDecl();
8215 // Check that the specialization uses the same tag kind as the
8216 // original template.
8217 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8218 assert(Kind != TTK_Enum &&
8219 "Invalid enum tag in class template explicit instantiation!");
8221 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8223 if (!ClassTemplate) {
8224 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8225 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
8226 Diag(TD->getLocation(), diag::note_previous_use);
8230 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
8231 Kind, /*isDefinition*/false, KWLoc,
8232 ClassTemplate->getIdentifier())) {
8233 Diag(KWLoc, diag::err_use_with_wrong_tag)
8235 << FixItHint::CreateReplacement(KWLoc,
8236 ClassTemplate->getTemplatedDecl()->getKindName());
8237 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8238 diag::note_previous_use);
8239 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8242 // C++0x [temp.explicit]p2:
8243 // There are two forms of explicit instantiation: an explicit instantiation
8244 // definition and an explicit instantiation declaration. An explicit
8245 // instantiation declaration begins with the extern keyword. [...]
8246 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8247 ? TSK_ExplicitInstantiationDefinition
8248 : TSK_ExplicitInstantiationDeclaration;
8250 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8251 // Check for dllexport class template instantiation declarations.
8252 for (AttributeList *A = Attr; A; A = A->getNext()) {
8253 if (A->getKind() == AttributeList::AT_DLLExport) {
8255 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8256 Diag(A->getLoc(), diag::note_attribute);
8261 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8263 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8264 Diag(A->getLocation(), diag::note_attribute);
8268 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8269 // instantiation declarations for most purposes.
8270 bool DLLImportExplicitInstantiationDef = false;
8271 if (TSK == TSK_ExplicitInstantiationDefinition &&
8272 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8273 // Check for dllimport class template instantiation definitions.
8275 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
8276 for (AttributeList *A = Attr; A; A = A->getNext()) {
8277 if (A->getKind() == AttributeList::AT_DLLImport)
8279 if (A->getKind() == AttributeList::AT_DLLExport) {
8280 // dllexport trumps dllimport here.
8286 TSK = TSK_ExplicitInstantiationDeclaration;
8287 DLLImportExplicitInstantiationDef = true;
8291 // Translate the parser's template argument list in our AST format.
8292 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8293 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8295 // Check that the template argument list is well-formed for this
8297 SmallVector<TemplateArgument, 4> Converted;
8298 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8299 TemplateArgs, false, Converted))
8302 // Find the class template specialization declaration that
8303 // corresponds to these arguments.
8304 void *InsertPos = nullptr;
8305 ClassTemplateSpecializationDecl *PrevDecl
8306 = ClassTemplate->findSpecialization(Converted, InsertPos);
8308 TemplateSpecializationKind PrevDecl_TSK
8309 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8311 // C++0x [temp.explicit]p2:
8312 // [...] An explicit instantiation shall appear in an enclosing
8313 // namespace of its template. [...]
8315 // This is C++ DR 275.
8316 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8320 ClassTemplateSpecializationDecl *Specialization = nullptr;
8322 bool HasNoEffect = false;
8324 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
8325 PrevDecl, PrevDecl_TSK,
8326 PrevDecl->getPointOfInstantiation(),
8330 // Even though HasNoEffect == true means that this explicit instantiation
8331 // has no effect on semantics, we go on to put its syntax in the AST.
8333 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8334 PrevDecl_TSK == TSK_Undeclared) {
8335 // Since the only prior class template specialization with these
8336 // arguments was referenced but not declared, reuse that
8337 // declaration node as our own, updating the source location
8338 // for the template name to reflect our new declaration.
8339 // (Other source locations will be updated later.)
8340 Specialization = PrevDecl;
8341 Specialization->setLocation(TemplateNameLoc);
8345 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8346 DLLImportExplicitInstantiationDef) {
8347 // The new specialization might add a dllimport attribute.
8348 HasNoEffect = false;
8352 if (!Specialization) {
8353 // Create a new class template specialization declaration node for
8354 // this explicit specialization.
8356 = ClassTemplateSpecializationDecl::Create(Context, Kind,
8357 ClassTemplate->getDeclContext(),
8358 KWLoc, TemplateNameLoc,
8362 SetNestedNameSpecifier(Specialization, SS);
8364 if (!HasNoEffect && !PrevDecl) {
8365 // Insert the new specialization.
8366 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8370 // Build the fully-sugared type for this explicit instantiation as
8371 // the user wrote in the explicit instantiation itself. This means
8372 // that we'll pretty-print the type retrieved from the
8373 // specialization's declaration the way that the user actually wrote
8374 // the explicit instantiation, rather than formatting the name based
8375 // on the "canonical" representation used to store the template
8376 // arguments in the specialization.
8377 TypeSourceInfo *WrittenTy
8378 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8380 Context.getTypeDeclType(Specialization));
8381 Specialization->setTypeAsWritten(WrittenTy);
8383 // Set source locations for keywords.
8384 Specialization->setExternLoc(ExternLoc);
8385 Specialization->setTemplateKeywordLoc(TemplateLoc);
8386 Specialization->setBraceRange(SourceRange());
8388 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
8390 ProcessDeclAttributeList(S, Specialization, Attr);
8392 // Add the explicit instantiation into its lexical context. However,
8393 // since explicit instantiations are never found by name lookup, we
8394 // just put it into the declaration context directly.
8395 Specialization->setLexicalDeclContext(CurContext);
8396 CurContext->addDecl(Specialization);
8398 // Syntax is now OK, so return if it has no other effect on semantics.
8400 // Set the template specialization kind.
8401 Specialization->setTemplateSpecializationKind(TSK);
8402 return Specialization;
8405 // C++ [temp.explicit]p3:
8406 // A definition of a class template or class member template
8407 // shall be in scope at the point of the explicit instantiation of
8408 // the class template or class member template.
8410 // This check comes when we actually try to perform the
8412 ClassTemplateSpecializationDecl *Def
8413 = cast_or_null<ClassTemplateSpecializationDecl>(
8414 Specialization->getDefinition());
8416 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
8417 else if (TSK == TSK_ExplicitInstantiationDefinition) {
8418 MarkVTableUsed(TemplateNameLoc, Specialization, true);
8419 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8422 // Instantiate the members of this class template specialization.
8423 Def = cast_or_null<ClassTemplateSpecializationDecl>(
8424 Specialization->getDefinition());
8426 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
8427 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8428 // TSK_ExplicitInstantiationDefinition
8429 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
8430 (TSK == TSK_ExplicitInstantiationDefinition ||
8431 DLLImportExplicitInstantiationDef)) {
8432 // FIXME: Need to notify the ASTMutationListener that we did this.
8433 Def->setTemplateSpecializationKind(TSK);
8435 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
8436 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8437 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8438 // In the MS ABI, an explicit instantiation definition can add a dll
8439 // attribute to a template with a previous instantiation declaration.
8440 // MinGW doesn't allow this.
8441 auto *A = cast<InheritableAttr>(
8442 getDLLAttr(Specialization)->clone(getASTContext()));
8443 A->setInherited(true);
8445 dllExportImportClassTemplateSpecialization(*this, Def);
8449 // Fix a TSK_ImplicitInstantiation followed by a
8450 // TSK_ExplicitInstantiationDefinition
8451 bool NewlyDLLExported =
8452 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8453 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
8454 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8455 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8456 // In the MS ABI, an explicit instantiation definition can add a dll
8457 // attribute to a template with a previous implicit instantiation.
8458 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8459 // avoid potentially strange codegen behavior. For example, if we extend
8460 // this conditional to dllimport, and we have a source file calling a
8461 // method on an implicitly instantiated template class instance and then
8462 // declaring a dllimport explicit instantiation definition for the same
8463 // template class, the codegen for the method call will not respect the
8464 // dllimport, while it will with cl. The Def will already have the DLL
8465 // attribute, since the Def and Specialization will be the same in the
8466 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8467 // attribute to the Specialization; we just need to make it take effect.
8468 assert(Def == Specialization &&
8469 "Def and Specialization should match for implicit instantiation");
8470 dllExportImportClassTemplateSpecialization(*this, Def);
8473 // Set the template specialization kind. Make sure it is set before
8474 // instantiating the members which will trigger ASTConsumer callbacks.
8475 Specialization->setTemplateSpecializationKind(TSK);
8476 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
8479 // Set the template specialization kind.
8480 Specialization->setTemplateSpecializationKind(TSK);
8483 return Specialization;
8486 // Explicit instantiation of a member class of a class template.
8488 Sema::ActOnExplicitInstantiation(Scope *S,
8489 SourceLocation ExternLoc,
8490 SourceLocation TemplateLoc,
8492 SourceLocation KWLoc,
8494 IdentifierInfo *Name,
8495 SourceLocation NameLoc,
8496 AttributeList *Attr) {
8499 bool IsDependent = false;
8500 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
8501 KWLoc, SS, Name, NameLoc, Attr, AS_none,
8502 /*ModulePrivateLoc=*/SourceLocation(),
8503 MultiTemplateParamsArg(), Owned, IsDependent,
8504 SourceLocation(), false, TypeResult(),
8505 /*IsTypeSpecifier*/false);
8506 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8511 TagDecl *Tag = cast<TagDecl>(TagD);
8512 assert(!Tag->isEnum() && "shouldn't see enumerations here");
8514 if (Tag->isInvalidDecl())
8517 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8518 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8520 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8521 << Context.getTypeDeclType(Record);
8522 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8526 // C++0x [temp.explicit]p2:
8527 // If the explicit instantiation is for a class or member class, the
8528 // elaborated-type-specifier in the declaration shall include a
8529 // simple-template-id.
8531 // C++98 has the same restriction, just worded differently.
8532 if (!ScopeSpecifierHasTemplateId(SS))
8533 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
8534 << Record << SS.getRange();
8536 // C++0x [temp.explicit]p2:
8537 // There are two forms of explicit instantiation: an explicit instantiation
8538 // definition and an explicit instantiation declaration. An explicit
8539 // instantiation declaration begins with the extern keyword. [...]
8540 TemplateSpecializationKind TSK
8541 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8542 : TSK_ExplicitInstantiationDeclaration;
8544 // C++0x [temp.explicit]p2:
8545 // [...] An explicit instantiation shall appear in an enclosing
8546 // namespace of its template. [...]
8548 // This is C++ DR 275.
8549 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
8551 // Verify that it is okay to explicitly instantiate here.
8552 CXXRecordDecl *PrevDecl
8553 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
8554 if (!PrevDecl && Record->getDefinition())
8557 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
8558 bool HasNoEffect = false;
8559 assert(MSInfo && "No member specialization information?");
8560 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
8562 MSInfo->getTemplateSpecializationKind(),
8563 MSInfo->getPointOfInstantiation(),
8570 CXXRecordDecl *RecordDef
8571 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8573 // C++ [temp.explicit]p3:
8574 // A definition of a member class of a class template shall be in scope
8575 // at the point of an explicit instantiation of the member class.
8577 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
8579 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8580 << 0 << Record->getDeclName() << Record->getDeclContext();
8581 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8585 if (InstantiateClass(NameLoc, Record, Def,
8586 getTemplateInstantiationArgs(Record),
8590 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8596 // Instantiate all of the members of the class.
8597 InstantiateClassMembers(NameLoc, RecordDef,
8598 getTemplateInstantiationArgs(Record), TSK);
8600 if (TSK == TSK_ExplicitInstantiationDefinition)
8601 MarkVTableUsed(NameLoc, RecordDef, true);
8603 // FIXME: We don't have any representation for explicit instantiations of
8604 // member classes. Such a representation is not needed for compilation, but it
8605 // should be available for clients that want to see all of the declarations in
8610 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8611 SourceLocation ExternLoc,
8612 SourceLocation TemplateLoc,
8614 // Explicit instantiations always require a name.
8615 // TODO: check if/when DNInfo should replace Name.
8616 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8617 DeclarationName Name = NameInfo.getName();
8619 if (!D.isInvalidType())
8620 Diag(D.getDeclSpec().getLocStart(),
8621 diag::err_explicit_instantiation_requires_name)
8622 << D.getDeclSpec().getSourceRange()
8623 << D.getSourceRange();
8628 // The scope passed in may not be a decl scope. Zip up the scope tree until
8629 // we find one that is.
8630 while ((S->getFlags() & Scope::DeclScope) == 0 ||
8631 (S->getFlags() & Scope::TemplateParamScope) != 0)
8634 // Determine the type of the declaration.
8635 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8636 QualType R = T->getType();
8641 // A storage-class-specifier shall not be specified in [...] an explicit
8642 // instantiation (14.7.2) directive.
8643 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
8644 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8647 } else if (D.getDeclSpec().getStorageClassSpec()
8648 != DeclSpec::SCS_unspecified) {
8649 // Complain about then remove the storage class specifier.
8650 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8651 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8653 D.getMutableDeclSpec().ClearStorageClassSpecs();
8656 // C++0x [temp.explicit]p1:
8657 // [...] An explicit instantiation of a function template shall not use the
8658 // inline or constexpr specifiers.
8659 // Presumably, this also applies to member functions of class templates as
8661 if (D.getDeclSpec().isInlineSpecified())
8662 Diag(D.getDeclSpec().getInlineSpecLoc(),
8663 getLangOpts().CPlusPlus11 ?
8664 diag::err_explicit_instantiation_inline :
8665 diag::warn_explicit_instantiation_inline_0x)
8666 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8667 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
8668 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8669 // not already specified.
8670 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8671 diag::err_explicit_instantiation_constexpr);
8673 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8674 // applied only to the definition of a function template or variable template,
8675 // declared in namespace scope.
8676 if (D.getDeclSpec().isConceptSpecified()) {
8677 Diag(D.getDeclSpec().getConceptSpecLoc(),
8678 diag::err_concept_specified_specialization) << 0;
8682 // A deduction guide is not on the list of entities that can be explicitly
8684 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8685 Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
8686 << /*explicit instantiation*/ 0;
8690 // C++0x [temp.explicit]p2:
8691 // There are two forms of explicit instantiation: an explicit instantiation
8692 // definition and an explicit instantiation declaration. An explicit
8693 // instantiation declaration begins with the extern keyword. [...]
8694 TemplateSpecializationKind TSK
8695 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8696 : TSK_ExplicitInstantiationDeclaration;
8698 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
8699 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
8701 if (!R->isFunctionType()) {
8702 // C++ [temp.explicit]p1:
8703 // A [...] static data member of a class template can be explicitly
8704 // instantiated from the member definition associated with its class
8706 // C++1y [temp.explicit]p1:
8707 // A [...] variable [...] template specialization can be explicitly
8708 // instantiated from its template.
8709 if (Previous.isAmbiguous())
8712 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
8713 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
8715 if (!PrevTemplate) {
8716 if (!Prev || !Prev->isStaticDataMember()) {
8717 // We expect to see a data data member here.
8718 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
8720 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8722 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
8726 if (!Prev->getInstantiatedFromStaticDataMember()) {
8727 // FIXME: Check for explicit specialization?
8728 Diag(D.getIdentifierLoc(),
8729 diag::err_explicit_instantiation_data_member_not_instantiated)
8731 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
8732 // FIXME: Can we provide a note showing where this was declared?
8736 // Explicitly instantiate a variable template.
8738 // C++1y [dcl.spec.auto]p6:
8739 // ... A program that uses auto or decltype(auto) in a context not
8740 // explicitly allowed in this section is ill-formed.
8742 // This includes auto-typed variable template instantiations.
8743 if (R->isUndeducedType()) {
8744 Diag(T->getTypeLoc().getLocStart(),
8745 diag::err_auto_not_allowed_var_inst);
8749 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8750 // C++1y [temp.explicit]p3:
8751 // If the explicit instantiation is for a variable, the unqualified-id
8752 // in the declaration shall be a template-id.
8753 Diag(D.getIdentifierLoc(),
8754 diag::err_explicit_instantiation_without_template_id)
8756 Diag(PrevTemplate->getLocation(),
8757 diag::note_explicit_instantiation_here);
8761 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8762 // explicit instantiation (14.8.2) [...] of a concept definition.
8763 if (PrevTemplate->isConcept()) {
8764 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8765 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
8766 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
8770 // Translate the parser's template argument list into our AST format.
8771 TemplateArgumentListInfo TemplateArgs =
8772 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
8774 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
8775 D.getIdentifierLoc(), TemplateArgs);
8776 if (Res.isInvalid())
8779 // Ignore access control bits, we don't need them for redeclaration
8781 Prev = cast<VarDecl>(Res.get());
8784 // C++0x [temp.explicit]p2:
8785 // If the explicit instantiation is for a member function, a member class
8786 // or a static data member of a class template specialization, the name of
8787 // the class template specialization in the qualified-id for the member
8788 // name shall be a simple-template-id.
8790 // C++98 has the same restriction, just worded differently.
8792 // This does not apply to variable template specializations, where the
8793 // template-id is in the unqualified-id instead.
8794 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
8795 Diag(D.getIdentifierLoc(),
8796 diag::ext_explicit_instantiation_without_qualified_id)
8797 << Prev << D.getCXXScopeSpec().getRange();
8799 // Check the scope of this explicit instantiation.
8800 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
8802 // Verify that it is okay to explicitly instantiate here.
8803 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
8804 SourceLocation POI = Prev->getPointOfInstantiation();
8805 bool HasNoEffect = false;
8806 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
8807 PrevTSK, POI, HasNoEffect))
8811 // Instantiate static data member or variable template.
8813 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8815 // Merge attributes.
8816 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
8817 ProcessDeclAttributeList(S, Prev, Attr);
8819 if (TSK == TSK_ExplicitInstantiationDefinition)
8820 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
8823 // Check the new variable specialization against the parsed input.
8824 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
8825 Diag(T->getTypeLoc().getLocStart(),
8826 diag::err_invalid_var_template_spec_type)
8827 << 0 << PrevTemplate << R << Prev->getType();
8828 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
8829 << 2 << PrevTemplate->getDeclName();
8833 // FIXME: Create an ExplicitInstantiation node?
8834 return (Decl*) nullptr;
8837 // If the declarator is a template-id, translate the parser's template
8838 // argument list into our AST format.
8839 bool HasExplicitTemplateArgs = false;
8840 TemplateArgumentListInfo TemplateArgs;
8841 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8842 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
8843 HasExplicitTemplateArgs = true;
8846 // C++ [temp.explicit]p1:
8847 // A [...] function [...] can be explicitly instantiated from its template.
8848 // A member function [...] of a class template can be explicitly
8849 // instantiated from the member definition associated with its class
8851 UnresolvedSet<8> Matches;
8852 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
8853 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
8854 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8856 NamedDecl *Prev = *P;
8857 if (!HasExplicitTemplateArgs) {
8858 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
8859 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
8860 /*AdjustExceptionSpec*/true);
8861 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
8864 Matches.addDecl(Method, P.getAccess());
8865 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
8871 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
8875 TemplateDeductionInfo Info(FailedCandidates.getLocation());
8876 FunctionDecl *Specialization = nullptr;
8877 if (TemplateDeductionResult TDK
8878 = DeduceTemplateArguments(FunTmpl,
8879 (HasExplicitTemplateArgs ? &TemplateArgs
8881 R, Specialization, Info)) {
8882 // Keep track of almost-matches.
8883 FailedCandidates.addCandidate()
8884 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
8885 MakeDeductionFailureInfo(Context, TDK, Info));
8890 // Target attributes are part of the cuda function signature, so
8891 // the cuda target of the instantiated function must match that of its
8892 // template. Given that C++ template deduction does not take
8893 // target attributes into account, we reject candidates here that
8894 // have a different target.
8895 if (LangOpts.CUDA &&
8896 IdentifyCUDATarget(Specialization,
8897 /* IgnoreImplicitHDAttributes = */ true) !=
8898 IdentifyCUDATarget(Attr)) {
8899 FailedCandidates.addCandidate().set(
8900 P.getPair(), FunTmpl->getTemplatedDecl(),
8901 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
8905 Matches.addDecl(Specialization, P.getAccess());
8908 // Find the most specialized function template specialization.
8909 UnresolvedSetIterator Result = getMostSpecialized(
8910 Matches.begin(), Matches.end(), FailedCandidates,
8911 D.getIdentifierLoc(),
8912 PDiag(diag::err_explicit_instantiation_not_known) << Name,
8913 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
8914 PDiag(diag::note_explicit_instantiation_candidate));
8916 if (Result == Matches.end())
8919 // Ignore access control bits, we don't need them for redeclaration checking.
8920 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
8922 // C++11 [except.spec]p4
8923 // In an explicit instantiation an exception-specification may be specified,
8924 // but is not required.
8925 // If an exception-specification is specified in an explicit instantiation
8926 // directive, it shall be compatible with the exception-specifications of
8927 // other declarations of that function.
8928 if (auto *FPT = R->getAs<FunctionProtoType>())
8929 if (FPT->hasExceptionSpec()) {
8931 diag::err_mismatched_exception_spec_explicit_instantiation;
8932 if (getLangOpts().MicrosoftExt)
8933 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
8934 bool Result = CheckEquivalentExceptionSpec(
8935 PDiag(DiagID) << Specialization->getType(),
8936 PDiag(diag::note_explicit_instantiation_here),
8937 Specialization->getType()->getAs<FunctionProtoType>(),
8938 Specialization->getLocation(), FPT, D.getLocStart());
8939 // In Microsoft mode, mismatching exception specifications just cause a
8941 if (!getLangOpts().MicrosoftExt && Result)
8945 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
8946 Diag(D.getIdentifierLoc(),
8947 diag::err_explicit_instantiation_member_function_not_instantiated)
8949 << (Specialization->getTemplateSpecializationKind() ==
8950 TSK_ExplicitSpecialization);
8951 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
8955 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
8956 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
8957 PrevDecl = Specialization;
8960 bool HasNoEffect = false;
8961 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
8963 PrevDecl->getTemplateSpecializationKind(),
8964 PrevDecl->getPointOfInstantiation(),
8968 // FIXME: We may still want to build some representation of this
8969 // explicit specialization.
8971 return (Decl*) nullptr;
8974 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8976 ProcessDeclAttributeList(S, Specialization, Attr);
8978 if (Specialization->isDefined()) {
8979 // Let the ASTConsumer know that this function has been explicitly
8980 // instantiated now, and its linkage might have changed.
8981 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
8982 } else if (TSK == TSK_ExplicitInstantiationDefinition)
8983 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
8985 // C++0x [temp.explicit]p2:
8986 // If the explicit instantiation is for a member function, a member class
8987 // or a static data member of a class template specialization, the name of
8988 // the class template specialization in the qualified-id for the member
8989 // name shall be a simple-template-id.
8991 // C++98 has the same restriction, just worded differently.
8992 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
8993 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
8994 D.getCXXScopeSpec().isSet() &&
8995 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
8996 Diag(D.getIdentifierLoc(),
8997 diag::ext_explicit_instantiation_without_qualified_id)
8998 << Specialization << D.getCXXScopeSpec().getRange();
9000 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
9001 // explicit instantiation (14.8.2) [...] of a concept definition.
9002 if (FunTmpl && FunTmpl->isConcept() &&
9003 !D.getDeclSpec().isConceptSpecified()) {
9004 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
9005 << 0 /*function*/ << 0 /*explicitly instantiated*/;
9006 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
9010 CheckExplicitInstantiationScope(*this,
9011 FunTmpl? (NamedDecl *)FunTmpl
9012 : Specialization->getInstantiatedFromMemberFunction(),
9013 D.getIdentifierLoc(),
9014 D.getCXXScopeSpec().isSet());
9016 // FIXME: Create some kind of ExplicitInstantiationDecl here.
9017 return (Decl*) nullptr;
9021 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9022 const CXXScopeSpec &SS, IdentifierInfo *Name,
9023 SourceLocation TagLoc, SourceLocation NameLoc) {
9024 // This has to hold, because SS is expected to be defined.
9025 assert(Name && "Expected a name in a dependent tag");
9027 NestedNameSpecifier *NNS = SS.getScopeRep();
9031 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9033 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9034 Diag(NameLoc, diag::err_dependent_tag_decl)
9035 << (TUK == TUK_Definition) << Kind << SS.getRange();
9039 // Create the resulting type.
9040 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9041 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
9043 // Create type-source location information for this type.
9045 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
9046 TL.setElaboratedKeywordLoc(TagLoc);
9047 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9048 TL.setNameLoc(NameLoc);
9049 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
9053 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9054 const CXXScopeSpec &SS, const IdentifierInfo &II,
9055 SourceLocation IdLoc) {
9059 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9061 getLangOpts().CPlusPlus11 ?
9062 diag::warn_cxx98_compat_typename_outside_of_template :
9063 diag::ext_typename_outside_of_template)
9064 << FixItHint::CreateRemoval(TypenameLoc);
9066 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9067 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9068 TypenameLoc, QualifierLoc, II, IdLoc);
9072 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9073 if (isa<DependentNameType>(T)) {
9074 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
9075 TL.setElaboratedKeywordLoc(TypenameLoc);
9076 TL.setQualifierLoc(QualifierLoc);
9077 TL.setNameLoc(IdLoc);
9079 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
9080 TL.setElaboratedKeywordLoc(TypenameLoc);
9081 TL.setQualifierLoc(QualifierLoc);
9082 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
9085 return CreateParsedType(T, TSI);
9089 Sema::ActOnTypenameType(Scope *S,
9090 SourceLocation TypenameLoc,
9091 const CXXScopeSpec &SS,
9092 SourceLocation TemplateKWLoc,
9093 TemplateTy TemplateIn,
9094 IdentifierInfo *TemplateII,
9095 SourceLocation TemplateIILoc,
9096 SourceLocation LAngleLoc,
9097 ASTTemplateArgsPtr TemplateArgsIn,
9098 SourceLocation RAngleLoc) {
9099 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9101 getLangOpts().CPlusPlus11 ?
9102 diag::warn_cxx98_compat_typename_outside_of_template :
9103 diag::ext_typename_outside_of_template)
9104 << FixItHint::CreateRemoval(TypenameLoc);
9106 // Strangely, non-type results are not ignored by this lookup, so the
9107 // program is ill-formed if it finds an injected-class-name.
9108 if (TypenameLoc.isValid()) {
9110 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9111 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9113 diag::ext_out_of_line_qualified_id_type_names_constructor)
9114 << TemplateII << 0 /*injected-class-name used as template name*/
9115 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9119 // Translate the parser's template argument list in our AST format.
9120 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9121 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9123 TemplateName Template = TemplateIn.get();
9124 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9125 // Construct a dependent template specialization type.
9126 assert(DTN && "dependent template has non-dependent name?");
9127 assert(DTN->getQualifier() == SS.getScopeRep());
9128 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9129 DTN->getQualifier(),
9130 DTN->getIdentifier(),
9133 // Create source-location information for this type.
9134 TypeLocBuilder Builder;
9135 DependentTemplateSpecializationTypeLoc SpecTL
9136 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
9137 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9138 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
9139 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9140 SpecTL.setTemplateNameLoc(TemplateIILoc);
9141 SpecTL.setLAngleLoc(LAngleLoc);
9142 SpecTL.setRAngleLoc(RAngleLoc);
9143 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9144 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9145 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
9148 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
9152 // Provide source-location information for the template specialization type.
9153 TypeLocBuilder Builder;
9154 TemplateSpecializationTypeLoc SpecTL
9155 = Builder.push<TemplateSpecializationTypeLoc>(T);
9156 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9157 SpecTL.setTemplateNameLoc(TemplateIILoc);
9158 SpecTL.setLAngleLoc(LAngleLoc);
9159 SpecTL.setRAngleLoc(RAngleLoc);
9160 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9161 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9163 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9164 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
9165 TL.setElaboratedKeywordLoc(TypenameLoc);
9166 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9168 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9169 return CreateParsedType(T, TSI);
9173 /// Determine whether this failed name lookup should be treated as being
9174 /// disabled by a usage of std::enable_if.
9175 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
9176 SourceRange &CondRange) {
9177 // We must be looking for a ::type...
9178 if (!II.isStr("type"))
9181 // ... within an explicitly-written template specialization...
9182 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9184 TypeLoc EnableIfTy = NNS.getTypeLoc();
9185 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9186 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9187 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
9189 const TemplateSpecializationType *EnableIfTST =
9190 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
9192 // ... which names a complete class template declaration...
9193 const TemplateDecl *EnableIfDecl =
9194 EnableIfTST->getTemplateName().getAsTemplateDecl();
9195 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9198 // ... called "enable_if".
9199 const IdentifierInfo *EnableIfII =
9200 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9201 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9204 // Assume the first template argument is the condition.
9205 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
9209 /// \brief Build the type that describes a C++ typename specifier,
9210 /// e.g., "typename T::type".
9212 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
9213 SourceLocation KeywordLoc,
9214 NestedNameSpecifierLoc QualifierLoc,
9215 const IdentifierInfo &II,
9216 SourceLocation IILoc) {
9218 SS.Adopt(QualifierLoc);
9220 DeclContext *Ctx = computeDeclContext(SS);
9222 // If the nested-name-specifier is dependent and couldn't be
9223 // resolved to a type, build a typename type.
9224 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
9225 return Context.getDependentNameType(Keyword,
9226 QualifierLoc.getNestedNameSpecifier(),
9230 // If the nested-name-specifier refers to the current instantiation,
9231 // the "typename" keyword itself is superfluous. In C++03, the
9232 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9233 // allows such extraneous "typename" keywords, and we retroactively
9234 // apply this DR to C++03 code with only a warning. In any case we continue.
9236 if (RequireCompleteDeclContext(SS, Ctx))
9239 DeclarationName Name(&II);
9240 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
9241 LookupQualifiedName(Result, Ctx, SS);
9242 unsigned DiagID = 0;
9243 Decl *Referenced = nullptr;
9244 switch (Result.getResultKind()) {
9245 case LookupResult::NotFound: {
9246 // If we're looking up 'type' within a template named 'enable_if', produce
9247 // a more specific diagnostic.
9248 SourceRange CondRange;
9249 if (isEnableIf(QualifierLoc, II, CondRange)) {
9250 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
9251 << Ctx << CondRange;
9255 DiagID = diag::err_typename_nested_not_found;
9259 case LookupResult::FoundUnresolvedValue: {
9260 // We found a using declaration that is a value. Most likely, the using
9261 // declaration itself is meant to have the 'typename' keyword.
9262 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9264 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9265 << Name << Ctx << FullRange;
9266 if (UnresolvedUsingValueDecl *Using
9267 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
9268 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
9269 Diag(Loc, diag::note_using_value_decl_missing_typename)
9270 << FixItHint::CreateInsertion(Loc, "typename ");
9273 // Fall through to create a dependent typename type, from which we can recover
9276 case LookupResult::NotFoundInCurrentInstantiation:
9277 // Okay, it's a member of an unknown instantiation.
9278 return Context.getDependentNameType(Keyword,
9279 QualifierLoc.getNestedNameSpecifier(),
9282 case LookupResult::Found:
9283 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
9284 // C++ [class.qual]p2:
9285 // In a lookup in which function names are not ignored and the
9286 // nested-name-specifier nominates a class C, if the name specified
9287 // after the nested-name-specifier, when looked up in C, is the
9288 // injected-class-name of C [...] then the name is instead considered
9289 // to name the constructor of class C.
9291 // Unlike in an elaborated-type-specifier, function names are not ignored
9292 // in typename-specifier lookup. However, they are ignored in all the
9293 // contexts where we form a typename type with no keyword (that is, in
9294 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9296 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9297 // ignore functions, but that appears to be an oversight.
9298 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9299 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9300 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9301 FoundRD->isInjectedClassName() &&
9302 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9303 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9304 << &II << 1 << 0 /*'typename' keyword used*/;
9306 // We found a type. Build an ElaboratedType, since the
9307 // typename-specifier was just sugar.
9308 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
9309 return Context.getElaboratedType(Keyword,
9310 QualifierLoc.getNestedNameSpecifier(),
9311 Context.getTypeDeclType(Type));
9314 // C++ [dcl.type.simple]p2:
9315 // A type-specifier of the form
9316 // typename[opt] nested-name-specifier[opt] template-name
9317 // is a placeholder for a deduced class type [...].
9318 if (getLangOpts().CPlusPlus1z) {
9319 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9320 return Context.getElaboratedType(
9321 Keyword, QualifierLoc.getNestedNameSpecifier(),
9322 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9323 QualType(), false));
9327 DiagID = diag::err_typename_nested_not_type;
9328 Referenced = Result.getFoundDecl();
9331 case LookupResult::FoundOverloaded:
9332 DiagID = diag::err_typename_nested_not_type;
9333 Referenced = *Result.begin();
9336 case LookupResult::Ambiguous:
9340 // If we get here, it's because name lookup did not find a
9341 // type. Emit an appropriate diagnostic and return an error.
9342 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9344 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
9346 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9352 // See Sema::RebuildTypeInCurrentInstantiation
9353 class CurrentInstantiationRebuilder
9354 : public TreeTransform<CurrentInstantiationRebuilder> {
9356 DeclarationName Entity;
9359 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
9361 CurrentInstantiationRebuilder(Sema &SemaRef,
9363 DeclarationName Entity)
9364 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
9365 Loc(Loc), Entity(Entity) { }
9367 /// \brief Determine whether the given type \p T has already been
9370 /// For the purposes of type reconstruction, a type has already been
9371 /// transformed if it is NULL or if it is not dependent.
9372 bool AlreadyTransformed(QualType T) {
9373 return T.isNull() || !T->isDependentType();
9376 /// \brief Returns the location of the entity whose type is being
9378 SourceLocation getBaseLocation() { return Loc; }
9380 /// \brief Returns the name of the entity whose type is being rebuilt.
9381 DeclarationName getBaseEntity() { return Entity; }
9383 /// \brief Sets the "base" location and entity when that
9384 /// information is known based on another transformation.
9385 void setBase(SourceLocation Loc, DeclarationName Entity) {
9387 this->Entity = Entity;
9390 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9391 // Lambdas never need to be transformed.
9395 } // end anonymous namespace
9397 /// \brief Rebuilds a type within the context of the current instantiation.
9399 /// The type \p T is part of the type of an out-of-line member definition of
9400 /// a class template (or class template partial specialization) that was parsed
9401 /// and constructed before we entered the scope of the class template (or
9402 /// partial specialization thereof). This routine will rebuild that type now
9403 /// that we have entered the declarator's scope, which may produce different
9404 /// canonical types, e.g.,
9407 /// template<typename T>
9409 /// typedef T* pointer;
9413 /// template<typename T>
9414 /// typename X<T>::pointer X<T>::data() { ... }
9417 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
9418 /// since we do not know that we can look into X<T> when we parsed the type.
9419 /// This function will rebuild the type, performing the lookup of "pointer"
9420 /// in X<T> and returning an ElaboratedType whose canonical type is the same
9421 /// as the canonical type of T*, allowing the return types of the out-of-line
9422 /// definition and the declaration to match.
9423 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9425 DeclarationName Name) {
9426 if (!T || !T->getType()->isDependentType())
9429 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9430 return Rebuilder.TransformType(T);
9433 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
9434 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9436 return Rebuilder.TransformExpr(E);
9439 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
9443 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9444 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9446 NestedNameSpecifierLoc Rebuilt
9447 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
9455 /// \brief Rebuild the template parameters now that we know we're in a current
9457 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9458 TemplateParameterList *Params) {
9459 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9460 Decl *Param = Params->getParam(I);
9462 // There is nothing to rebuild in a type parameter.
9463 if (isa<TemplateTypeParmDecl>(Param))
9466 // Rebuild the template parameter list of a template template parameter.
9467 if (TemplateTemplateParmDecl *TTP
9468 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9469 if (RebuildTemplateParamsInCurrentInstantiation(
9470 TTP->getTemplateParameters()))
9476 // Rebuild the type of a non-type template parameter.
9477 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
9478 TypeSourceInfo *NewTSI
9479 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9480 NTTP->getLocation(),
9481 NTTP->getDeclName());
9485 if (NewTSI != NTTP->getTypeSourceInfo()) {
9486 NTTP->setTypeSourceInfo(NewTSI);
9487 NTTP->setType(NewTSI->getType());
9494 /// \brief Produces a formatted string that describes the binding of
9495 /// template parameters to template arguments.
9497 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9498 const TemplateArgumentList &Args) {
9499 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
9503 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9504 const TemplateArgument *Args,
9506 SmallString<128> Str;
9507 llvm::raw_svector_ostream Out(Str);
9509 if (!Params || Params->size() == 0 || NumArgs == 0)
9510 return std::string();
9512 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9521 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
9522 Out << Id->getName();
9528 Args[I].print(getPrintingPolicy(), Out);
9535 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9536 CachedTokens &Toks) {
9540 auto LPT = llvm::make_unique<LateParsedTemplate>();
9542 // Take tokens to avoid allocations
9543 LPT->Toks.swap(Toks);
9545 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
9547 FD->setLateTemplateParsed(true);
9550 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9553 FD->setLateTemplateParsed(false);
9556 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9557 DeclContext *DC = CurContext;
9560 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9561 const FunctionDecl *FD = RD->isLocalClass();
9562 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9563 } else if (DC->isTranslationUnit() || DC->isNamespace())
9566 DC = DC->getParent();
9572 /// \brief Walk the path from which a declaration was instantiated, and check
9573 /// that every explicit specialization along that path is visible. This enforces
9574 /// C++ [temp.expl.spec]/6:
9576 /// If a template, a member template or a member of a class template is
9577 /// explicitly specialized then that specialization shall be declared before
9578 /// the first use of that specialization that would cause an implicit
9579 /// instantiation to take place, in every translation unit in which such a
9580 /// use occurs; no diagnostic is required.
9582 /// and also C++ [temp.class.spec]/1:
9584 /// A partial specialization shall be declared before the first use of a
9585 /// class template specialization that would make use of the partial
9586 /// specialization as the result of an implicit or explicit instantiation
9587 /// in every translation unit in which such a use occurs; no diagnostic is
9589 class ExplicitSpecializationVisibilityChecker {
9592 llvm::SmallVector<Module *, 8> Modules;
9595 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9598 void check(NamedDecl *ND) {
9599 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9600 return checkImpl(FD);
9601 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9602 return checkImpl(RD);
9603 if (auto *VD = dyn_cast<VarDecl>(ND))
9604 return checkImpl(VD);
9605 if (auto *ED = dyn_cast<EnumDecl>(ND))
9606 return checkImpl(ED);
9610 void diagnose(NamedDecl *D, bool IsPartialSpec) {
9611 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9612 : Sema::MissingImportKind::ExplicitSpecialization;
9613 const bool Recover = true;
9615 // If we got a custom set of modules (because only a subset of the
9616 // declarations are interesting), use them, otherwise let
9617 // diagnoseMissingImport intelligently pick some.
9618 if (Modules.empty())
9619 S.diagnoseMissingImport(Loc, D, Kind, Recover);
9621 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9624 // Check a specific declaration. There are three problematic cases:
9626 // 1) The declaration is an explicit specialization of a template
9628 // 2) The declaration is an explicit specialization of a member of an
9630 // 3) The declaration is an instantiation of a template, and that template
9631 // is an explicit specialization of a member of a templated class.
9633 // We don't need to go any deeper than that, as the instantiation of the
9634 // surrounding class / etc is not triggered by whatever triggered this
9635 // instantiation, and thus should be checked elsewhere.
9636 template<typename SpecDecl>
9637 void checkImpl(SpecDecl *Spec) {
9638 bool IsHiddenExplicitSpecialization = false;
9639 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
9640 IsHiddenExplicitSpecialization =
9641 Spec->getMemberSpecializationInfo()
9642 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
9643 : !S.hasVisibleDeclaration(Spec);
9645 checkInstantiated(Spec);
9648 if (IsHiddenExplicitSpecialization)
9649 diagnose(Spec->getMostRecentDecl(), false);
9652 void checkInstantiated(FunctionDecl *FD) {
9653 if (auto *TD = FD->getPrimaryTemplate())
9657 void checkInstantiated(CXXRecordDecl *RD) {
9658 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
9662 auto From = SD->getSpecializedTemplateOrPartial();
9663 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
9666 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
9667 if (!S.hasVisibleDeclaration(TD))
9673 void checkInstantiated(VarDecl *RD) {
9674 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
9678 auto From = SD->getSpecializedTemplateOrPartial();
9679 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
9682 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
9683 if (!S.hasVisibleDeclaration(TD))
9689 void checkInstantiated(EnumDecl *FD) {}
9691 template<typename TemplDecl>
9692 void checkTemplate(TemplDecl *TD) {
9693 if (TD->isMemberSpecialization()) {
9694 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
9695 diagnose(TD->getMostRecentDecl(), false);
9699 } // end anonymous namespace
9701 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
9702 if (!getLangOpts().Modules)
9705 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
9708 /// \brief Check whether a template partial specialization that we've discovered
9709 /// is hidden, and produce suitable diagnostics if so.
9710 void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
9712 llvm::SmallVector<Module *, 8> Modules;
9713 if (!hasVisibleDeclaration(Spec, &Modules))
9714 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
9715 MissingImportKind::PartialSpecialization,