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 void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
460 SourceLocation Greater) {
461 if (TemplateName.isInvalid())
464 DeclarationNameInfo NameInfo;
466 LookupNameKind LookupKind;
468 DeclContext *LookupCtx = nullptr;
469 NamedDecl *Found = nullptr;
471 // Figure out what name we looked up.
472 if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
473 NameInfo = ME->getMemberNameInfo();
474 SS.Adopt(ME->getQualifierLoc());
475 LookupKind = LookupMemberName;
476 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
477 Found = ME->getMemberDecl();
479 auto *DRE = cast<DeclRefExpr>(TemplateName.get());
480 NameInfo = DRE->getNameInfo();
481 SS.Adopt(DRE->getQualifierLoc());
482 LookupKind = LookupOrdinaryName;
483 Found = DRE->getFoundDecl();
486 // Try to correct the name by looking for templates and C++ named casts.
487 struct TemplateCandidateFilter : CorrectionCandidateCallback {
488 TemplateCandidateFilter() {
489 WantTypeSpecifiers = false;
490 WantExpressionKeywords = false;
491 WantRemainingKeywords = false;
492 WantCXXNamedCasts = true;
494 bool ValidateCandidate(const TypoCorrection &Candidate) override {
495 if (auto *ND = Candidate.getCorrectionDecl())
496 return isAcceptableTemplateName(ND->getASTContext(), ND, true);
497 return Candidate.isKeyword();
501 DeclarationName Name = NameInfo.getName();
502 if (TypoCorrection Corrected =
503 CorrectTypo(NameInfo, LookupKind, S, &SS,
504 llvm::make_unique<TemplateCandidateFilter>(),
505 CTK_ErrorRecovery, LookupCtx)) {
506 auto *ND = Corrected.getFoundDecl();
508 ND = isAcceptableTemplateName(Context, ND,
509 /*AllowFunctionTemplates*/ true);
510 if (ND || Corrected.isKeyword()) {
512 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
513 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
514 Name.getAsString() == CorrectedStr;
515 diagnoseTypo(Corrected,
516 PDiag(diag::err_non_template_in_member_template_id_suggest)
517 << Name << LookupCtx << DroppedSpecifier
518 << SS.getRange(), false);
520 diagnoseTypo(Corrected,
521 PDiag(diag::err_non_template_in_template_id_suggest)
525 Diag(Found->getLocation(),
526 diag::note_non_template_in_template_id_found);
531 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
532 << Name << SourceRange(Less, Greater);
534 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
537 /// ActOnDependentIdExpression - Handle a dependent id-expression that
538 /// was just parsed. This is only possible with an explicit scope
539 /// specifier naming a dependent type.
541 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
542 SourceLocation TemplateKWLoc,
543 const DeclarationNameInfo &NameInfo,
544 bool isAddressOfOperand,
545 const TemplateArgumentListInfo *TemplateArgs) {
546 DeclContext *DC = getFunctionLevelDeclContext();
548 // C++11 [expr.prim.general]p12:
549 // An id-expression that denotes a non-static data member or non-static
550 // member function of a class can only be used:
552 // - if that id-expression denotes a non-static data member and it
553 // appears in an unevaluated operand.
555 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
556 // CXXDependentScopeMemberExpr. The former can instantiate to either
557 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
558 // always a MemberExpr.
559 bool MightBeCxx11UnevalField =
560 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
562 // Check if the nested name specifier is an enum type.
564 if (NestedNameSpecifier *NNS = SS.getScopeRep())
565 IsEnum = dyn_cast_or_null<EnumType>(NNS->getAsType());
567 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
568 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
569 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
571 // Since the 'this' expression is synthesized, we don't need to
572 // perform the double-lookup check.
573 NamedDecl *FirstQualifierInScope = nullptr;
575 return CXXDependentScopeMemberExpr::Create(
576 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
577 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
578 FirstQualifierInScope, NameInfo, TemplateArgs);
581 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
585 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
586 SourceLocation TemplateKWLoc,
587 const DeclarationNameInfo &NameInfo,
588 const TemplateArgumentListInfo *TemplateArgs) {
589 return DependentScopeDeclRefExpr::Create(
590 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
595 /// Determine whether we would be unable to instantiate this template (because
596 /// it either has no definition, or is in the process of being instantiated).
597 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
598 NamedDecl *Instantiation,
599 bool InstantiatedFromMember,
600 const NamedDecl *Pattern,
601 const NamedDecl *PatternDef,
602 TemplateSpecializationKind TSK,
603 bool Complain /*= true*/) {
604 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
605 isa<VarDecl>(Instantiation));
607 bool IsEntityBeingDefined = false;
608 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
609 IsEntityBeingDefined = TD->isBeingDefined();
611 if (PatternDef && !IsEntityBeingDefined) {
612 NamedDecl *SuggestedDef = nullptr;
613 if (!hasVisibleDefinition(const_cast<NamedDecl*>(PatternDef), &SuggestedDef,
614 /*OnlyNeedComplete*/false)) {
615 // If we're allowed to diagnose this and recover, do so.
616 bool Recover = Complain && !isSFINAEContext();
618 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
619 Sema::MissingImportKind::Definition, Recover);
625 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
628 llvm::Optional<unsigned> Note;
629 QualType InstantiationTy;
630 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
631 InstantiationTy = Context.getTypeDeclType(TD);
633 Diag(PointOfInstantiation,
634 diag::err_template_instantiate_within_definition)
635 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
637 // Not much point in noting the template declaration here, since
638 // we're lexically inside it.
639 Instantiation->setInvalidDecl();
640 } else if (InstantiatedFromMember) {
641 if (isa<FunctionDecl>(Instantiation)) {
642 Diag(PointOfInstantiation,
643 diag::err_explicit_instantiation_undefined_member)
644 << /*member function*/ 1 << Instantiation->getDeclName()
645 << Instantiation->getDeclContext();
646 Note = diag::note_explicit_instantiation_here;
648 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
649 Diag(PointOfInstantiation,
650 diag::err_implicit_instantiate_member_undefined)
652 Note = diag::note_member_declared_at;
655 if (isa<FunctionDecl>(Instantiation)) {
656 Diag(PointOfInstantiation,
657 diag::err_explicit_instantiation_undefined_func_template)
659 Note = diag::note_explicit_instantiation_here;
660 } else if (isa<TagDecl>(Instantiation)) {
661 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
662 << (TSK != TSK_ImplicitInstantiation)
664 Note = diag::note_template_decl_here;
666 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
667 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
668 Diag(PointOfInstantiation,
669 diag::err_explicit_instantiation_undefined_var_template)
671 Instantiation->setInvalidDecl();
673 Diag(PointOfInstantiation,
674 diag::err_explicit_instantiation_undefined_member)
675 << /*static data member*/ 2 << Instantiation->getDeclName()
676 << Instantiation->getDeclContext();
677 Note = diag::note_explicit_instantiation_here;
680 if (Note) // Diagnostics were emitted.
681 Diag(Pattern->getLocation(), Note.getValue());
683 // In general, Instantiation isn't marked invalid to get more than one
684 // error for multiple undefined instantiations. But the code that does
685 // explicit declaration -> explicit definition conversion can't handle
686 // invalid declarations, so mark as invalid in that case.
687 if (TSK == TSK_ExplicitInstantiationDeclaration)
688 Instantiation->setInvalidDecl();
692 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
693 /// that the template parameter 'PrevDecl' is being shadowed by a new
694 /// declaration at location Loc. Returns true to indicate that this is
695 /// an error, and false otherwise.
696 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
697 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
699 // Microsoft Visual C++ permits template parameters to be shadowed.
700 if (getLangOpts().MicrosoftExt)
703 // C++ [temp.local]p4:
704 // A template-parameter shall not be redeclared within its
705 // scope (including nested scopes).
706 Diag(Loc, diag::err_template_param_shadow)
707 << cast<NamedDecl>(PrevDecl)->getDeclName();
708 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
711 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
712 /// the parameter D to reference the templated declaration and return a pointer
713 /// to the template declaration. Otherwise, do nothing to D and return null.
714 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
715 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
716 D = Temp->getTemplatedDecl();
722 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
723 SourceLocation EllipsisLoc) const {
724 assert(Kind == Template &&
725 "Only template template arguments can be pack expansions here");
726 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
727 "Template template argument pack expansion without packs");
728 ParsedTemplateArgument Result(*this);
729 Result.EllipsisLoc = EllipsisLoc;
733 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
734 const ParsedTemplateArgument &Arg) {
736 switch (Arg.getKind()) {
737 case ParsedTemplateArgument::Type: {
739 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
741 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
742 return TemplateArgumentLoc(TemplateArgument(T), DI);
745 case ParsedTemplateArgument::NonType: {
746 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
747 return TemplateArgumentLoc(TemplateArgument(E), E);
750 case ParsedTemplateArgument::Template: {
751 TemplateName Template = Arg.getAsTemplate().get();
752 TemplateArgument TArg;
753 if (Arg.getEllipsisLoc().isValid())
754 TArg = TemplateArgument(Template, Optional<unsigned int>());
757 return TemplateArgumentLoc(TArg,
758 Arg.getScopeSpec().getWithLocInContext(
761 Arg.getEllipsisLoc());
765 llvm_unreachable("Unhandled parsed template argument");
768 /// \brief Translates template arguments as provided by the parser
769 /// into template arguments used by semantic analysis.
770 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
771 TemplateArgumentListInfo &TemplateArgs) {
772 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
773 TemplateArgs.addArgument(translateTemplateArgument(*this,
777 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
779 IdentifierInfo *Name) {
780 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
781 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
782 if (PrevDecl && PrevDecl->isTemplateParameter())
783 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
786 /// ActOnTypeParameter - Called when a C++ template type parameter
787 /// (e.g., "typename T") has been parsed. Typename specifies whether
788 /// the keyword "typename" was used to declare the type parameter
789 /// (otherwise, "class" was used), and KeyLoc is the location of the
790 /// "class" or "typename" keyword. ParamName is the name of the
791 /// parameter (NULL indicates an unnamed template parameter) and
792 /// ParamNameLoc is the location of the parameter name (if any).
793 /// If the type parameter has a default argument, it will be added
794 /// later via ActOnTypeParameterDefault.
795 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
796 SourceLocation EllipsisLoc,
797 SourceLocation KeyLoc,
798 IdentifierInfo *ParamName,
799 SourceLocation ParamNameLoc,
800 unsigned Depth, unsigned Position,
801 SourceLocation EqualLoc,
802 ParsedType DefaultArg) {
803 assert(S->isTemplateParamScope() &&
804 "Template type parameter not in template parameter scope!");
806 SourceLocation Loc = ParamNameLoc;
810 bool IsParameterPack = EllipsisLoc.isValid();
811 TemplateTypeParmDecl *Param
812 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
813 KeyLoc, Loc, Depth, Position, ParamName,
814 Typename, IsParameterPack);
815 Param->setAccess(AS_public);
818 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
820 // Add the template parameter into the current scope.
822 IdResolver.AddDecl(Param);
825 // C++0x [temp.param]p9:
826 // A default template-argument may be specified for any kind of
827 // template-parameter that is not a template parameter pack.
828 if (DefaultArg && IsParameterPack) {
829 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
830 DefaultArg = nullptr;
833 // Handle the default argument, if provided.
835 TypeSourceInfo *DefaultTInfo;
836 GetTypeFromParser(DefaultArg, &DefaultTInfo);
838 assert(DefaultTInfo && "expected source information for type");
840 // Check for unexpanded parameter packs.
841 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
842 UPPC_DefaultArgument))
845 // Check the template argument itself.
846 if (CheckTemplateArgument(Param, DefaultTInfo)) {
847 Param->setInvalidDecl();
851 Param->setDefaultArgument(DefaultTInfo);
857 /// \brief Check that the type of a non-type template parameter is
860 /// \returns the (possibly-promoted) parameter type if valid;
861 /// otherwise, produces a diagnostic and returns a NULL type.
862 QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
863 SourceLocation Loc) {
864 if (TSI->getType()->isUndeducedType()) {
865 // C++1z [temp.dep.expr]p3:
866 // An id-expression is type-dependent if it contains
867 // - an identifier associated by name lookup with a non-type
868 // template-parameter declared with a type that contains a
869 // placeholder type (7.1.7.4),
870 TSI = SubstAutoTypeSourceInfo(TSI, Context.DependentTy);
873 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
876 QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
877 SourceLocation Loc) {
878 // We don't allow variably-modified types as the type of non-type template
880 if (T->isVariablyModifiedType()) {
881 Diag(Loc, diag::err_variably_modified_nontype_template_param)
886 // C++ [temp.param]p4:
888 // A non-type template-parameter shall have one of the following
889 // (optionally cv-qualified) types:
891 // -- integral or enumeration type,
892 if (T->isIntegralOrEnumerationType() ||
893 // -- pointer to object or pointer to function,
894 T->isPointerType() ||
895 // -- reference to object or reference to function,
896 T->isReferenceType() ||
897 // -- pointer to member,
898 T->isMemberPointerType() ||
899 // -- std::nullptr_t.
900 T->isNullPtrType() ||
901 // If T is a dependent type, we can't do the check now, so we
902 // assume that it is well-formed.
903 T->isDependentType() ||
904 // Allow use of auto in template parameter declarations.
905 T->isUndeducedType()) {
906 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
907 // are ignored when determining its type.
908 return T.getUnqualifiedType();
911 // C++ [temp.param]p8:
913 // A non-type template-parameter of type "array of T" or
914 // "function returning T" is adjusted to be of type "pointer to
915 // T" or "pointer to function returning T", respectively.
916 else if (T->isArrayType() || T->isFunctionType())
917 return Context.getDecayedType(T);
919 Diag(Loc, diag::err_template_nontype_parm_bad_type)
925 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
928 SourceLocation EqualLoc,
930 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
932 if (TInfo->getType()->isUndeducedType()) {
933 Diag(D.getIdentifierLoc(),
934 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
935 << QualType(TInfo->getType()->getContainedAutoType(), 0);
938 assert(S->isTemplateParamScope() &&
939 "Non-type template parameter not in template parameter scope!");
940 bool Invalid = false;
942 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
944 T = Context.IntTy; // Recover with an 'int' type.
948 IdentifierInfo *ParamName = D.getIdentifier();
949 bool IsParameterPack = D.hasEllipsis();
950 NonTypeTemplateParmDecl *Param
951 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
953 D.getIdentifierLoc(),
954 Depth, Position, ParamName, T,
955 IsParameterPack, TInfo);
956 Param->setAccess(AS_public);
959 Param->setInvalidDecl();
962 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
965 // Add the template parameter into the current scope.
967 IdResolver.AddDecl(Param);
970 // C++0x [temp.param]p9:
971 // A default template-argument may be specified for any kind of
972 // template-parameter that is not a template parameter pack.
973 if (Default && IsParameterPack) {
974 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
978 // Check the well-formedness of the default template argument, if provided.
980 // Check for unexpanded parameter packs.
981 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
984 TemplateArgument Converted;
985 ExprResult DefaultRes =
986 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
987 if (DefaultRes.isInvalid()) {
988 Param->setInvalidDecl();
991 Default = DefaultRes.get();
993 Param->setDefaultArgument(Default);
999 /// ActOnTemplateTemplateParameter - Called when a C++ template template
1000 /// parameter (e.g. T in template <template \<typename> class T> class array)
1001 /// has been parsed. S is the current scope.
1002 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1003 SourceLocation TmpLoc,
1004 TemplateParameterList *Params,
1005 SourceLocation EllipsisLoc,
1006 IdentifierInfo *Name,
1007 SourceLocation NameLoc,
1010 SourceLocation EqualLoc,
1011 ParsedTemplateArgument Default) {
1012 assert(S->isTemplateParamScope() &&
1013 "Template template parameter not in template parameter scope!");
1015 // Construct the parameter object.
1016 bool IsParameterPack = EllipsisLoc.isValid();
1017 TemplateTemplateParmDecl *Param =
1018 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1019 NameLoc.isInvalid()? TmpLoc : NameLoc,
1020 Depth, Position, IsParameterPack,
1022 Param->setAccess(AS_public);
1024 // If the template template parameter has a name, then link the identifier
1025 // into the scope and lookup mechanisms.
1027 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1030 IdResolver.AddDecl(Param);
1033 if (Params->size() == 0) {
1034 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1035 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1036 Param->setInvalidDecl();
1039 // C++0x [temp.param]p9:
1040 // A default template-argument may be specified for any kind of
1041 // template-parameter that is not a template parameter pack.
1042 if (IsParameterPack && !Default.isInvalid()) {
1043 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1044 Default = ParsedTemplateArgument();
1047 if (!Default.isInvalid()) {
1048 // Check only that we have a template template argument. We don't want to
1049 // try to check well-formedness now, because our template template parameter
1050 // might have dependent types in its template parameters, which we wouldn't
1051 // be able to match now.
1053 // If none of the template template parameter's template arguments mention
1054 // other template parameters, we could actually perform more checking here.
1055 // However, it isn't worth doing.
1056 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1057 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1058 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1059 << DefaultArg.getSourceRange();
1063 // Check for unexpanded parameter packs.
1064 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1065 DefaultArg.getArgument().getAsTemplate(),
1066 UPPC_DefaultArgument))
1069 Param->setDefaultArgument(Context, DefaultArg);
1075 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1076 /// constrained by RequiresClause, that contains the template parameters in
1078 TemplateParameterList *
1079 Sema::ActOnTemplateParameterList(unsigned Depth,
1080 SourceLocation ExportLoc,
1081 SourceLocation TemplateLoc,
1082 SourceLocation LAngleLoc,
1083 ArrayRef<Decl *> Params,
1084 SourceLocation RAngleLoc,
1085 Expr *RequiresClause) {
1086 if (ExportLoc.isValid())
1087 Diag(ExportLoc, diag::warn_template_export_unsupported);
1089 return TemplateParameterList::Create(
1090 Context, TemplateLoc, LAngleLoc,
1091 llvm::makeArrayRef((NamedDecl *const *)Params.data(), Params.size()),
1092 RAngleLoc, RequiresClause);
1095 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
1097 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
1101 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
1102 SourceLocation KWLoc, CXXScopeSpec &SS,
1103 IdentifierInfo *Name, SourceLocation NameLoc,
1104 AttributeList *Attr,
1105 TemplateParameterList *TemplateParams,
1106 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1107 SourceLocation FriendLoc,
1108 unsigned NumOuterTemplateParamLists,
1109 TemplateParameterList** OuterTemplateParamLists,
1110 SkipBodyInfo *SkipBody) {
1111 assert(TemplateParams && TemplateParams->size() > 0 &&
1112 "No template parameters");
1113 assert(TUK != TUK_Reference && "Can only declare or define class templates");
1114 bool Invalid = false;
1116 // Check that we can declare a template here.
1117 if (CheckTemplateDeclScope(S, TemplateParams))
1120 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1121 assert(Kind != TTK_Enum && "can't build template of enumerated type");
1123 // There is no such thing as an unnamed class template.
1125 Diag(KWLoc, diag::err_template_unnamed_class);
1129 // Find any previous declaration with this name. For a friend with no
1130 // scope explicitly specified, we only look for tag declarations (per
1131 // C++11 [basic.lookup.elab]p2).
1132 DeclContext *SemanticContext;
1133 LookupResult Previous(*this, Name, NameLoc,
1134 (SS.isEmpty() && TUK == TUK_Friend)
1135 ? LookupTagName : LookupOrdinaryName,
1137 if (SS.isNotEmpty() && !SS.isInvalid()) {
1138 SemanticContext = computeDeclContext(SS, true);
1139 if (!SemanticContext) {
1140 // FIXME: Horrible, horrible hack! We can't currently represent this
1141 // in the AST, and historically we have just ignored such friend
1142 // class templates, so don't complain here.
1143 Diag(NameLoc, TUK == TUK_Friend
1144 ? diag::warn_template_qualified_friend_ignored
1145 : diag::err_template_qualified_declarator_no_match)
1146 << SS.getScopeRep() << SS.getRange();
1147 return TUK != TUK_Friend;
1150 if (RequireCompleteDeclContext(SS, SemanticContext))
1153 // If we're adding a template to a dependent context, we may need to
1154 // rebuilding some of the types used within the template parameter list,
1155 // now that we know what the current instantiation is.
1156 if (SemanticContext->isDependentContext()) {
1157 ContextRAII SavedContext(*this, SemanticContext);
1158 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1160 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1161 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
1163 LookupQualifiedName(Previous, SemanticContext);
1165 SemanticContext = CurContext;
1167 // C++14 [class.mem]p14:
1168 // If T is the name of a class, then each of the following shall have a
1169 // name different from T:
1170 // -- every member template of class T
1171 if (TUK != TUK_Friend &&
1172 DiagnoseClassNameShadow(SemanticContext,
1173 DeclarationNameInfo(Name, NameLoc)))
1176 LookupName(Previous, S);
1179 if (Previous.isAmbiguous())
1182 NamedDecl *PrevDecl = nullptr;
1183 if (Previous.begin() != Previous.end())
1184 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1186 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1187 // Maybe we will complain about the shadowed template parameter.
1188 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1189 // Just pretend that we didn't see the previous declaration.
1193 // If there is a previous declaration with the same name, check
1194 // whether this is a valid redeclaration.
1195 ClassTemplateDecl *PrevClassTemplate
1196 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1198 // We may have found the injected-class-name of a class template,
1199 // class template partial specialization, or class template specialization.
1200 // In these cases, grab the template that is being defined or specialized.
1201 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1202 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1203 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1205 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1206 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1208 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1209 ->getSpecializedTemplate();
1213 if (TUK == TUK_Friend) {
1214 // C++ [namespace.memdef]p3:
1215 // [...] When looking for a prior declaration of a class or a function
1216 // declared as a friend, and when the name of the friend class or
1217 // function is neither a qualified name nor a template-id, scopes outside
1218 // the innermost enclosing namespace scope are not considered.
1220 DeclContext *OutermostContext = CurContext;
1221 while (!OutermostContext->isFileContext())
1222 OutermostContext = OutermostContext->getLookupParent();
1225 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1226 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1227 SemanticContext = PrevDecl->getDeclContext();
1229 // Declarations in outer scopes don't matter. However, the outermost
1230 // context we computed is the semantic context for our new
1232 PrevDecl = PrevClassTemplate = nullptr;
1233 SemanticContext = OutermostContext;
1235 // Check that the chosen semantic context doesn't already contain a
1236 // declaration of this name as a non-tag type.
1237 Previous.clear(LookupOrdinaryName);
1238 DeclContext *LookupContext = SemanticContext;
1239 while (LookupContext->isTransparentContext())
1240 LookupContext = LookupContext->getLookupParent();
1241 LookupQualifiedName(Previous, LookupContext);
1243 if (Previous.isAmbiguous())
1246 if (Previous.begin() != Previous.end())
1247 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1250 } else if (PrevDecl &&
1251 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1253 PrevDecl = PrevClassTemplate = nullptr;
1255 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1256 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1258 !(PrevClassTemplate &&
1259 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1260 SemanticContext->getRedeclContext()))) {
1261 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1262 Diag(Shadow->getTargetDecl()->getLocation(),
1263 diag::note_using_decl_target);
1264 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
1265 // Recover by ignoring the old declaration.
1266 PrevDecl = PrevClassTemplate = nullptr;
1270 // TODO Memory management; associated constraints are not always stored.
1271 Expr *const CurAC = formAssociatedConstraints(TemplateParams, nullptr);
1273 if (PrevClassTemplate) {
1274 // Ensure that the template parameter lists are compatible. Skip this check
1275 // for a friend in a dependent context: the template parameter list itself
1276 // could be dependent.
1277 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1278 !TemplateParameterListsAreEqual(TemplateParams,
1279 PrevClassTemplate->getTemplateParameters(),
1284 // Check for matching associated constraints on redeclarations.
1285 const Expr *const PrevAC = PrevClassTemplate->getAssociatedConstraints();
1286 const bool RedeclACMismatch = [&] {
1287 if (!(CurAC || PrevAC))
1288 return false; // Nothing to check; no mismatch.
1289 if (CurAC && PrevAC) {
1290 llvm::FoldingSetNodeID CurACInfo, PrevACInfo;
1291 CurAC->Profile(CurACInfo, Context, /*Canonical=*/true);
1292 PrevAC->Profile(PrevACInfo, Context, /*Canonical=*/true);
1293 if (CurACInfo == PrevACInfo)
1294 return false; // All good; no mismatch.
1299 if (RedeclACMismatch) {
1300 Diag(CurAC ? CurAC->getLocStart() : NameLoc,
1301 diag::err_template_different_associated_constraints);
1302 Diag(PrevAC ? PrevAC->getLocStart() : PrevClassTemplate->getLocation(),
1303 diag::note_template_prev_declaration) << /*declaration*/0;
1307 // C++ [temp.class]p4:
1308 // In a redeclaration, partial specialization, explicit
1309 // specialization or explicit instantiation of a class template,
1310 // the class-key shall agree in kind with the original class
1311 // template declaration (7.1.5.3).
1312 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1313 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1314 TUK == TUK_Definition, KWLoc, Name)) {
1315 Diag(KWLoc, diag::err_use_with_wrong_tag)
1317 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1318 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1319 Kind = PrevRecordDecl->getTagKind();
1322 // Check for redefinition of this class template.
1323 if (TUK == TUK_Definition) {
1324 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1325 // If we have a prior definition that is not visible, treat this as
1326 // simply making that previous definition visible.
1327 NamedDecl *Hidden = nullptr;
1328 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1329 SkipBody->ShouldSkip = true;
1330 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1331 assert(Tmpl && "original definition of a class template is not a "
1333 makeMergedDefinitionVisible(Hidden);
1334 makeMergedDefinitionVisible(Tmpl);
1338 Diag(NameLoc, diag::err_redefinition) << Name;
1339 Diag(Def->getLocation(), diag::note_previous_definition);
1340 // FIXME: Would it make sense to try to "forget" the previous
1341 // definition, as part of error recovery?
1345 } else if (PrevDecl) {
1347 // A class template shall not have the same name as any other
1348 // template, class, function, object, enumeration, enumerator,
1349 // namespace, or type in the same scope (3.3), except as specified
1351 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1352 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1356 // Check the template parameter list of this declaration, possibly
1357 // merging in the template parameter list from the previous class
1358 // template declaration. Skip this check for a friend in a dependent
1359 // context, because the template parameter list might be dependent.
1360 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1361 CheckTemplateParameterList(
1363 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1365 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1366 SemanticContext->isDependentContext())
1367 ? TPC_ClassTemplateMember
1368 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1369 : TPC_ClassTemplate))
1373 // If the name of the template was qualified, we must be defining the
1374 // template out-of-line.
1375 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1376 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1377 : diag::err_member_decl_does_not_match)
1378 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1383 // If this is a templated friend in a dependent context we should not put it
1384 // on the redecl chain. In some cases, the templated friend can be the most
1385 // recent declaration tricking the template instantiator to make substitutions
1387 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1388 bool ShouldAddRedecl
1389 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1391 CXXRecordDecl *NewClass =
1392 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1393 PrevClassTemplate && ShouldAddRedecl ?
1394 PrevClassTemplate->getTemplatedDecl() : nullptr,
1395 /*DelayTypeCreation=*/true);
1396 SetNestedNameSpecifier(NewClass, SS);
1397 if (NumOuterTemplateParamLists > 0)
1398 NewClass->setTemplateParameterListsInfo(
1399 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1400 NumOuterTemplateParamLists));
1402 // Add alignment attributes if necessary; these attributes are checked when
1403 // the ASTContext lays out the structure.
1404 if (TUK == TUK_Definition) {
1405 AddAlignmentAttributesForRecord(NewClass);
1406 AddMsStructLayoutForRecord(NewClass);
1409 // Attach the associated constraints when the declaration will not be part of
1411 Expr *const ACtoAttach =
1412 PrevClassTemplate && ShouldAddRedecl ? nullptr : CurAC;
1414 ClassTemplateDecl *NewTemplate
1415 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1416 DeclarationName(Name), TemplateParams,
1417 NewClass, ACtoAttach);
1419 if (ShouldAddRedecl)
1420 NewTemplate->setPreviousDecl(PrevClassTemplate);
1422 NewClass->setDescribedClassTemplate(NewTemplate);
1424 if (ModulePrivateLoc.isValid())
1425 NewTemplate->setModulePrivate();
1427 // Build the type for the class template declaration now.
1428 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1429 T = Context.getInjectedClassNameType(NewClass, T);
1430 assert(T->isDependentType() && "Class template type is not dependent?");
1433 // If we are providing an explicit specialization of a member that is a
1434 // class template, make a note of that.
1435 if (PrevClassTemplate &&
1436 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1437 PrevClassTemplate->setMemberSpecialization();
1439 // Set the access specifier.
1440 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1441 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1443 // Set the lexical context of these templates
1444 NewClass->setLexicalDeclContext(CurContext);
1445 NewTemplate->setLexicalDeclContext(CurContext);
1447 if (TUK == TUK_Definition)
1448 NewClass->startDefinition();
1451 ProcessDeclAttributeList(S, NewClass, Attr);
1453 if (PrevClassTemplate)
1454 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1456 AddPushedVisibilityAttribute(NewClass);
1458 if (TUK != TUK_Friend) {
1459 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1461 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1462 Outer = Outer->getParent();
1463 PushOnScopeChains(NewTemplate, Outer);
1465 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1466 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1467 NewClass->setAccess(PrevClassTemplate->getAccess());
1470 NewTemplate->setObjectOfFriendDecl();
1472 // Friend templates are visible in fairly strange ways.
1473 if (!CurContext->isDependentContext()) {
1474 DeclContext *DC = SemanticContext->getRedeclContext();
1475 DC->makeDeclVisibleInContext(NewTemplate);
1476 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1477 PushOnScopeChains(NewTemplate, EnclosingScope,
1478 /* AddToContext = */ false);
1481 FriendDecl *Friend = FriendDecl::Create(
1482 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1483 Friend->setAccess(AS_public);
1484 CurContext->addDecl(Friend);
1488 NewTemplate->setInvalidDecl();
1489 NewClass->setInvalidDecl();
1492 ActOnDocumentableDecl(NewTemplate);
1498 /// Transform to convert portions of a constructor declaration into the
1499 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
1500 struct ConvertConstructorToDeductionGuideTransform {
1501 ConvertConstructorToDeductionGuideTransform(Sema &S,
1502 ClassTemplateDecl *Template)
1503 : SemaRef(S), Template(Template) {}
1506 ClassTemplateDecl *Template;
1508 DeclContext *DC = Template->getDeclContext();
1509 CXXRecordDecl *Primary = Template->getTemplatedDecl();
1510 DeclarationName DeductionGuideName =
1511 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
1513 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
1515 // Index adjustment to apply to convert depth-1 template parameters into
1516 // depth-0 template parameters.
1517 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
1519 /// Transform a constructor declaration into a deduction guide.
1520 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
1521 CXXConstructorDecl *CD) {
1522 SmallVector<TemplateArgument, 16> SubstArgs;
1524 LocalInstantiationScope Scope(SemaRef);
1526 // C++ [over.match.class.deduct]p1:
1527 // -- For each constructor of the class template designated by the
1528 // template-name, a function template with the following properties:
1530 // -- The template parameters are the template parameters of the class
1531 // template followed by the template parameters (including default
1532 // template arguments) of the constructor, if any.
1533 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
1535 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
1536 SmallVector<NamedDecl *, 16> AllParams;
1537 AllParams.reserve(TemplateParams->size() + InnerParams->size());
1538 AllParams.insert(AllParams.begin(),
1539 TemplateParams->begin(), TemplateParams->end());
1540 SubstArgs.reserve(InnerParams->size());
1542 // Later template parameters could refer to earlier ones, so build up
1543 // a list of substituted template arguments as we go.
1544 for (NamedDecl *Param : *InnerParams) {
1545 MultiLevelTemplateArgumentList Args;
1546 Args.addOuterTemplateArguments(SubstArgs);
1547 Args.addOuterRetainedLevel();
1548 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
1551 AllParams.push_back(NewParam);
1552 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
1553 SemaRef.Context.getInjectedTemplateArg(NewParam)));
1555 TemplateParams = TemplateParameterList::Create(
1556 SemaRef.Context, InnerParams->getTemplateLoc(),
1557 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
1558 /*FIXME: RequiresClause*/ nullptr);
1561 // If we built a new template-parameter-list, track that we need to
1562 // substitute references to the old parameters into references to the
1564 MultiLevelTemplateArgumentList Args;
1566 Args.addOuterTemplateArguments(SubstArgs);
1567 Args.addOuterRetainedLevel();
1570 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
1571 .getAsAdjusted<FunctionProtoTypeLoc>();
1572 assert(FPTL && "no prototype for constructor declaration");
1574 // Transform the type of the function, adjusting the return type and
1575 // replacing references to the old parameters with references to the
1578 SmallVector<ParmVarDecl*, 8> Params;
1579 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args);
1580 if (NewType.isNull())
1582 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
1584 return buildDeductionGuide(TemplateParams, CD->isExplicit(), NewTInfo,
1585 CD->getLocStart(), CD->getLocation(),
1589 /// Build a deduction guide with the specified parameter types.
1590 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
1591 SourceLocation Loc = Template->getLocation();
1593 // Build the requested type.
1594 FunctionProtoType::ExtProtoInfo EPI;
1595 EPI.HasTrailingReturn = true;
1596 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
1597 DeductionGuideName, EPI);
1598 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
1600 FunctionProtoTypeLoc FPTL =
1601 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
1603 // Build the parameters, needed during deduction / substitution.
1604 SmallVector<ParmVarDecl*, 4> Params;
1605 for (auto T : ParamTypes) {
1606 ParmVarDecl *NewParam = ParmVarDecl::Create(
1607 SemaRef.Context, DC, Loc, Loc, nullptr, T,
1608 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
1609 NewParam->setScopeInfo(0, Params.size());
1610 FPTL.setParam(Params.size(), NewParam);
1611 Params.push_back(NewParam);
1614 return buildDeductionGuide(Template->getTemplateParameters(), false, TSI,
1619 /// Transform a constructor template parameter into a deduction guide template
1620 /// parameter, rebuilding any internal references to earlier parameters and
1621 /// renumbering as we go.
1622 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
1623 MultiLevelTemplateArgumentList &Args) {
1624 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
1625 // TemplateTypeParmDecl's index cannot be changed after creation, so
1626 // substitute it directly.
1627 auto *NewTTP = TemplateTypeParmDecl::Create(
1628 SemaRef.Context, DC, TTP->getLocStart(), TTP->getLocation(),
1629 /*Depth*/0, Depth1IndexAdjustment + TTP->getIndex(),
1630 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
1631 TTP->isParameterPack());
1632 if (TTP->hasDefaultArgument()) {
1633 TypeSourceInfo *InstantiatedDefaultArg =
1634 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
1635 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
1636 if (InstantiatedDefaultArg)
1637 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
1639 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
1644 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
1645 return transformTemplateParameterImpl(TTP, Args);
1647 return transformTemplateParameterImpl(
1648 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
1650 template<typename TemplateParmDecl>
1652 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
1653 MultiLevelTemplateArgumentList &Args) {
1654 // Ask the template instantiator to do the heavy lifting for us, then adjust
1655 // the index of the parameter once it's done.
1657 cast_or_null<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
1658 assert(NewParam->getDepth() == 0 && "unexpected template param depth");
1659 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
1663 QualType transformFunctionProtoType(TypeLocBuilder &TLB,
1664 FunctionProtoTypeLoc TL,
1665 SmallVectorImpl<ParmVarDecl*> &Params,
1666 MultiLevelTemplateArgumentList &Args) {
1667 SmallVector<QualType, 4> ParamTypes;
1668 const FunctionProtoType *T = TL.getTypePtr();
1670 // -- The types of the function parameters are those of the constructor.
1671 for (auto *OldParam : TL.getParams()) {
1672 ParmVarDecl *NewParam = transformFunctionTypeParam(OldParam, Args);
1675 ParamTypes.push_back(NewParam->getType());
1676 Params.push_back(NewParam);
1679 // -- The return type is the class template specialization designated by
1680 // the template-name and template arguments corresponding to the
1681 // template parameters obtained from the class template.
1683 // We use the injected-class-name type of the primary template instead.
1684 // This has the convenient property that it is different from any type that
1685 // the user can write in a deduction-guide (because they cannot enter the
1686 // context of the template), so implicit deduction guides can never collide
1687 // with explicit ones.
1688 QualType ReturnType = DeducedType;
1689 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
1691 // Resolving a wording defect, we also inherit the variadicness of the
1693 FunctionProtoType::ExtProtoInfo EPI;
1694 EPI.Variadic = T->isVariadic();
1695 EPI.HasTrailingReturn = true;
1697 QualType Result = SemaRef.BuildFunctionType(
1698 ReturnType, ParamTypes, TL.getLocStart(), DeductionGuideName, EPI);
1699 if (Result.isNull())
1702 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
1703 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
1704 NewTL.setLParenLoc(TL.getLParenLoc());
1705 NewTL.setRParenLoc(TL.getRParenLoc());
1706 NewTL.setExceptionSpecRange(SourceRange());
1707 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
1708 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
1709 NewTL.setParam(I, Params[I]);
1715 transformFunctionTypeParam(ParmVarDecl *OldParam,
1716 MultiLevelTemplateArgumentList &Args) {
1717 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
1718 TypeSourceInfo *NewDI;
1719 if (!Args.getNumLevels())
1721 else if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
1722 // Expand out the one and only element in each inner pack.
1723 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
1725 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
1726 OldParam->getLocation(), OldParam->getDeclName());
1727 if (!NewDI) return nullptr;
1729 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
1730 PackTL.getTypePtr()->getNumExpansions());
1732 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
1733 OldParam->getDeclName());
1737 // Canonicalize the type. This (for instance) replaces references to
1738 // typedef members of the current instantiations with the definitions of
1739 // those typedefs, avoiding triggering instantiation of the deduced type
1740 // during deduction.
1741 // FIXME: It would be preferable to retain type sugar and source
1742 // information here (and handle this in substitution instead).
1743 NewDI = SemaRef.Context.getTrivialTypeSourceInfo(
1744 SemaRef.Context.getCanonicalType(NewDI->getType()),
1745 OldParam->getLocation());
1747 // Resolving a wording defect, we also inherit default arguments from the
1749 ExprResult NewDefArg;
1750 if (OldParam->hasDefaultArg()) {
1751 NewDefArg = Args.getNumLevels()
1752 ? SemaRef.SubstExpr(OldParam->getDefaultArg(), Args)
1753 : OldParam->getDefaultArg();
1754 if (NewDefArg.isInvalid())
1758 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
1759 OldParam->getInnerLocStart(),
1760 OldParam->getLocation(),
1761 OldParam->getIdentifier(),
1764 OldParam->getStorageClass(),
1766 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
1767 OldParam->getFunctionScopeIndex());
1771 NamedDecl *buildDeductionGuide(TemplateParameterList *TemplateParams,
1772 bool Explicit, TypeSourceInfo *TInfo,
1773 SourceLocation LocStart, SourceLocation Loc,
1774 SourceLocation LocEnd) {
1775 DeclarationNameInfo Name(DeductionGuideName, Loc);
1776 ArrayRef<ParmVarDecl *> Params =
1777 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
1779 // Build the implicit deduction guide template.
1781 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, Explicit,
1782 Name, TInfo->getType(), TInfo, LocEnd);
1783 Guide->setImplicit();
1784 Guide->setParams(Params);
1786 for (auto *Param : Params)
1787 Param->setDeclContext(Guide);
1789 auto *GuideTemplate = FunctionTemplateDecl::Create(
1790 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
1791 GuideTemplate->setImplicit();
1792 Guide->setDescribedFunctionTemplate(GuideTemplate);
1794 if (isa<CXXRecordDecl>(DC)) {
1795 Guide->setAccess(AS_public);
1796 GuideTemplate->setAccess(AS_public);
1799 DC->addDecl(GuideTemplate);
1800 return GuideTemplate;
1805 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
1806 SourceLocation Loc) {
1807 DeclContext *DC = Template->getDeclContext();
1808 if (DC->isDependentContext())
1811 ConvertConstructorToDeductionGuideTransform Transform(
1812 *this, cast<ClassTemplateDecl>(Template));
1813 if (!isCompleteType(Loc, Transform.DeducedType))
1816 // Check whether we've already declared deduction guides for this template.
1817 // FIXME: Consider storing a flag on the template to indicate this.
1818 auto Existing = DC->lookup(Transform.DeductionGuideName);
1819 for (auto *D : Existing)
1820 if (D->isImplicit())
1823 // In case we were expanding a pack when we attempted to declare deduction
1824 // guides, turn off pack expansion for everything we're about to do.
1825 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1826 // Create a template instantiation record to track the "instantiation" of
1827 // constructors into deduction guides.
1828 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
1829 // this substitution process actually fail?
1830 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
1832 // Convert declared constructors into deduction guide templates.
1833 // FIXME: Skip constructors for which deduction must necessarily fail (those
1834 // for which some class template parameter without a default argument never
1835 // appears in a deduced context).
1836 bool AddedAny = false;
1837 bool AddedCopyOrMove = false;
1838 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
1839 D = D->getUnderlyingDecl();
1840 if (D->isInvalidDecl() || D->isImplicit())
1842 D = cast<NamedDecl>(D->getCanonicalDecl());
1844 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
1846 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
1847 // Class-scope explicit specializations (MS extension) do not result in
1848 // deduction guides.
1849 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
1852 Transform.transformConstructor(FTD, CD);
1855 AddedCopyOrMove |= CD->isCopyOrMoveConstructor();
1858 // Synthesize an X() -> X<...> guide if there were no declared constructors.
1859 // FIXME: The standard doesn't say (how) to do this.
1861 Transform.buildSimpleDeductionGuide(None);
1863 // Synthesize an X(X<...>) -> X<...> guide if there was no declared constructor
1864 // resembling a copy or move constructor.
1865 // FIXME: The standard doesn't say (how) to do this.
1866 if (!AddedCopyOrMove)
1867 Transform.buildSimpleDeductionGuide(Transform.DeducedType);
1870 /// \brief Diagnose the presence of a default template argument on a
1871 /// template parameter, which is ill-formed in certain contexts.
1873 /// \returns true if the default template argument should be dropped.
1874 static bool DiagnoseDefaultTemplateArgument(Sema &S,
1875 Sema::TemplateParamListContext TPC,
1876 SourceLocation ParamLoc,
1877 SourceRange DefArgRange) {
1879 case Sema::TPC_ClassTemplate:
1880 case Sema::TPC_VarTemplate:
1881 case Sema::TPC_TypeAliasTemplate:
1884 case Sema::TPC_FunctionTemplate:
1885 case Sema::TPC_FriendFunctionTemplateDefinition:
1886 // C++ [temp.param]p9:
1887 // A default template-argument shall not be specified in a
1888 // function template declaration or a function template
1890 // If a friend function template declaration specifies a default
1891 // template-argument, that declaration shall be a definition and shall be
1892 // the only declaration of the function template in the translation unit.
1893 // (C++98/03 doesn't have this wording; see DR226).
1894 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1895 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1896 : diag::ext_template_parameter_default_in_function_template)
1900 case Sema::TPC_ClassTemplateMember:
1901 // C++0x [temp.param]p9:
1902 // A default template-argument shall not be specified in the
1903 // template-parameter-lists of the definition of a member of a
1904 // class template that appears outside of the member's class.
1905 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1909 case Sema::TPC_FriendClassTemplate:
1910 case Sema::TPC_FriendFunctionTemplate:
1911 // C++ [temp.param]p9:
1912 // A default template-argument shall not be specified in a
1913 // friend template declaration.
1914 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1918 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1919 // for friend function templates if there is only a single
1920 // declaration (and it is a definition). Strange!
1923 llvm_unreachable("Invalid TemplateParamListContext!");
1926 /// \brief Check for unexpanded parameter packs within the template parameters
1927 /// of a template template parameter, recursively.
1928 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1929 TemplateTemplateParmDecl *TTP) {
1930 // A template template parameter which is a parameter pack is also a pack
1932 if (TTP->isParameterPack())
1935 TemplateParameterList *Params = TTP->getTemplateParameters();
1936 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1937 NamedDecl *P = Params->getParam(I);
1938 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1939 if (!NTTP->isParameterPack() &&
1940 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1941 NTTP->getTypeSourceInfo(),
1942 Sema::UPPC_NonTypeTemplateParameterType))
1948 if (TemplateTemplateParmDecl *InnerTTP
1949 = dyn_cast<TemplateTemplateParmDecl>(P))
1950 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1957 /// \brief Checks the validity of a template parameter list, possibly
1958 /// considering the template parameter list from a previous
1961 /// If an "old" template parameter list is provided, it must be
1962 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1963 /// template parameter list.
1965 /// \param NewParams Template parameter list for a new template
1966 /// declaration. This template parameter list will be updated with any
1967 /// default arguments that are carried through from the previous
1968 /// template parameter list.
1970 /// \param OldParams If provided, template parameter list from a
1971 /// previous declaration of the same template. Default template
1972 /// arguments will be merged from the old template parameter list to
1973 /// the new template parameter list.
1975 /// \param TPC Describes the context in which we are checking the given
1976 /// template parameter list.
1978 /// \returns true if an error occurred, false otherwise.
1979 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1980 TemplateParameterList *OldParams,
1981 TemplateParamListContext TPC) {
1982 bool Invalid = false;
1984 // C++ [temp.param]p10:
1985 // The set of default template-arguments available for use with a
1986 // template declaration or definition is obtained by merging the
1987 // default arguments from the definition (if in scope) and all
1988 // declarations in scope in the same way default function
1989 // arguments are (8.3.6).
1990 bool SawDefaultArgument = false;
1991 SourceLocation PreviousDefaultArgLoc;
1993 // Dummy initialization to avoid warnings.
1994 TemplateParameterList::iterator OldParam = NewParams->end();
1996 OldParam = OldParams->begin();
1998 bool RemoveDefaultArguments = false;
1999 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2000 NewParamEnd = NewParams->end();
2001 NewParam != NewParamEnd; ++NewParam) {
2002 // Variables used to diagnose redundant default arguments
2003 bool RedundantDefaultArg = false;
2004 SourceLocation OldDefaultLoc;
2005 SourceLocation NewDefaultLoc;
2007 // Variable used to diagnose missing default arguments
2008 bool MissingDefaultArg = false;
2010 // Variable used to diagnose non-final parameter packs
2011 bool SawParameterPack = false;
2013 if (TemplateTypeParmDecl *NewTypeParm
2014 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2015 // Check the presence of a default argument here.
2016 if (NewTypeParm->hasDefaultArgument() &&
2017 DiagnoseDefaultTemplateArgument(*this, TPC,
2018 NewTypeParm->getLocation(),
2019 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2021 NewTypeParm->removeDefaultArgument();
2023 // Merge default arguments for template type parameters.
2024 TemplateTypeParmDecl *OldTypeParm
2025 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2026 if (NewTypeParm->isParameterPack()) {
2027 assert(!NewTypeParm->hasDefaultArgument() &&
2028 "Parameter packs can't have a default argument!");
2029 SawParameterPack = true;
2030 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2031 NewTypeParm->hasDefaultArgument()) {
2032 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2033 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2034 SawDefaultArgument = true;
2035 RedundantDefaultArg = true;
2036 PreviousDefaultArgLoc = NewDefaultLoc;
2037 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2038 // Merge the default argument from the old declaration to the
2040 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2041 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2042 } else if (NewTypeParm->hasDefaultArgument()) {
2043 SawDefaultArgument = true;
2044 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2045 } else if (SawDefaultArgument)
2046 MissingDefaultArg = true;
2047 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2048 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2049 // Check for unexpanded parameter packs.
2050 if (!NewNonTypeParm->isParameterPack() &&
2051 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2052 NewNonTypeParm->getTypeSourceInfo(),
2053 UPPC_NonTypeTemplateParameterType)) {
2058 // Check the presence of a default argument here.
2059 if (NewNonTypeParm->hasDefaultArgument() &&
2060 DiagnoseDefaultTemplateArgument(*this, TPC,
2061 NewNonTypeParm->getLocation(),
2062 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2063 NewNonTypeParm->removeDefaultArgument();
2066 // Merge default arguments for non-type template parameters
2067 NonTypeTemplateParmDecl *OldNonTypeParm
2068 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2069 if (NewNonTypeParm->isParameterPack()) {
2070 assert(!NewNonTypeParm->hasDefaultArgument() &&
2071 "Parameter packs can't have a default argument!");
2072 if (!NewNonTypeParm->isPackExpansion())
2073 SawParameterPack = true;
2074 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2075 NewNonTypeParm->hasDefaultArgument()) {
2076 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2077 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2078 SawDefaultArgument = true;
2079 RedundantDefaultArg = true;
2080 PreviousDefaultArgLoc = NewDefaultLoc;
2081 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2082 // Merge the default argument from the old declaration to the
2084 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2085 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2086 } else if (NewNonTypeParm->hasDefaultArgument()) {
2087 SawDefaultArgument = true;
2088 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2089 } else if (SawDefaultArgument)
2090 MissingDefaultArg = true;
2092 TemplateTemplateParmDecl *NewTemplateParm
2093 = cast<TemplateTemplateParmDecl>(*NewParam);
2095 // Check for unexpanded parameter packs, recursively.
2096 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2101 // Check the presence of a default argument here.
2102 if (NewTemplateParm->hasDefaultArgument() &&
2103 DiagnoseDefaultTemplateArgument(*this, TPC,
2104 NewTemplateParm->getLocation(),
2105 NewTemplateParm->getDefaultArgument().getSourceRange()))
2106 NewTemplateParm->removeDefaultArgument();
2108 // Merge default arguments for template template parameters
2109 TemplateTemplateParmDecl *OldTemplateParm
2110 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2111 if (NewTemplateParm->isParameterPack()) {
2112 assert(!NewTemplateParm->hasDefaultArgument() &&
2113 "Parameter packs can't have a default argument!");
2114 if (!NewTemplateParm->isPackExpansion())
2115 SawParameterPack = true;
2116 } else if (OldTemplateParm &&
2117 hasVisibleDefaultArgument(OldTemplateParm) &&
2118 NewTemplateParm->hasDefaultArgument()) {
2119 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2120 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2121 SawDefaultArgument = true;
2122 RedundantDefaultArg = true;
2123 PreviousDefaultArgLoc = NewDefaultLoc;
2124 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2125 // Merge the default argument from the old declaration to the
2127 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2128 PreviousDefaultArgLoc
2129 = OldTemplateParm->getDefaultArgument().getLocation();
2130 } else if (NewTemplateParm->hasDefaultArgument()) {
2131 SawDefaultArgument = true;
2132 PreviousDefaultArgLoc
2133 = NewTemplateParm->getDefaultArgument().getLocation();
2134 } else if (SawDefaultArgument)
2135 MissingDefaultArg = true;
2138 // C++11 [temp.param]p11:
2139 // If a template parameter of a primary class template or alias template
2140 // is a template parameter pack, it shall be the last template parameter.
2141 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2142 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2143 TPC == TPC_TypeAliasTemplate)) {
2144 Diag((*NewParam)->getLocation(),
2145 diag::err_template_param_pack_must_be_last_template_parameter);
2149 if (RedundantDefaultArg) {
2150 // C++ [temp.param]p12:
2151 // A template-parameter shall not be given default arguments
2152 // by two different declarations in the same scope.
2153 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2154 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2156 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2157 // C++ [temp.param]p11:
2158 // If a template-parameter of a class template has a default
2159 // template-argument, each subsequent template-parameter shall either
2160 // have a default template-argument supplied or be a template parameter
2162 Diag((*NewParam)->getLocation(),
2163 diag::err_template_param_default_arg_missing);
2164 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2166 RemoveDefaultArguments = true;
2169 // If we have an old template parameter list that we're merging
2170 // in, move on to the next parameter.
2175 // We were missing some default arguments at the end of the list, so remove
2176 // all of the default arguments.
2177 if (RemoveDefaultArguments) {
2178 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2179 NewParamEnd = NewParams->end();
2180 NewParam != NewParamEnd; ++NewParam) {
2181 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2182 TTP->removeDefaultArgument();
2183 else if (NonTypeTemplateParmDecl *NTTP
2184 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2185 NTTP->removeDefaultArgument();
2187 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2196 /// A class which looks for a use of a certain level of template
2198 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2199 typedef RecursiveASTVisitor<DependencyChecker> super;
2203 // Whether we're looking for a use of a template parameter that makes the
2204 // overall construct type-dependent / a dependent type. This is strictly
2205 // best-effort for now; we may fail to match at all for a dependent type
2206 // in some cases if this is set.
2207 bool IgnoreNonTypeDependent;
2210 SourceLocation MatchLoc;
2212 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2213 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2216 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2217 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2218 NamedDecl *ND = Params->getParam(0);
2219 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2220 Depth = PD->getDepth();
2221 } else if (NonTypeTemplateParmDecl *PD =
2222 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2223 Depth = PD->getDepth();
2225 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2229 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2230 if (ParmDepth >= Depth) {
2238 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2239 // Prune out non-type-dependent expressions if requested. This can
2240 // sometimes result in us failing to find a template parameter reference
2241 // (if a value-dependent expression creates a dependent type), but this
2242 // mode is best-effort only.
2243 if (auto *E = dyn_cast_or_null<Expr>(S))
2244 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2246 return super::TraverseStmt(S, Q);
2249 bool TraverseTypeLoc(TypeLoc TL) {
2250 if (IgnoreNonTypeDependent && !TL.isNull() &&
2251 !TL.getType()->isDependentType())
2253 return super::TraverseTypeLoc(TL);
2256 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
2257 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
2260 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
2261 // For a best-effort search, keep looking until we find a location.
2262 return IgnoreNonTypeDependent || !Matches(T->getDepth());
2265 bool TraverseTemplateName(TemplateName N) {
2266 if (TemplateTemplateParmDecl *PD =
2267 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
2268 if (Matches(PD->getDepth()))
2270 return super::TraverseTemplateName(N);
2273 bool VisitDeclRefExpr(DeclRefExpr *E) {
2274 if (NonTypeTemplateParmDecl *PD =
2275 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
2276 if (Matches(PD->getDepth(), E->getExprLoc()))
2278 return super::VisitDeclRefExpr(E);
2281 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
2282 return TraverseType(T->getReplacementType());
2286 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
2287 return TraverseTemplateArgument(T->getArgumentPack());
2290 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
2291 return TraverseType(T->getInjectedSpecializationType());
2294 } // end anonymous namespace
2296 /// Determines whether a given type depends on the given parameter
2299 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2300 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2301 Checker.TraverseType(T);
2302 return Checker.Match;
2305 // Find the source range corresponding to the named type in the given
2306 // nested-name-specifier, if any.
2307 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2309 const CXXScopeSpec &SS) {
2310 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2311 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2312 if (const Type *CurType = NNS->getAsType()) {
2313 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
2314 return NNSLoc.getTypeLoc().getSourceRange();
2318 NNSLoc = NNSLoc.getPrefix();
2321 return SourceRange();
2324 /// \brief Match the given template parameter lists to the given scope
2325 /// specifier, returning the template parameter list that applies to the
2328 /// \param DeclStartLoc the start of the declaration that has a scope
2329 /// specifier or a template parameter list.
2331 /// \param DeclLoc The location of the declaration itself.
2333 /// \param SS the scope specifier that will be matched to the given template
2334 /// parameter lists. This scope specifier precedes a qualified name that is
2337 /// \param TemplateId The template-id following the scope specifier, if there
2338 /// is one. Used to check for a missing 'template<>'.
2340 /// \param ParamLists the template parameter lists, from the outermost to the
2341 /// innermost template parameter lists.
2343 /// \param IsFriend Whether to apply the slightly different rules for
2344 /// matching template parameters to scope specifiers in friend
2347 /// \param IsMemberSpecialization will be set true if the scope specifier
2348 /// denotes a fully-specialized type, and therefore this is a declaration of
2349 /// a member specialization.
2351 /// \returns the template parameter list, if any, that corresponds to the
2352 /// name that is preceded by the scope specifier @p SS. This template
2353 /// parameter list may have template parameters (if we're declaring a
2354 /// template) or may have no template parameters (if we're declaring a
2355 /// template specialization), or may be NULL (if what we're declaring isn't
2356 /// itself a template).
2357 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2358 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2359 TemplateIdAnnotation *TemplateId,
2360 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2361 bool &IsMemberSpecialization, bool &Invalid) {
2362 IsMemberSpecialization = false;
2365 // The sequence of nested types to which we will match up the template
2366 // parameter lists. We first build this list by starting with the type named
2367 // by the nested-name-specifier and walking out until we run out of types.
2368 SmallVector<QualType, 4> NestedTypes;
2370 if (SS.getScopeRep()) {
2371 if (CXXRecordDecl *Record
2372 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
2373 T = Context.getTypeDeclType(Record);
2375 T = QualType(SS.getScopeRep()->getAsType(), 0);
2378 // If we found an explicit specialization that prevents us from needing
2379 // 'template<>' headers, this will be set to the location of that
2380 // explicit specialization.
2381 SourceLocation ExplicitSpecLoc;
2383 while (!T.isNull()) {
2384 NestedTypes.push_back(T);
2386 // Retrieve the parent of a record type.
2387 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2388 // If this type is an explicit specialization, we're done.
2389 if (ClassTemplateSpecializationDecl *Spec
2390 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2391 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
2392 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2393 ExplicitSpecLoc = Spec->getLocation();
2396 } else if (Record->getTemplateSpecializationKind()
2397 == TSK_ExplicitSpecialization) {
2398 ExplicitSpecLoc = Record->getLocation();
2402 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
2403 T = Context.getTypeDeclType(Parent);
2409 if (const TemplateSpecializationType *TST
2410 = T->getAs<TemplateSpecializationType>()) {
2411 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2412 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
2413 T = Context.getTypeDeclType(Parent);
2420 // Look one step prior in a dependent template specialization type.
2421 if (const DependentTemplateSpecializationType *DependentTST
2422 = T->getAs<DependentTemplateSpecializationType>()) {
2423 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
2424 T = QualType(NNS->getAsType(), 0);
2430 // Look one step prior in a dependent name type.
2431 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2432 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2433 T = QualType(NNS->getAsType(), 0);
2439 // Retrieve the parent of an enumeration type.
2440 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2441 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2443 EnumDecl *Enum = EnumT->getDecl();
2445 // Get to the parent type.
2446 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
2447 T = Context.getTypeDeclType(Parent);
2455 // Reverse the nested types list, since we want to traverse from the outermost
2456 // to the innermost while checking template-parameter-lists.
2457 std::reverse(NestedTypes.begin(), NestedTypes.end());
2459 // C++0x [temp.expl.spec]p17:
2460 // A member or a member template may be nested within many
2461 // enclosing class templates. In an explicit specialization for
2462 // such a member, the member declaration shall be preceded by a
2463 // template<> for each enclosing class template that is
2464 // explicitly specialized.
2465 bool SawNonEmptyTemplateParameterList = false;
2467 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2468 if (SawNonEmptyTemplateParameterList) {
2469 Diag(DeclLoc, diag::err_specialize_member_of_template)
2470 << !Recovery << Range;
2472 IsMemberSpecialization = false;
2479 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2480 // Check that we can have an explicit specialization here.
2481 if (CheckExplicitSpecialization(Range, true))
2484 // We don't have a template header, but we should.
2485 SourceLocation ExpectedTemplateLoc;
2486 if (!ParamLists.empty())
2487 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2489 ExpectedTemplateLoc = DeclStartLoc;
2491 Diag(DeclLoc, diag::err_template_spec_needs_header)
2493 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
2497 unsigned ParamIdx = 0;
2498 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2500 T = NestedTypes[TypeIdx];
2502 // Whether we expect a 'template<>' header.
2503 bool NeedEmptyTemplateHeader = false;
2505 // Whether we expect a template header with parameters.
2506 bool NeedNonemptyTemplateHeader = false;
2508 // For a dependent type, the set of template parameters that we
2510 TemplateParameterList *ExpectedTemplateParams = nullptr;
2512 // C++0x [temp.expl.spec]p15:
2513 // A member or a member template may be nested within many enclosing
2514 // class templates. In an explicit specialization for such a member, the
2515 // member declaration shall be preceded by a template<> for each
2516 // enclosing class template that is explicitly specialized.
2517 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2518 if (ClassTemplatePartialSpecializationDecl *Partial
2519 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
2520 ExpectedTemplateParams = Partial->getTemplateParameters();
2521 NeedNonemptyTemplateHeader = true;
2522 } else if (Record->isDependentType()) {
2523 if (Record->getDescribedClassTemplate()) {
2524 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2525 ->getTemplateParameters();
2526 NeedNonemptyTemplateHeader = true;
2528 } else if (ClassTemplateSpecializationDecl *Spec
2529 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
2530 // C++0x [temp.expl.spec]p4:
2531 // Members of an explicitly specialized class template are defined
2532 // in the same manner as members of normal classes, and not using
2533 // the template<> syntax.
2534 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2535 NeedEmptyTemplateHeader = true;
2538 } else if (Record->getTemplateSpecializationKind()) {
2539 if (Record->getTemplateSpecializationKind()
2540 != TSK_ExplicitSpecialization &&
2541 TypeIdx == NumTypes - 1)
2542 IsMemberSpecialization = true;
2546 } else if (const TemplateSpecializationType *TST
2547 = T->getAs<TemplateSpecializationType>()) {
2548 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2549 ExpectedTemplateParams = Template->getTemplateParameters();
2550 NeedNonemptyTemplateHeader = true;
2552 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2553 // FIXME: We actually could/should check the template arguments here
2554 // against the corresponding template parameter list.
2555 NeedNonemptyTemplateHeader = false;
2558 // C++ [temp.expl.spec]p16:
2559 // In an explicit specialization declaration for a member of a class
2560 // template or a member template that ap- pears in namespace scope, the
2561 // member template and some of its enclosing class templates may remain
2562 // unspecialized, except that the declaration shall not explicitly
2563 // specialize a class member template if its en- closing class templates
2564 // are not explicitly specialized as well.
2565 if (ParamIdx < ParamLists.size()) {
2566 if (ParamLists[ParamIdx]->size() == 0) {
2567 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2571 SawNonEmptyTemplateParameterList = true;
2574 if (NeedEmptyTemplateHeader) {
2575 // If we're on the last of the types, and we need a 'template<>' header
2576 // here, then it's a member specialization.
2577 if (TypeIdx == NumTypes - 1)
2578 IsMemberSpecialization = true;
2580 if (ParamIdx < ParamLists.size()) {
2581 if (ParamLists[ParamIdx]->size() > 0) {
2582 // The header has template parameters when it shouldn't. Complain.
2583 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2584 diag::err_template_param_list_matches_nontemplate)
2586 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2587 ParamLists[ParamIdx]->getRAngleLoc())
2588 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2593 // Consume this template header.
2599 if (DiagnoseMissingExplicitSpecialization(
2600 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2606 if (NeedNonemptyTemplateHeader) {
2607 // In friend declarations we can have template-ids which don't
2608 // depend on the corresponding template parameter lists. But
2609 // assume that empty parameter lists are supposed to match this
2611 if (IsFriend && T->isDependentType()) {
2612 if (ParamIdx < ParamLists.size() &&
2613 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
2614 ExpectedTemplateParams = nullptr;
2619 if (ParamIdx < ParamLists.size()) {
2620 // Check the template parameter list, if we can.
2621 if (ExpectedTemplateParams &&
2622 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
2623 ExpectedTemplateParams,
2624 true, TPL_TemplateMatch))
2628 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
2629 TPC_ClassTemplateMember))
2636 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
2638 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2644 // If there were at least as many template-ids as there were template
2645 // parameter lists, then there are no template parameter lists remaining for
2646 // the declaration itself.
2647 if (ParamIdx >= ParamLists.size()) {
2648 if (TemplateId && !IsFriend) {
2649 // We don't have a template header for the declaration itself, but we
2651 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
2652 TemplateId->RAngleLoc));
2654 // Fabricate an empty template parameter list for the invented header.
2655 return TemplateParameterList::Create(Context, SourceLocation(),
2656 SourceLocation(), None,
2657 SourceLocation(), nullptr);
2663 // If there were too many template parameter lists, complain about that now.
2664 if (ParamIdx < ParamLists.size() - 1) {
2665 bool HasAnyExplicitSpecHeader = false;
2666 bool AllExplicitSpecHeaders = true;
2667 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
2668 if (ParamLists[I]->size() == 0)
2669 HasAnyExplicitSpecHeader = true;
2671 AllExplicitSpecHeaders = false;
2674 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
2675 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
2676 : diag::err_template_spec_extra_headers)
2677 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
2678 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
2680 // If there was a specialization somewhere, such that 'template<>' is
2681 // not required, and there were any 'template<>' headers, note where the
2682 // specialization occurred.
2683 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
2684 Diag(ExplicitSpecLoc,
2685 diag::note_explicit_template_spec_does_not_need_header)
2686 << NestedTypes.back();
2688 // We have a template parameter list with no corresponding scope, which
2689 // means that the resulting template declaration can't be instantiated
2690 // properly (we'll end up with dependent nodes when we shouldn't).
2691 if (!AllExplicitSpecHeaders)
2695 // C++ [temp.expl.spec]p16:
2696 // In an explicit specialization declaration for a member of a class
2697 // template or a member template that ap- pears in namespace scope, the
2698 // member template and some of its enclosing class templates may remain
2699 // unspecialized, except that the declaration shall not explicitly
2700 // specialize a class member template if its en- closing class templates
2701 // are not explicitly specialized as well.
2702 if (ParamLists.back()->size() == 0 &&
2703 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2707 // Return the last template parameter list, which corresponds to the
2708 // entity being declared.
2709 return ParamLists.back();
2712 void Sema::NoteAllFoundTemplates(TemplateName Name) {
2713 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2714 Diag(Template->getLocation(), diag::note_template_declared_here)
2715 << (isa<FunctionTemplateDecl>(Template)
2717 : isa<ClassTemplateDecl>(Template)
2719 : isa<VarTemplateDecl>(Template)
2721 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
2722 << Template->getDeclName();
2726 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
2727 for (OverloadedTemplateStorage::iterator I = OST->begin(),
2730 Diag((*I)->getLocation(), diag::note_template_declared_here)
2731 << 0 << (*I)->getDeclName();
2738 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
2739 const SmallVectorImpl<TemplateArgument> &Converted,
2740 SourceLocation TemplateLoc,
2741 TemplateArgumentListInfo &TemplateArgs) {
2742 ASTContext &Context = SemaRef.getASTContext();
2743 switch (BTD->getBuiltinTemplateKind()) {
2744 case BTK__make_integer_seq: {
2745 // Specializations of __make_integer_seq<S, T, N> are treated like
2746 // S<T, 0, ..., N-1>.
2748 // C++14 [inteseq.intseq]p1:
2749 // T shall be an integer type.
2750 if (!Converted[1].getAsType()->isIntegralType(Context)) {
2751 SemaRef.Diag(TemplateArgs[1].getLocation(),
2752 diag::err_integer_sequence_integral_element_type);
2756 // C++14 [inteseq.make]p1:
2757 // If N is negative the program is ill-formed.
2758 TemplateArgument NumArgsArg = Converted[2];
2759 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
2761 SemaRef.Diag(TemplateArgs[2].getLocation(),
2762 diag::err_integer_sequence_negative_length);
2766 QualType ArgTy = NumArgsArg.getIntegralType();
2767 TemplateArgumentListInfo SyntheticTemplateArgs;
2768 // The type argument gets reused as the first template argument in the
2769 // synthetic template argument list.
2770 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
2771 // Expand N into 0 ... N-1.
2772 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
2774 TemplateArgument TA(Context, I, ArgTy);
2775 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
2776 TA, ArgTy, TemplateArgs[2].getLocation()));
2778 // The first template argument will be reused as the template decl that
2779 // our synthetic template arguments will be applied to.
2780 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
2781 TemplateLoc, SyntheticTemplateArgs);
2784 case BTK__type_pack_element:
2785 // Specializations of
2786 // __type_pack_element<Index, T_1, ..., T_N>
2787 // are treated like T_Index.
2788 assert(Converted.size() == 2 &&
2789 "__type_pack_element should be given an index and a parameter pack");
2791 // If the Index is out of bounds, the program is ill-formed.
2792 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
2793 llvm::APSInt Index = IndexArg.getAsIntegral();
2794 assert(Index >= 0 && "the index used with __type_pack_element should be of "
2795 "type std::size_t, and hence be non-negative");
2796 if (Index >= Ts.pack_size()) {
2797 SemaRef.Diag(TemplateArgs[0].getLocation(),
2798 diag::err_type_pack_element_out_of_bounds);
2802 // We simply return the type at index `Index`.
2803 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
2804 return Nth->getAsType();
2806 llvm_unreachable("unexpected BuiltinTemplateDecl!");
2809 QualType Sema::CheckTemplateIdType(TemplateName Name,
2810 SourceLocation TemplateLoc,
2811 TemplateArgumentListInfo &TemplateArgs) {
2812 DependentTemplateName *DTN
2813 = Name.getUnderlying().getAsDependentTemplateName();
2814 if (DTN && DTN->isIdentifier())
2815 // When building a template-id where the template-name is dependent,
2816 // assume the template is a type template. Either our assumption is
2817 // correct, or the code is ill-formed and will be diagnosed when the
2818 // dependent name is substituted.
2819 return Context.getDependentTemplateSpecializationType(ETK_None,
2820 DTN->getQualifier(),
2821 DTN->getIdentifier(),
2824 TemplateDecl *Template = Name.getAsTemplateDecl();
2825 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2826 isa<VarTemplateDecl>(Template)) {
2827 // We might have a substituted template template parameter pack. If so,
2828 // build a template specialization type for it.
2829 if (Name.getAsSubstTemplateTemplateParmPack())
2830 return Context.getTemplateSpecializationType(Name, TemplateArgs);
2832 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2834 NoteAllFoundTemplates(Name);
2838 // Check that the template argument list is well-formed for this
2840 SmallVector<TemplateArgument, 4> Converted;
2841 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2847 bool InstantiationDependent = false;
2848 if (TypeAliasTemplateDecl *AliasTemplate =
2849 dyn_cast<TypeAliasTemplateDecl>(Template)) {
2850 // Find the canonical type for this type alias template specialization.
2851 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2852 if (Pattern->isInvalidDecl())
2855 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2858 // Only substitute for the innermost template argument list.
2859 MultiLevelTemplateArgumentList TemplateArgLists;
2860 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
2861 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2862 for (unsigned I = 0; I < Depth; ++I)
2863 TemplateArgLists.addOuterTemplateArguments(None);
2865 LocalInstantiationScope Scope(*this);
2866 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2867 if (Inst.isInvalid())
2870 CanonType = SubstType(Pattern->getUnderlyingType(),
2871 TemplateArgLists, AliasTemplate->getLocation(),
2872 AliasTemplate->getDeclName());
2873 if (CanonType.isNull())
2875 } else if (Name.isDependent() ||
2876 TemplateSpecializationType::anyDependentTemplateArguments(
2877 TemplateArgs, InstantiationDependent)) {
2878 // This class template specialization is a dependent
2879 // type. Therefore, its canonical type is another class template
2880 // specialization type that contains all of the converted
2881 // arguments in canonical form. This ensures that, e.g., A<T> and
2882 // A<T, T> have identical types when A is declared as:
2884 // template<typename T, typename U = T> struct A;
2885 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
2887 // This might work out to be a current instantiation, in which
2888 // case the canonical type needs to be the InjectedClassNameType.
2890 // TODO: in theory this could be a simple hashtable lookup; most
2891 // changes to CurContext don't change the set of current
2893 if (isa<ClassTemplateDecl>(Template)) {
2894 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2895 // If we get out to a namespace, we're done.
2896 if (Ctx->isFileContext()) break;
2898 // If this isn't a record, keep looking.
2899 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2900 if (!Record) continue;
2902 // Look for one of the two cases with InjectedClassNameTypes
2903 // and check whether it's the same template.
2904 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2905 !Record->getDescribedClassTemplate())
2908 // Fetch the injected class name type and check whether its
2909 // injected type is equal to the type we just built.
2910 QualType ICNT = Context.getTypeDeclType(Record);
2911 QualType Injected = cast<InjectedClassNameType>(ICNT)
2912 ->getInjectedSpecializationType();
2914 if (CanonType != Injected->getCanonicalTypeInternal())
2917 // If so, the canonical type of this TST is the injected
2918 // class name type of the record we just found.
2919 assert(ICNT.isCanonical());
2924 } else if (ClassTemplateDecl *ClassTemplate
2925 = dyn_cast<ClassTemplateDecl>(Template)) {
2926 // Find the class template specialization declaration that
2927 // corresponds to these arguments.
2928 void *InsertPos = nullptr;
2929 ClassTemplateSpecializationDecl *Decl
2930 = ClassTemplate->findSpecialization(Converted, InsertPos);
2932 // This is the first time we have referenced this class template
2933 // specialization. Create the canonical declaration and add it to
2934 // the set of specializations.
2935 Decl = ClassTemplateSpecializationDecl::Create(Context,
2936 ClassTemplate->getTemplatedDecl()->getTagKind(),
2937 ClassTemplate->getDeclContext(),
2938 ClassTemplate->getTemplatedDecl()->getLocStart(),
2939 ClassTemplate->getLocation(),
2941 Converted, nullptr);
2942 ClassTemplate->AddSpecialization(Decl, InsertPos);
2943 if (ClassTemplate->isOutOfLine())
2944 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2947 if (Decl->getSpecializationKind() == TSK_Undeclared) {
2948 MultiLevelTemplateArgumentList TemplateArgLists;
2949 TemplateArgLists.addOuterTemplateArguments(Converted);
2950 InstantiateAttrsForDecl(TemplateArgLists, ClassTemplate->getTemplatedDecl(),
2954 // Diagnose uses of this specialization.
2955 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2957 CanonType = Context.getTypeDeclType(Decl);
2958 assert(isa<RecordType>(CanonType) &&
2959 "type of non-dependent specialization is not a RecordType");
2960 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
2961 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
2965 // Build the fully-sugared type for this class template
2966 // specialization, which refers back to the class template
2967 // specialization we created or found.
2968 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2972 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2973 TemplateTy TemplateD, IdentifierInfo *TemplateII,
2974 SourceLocation TemplateIILoc,
2975 SourceLocation LAngleLoc,
2976 ASTTemplateArgsPtr TemplateArgsIn,
2977 SourceLocation RAngleLoc,
2978 bool IsCtorOrDtorName, bool IsClassName) {
2982 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
2983 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
2985 // C++ [temp.res]p3:
2986 // A qualified-id that refers to a type and in which the
2987 // nested-name-specifier depends on a template-parameter (14.6.2)
2988 // shall be prefixed by the keyword typename to indicate that the
2989 // qualified-id denotes a type, forming an
2990 // elaborated-type-specifier (7.1.5.3).
2991 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
2992 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
2993 << SS.getScopeRep() << TemplateII->getName();
2994 // Recover as if 'typename' were specified.
2995 // FIXME: This is not quite correct recovery as we don't transform SS
2996 // into the corresponding dependent form (and we don't diagnose missing
2997 // 'template' keywords within SS as a result).
2998 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
2999 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3000 TemplateArgsIn, RAngleLoc);
3003 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3004 // it's not actually allowed to be used as a type in most cases. Because
3005 // we annotate it before we know whether it's valid, we have to check for
3007 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3008 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3010 TemplateKWLoc.isInvalid()
3011 ? diag::err_out_of_line_qualified_id_type_names_constructor
3012 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3013 << TemplateII << 0 /*injected-class-name used as template name*/
3014 << 1 /*if any keyword was present, it was 'template'*/;
3018 TemplateName Template = TemplateD.get();
3020 // Translate the parser's template argument list in our AST format.
3021 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3022 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3024 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3026 = Context.getDependentTemplateSpecializationType(ETK_None,
3027 DTN->getQualifier(),
3028 DTN->getIdentifier(),
3030 // Build type-source information.
3032 DependentTemplateSpecializationTypeLoc SpecTL
3033 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3034 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3035 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3036 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3037 SpecTL.setTemplateNameLoc(TemplateIILoc);
3038 SpecTL.setLAngleLoc(LAngleLoc);
3039 SpecTL.setRAngleLoc(RAngleLoc);
3040 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3041 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3042 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3045 QualType Result = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
3046 if (Result.isNull())
3049 // Build type-source information.
3051 TemplateSpecializationTypeLoc SpecTL
3052 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3053 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3054 SpecTL.setTemplateNameLoc(TemplateIILoc);
3055 SpecTL.setLAngleLoc(LAngleLoc);
3056 SpecTL.setRAngleLoc(RAngleLoc);
3057 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3058 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3060 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
3061 // constructor or destructor name (in such a case, the scope specifier
3062 // will be attached to the enclosing Decl or Expr node).
3063 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
3064 // Create an elaborated-type-specifier containing the nested-name-specifier.
3065 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
3066 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3067 ElabTL.setElaboratedKeywordLoc(SourceLocation());
3068 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3071 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3074 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3075 TypeSpecifierType TagSpec,
3076 SourceLocation TagLoc,
3078 SourceLocation TemplateKWLoc,
3079 TemplateTy TemplateD,
3080 SourceLocation TemplateLoc,
3081 SourceLocation LAngleLoc,
3082 ASTTemplateArgsPtr TemplateArgsIn,
3083 SourceLocation RAngleLoc) {
3084 TemplateName Template = TemplateD.get();
3086 // Translate the parser's template argument list in our AST format.
3087 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3088 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3090 // Determine the tag kind
3091 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
3092 ElaboratedTypeKeyword Keyword
3093 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
3095 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3096 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
3097 DTN->getQualifier(),
3098 DTN->getIdentifier(),
3101 // Build type-source information.
3103 DependentTemplateSpecializationTypeLoc SpecTL
3104 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3105 SpecTL.setElaboratedKeywordLoc(TagLoc);
3106 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3107 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3108 SpecTL.setTemplateNameLoc(TemplateLoc);
3109 SpecTL.setLAngleLoc(LAngleLoc);
3110 SpecTL.setRAngleLoc(RAngleLoc);
3111 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3112 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
3113 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
3116 if (TypeAliasTemplateDecl *TAT =
3117 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
3118 // C++0x [dcl.type.elab]p2:
3119 // If the identifier resolves to a typedef-name or the simple-template-id
3120 // resolves to an alias template specialization, the
3121 // elaborated-type-specifier is ill-formed.
3122 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
3123 << TAT << NTK_TypeAliasTemplate << TagKind;
3124 Diag(TAT->getLocation(), diag::note_declared_at);
3127 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
3128 if (Result.isNull())
3129 return TypeResult(true);
3131 // Check the tag kind
3132 if (const RecordType *RT = Result->getAs<RecordType>()) {
3133 RecordDecl *D = RT->getDecl();
3135 IdentifierInfo *Id = D->getIdentifier();
3136 assert(Id && "templated class must have an identifier");
3138 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
3140 Diag(TagLoc, diag::err_use_with_wrong_tag)
3142 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
3143 Diag(D->getLocation(), diag::note_previous_use);
3147 // Provide source-location information for the template specialization.
3149 TemplateSpecializationTypeLoc SpecTL
3150 = TLB.push<TemplateSpecializationTypeLoc>(Result);
3151 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3152 SpecTL.setTemplateNameLoc(TemplateLoc);
3153 SpecTL.setLAngleLoc(LAngleLoc);
3154 SpecTL.setRAngleLoc(RAngleLoc);
3155 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3156 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
3158 // Construct an elaborated type containing the nested-name-specifier (if any)
3160 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
3161 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
3162 ElabTL.setElaboratedKeywordLoc(TagLoc);
3163 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3164 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
3167 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
3168 NamedDecl *PrevDecl,
3170 bool IsPartialSpecialization);
3172 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
3174 static bool isTemplateArgumentTemplateParameter(
3175 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
3176 switch (Arg.getKind()) {
3177 case TemplateArgument::Null:
3178 case TemplateArgument::NullPtr:
3179 case TemplateArgument::Integral:
3180 case TemplateArgument::Declaration:
3181 case TemplateArgument::Pack:
3182 case TemplateArgument::TemplateExpansion:
3185 case TemplateArgument::Type: {
3186 QualType Type = Arg.getAsType();
3187 const TemplateTypeParmType *TPT =
3188 Arg.getAsType()->getAs<TemplateTypeParmType>();
3189 return TPT && !Type.hasQualifiers() &&
3190 TPT->getDepth() == Depth && TPT->getIndex() == Index;
3193 case TemplateArgument::Expression: {
3194 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
3195 if (!DRE || !DRE->getDecl())
3197 const NonTypeTemplateParmDecl *NTTP =
3198 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
3199 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
3202 case TemplateArgument::Template:
3203 const TemplateTemplateParmDecl *TTP =
3204 dyn_cast_or_null<TemplateTemplateParmDecl>(
3205 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
3206 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
3208 llvm_unreachable("unexpected kind of template argument");
3211 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
3212 ArrayRef<TemplateArgument> Args) {
3213 if (Params->size() != Args.size())
3216 unsigned Depth = Params->getDepth();
3218 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3219 TemplateArgument Arg = Args[I];
3221 // If the parameter is a pack expansion, the argument must be a pack
3222 // whose only element is a pack expansion.
3223 if (Params->getParam(I)->isParameterPack()) {
3224 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
3225 !Arg.pack_begin()->isPackExpansion())
3227 Arg = Arg.pack_begin()->getPackExpansionPattern();
3230 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
3237 /// Convert the parser's template argument list representation into our form.
3238 static TemplateArgumentListInfo
3239 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
3240 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
3241 TemplateId.RAngleLoc);
3242 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
3243 TemplateId.NumArgs);
3244 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
3245 return TemplateArgs;
3248 template<typename PartialSpecDecl>
3249 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
3250 if (Partial->getDeclContext()->isDependentContext())
3253 // FIXME: Get the TDK from deduction in order to provide better diagnostics
3254 // for non-substitution-failure issues?
3255 TemplateDeductionInfo Info(Partial->getLocation());
3256 if (S.isMoreSpecializedThanPrimary(Partial, Info))
3259 auto *Template = Partial->getSpecializedTemplate();
3260 S.Diag(Partial->getLocation(),
3261 diag::ext_partial_spec_not_more_specialized_than_primary)
3262 << isa<VarTemplateDecl>(Template);
3264 if (Info.hasSFINAEDiagnostic()) {
3265 PartialDiagnosticAt Diag = {SourceLocation(),
3266 PartialDiagnostic::NullDiagnostic()};
3267 Info.takeSFINAEDiagnostic(Diag);
3268 SmallString<128> SFINAEArgString;
3269 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
3271 diag::note_partial_spec_not_more_specialized_than_primary)
3275 S.Diag(Template->getLocation(), diag::note_template_decl_here);
3279 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
3280 const llvm::SmallBitVector &DeducibleParams) {
3281 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
3282 if (!DeducibleParams[I]) {
3283 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
3284 if (Param->getDeclName())
3285 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3286 << Param->getDeclName();
3288 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
3295 template<typename PartialSpecDecl>
3296 static void checkTemplatePartialSpecialization(Sema &S,
3297 PartialSpecDecl *Partial) {
3298 // C++1z [temp.class.spec]p8: (DR1495)
3299 // - The specialization shall be more specialized than the primary
3300 // template (14.5.5.2).
3301 checkMoreSpecializedThanPrimary(S, Partial);
3303 // C++ [temp.class.spec]p8: (DR1315)
3304 // - Each template-parameter shall appear at least once in the
3305 // template-id outside a non-deduced context.
3306 // C++1z [temp.class.spec.match]p3 (P0127R2)
3307 // If the template arguments of a partial specialization cannot be
3308 // deduced because of the structure of its template-parameter-list
3309 // and the template-id, the program is ill-formed.
3310 auto *TemplateParams = Partial->getTemplateParameters();
3311 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3312 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
3313 TemplateParams->getDepth(), DeducibleParams);
3315 if (!DeducibleParams.all()) {
3316 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3317 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
3318 << isa<VarTemplatePartialSpecializationDecl>(Partial)
3319 << (NumNonDeducible > 1)
3320 << SourceRange(Partial->getLocation(),
3321 Partial->getTemplateArgsAsWritten()->RAngleLoc);
3322 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
3326 void Sema::CheckTemplatePartialSpecialization(
3327 ClassTemplatePartialSpecializationDecl *Partial) {
3328 checkTemplatePartialSpecialization(*this, Partial);
3331 void Sema::CheckTemplatePartialSpecialization(
3332 VarTemplatePartialSpecializationDecl *Partial) {
3333 checkTemplatePartialSpecialization(*this, Partial);
3336 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
3337 // C++1z [temp.param]p11:
3338 // A template parameter of a deduction guide template that does not have a
3339 // default-argument shall be deducible from the parameter-type-list of the
3340 // deduction guide template.
3341 auto *TemplateParams = TD->getTemplateParameters();
3342 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
3343 MarkDeducedTemplateParameters(TD, DeducibleParams);
3344 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
3345 // A parameter pack is deducible (to an empty pack).
3346 auto *Param = TemplateParams->getParam(I);
3347 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
3348 DeducibleParams[I] = true;
3351 if (!DeducibleParams.all()) {
3352 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
3353 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
3354 << (NumNonDeducible > 1);
3355 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
3359 DeclResult Sema::ActOnVarTemplateSpecialization(
3360 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
3361 TemplateParameterList *TemplateParams, StorageClass SC,
3362 bool IsPartialSpecialization) {
3363 // D must be variable template id.
3364 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
3365 "Variable template specialization is declared with a template it.");
3367 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
3368 TemplateArgumentListInfo TemplateArgs =
3369 makeTemplateArgumentListInfo(*this, *TemplateId);
3370 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
3371 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
3372 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
3374 TemplateName Name = TemplateId->Template.get();
3376 // The template-id must name a variable template.
3377 VarTemplateDecl *VarTemplate =
3378 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
3380 NamedDecl *FnTemplate;
3381 if (auto *OTS = Name.getAsOverloadedTemplate())
3382 FnTemplate = *OTS->begin();
3384 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
3386 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
3387 << FnTemplate->getDeclName();
3388 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
3389 << IsPartialSpecialization;
3392 // Check for unexpanded parameter packs in any of the template arguments.
3393 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3394 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
3395 UPPC_PartialSpecialization))
3398 // Check that the template argument list is well-formed for this
3400 SmallVector<TemplateArgument, 4> Converted;
3401 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
3405 // Find the variable template (partial) specialization declaration that
3406 // corresponds to these arguments.
3407 if (IsPartialSpecialization) {
3408 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
3409 TemplateArgs.size(), Converted))
3412 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
3413 // also do them during instantiation.
3414 bool InstantiationDependent;
3415 if (!Name.isDependent() &&
3416 !TemplateSpecializationType::anyDependentTemplateArguments(
3417 TemplateArgs.arguments(),
3418 InstantiationDependent)) {
3419 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
3420 << VarTemplate->getDeclName();
3421 IsPartialSpecialization = false;
3424 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
3426 // C++ [temp.class.spec]p9b3:
3428 // -- The argument list of the specialization shall not be identical
3429 // to the implicit argument list of the primary template.
3430 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
3431 << /*variable template*/ 1
3432 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
3433 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
3434 // FIXME: Recover from this by treating the declaration as a redeclaration
3435 // of the primary template.
3440 void *InsertPos = nullptr;
3441 VarTemplateSpecializationDecl *PrevDecl = nullptr;
3443 if (IsPartialSpecialization)
3444 // FIXME: Template parameter list matters too
3445 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
3447 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
3449 VarTemplateSpecializationDecl *Specialization = nullptr;
3451 // Check whether we can declare a variable template specialization in
3452 // the current scope.
3453 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
3455 IsPartialSpecialization))
3458 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
3459 // Since the only prior variable template specialization with these
3460 // arguments was referenced but not declared, reuse that
3461 // declaration node as our own, updating its source location and
3462 // the list of outer template parameters to reflect our new declaration.
3463 Specialization = PrevDecl;
3464 Specialization->setLocation(TemplateNameLoc);
3466 } else if (IsPartialSpecialization) {
3467 // Create a new class template partial specialization declaration node.
3468 VarTemplatePartialSpecializationDecl *PrevPartial =
3469 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
3470 VarTemplatePartialSpecializationDecl *Partial =
3471 VarTemplatePartialSpecializationDecl::Create(
3472 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
3473 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
3474 Converted, TemplateArgs);
3477 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
3478 Specialization = Partial;
3480 // If we are providing an explicit specialization of a member variable
3481 // template specialization, make a note of that.
3482 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
3483 PrevPartial->setMemberSpecialization();
3485 CheckTemplatePartialSpecialization(Partial);
3487 // Create a new class template specialization declaration node for
3488 // this explicit specialization or friend declaration.
3489 Specialization = VarTemplateSpecializationDecl::Create(
3490 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
3491 VarTemplate, DI->getType(), DI, SC, Converted);
3492 Specialization->setTemplateArgsInfo(TemplateArgs);
3495 VarTemplate->AddSpecialization(Specialization, InsertPos);
3498 // C++ [temp.expl.spec]p6:
3499 // If a template, a member template or the member of a class template is
3500 // explicitly specialized then that specialization shall be declared
3501 // before the first use of that specialization that would cause an implicit
3502 // instantiation to take place, in every translation unit in which such a
3503 // use occurs; no diagnostic is required.
3504 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
3506 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
3507 // Is there any previous explicit specialization declaration?
3508 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
3515 SourceRange Range(TemplateNameLoc, RAngleLoc);
3516 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
3519 Diag(PrevDecl->getPointOfInstantiation(),
3520 diag::note_instantiation_required_here)
3521 << (PrevDecl->getTemplateSpecializationKind() !=
3522 TSK_ImplicitInstantiation);
3527 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
3528 Specialization->setLexicalDeclContext(CurContext);
3530 // Add the specialization into its lexical context, so that it can
3531 // be seen when iterating through the list of declarations in that
3532 // context. However, specializations are not found by name lookup.
3533 CurContext->addDecl(Specialization);
3535 // Note that this is an explicit specialization.
3536 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
3539 // Check that this isn't a redefinition of this specialization,
3540 // merging with previous declarations.
3541 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
3543 PrevSpec.addDecl(PrevDecl);
3544 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
3545 } else if (Specialization->isStaticDataMember() &&
3546 Specialization->isOutOfLine()) {
3547 Specialization->setAccess(VarTemplate->getAccess());
3550 // Link instantiations of static data members back to the template from
3551 // which they were instantiated.
3552 if (Specialization->isStaticDataMember())
3553 Specialization->setInstantiationOfStaticDataMember(
3554 VarTemplate->getTemplatedDecl(),
3555 Specialization->getSpecializationKind());
3557 return Specialization;
3561 /// \brief A partial specialization whose template arguments have matched
3562 /// a given template-id.
3563 struct PartialSpecMatchResult {
3564 VarTemplatePartialSpecializationDecl *Partial;
3565 TemplateArgumentList *Args;
3567 } // end anonymous namespace
3570 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
3571 SourceLocation TemplateNameLoc,
3572 const TemplateArgumentListInfo &TemplateArgs) {
3573 assert(Template && "A variable template id without template?");
3575 // Check that the template argument list is well-formed for this template.
3576 SmallVector<TemplateArgument, 4> Converted;
3577 if (CheckTemplateArgumentList(
3578 Template, TemplateNameLoc,
3579 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
3583 // Find the variable template specialization declaration that
3584 // corresponds to these arguments.
3585 void *InsertPos = nullptr;
3586 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
3587 Converted, InsertPos)) {
3588 checkSpecializationVisibility(TemplateNameLoc, Spec);
3589 // If we already have a variable template specialization, return it.
3593 // This is the first time we have referenced this variable template
3594 // specialization. Create the canonical declaration and add it to
3595 // the set of specializations, based on the closest partial specialization
3596 // that it represents. That is,
3597 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
3598 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
3600 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
3601 bool AmbiguousPartialSpec = false;
3602 typedef PartialSpecMatchResult MatchResult;
3603 SmallVector<MatchResult, 4> Matched;
3604 SourceLocation PointOfInstantiation = TemplateNameLoc;
3605 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
3606 /*ForTakingAddress=*/false);
3608 // 1. Attempt to find the closest partial specialization that this
3609 // specializes, if any.
3610 // If any of the template arguments is dependent, then this is probably
3611 // a placeholder for an incomplete declarative context; which must be
3612 // complete by instantiation time. Thus, do not search through the partial
3613 // specializations yet.
3614 // TODO: Unify with InstantiateClassTemplateSpecialization()?
3615 // Perhaps better after unification of DeduceTemplateArguments() and
3616 // getMoreSpecializedPartialSpecialization().
3617 bool InstantiationDependent = false;
3618 if (!TemplateSpecializationType::anyDependentTemplateArguments(
3619 TemplateArgs, InstantiationDependent)) {
3621 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3622 Template->getPartialSpecializations(PartialSpecs);
3624 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3625 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3626 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3628 if (TemplateDeductionResult Result =
3629 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
3630 // Store the failed-deduction information for use in diagnostics, later.
3631 // TODO: Actually use the failed-deduction info?
3632 FailedCandidates.addCandidate().set(
3633 DeclAccessPair::make(Template, AS_public), Partial,
3634 MakeDeductionFailureInfo(Context, Result, Info));
3637 Matched.push_back(PartialSpecMatchResult());
3638 Matched.back().Partial = Partial;
3639 Matched.back().Args = Info.take();
3643 if (Matched.size() >= 1) {
3644 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
3645 if (Matched.size() == 1) {
3646 // -- If exactly one matching specialization is found, the
3647 // instantiation is generated from that specialization.
3648 // We don't need to do anything for this.
3650 // -- If more than one matching specialization is found, the
3651 // partial order rules (14.5.4.2) are used to determine
3652 // whether one of the specializations is more specialized
3653 // than the others. If none of the specializations is more
3654 // specialized than all of the other matching
3655 // specializations, then the use of the variable template is
3656 // ambiguous and the program is ill-formed.
3657 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
3658 PEnd = Matched.end();
3660 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
3661 PointOfInstantiation) ==
3666 // Determine if the best partial specialization is more specialized than
3668 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
3669 PEnd = Matched.end();
3671 if (P != Best && getMoreSpecializedPartialSpecialization(
3672 P->Partial, Best->Partial,
3673 PointOfInstantiation) != Best->Partial) {
3674 AmbiguousPartialSpec = true;
3680 // Instantiate using the best variable template partial specialization.
3681 InstantiationPattern = Best->Partial;
3682 InstantiationArgs = Best->Args;
3684 // -- If no match is found, the instantiation is generated
3685 // from the primary template.
3686 // InstantiationPattern = Template->getTemplatedDecl();
3690 // 2. Create the canonical declaration.
3691 // Note that we do not instantiate a definition until we see an odr-use
3692 // in DoMarkVarDeclReferenced().
3693 // FIXME: LateAttrs et al.?
3694 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
3695 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
3696 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
3700 if (AmbiguousPartialSpec) {
3701 // Partial ordering did not produce a clear winner. Complain.
3702 Decl->setInvalidDecl();
3703 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
3706 // Print the matching partial specializations.
3707 for (MatchResult P : Matched)
3708 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
3709 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
3714 if (VarTemplatePartialSpecializationDecl *D =
3715 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
3716 Decl->setInstantiationOf(D, InstantiationArgs);
3718 checkSpecializationVisibility(TemplateNameLoc, Decl);
3720 assert(Decl && "No variable template specialization?");
3725 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
3726 const DeclarationNameInfo &NameInfo,
3727 VarTemplateDecl *Template, SourceLocation TemplateLoc,
3728 const TemplateArgumentListInfo *TemplateArgs) {
3730 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
3732 if (Decl.isInvalid())
3735 VarDecl *Var = cast<VarDecl>(Decl.get());
3736 if (!Var->getTemplateSpecializationKind())
3737 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
3740 // Build an ordinary singleton decl ref.
3741 return BuildDeclarationNameExpr(SS, NameInfo, Var,
3742 /*FoundD=*/nullptr, TemplateArgs);
3745 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
3746 SourceLocation TemplateKWLoc,
3749 const TemplateArgumentListInfo *TemplateArgs) {
3750 // FIXME: Can we do any checking at this point? I guess we could check the
3751 // template arguments that we have against the template name, if the template
3752 // name refers to a single template. That's not a terribly common case,
3754 // foo<int> could identify a single function unambiguously
3755 // This approach does NOT work, since f<int>(1);
3756 // gets resolved prior to resorting to overload resolution
3757 // i.e., template<class T> void f(double);
3758 // vs template<class T, class U> void f(U);
3760 // These should be filtered out by our callers.
3761 assert(!R.empty() && "empty lookup results when building templateid");
3762 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
3764 // In C++1y, check variable template ids.
3765 bool InstantiationDependent;
3766 if (R.getAsSingle<VarTemplateDecl>() &&
3767 !TemplateSpecializationType::anyDependentTemplateArguments(
3768 *TemplateArgs, InstantiationDependent)) {
3769 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
3770 R.getAsSingle<VarTemplateDecl>(),
3771 TemplateKWLoc, TemplateArgs);
3774 // We don't want lookup warnings at this point.
3775 R.suppressDiagnostics();
3777 UnresolvedLookupExpr *ULE
3778 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3779 SS.getWithLocInContext(Context),
3781 R.getLookupNameInfo(),
3782 RequiresADL, TemplateArgs,
3783 R.begin(), R.end());
3788 // We actually only call this from template instantiation.
3790 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
3791 SourceLocation TemplateKWLoc,
3792 const DeclarationNameInfo &NameInfo,
3793 const TemplateArgumentListInfo *TemplateArgs) {
3795 assert(TemplateArgs || TemplateKWLoc.isValid());
3797 if (!(DC = computeDeclContext(SS, false)) ||
3798 DC->isDependentContext() ||
3799 RequireCompleteDeclContext(SS, DC))
3800 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
3802 bool MemberOfUnknownSpecialization;
3803 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3804 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
3805 MemberOfUnknownSpecialization);
3807 if (R.isAmbiguous())
3811 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
3812 << NameInfo.getName() << SS.getRange();
3816 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
3817 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
3819 << NameInfo.getName().getAsString() << SS.getRange();
3820 Diag(Temp->getLocation(), diag::note_referenced_class_template);
3824 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
3827 /// \brief Form a dependent template name.
3829 /// This action forms a dependent template name given the template
3830 /// name and its (presumably dependent) scope specifier. For
3831 /// example, given "MetaFun::template apply", the scope specifier \p
3832 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
3833 /// of the "template" keyword, and "apply" is the \p Name.
3834 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
3836 SourceLocation TemplateKWLoc,
3837 UnqualifiedId &Name,
3838 ParsedType ObjectType,
3839 bool EnteringContext,
3841 bool AllowInjectedClassName) {
3842 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
3844 getLangOpts().CPlusPlus11 ?
3845 diag::warn_cxx98_compat_template_outside_of_template :
3846 diag::ext_template_outside_of_template)
3847 << FixItHint::CreateRemoval(TemplateKWLoc);
3849 DeclContext *LookupCtx = nullptr;
3851 LookupCtx = computeDeclContext(SS, EnteringContext);
3852 if (!LookupCtx && ObjectType)
3853 LookupCtx = computeDeclContext(ObjectType.get());
3855 // C++0x [temp.names]p5:
3856 // If a name prefixed by the keyword template is not the name of
3857 // a template, the program is ill-formed. [Note: the keyword
3858 // template may not be applied to non-template members of class
3859 // templates. -end note ] [ Note: as is the case with the
3860 // typename prefix, the template prefix is allowed in cases
3861 // where it is not strictly necessary; i.e., when the
3862 // nested-name-specifier or the expression on the left of the ->
3863 // or . is not dependent on a template-parameter, or the use
3864 // does not appear in the scope of a template. -end note]
3866 // Note: C++03 was more strict here, because it banned the use of
3867 // the "template" keyword prior to a template-name that was not a
3868 // dependent name. C++ DR468 relaxed this requirement (the
3869 // "template" keyword is now permitted). We follow the C++0x
3870 // rules, even in C++03 mode with a warning, retroactively applying the DR.
3871 bool MemberOfUnknownSpecialization;
3872 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
3873 ObjectType, EnteringContext, Result,
3874 MemberOfUnknownSpecialization);
3875 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
3876 isa<CXXRecordDecl>(LookupCtx) &&
3877 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
3878 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
3879 // This is a dependent template. Handle it below.
3880 } else if (TNK == TNK_Non_template) {
3881 Diag(Name.getLocStart(),
3882 diag::err_template_kw_refers_to_non_template)
3883 << GetNameFromUnqualifiedId(Name).getName()
3884 << Name.getSourceRange()
3886 return TNK_Non_template;
3888 // We found something; return it.
3889 auto *LookupRD = dyn_cast<CXXRecordDecl>(LookupCtx);
3890 if (!AllowInjectedClassName && SS.isSet() && LookupRD &&
3891 Name.getKind() == UnqualifiedId::IK_Identifier && Name.Identifier &&
3892 LookupRD->getIdentifier() == Name.Identifier) {
3893 // C++14 [class.qual]p2:
3894 // In a lookup in which function names are not ignored and the
3895 // nested-name-specifier nominates a class C, if the name specified
3896 // [...] is the injected-class-name of C, [...] the name is instead
3897 // considered to name the constructor
3899 // We don't get here if naming the constructor would be valid, so we
3900 // just reject immediately and recover by treating the
3901 // injected-class-name as naming the template.
3902 Diag(Name.getLocStart(),
3903 diag::ext_out_of_line_qualified_id_type_names_constructor)
3904 << Name.Identifier << 0 /*injected-class-name used as template name*/
3905 << 1 /*'template' keyword was used*/;
3911 NestedNameSpecifier *Qualifier = SS.getScopeRep();
3913 switch (Name.getKind()) {
3914 case UnqualifiedId::IK_Identifier:
3915 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
3917 return TNK_Dependent_template_name;
3919 case UnqualifiedId::IK_OperatorFunctionId:
3920 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
3921 Name.OperatorFunctionId.Operator));
3922 return TNK_Function_template;
3924 case UnqualifiedId::IK_LiteralOperatorId:
3925 llvm_unreachable("literal operator id cannot have a dependent scope");
3931 Diag(Name.getLocStart(),
3932 diag::err_template_kw_refers_to_non_template)
3933 << GetNameFromUnqualifiedId(Name).getName()
3934 << Name.getSourceRange()
3936 return TNK_Non_template;
3939 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
3940 TemplateArgumentLoc &AL,
3941 SmallVectorImpl<TemplateArgument> &Converted) {
3942 const TemplateArgument &Arg = AL.getArgument();
3944 TypeSourceInfo *TSI = nullptr;
3946 // Check template type parameter.
3947 switch(Arg.getKind()) {
3948 case TemplateArgument::Type:
3949 // C++ [temp.arg.type]p1:
3950 // A template-argument for a template-parameter which is a
3951 // type shall be a type-id.
3952 ArgType = Arg.getAsType();
3953 TSI = AL.getTypeSourceInfo();
3955 case TemplateArgument::Template: {
3956 // We have a template type parameter but the template argument
3957 // is a template without any arguments.
3958 SourceRange SR = AL.getSourceRange();
3959 TemplateName Name = Arg.getAsTemplate();
3960 Diag(SR.getBegin(), diag::err_template_missing_args)
3961 << (int)getTemplateNameKindForDiagnostics(Name) << Name << SR;
3962 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3963 Diag(Decl->getLocation(), diag::note_template_decl_here);
3967 case TemplateArgument::Expression: {
3968 // We have a template type parameter but the template argument is an
3969 // expression; see if maybe it is missing the "typename" keyword.
3971 DeclarationNameInfo NameInfo;
3973 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3974 SS.Adopt(ArgExpr->getQualifierLoc());
3975 NameInfo = ArgExpr->getNameInfo();
3976 } else if (DependentScopeDeclRefExpr *ArgExpr =
3977 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3978 SS.Adopt(ArgExpr->getQualifierLoc());
3979 NameInfo = ArgExpr->getNameInfo();
3980 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3981 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
3982 if (ArgExpr->isImplicitAccess()) {
3983 SS.Adopt(ArgExpr->getQualifierLoc());
3984 NameInfo = ArgExpr->getMemberNameInfo();
3988 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
3989 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3990 LookupParsedName(Result, CurScope, &SS);
3992 if (Result.getAsSingle<TypeDecl>() ||
3993 Result.getResultKind() ==
3994 LookupResult::NotFoundInCurrentInstantiation) {
3995 // Suggest that the user add 'typename' before the NNS.
3996 SourceLocation Loc = AL.getSourceRange().getBegin();
3997 Diag(Loc, getLangOpts().MSVCCompat
3998 ? diag::ext_ms_template_type_arg_missing_typename
3999 : diag::err_template_arg_must_be_type_suggest)
4000 << FixItHint::CreateInsertion(Loc, "typename ");
4001 Diag(Param->getLocation(), diag::note_template_param_here);
4003 // Recover by synthesizing a type using the location information that we
4006 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
4008 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
4009 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
4010 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4011 TL.setNameLoc(NameInfo.getLoc());
4012 TSI = TLB.getTypeSourceInfo(Context, ArgType);
4014 // Overwrite our input TemplateArgumentLoc so that we can recover
4016 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
4017 TemplateArgumentLocInfo(TSI));
4026 // We have a template type parameter but the template argument
4028 SourceRange SR = AL.getSourceRange();
4029 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
4030 Diag(Param->getLocation(), diag::note_template_param_here);
4036 if (CheckTemplateArgument(Param, TSI))
4039 // Add the converted template type argument.
4040 ArgType = Context.getCanonicalType(ArgType);
4043 // If an explicitly-specified template argument type is a lifetime type
4044 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
4045 if (getLangOpts().ObjCAutoRefCount &&
4046 ArgType->isObjCLifetimeType() &&
4047 !ArgType.getObjCLifetime()) {
4049 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
4050 ArgType = Context.getQualifiedType(ArgType, Qs);
4053 Converted.push_back(TemplateArgument(ArgType));
4057 /// \brief Substitute template arguments into the default template argument for
4058 /// the given template type parameter.
4060 /// \param SemaRef the semantic analysis object for which we are performing
4061 /// the substitution.
4063 /// \param Template the template that we are synthesizing template arguments
4066 /// \param TemplateLoc the location of the template name that started the
4067 /// template-id we are checking.
4069 /// \param RAngleLoc the location of the right angle bracket ('>') that
4070 /// terminates the template-id.
4072 /// \param Param the template template parameter whose default we are
4073 /// substituting into.
4075 /// \param Converted the list of template arguments provided for template
4076 /// parameters that precede \p Param in the template parameter list.
4077 /// \returns the substituted template argument, or NULL if an error occurred.
4078 static TypeSourceInfo *
4079 SubstDefaultTemplateArgument(Sema &SemaRef,
4080 TemplateDecl *Template,
4081 SourceLocation TemplateLoc,
4082 SourceLocation RAngleLoc,
4083 TemplateTypeParmDecl *Param,
4084 SmallVectorImpl<TemplateArgument> &Converted) {
4085 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
4087 // If the argument type is dependent, instantiate it now based
4088 // on the previously-computed template arguments.
4089 if (ArgType->getType()->isDependentType()) {
4090 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4091 Param, Template, Converted,
4092 SourceRange(TemplateLoc, RAngleLoc));
4093 if (Inst.isInvalid())
4096 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4098 // Only substitute for the innermost template argument list.
4099 MultiLevelTemplateArgumentList TemplateArgLists;
4100 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4101 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4102 TemplateArgLists.addOuterTemplateArguments(None);
4104 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4106 SemaRef.SubstType(ArgType, TemplateArgLists,
4107 Param->getDefaultArgumentLoc(), Param->getDeclName());
4113 /// \brief Substitute template arguments into the default template argument for
4114 /// the given non-type template parameter.
4116 /// \param SemaRef the semantic analysis object for which we are performing
4117 /// the substitution.
4119 /// \param Template the template that we are synthesizing template arguments
4122 /// \param TemplateLoc the location of the template name that started the
4123 /// template-id we are checking.
4125 /// \param RAngleLoc the location of the right angle bracket ('>') that
4126 /// terminates the template-id.
4128 /// \param Param the non-type template parameter whose default we are
4129 /// substituting into.
4131 /// \param Converted the list of template arguments provided for template
4132 /// parameters that precede \p Param in the template parameter list.
4134 /// \returns the substituted template argument, or NULL if an error occurred.
4136 SubstDefaultTemplateArgument(Sema &SemaRef,
4137 TemplateDecl *Template,
4138 SourceLocation TemplateLoc,
4139 SourceLocation RAngleLoc,
4140 NonTypeTemplateParmDecl *Param,
4141 SmallVectorImpl<TemplateArgument> &Converted) {
4142 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
4143 Param, Template, Converted,
4144 SourceRange(TemplateLoc, RAngleLoc));
4145 if (Inst.isInvalid())
4148 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4150 // Only substitute for the innermost template argument list.
4151 MultiLevelTemplateArgumentList TemplateArgLists;
4152 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4153 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4154 TemplateArgLists.addOuterTemplateArguments(None);
4156 EnterExpressionEvaluationContext ConstantEvaluated(
4157 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4158 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
4161 /// \brief Substitute template arguments into the default template argument for
4162 /// the given template template parameter.
4164 /// \param SemaRef the semantic analysis object for which we are performing
4165 /// the substitution.
4167 /// \param Template the template that we are synthesizing template arguments
4170 /// \param TemplateLoc the location of the template name that started the
4171 /// template-id we are checking.
4173 /// \param RAngleLoc the location of the right angle bracket ('>') that
4174 /// terminates the template-id.
4176 /// \param Param the template template parameter whose default we are
4177 /// substituting into.
4179 /// \param Converted the list of template arguments provided for template
4180 /// parameters that precede \p Param in the template parameter list.
4182 /// \param QualifierLoc Will be set to the nested-name-specifier (with
4183 /// source-location information) that precedes the template name.
4185 /// \returns the substituted template argument, or NULL if an error occurred.
4187 SubstDefaultTemplateArgument(Sema &SemaRef,
4188 TemplateDecl *Template,
4189 SourceLocation TemplateLoc,
4190 SourceLocation RAngleLoc,
4191 TemplateTemplateParmDecl *Param,
4192 SmallVectorImpl<TemplateArgument> &Converted,
4193 NestedNameSpecifierLoc &QualifierLoc) {
4194 Sema::InstantiatingTemplate Inst(
4195 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
4196 SourceRange(TemplateLoc, RAngleLoc));
4197 if (Inst.isInvalid())
4198 return TemplateName();
4200 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4202 // Only substitute for the innermost template argument list.
4203 MultiLevelTemplateArgumentList TemplateArgLists;
4204 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
4205 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
4206 TemplateArgLists.addOuterTemplateArguments(None);
4208 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
4209 // Substitute into the nested-name-specifier first,
4210 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
4213 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
4215 return TemplateName();
4218 return SemaRef.SubstTemplateName(
4220 Param->getDefaultArgument().getArgument().getAsTemplate(),
4221 Param->getDefaultArgument().getTemplateNameLoc(),
4225 /// \brief If the given template parameter has a default template
4226 /// argument, substitute into that default template argument and
4227 /// return the corresponding template argument.
4229 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
4230 SourceLocation TemplateLoc,
4231 SourceLocation RAngleLoc,
4233 SmallVectorImpl<TemplateArgument>
4235 bool &HasDefaultArg) {
4236 HasDefaultArg = false;
4238 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
4239 if (!hasVisibleDefaultArgument(TypeParm))
4240 return TemplateArgumentLoc();
4242 HasDefaultArg = true;
4243 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
4249 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4251 return TemplateArgumentLoc();
4254 if (NonTypeTemplateParmDecl *NonTypeParm
4255 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4256 if (!hasVisibleDefaultArgument(NonTypeParm))
4257 return TemplateArgumentLoc();
4259 HasDefaultArg = true;
4260 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
4265 if (Arg.isInvalid())
4266 return TemplateArgumentLoc();
4268 Expr *ArgE = Arg.getAs<Expr>();
4269 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
4272 TemplateTemplateParmDecl *TempTempParm
4273 = cast<TemplateTemplateParmDecl>(Param);
4274 if (!hasVisibleDefaultArgument(TempTempParm))
4275 return TemplateArgumentLoc();
4277 HasDefaultArg = true;
4278 NestedNameSpecifierLoc QualifierLoc;
4279 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
4286 return TemplateArgumentLoc();
4288 return TemplateArgumentLoc(TemplateArgument(TName),
4289 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
4290 TempTempParm->getDefaultArgument().getTemplateNameLoc());
4293 /// Convert a template-argument that we parsed as a type into a template, if
4294 /// possible. C++ permits injected-class-names to perform dual service as
4295 /// template template arguments and as template type arguments.
4296 static TemplateArgumentLoc convertTypeTemplateArgumentToTemplate(TypeLoc TLoc) {
4297 // Extract and step over any surrounding nested-name-specifier.
4298 NestedNameSpecifierLoc QualLoc;
4299 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
4300 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
4301 return TemplateArgumentLoc();
4303 QualLoc = ETLoc.getQualifierLoc();
4304 TLoc = ETLoc.getNamedTypeLoc();
4307 // If this type was written as an injected-class-name, it can be used as a
4308 // template template argument.
4309 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
4310 return TemplateArgumentLoc(InjLoc.getTypePtr()->getTemplateName(),
4311 QualLoc, InjLoc.getNameLoc());
4313 // If this type was written as an injected-class-name, it may have been
4314 // converted to a RecordType during instantiation. If the RecordType is
4315 // *not* wrapped in a TemplateSpecializationType and denotes a class
4316 // template specialization, it must have come from an injected-class-name.
4317 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
4319 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
4320 return TemplateArgumentLoc(TemplateName(CTSD->getSpecializedTemplate()),
4321 QualLoc, RecLoc.getNameLoc());
4323 return TemplateArgumentLoc();
4326 /// \brief Check that the given template argument corresponds to the given
4327 /// template parameter.
4329 /// \param Param The template parameter against which the argument will be
4332 /// \param Arg The template argument, which may be updated due to conversions.
4334 /// \param Template The template in which the template argument resides.
4336 /// \param TemplateLoc The location of the template name for the template
4337 /// whose argument list we're matching.
4339 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
4340 /// the template argument list.
4342 /// \param ArgumentPackIndex The index into the argument pack where this
4343 /// argument will be placed. Only valid if the parameter is a parameter pack.
4345 /// \param Converted The checked, converted argument will be added to the
4346 /// end of this small vector.
4348 /// \param CTAK Describes how we arrived at this particular template argument:
4349 /// explicitly written, deduced, etc.
4351 /// \returns true on error, false otherwise.
4352 bool Sema::CheckTemplateArgument(NamedDecl *Param,
4353 TemplateArgumentLoc &Arg,
4354 NamedDecl *Template,
4355 SourceLocation TemplateLoc,
4356 SourceLocation RAngleLoc,
4357 unsigned ArgumentPackIndex,
4358 SmallVectorImpl<TemplateArgument> &Converted,
4359 CheckTemplateArgumentKind CTAK) {
4360 // Check template type parameters.
4361 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
4362 return CheckTemplateTypeArgument(TTP, Arg, Converted);
4364 // Check non-type template parameters.
4365 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4366 // Do substitution on the type of the non-type template parameter
4367 // with the template arguments we've seen thus far. But if the
4368 // template has a dependent context then we cannot substitute yet.
4369 QualType NTTPType = NTTP->getType();
4370 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
4371 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
4373 if (NTTPType->isDependentType() &&
4374 !isa<TemplateTemplateParmDecl>(Template) &&
4375 !Template->getDeclContext()->isDependentContext()) {
4376 // Do substitution on the type of the non-type template parameter.
4377 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4379 SourceRange(TemplateLoc, RAngleLoc));
4380 if (Inst.isInvalid())
4383 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
4385 NTTPType = SubstType(NTTPType,
4386 MultiLevelTemplateArgumentList(TemplateArgs),
4387 NTTP->getLocation(),
4388 NTTP->getDeclName());
4389 // If that worked, check the non-type template parameter type
4391 if (!NTTPType.isNull())
4392 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
4393 NTTP->getLocation());
4394 if (NTTPType.isNull())
4398 switch (Arg.getArgument().getKind()) {
4399 case TemplateArgument::Null:
4400 llvm_unreachable("Should never see a NULL template argument here");
4402 case TemplateArgument::Expression: {
4403 TemplateArgument Result;
4405 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
4407 if (Res.isInvalid())
4410 // If the resulting expression is new, then use it in place of the
4411 // old expression in the template argument.
4412 if (Res.get() != Arg.getArgument().getAsExpr()) {
4413 TemplateArgument TA(Res.get());
4414 Arg = TemplateArgumentLoc(TA, Res.get());
4417 Converted.push_back(Result);
4421 case TemplateArgument::Declaration:
4422 case TemplateArgument::Integral:
4423 case TemplateArgument::NullPtr:
4424 // We've already checked this template argument, so just copy
4425 // it to the list of converted arguments.
4426 Converted.push_back(Arg.getArgument());
4429 case TemplateArgument::Template:
4430 case TemplateArgument::TemplateExpansion:
4431 // We were given a template template argument. It may not be ill-formed;
4433 if (DependentTemplateName *DTN
4434 = Arg.getArgument().getAsTemplateOrTemplatePattern()
4435 .getAsDependentTemplateName()) {
4436 // We have a template argument such as \c T::template X, which we
4437 // parsed as a template template argument. However, since we now
4438 // know that we need a non-type template argument, convert this
4439 // template name into an expression.
4441 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
4442 Arg.getTemplateNameLoc());
4445 SS.Adopt(Arg.getTemplateQualifierLoc());
4446 // FIXME: the template-template arg was a DependentTemplateName,
4447 // so it was provided with a template keyword. However, its source
4448 // location is not stored in the template argument structure.
4449 SourceLocation TemplateKWLoc;
4450 ExprResult E = DependentScopeDeclRefExpr::Create(
4451 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
4454 // If we parsed the template argument as a pack expansion, create a
4455 // pack expansion expression.
4456 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
4457 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
4462 TemplateArgument Result;
4463 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
4467 Converted.push_back(Result);
4471 // We have a template argument that actually does refer to a class
4472 // template, alias template, or template template parameter, and
4473 // therefore cannot be a non-type template argument.
4474 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
4475 << Arg.getSourceRange();
4477 Diag(Param->getLocation(), diag::note_template_param_here);
4480 case TemplateArgument::Type: {
4481 // We have a non-type template parameter but the template
4482 // argument is a type.
4484 // C++ [temp.arg]p2:
4485 // In a template-argument, an ambiguity between a type-id and
4486 // an expression is resolved to a type-id, regardless of the
4487 // form of the corresponding template-parameter.
4489 // We warn specifically about this case, since it can be rather
4490 // confusing for users.
4491 QualType T = Arg.getArgument().getAsType();
4492 SourceRange SR = Arg.getSourceRange();
4493 if (T->isFunctionType())
4494 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
4496 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
4497 Diag(Param->getLocation(), diag::note_template_param_here);
4501 case TemplateArgument::Pack:
4502 llvm_unreachable("Caller must expand template argument packs");
4509 // Check template template parameters.
4510 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
4512 // Substitute into the template parameter list of the template
4513 // template parameter, since previously-supplied template arguments
4514 // may appear within the template template parameter.
4516 // Set up a template instantiation context.
4517 LocalInstantiationScope Scope(*this);
4518 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
4519 TempParm, Converted,
4520 SourceRange(TemplateLoc, RAngleLoc));
4521 if (Inst.isInvalid())
4524 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
4525 TempParm = cast_or_null<TemplateTemplateParmDecl>(
4526 SubstDecl(TempParm, CurContext,
4527 MultiLevelTemplateArgumentList(TemplateArgs)));
4532 // C++1z [temp.local]p1: (DR1004)
4533 // When [the injected-class-name] is used [...] as a template-argument for
4534 // a template template-parameter [...] it refers to the class template
4536 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
4537 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
4538 Arg.getTypeSourceInfo()->getTypeLoc());
4539 if (!ConvertedArg.getArgument().isNull())
4543 switch (Arg.getArgument().getKind()) {
4544 case TemplateArgument::Null:
4545 llvm_unreachable("Should never see a NULL template argument here");
4547 case TemplateArgument::Template:
4548 case TemplateArgument::TemplateExpansion:
4549 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
4552 Converted.push_back(Arg.getArgument());
4555 case TemplateArgument::Expression:
4556 case TemplateArgument::Type:
4557 // We have a template template parameter but the template
4558 // argument does not refer to a template.
4559 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
4560 << getLangOpts().CPlusPlus11;
4563 case TemplateArgument::Declaration:
4564 llvm_unreachable("Declaration argument with template template parameter");
4565 case TemplateArgument::Integral:
4566 llvm_unreachable("Integral argument with template template parameter");
4567 case TemplateArgument::NullPtr:
4568 llvm_unreachable("Null pointer argument with template template parameter");
4570 case TemplateArgument::Pack:
4571 llvm_unreachable("Caller must expand template argument packs");
4577 /// \brief Diagnose an arity mismatch in the
4578 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
4579 SourceLocation TemplateLoc,
4580 TemplateArgumentListInfo &TemplateArgs) {
4581 TemplateParameterList *Params = Template->getTemplateParameters();
4582 unsigned NumParams = Params->size();
4583 unsigned NumArgs = TemplateArgs.size();
4586 if (NumArgs > NumParams)
4587 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
4588 TemplateArgs.getRAngleLoc());
4589 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4590 << (NumArgs > NumParams)
4591 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(Template))
4592 << Template << Range;
4593 S.Diag(Template->getLocation(), diag::note_template_decl_here)
4594 << Params->getSourceRange();
4598 /// \brief Check whether the template parameter is a pack expansion, and if so,
4599 /// determine the number of parameters produced by that expansion. For instance:
4602 /// template<typename ...Ts> struct A {
4603 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
4607 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
4608 /// is not a pack expansion, so returns an empty Optional.
4609 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
4610 if (NonTypeTemplateParmDecl *NTTP
4611 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4612 if (NTTP->isExpandedParameterPack())
4613 return NTTP->getNumExpansionTypes();
4616 if (TemplateTemplateParmDecl *TTP
4617 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
4618 if (TTP->isExpandedParameterPack())
4619 return TTP->getNumExpansionTemplateParameters();
4625 /// Diagnose a missing template argument.
4626 template<typename TemplateParmDecl>
4627 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
4629 const TemplateParmDecl *D,
4630 TemplateArgumentListInfo &Args) {
4631 // Dig out the most recent declaration of the template parameter; there may be
4632 // declarations of the template that are more recent than TD.
4633 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
4634 ->getTemplateParameters()
4635 ->getParam(D->getIndex()));
4637 // If there's a default argument that's not visible, diagnose that we're
4638 // missing a module import.
4639 llvm::SmallVector<Module*, 8> Modules;
4640 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
4641 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
4642 D->getDefaultArgumentLoc(), Modules,
4643 Sema::MissingImportKind::DefaultArgument,
4648 // FIXME: If there's a more recent default argument that *is* visible,
4649 // diagnose that it was declared too late.
4651 return diagnoseArityMismatch(S, TD, Loc, Args);
4654 /// \brief Check that the given template argument list is well-formed
4655 /// for specializing the given template.
4656 bool Sema::CheckTemplateArgumentList(
4657 TemplateDecl *Template, SourceLocation TemplateLoc,
4658 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
4659 SmallVectorImpl<TemplateArgument> &Converted,
4660 bool UpdateArgsWithConversions) {
4661 // Make a copy of the template arguments for processing. Only make the
4662 // changes at the end when successful in matching the arguments to the
4664 TemplateArgumentListInfo NewArgs = TemplateArgs;
4666 TemplateParameterList *Params = Template->getTemplateParameters();
4668 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
4670 // C++ [temp.arg]p1:
4671 // [...] The type and form of each template-argument specified in
4672 // a template-id shall match the type and form specified for the
4673 // corresponding parameter declared by the template in its
4674 // template-parameter-list.
4675 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
4676 SmallVector<TemplateArgument, 2> ArgumentPack;
4677 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
4678 LocalInstantiationScope InstScope(*this, true);
4679 for (TemplateParameterList::iterator Param = Params->begin(),
4680 ParamEnd = Params->end();
4681 Param != ParamEnd; /* increment in loop */) {
4682 // If we have an expanded parameter pack, make sure we don't have too
4684 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
4685 if (*Expansions == ArgumentPack.size()) {
4686 // We're done with this parameter pack. Pack up its arguments and add
4687 // them to the list.
4688 Converted.push_back(
4689 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4690 ArgumentPack.clear();
4692 // This argument is assigned to the next parameter.
4695 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
4696 // Not enough arguments for this parameter pack.
4697 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
4699 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
4701 Diag(Template->getLocation(), diag::note_template_decl_here)
4702 << Params->getSourceRange();
4707 if (ArgIdx < NumArgs) {
4708 // Check the template argument we were given.
4709 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
4710 TemplateLoc, RAngleLoc,
4711 ArgumentPack.size(), Converted))
4714 bool PackExpansionIntoNonPack =
4715 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
4716 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
4717 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
4718 // Core issue 1430: we have a pack expansion as an argument to an
4719 // alias template, and it's not part of a parameter pack. This
4720 // can't be canonicalized, so reject it now.
4721 Diag(NewArgs[ArgIdx].getLocation(),
4722 diag::err_alias_template_expansion_into_fixed_list)
4723 << NewArgs[ArgIdx].getSourceRange();
4724 Diag((*Param)->getLocation(), diag::note_template_param_here);
4728 // We're now done with this argument.
4731 if ((*Param)->isTemplateParameterPack()) {
4732 // The template parameter was a template parameter pack, so take the
4733 // deduced argument and place it on the argument pack. Note that we
4734 // stay on the same template parameter so that we can deduce more
4736 ArgumentPack.push_back(Converted.pop_back_val());
4738 // Move to the next template parameter.
4742 // If we just saw a pack expansion into a non-pack, then directly convert
4743 // the remaining arguments, because we don't know what parameters they'll
4745 if (PackExpansionIntoNonPack) {
4746 if (!ArgumentPack.empty()) {
4747 // If we were part way through filling in an expanded parameter pack,
4748 // fall back to just producing individual arguments.
4749 Converted.insert(Converted.end(),
4750 ArgumentPack.begin(), ArgumentPack.end());
4751 ArgumentPack.clear();
4754 while (ArgIdx < NumArgs) {
4755 Converted.push_back(NewArgs[ArgIdx].getArgument());
4765 // If we're checking a partial template argument list, we're done.
4766 if (PartialTemplateArgs) {
4767 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
4768 Converted.push_back(
4769 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4774 // If we have a template parameter pack with no more corresponding
4775 // arguments, just break out now and we'll fill in the argument pack below.
4776 if ((*Param)->isTemplateParameterPack()) {
4777 assert(!getExpandedPackSize(*Param) &&
4778 "Should have dealt with this already");
4780 // A non-expanded parameter pack before the end of the parameter list
4781 // only occurs for an ill-formed template parameter list, unless we've
4782 // got a partial argument list for a function template, so just bail out.
4783 if (Param + 1 != ParamEnd)
4786 Converted.push_back(
4787 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
4788 ArgumentPack.clear();
4794 // Check whether we have a default argument.
4795 TemplateArgumentLoc Arg;
4797 // Retrieve the default template argument from the template
4798 // parameter. For each kind of template parameter, we substitute the
4799 // template arguments provided thus far and any "outer" template arguments
4800 // (when the template parameter was part of a nested template) into
4801 // the default argument.
4802 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
4803 if (!hasVisibleDefaultArgument(TTP))
4804 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
4807 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
4816 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
4818 } else if (NonTypeTemplateParmDecl *NTTP
4819 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
4820 if (!hasVisibleDefaultArgument(NTTP))
4821 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
4824 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
4832 Expr *Ex = E.getAs<Expr>();
4833 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
4835 TemplateTemplateParmDecl *TempParm
4836 = cast<TemplateTemplateParmDecl>(*Param);
4838 if (!hasVisibleDefaultArgument(TempParm))
4839 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
4842 NestedNameSpecifierLoc QualifierLoc;
4843 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
4852 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
4853 TempParm->getDefaultArgument().getTemplateNameLoc());
4856 // Introduce an instantiation record that describes where we are using
4857 // the default template argument. We're not actually instantiating a
4858 // template here, we just create this object to put a note into the
4860 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
4861 SourceRange(TemplateLoc, RAngleLoc));
4862 if (Inst.isInvalid())
4865 // Check the default template argument.
4866 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
4867 RAngleLoc, 0, Converted))
4870 // Core issue 150 (assumed resolution): if this is a template template
4871 // parameter, keep track of the default template arguments from the
4872 // template definition.
4873 if (isTemplateTemplateParameter)
4874 NewArgs.addArgument(Arg);
4876 // Move to the next template parameter and argument.
4881 // If we're performing a partial argument substitution, allow any trailing
4882 // pack expansions; they might be empty. This can happen even if
4883 // PartialTemplateArgs is false (the list of arguments is complete but
4884 // still dependent).
4885 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
4886 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
4887 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
4888 Converted.push_back(NewArgs[ArgIdx++].getArgument());
4891 // If we have any leftover arguments, then there were too many arguments.
4892 // Complain and fail.
4893 if (ArgIdx < NumArgs)
4894 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
4896 // No problems found with the new argument list, propagate changes back
4898 if (UpdateArgsWithConversions)
4899 TemplateArgs = std::move(NewArgs);
4905 class UnnamedLocalNoLinkageFinder
4906 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
4911 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
4914 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
4916 bool Visit(QualType T) {
4917 return T.isNull() ? false : inherited::Visit(T.getTypePtr());
4920 #define TYPE(Class, Parent) \
4921 bool Visit##Class##Type(const Class##Type *);
4922 #define ABSTRACT_TYPE(Class, Parent) \
4923 bool Visit##Class##Type(const Class##Type *) { return false; }
4924 #define NON_CANONICAL_TYPE(Class, Parent) \
4925 bool Visit##Class##Type(const Class##Type *) { return false; }
4926 #include "clang/AST/TypeNodes.def"
4928 bool VisitTagDecl(const TagDecl *Tag);
4929 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
4931 } // end anonymous namespace
4933 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
4937 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
4938 return Visit(T->getElementType());
4941 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
4942 return Visit(T->getPointeeType());
4945 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
4946 const BlockPointerType* T) {
4947 return Visit(T->getPointeeType());
4950 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
4951 const LValueReferenceType* T) {
4952 return Visit(T->getPointeeType());
4955 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
4956 const RValueReferenceType* T) {
4957 return Visit(T->getPointeeType());
4960 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
4961 const MemberPointerType* T) {
4962 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
4965 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
4966 const ConstantArrayType* T) {
4967 return Visit(T->getElementType());
4970 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
4971 const IncompleteArrayType* T) {
4972 return Visit(T->getElementType());
4975 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
4976 const VariableArrayType* T) {
4977 return Visit(T->getElementType());
4980 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
4981 const DependentSizedArrayType* T) {
4982 return Visit(T->getElementType());
4985 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
4986 const DependentSizedExtVectorType* T) {
4987 return Visit(T->getElementType());
4990 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4991 return Visit(T->getElementType());
4994 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4995 return Visit(T->getElementType());
4998 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4999 const FunctionProtoType* T) {
5000 for (const auto &A : T->param_types()) {
5005 return Visit(T->getReturnType());
5008 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
5009 const FunctionNoProtoType* T) {
5010 return Visit(T->getReturnType());
5013 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
5014 const UnresolvedUsingType*) {
5018 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
5022 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
5023 return Visit(T->getUnderlyingType());
5026 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
5030 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
5031 const UnaryTransformType*) {
5035 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
5036 return Visit(T->getDeducedType());
5039 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
5040 const DeducedTemplateSpecializationType *T) {
5041 return Visit(T->getDeducedType());
5044 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
5045 return VisitTagDecl(T->getDecl());
5048 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
5049 return VisitTagDecl(T->getDecl());
5052 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
5053 const TemplateTypeParmType*) {
5057 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
5058 const SubstTemplateTypeParmPackType *) {
5062 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
5063 const TemplateSpecializationType*) {
5067 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
5068 const InjectedClassNameType* T) {
5069 return VisitTagDecl(T->getDecl());
5072 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
5073 const DependentNameType* T) {
5074 return VisitNestedNameSpecifier(T->getQualifier());
5077 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
5078 const DependentTemplateSpecializationType* T) {
5079 return VisitNestedNameSpecifier(T->getQualifier());
5082 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
5083 const PackExpansionType* T) {
5084 return Visit(T->getPattern());
5087 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
5091 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
5092 const ObjCInterfaceType *) {
5096 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
5097 const ObjCObjectPointerType *) {
5101 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
5102 return Visit(T->getValueType());
5105 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
5109 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
5110 if (Tag->getDeclContext()->isFunctionOrMethod()) {
5111 S.Diag(SR.getBegin(),
5112 S.getLangOpts().CPlusPlus11 ?
5113 diag::warn_cxx98_compat_template_arg_local_type :
5114 diag::ext_template_arg_local_type)
5115 << S.Context.getTypeDeclType(Tag) << SR;
5119 if (!Tag->hasNameForLinkage()) {
5120 S.Diag(SR.getBegin(),
5121 S.getLangOpts().CPlusPlus11 ?
5122 diag::warn_cxx98_compat_template_arg_unnamed_type :
5123 diag::ext_template_arg_unnamed_type) << SR;
5124 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
5131 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
5132 NestedNameSpecifier *NNS) {
5133 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
5136 switch (NNS->getKind()) {
5137 case NestedNameSpecifier::Identifier:
5138 case NestedNameSpecifier::Namespace:
5139 case NestedNameSpecifier::NamespaceAlias:
5140 case NestedNameSpecifier::Global:
5141 case NestedNameSpecifier::Super:
5144 case NestedNameSpecifier::TypeSpec:
5145 case NestedNameSpecifier::TypeSpecWithTemplate:
5146 return Visit(QualType(NNS->getAsType(), 0));
5148 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
5151 /// \brief Check a template argument against its corresponding
5152 /// template type parameter.
5154 /// This routine implements the semantics of C++ [temp.arg.type]. It
5155 /// returns true if an error occurred, and false otherwise.
5156 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
5157 TypeSourceInfo *ArgInfo) {
5158 assert(ArgInfo && "invalid TypeSourceInfo");
5159 QualType Arg = ArgInfo->getType();
5160 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
5162 if (Arg->isVariablyModifiedType()) {
5163 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
5164 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
5165 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
5168 // C++03 [temp.arg.type]p2:
5169 // A local type, a type with no linkage, an unnamed type or a type
5170 // compounded from any of these types shall not be used as a
5171 // template-argument for a template type-parameter.
5173 // C++11 allows these, and even in C++03 we allow them as an extension with
5175 if (LangOpts.CPlusPlus11 || Arg->hasUnnamedOrLocalType()) {
5176 UnnamedLocalNoLinkageFinder Finder(*this, SR);
5177 (void)Finder.Visit(Context.getCanonicalType(Arg));
5183 enum NullPointerValueKind {
5189 /// \brief Determine whether the given template argument is a null pointer
5190 /// value of the appropriate type.
5191 static NullPointerValueKind
5192 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
5193 QualType ParamType, Expr *Arg) {
5194 if (Arg->isValueDependent() || Arg->isTypeDependent())
5195 return NPV_NotNullPointer;
5197 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))
5199 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
5201 if (!S.getLangOpts().CPlusPlus11)
5202 return NPV_NotNullPointer;
5204 // Determine whether we have a constant expression.
5205 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
5206 if (ArgRV.isInvalid())
5210 Expr::EvalResult EvalResult;
5211 SmallVector<PartialDiagnosticAt, 8> Notes;
5212 EvalResult.Diag = &Notes;
5213 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
5214 EvalResult.HasSideEffects) {
5215 SourceLocation DiagLoc = Arg->getExprLoc();
5217 // If our only note is the usual "invalid subexpression" note, just point
5218 // the caret at its location rather than producing an essentially
5220 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
5221 diag::note_invalid_subexpr_in_const_expr) {
5222 DiagLoc = Notes[0].first;
5226 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
5227 << Arg->getType() << Arg->getSourceRange();
5228 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
5229 S.Diag(Notes[I].first, Notes[I].second);
5231 S.Diag(Param->getLocation(), diag::note_template_param_here);
5235 // C++11 [temp.arg.nontype]p1:
5236 // - an address constant expression of type std::nullptr_t
5237 if (Arg->getType()->isNullPtrType())
5238 return NPV_NullPointer;
5240 // - a constant expression that evaluates to a null pointer value (4.10); or
5241 // - a constant expression that evaluates to a null member pointer value
5243 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
5244 (EvalResult.Val.isMemberPointer() &&
5245 !EvalResult.Val.getMemberPointerDecl())) {
5246 // If our expression has an appropriate type, we've succeeded.
5247 bool ObjCLifetimeConversion;
5248 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
5249 S.IsQualificationConversion(Arg->getType(), ParamType, false,
5250 ObjCLifetimeConversion))
5251 return NPV_NullPointer;
5253 // The types didn't match, but we know we got a null pointer; complain,
5254 // then recover as if the types were correct.
5255 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
5256 << Arg->getType() << ParamType << Arg->getSourceRange();
5257 S.Diag(Param->getLocation(), diag::note_template_param_here);
5258 return NPV_NullPointer;
5261 // If we don't have a null pointer value, but we do have a NULL pointer
5262 // constant, suggest a cast to the appropriate type.
5263 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
5264 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
5265 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
5266 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
5267 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
5269 S.Diag(Param->getLocation(), diag::note_template_param_here);
5270 return NPV_NullPointer;
5273 // FIXME: If we ever want to support general, address-constant expressions
5274 // as non-type template arguments, we should return the ExprResult here to
5275 // be interpreted by the caller.
5276 return NPV_NotNullPointer;
5279 /// \brief Checks whether the given template argument is compatible with its
5280 /// template parameter.
5281 static bool CheckTemplateArgumentIsCompatibleWithParameter(
5282 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
5283 Expr *Arg, QualType ArgType) {
5284 bool ObjCLifetimeConversion;
5285 if (ParamType->isPointerType() &&
5286 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
5287 S.IsQualificationConversion(ArgType, ParamType, false,
5288 ObjCLifetimeConversion)) {
5289 // For pointer-to-object types, qualification conversions are
5292 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
5293 if (!ParamRef->getPointeeType()->isFunctionType()) {
5294 // C++ [temp.arg.nontype]p5b3:
5295 // For a non-type template-parameter of type reference to
5296 // object, no conversions apply. The type referred to by the
5297 // reference may be more cv-qualified than the (otherwise
5298 // identical) type of the template- argument. The
5299 // template-parameter is bound directly to the
5300 // template-argument, which shall be an lvalue.
5302 // FIXME: Other qualifiers?
5303 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
5304 unsigned ArgQuals = ArgType.getCVRQualifiers();
5306 if ((ParamQuals | ArgQuals) != ParamQuals) {
5307 S.Diag(Arg->getLocStart(),
5308 diag::err_template_arg_ref_bind_ignores_quals)
5309 << ParamType << Arg->getType() << Arg->getSourceRange();
5310 S.Diag(Param->getLocation(), diag::note_template_param_here);
5316 // At this point, the template argument refers to an object or
5317 // function with external linkage. We now need to check whether the
5318 // argument and parameter types are compatible.
5319 if (!S.Context.hasSameUnqualifiedType(ArgType,
5320 ParamType.getNonReferenceType())) {
5321 // We can't perform this conversion or binding.
5322 if (ParamType->isReferenceType())
5323 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
5324 << ParamType << ArgIn->getType() << Arg->getSourceRange();
5326 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5327 << ArgIn->getType() << ParamType << Arg->getSourceRange();
5328 S.Diag(Param->getLocation(), diag::note_template_param_here);
5336 /// \brief Checks whether the given template argument is the address
5337 /// of an object or function according to C++ [temp.arg.nontype]p1.
5339 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
5340 NonTypeTemplateParmDecl *Param,
5343 TemplateArgument &Converted) {
5344 bool Invalid = false;
5346 QualType ArgType = Arg->getType();
5348 bool AddressTaken = false;
5349 SourceLocation AddrOpLoc;
5350 if (S.getLangOpts().MicrosoftExt) {
5351 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
5352 // dereference and address-of operators.
5353 Arg = Arg->IgnoreParenCasts();
5355 bool ExtWarnMSTemplateArg = false;
5356 UnaryOperatorKind FirstOpKind;
5357 SourceLocation FirstOpLoc;
5358 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5359 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
5360 if (UnOpKind == UO_Deref)
5361 ExtWarnMSTemplateArg = true;
5362 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
5363 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
5364 if (!AddrOpLoc.isValid()) {
5365 FirstOpKind = UnOpKind;
5366 FirstOpLoc = UnOp->getOperatorLoc();
5371 if (FirstOpLoc.isValid()) {
5372 if (ExtWarnMSTemplateArg)
5373 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
5374 << ArgIn->getSourceRange();
5376 if (FirstOpKind == UO_AddrOf)
5377 AddressTaken = true;
5378 else if (Arg->getType()->isPointerType()) {
5379 // We cannot let pointers get dereferenced here, that is obviously not a
5380 // constant expression.
5381 assert(FirstOpKind == UO_Deref);
5382 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5383 << Arg->getSourceRange();
5387 // See through any implicit casts we added to fix the type.
5388 Arg = Arg->IgnoreImpCasts();
5390 // C++ [temp.arg.nontype]p1:
5392 // A template-argument for a non-type, non-template
5393 // template-parameter shall be one of: [...]
5395 // -- the address of an object or function with external
5396 // linkage, including function templates and function
5397 // template-ids but excluding non-static class members,
5398 // expressed as & id-expression where the & is optional if
5399 // the name refers to a function or array, or if the
5400 // corresponding template-parameter is a reference; or
5402 // In C++98/03 mode, give an extension warning on any extra parentheses.
5403 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5404 bool ExtraParens = false;
5405 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5406 if (!Invalid && !ExtraParens) {
5407 S.Diag(Arg->getLocStart(),
5408 S.getLangOpts().CPlusPlus11
5409 ? diag::warn_cxx98_compat_template_arg_extra_parens
5410 : diag::ext_template_arg_extra_parens)
5411 << Arg->getSourceRange();
5415 Arg = Parens->getSubExpr();
5418 while (SubstNonTypeTemplateParmExpr *subst =
5419 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5420 Arg = subst->getReplacement()->IgnoreImpCasts();
5422 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5423 if (UnOp->getOpcode() == UO_AddrOf) {
5424 Arg = UnOp->getSubExpr();
5425 AddressTaken = true;
5426 AddrOpLoc = UnOp->getOperatorLoc();
5430 while (SubstNonTypeTemplateParmExpr *subst =
5431 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5432 Arg = subst->getReplacement()->IgnoreImpCasts();
5435 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
5436 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
5438 // If our parameter has pointer type, check for a null template value.
5439 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
5440 NullPointerValueKind NPV;
5441 // dllimport'd entities aren't constant but are available inside of template
5443 if (Entity && Entity->hasAttr<DLLImportAttr>())
5444 NPV = NPV_NotNullPointer;
5446 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
5448 case NPV_NullPointer:
5449 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5450 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5451 /*isNullPtr=*/true);
5457 case NPV_NotNullPointer:
5462 // Stop checking the precise nature of the argument if it is value dependent,
5463 // it should be checked when instantiated.
5464 if (Arg->isValueDependent()) {
5465 Converted = TemplateArgument(ArgIn);
5469 if (isa<CXXUuidofExpr>(Arg)) {
5470 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
5471 ArgIn, Arg, ArgType))
5474 Converted = TemplateArgument(ArgIn);
5479 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5480 << Arg->getSourceRange();
5481 S.Diag(Param->getLocation(), diag::note_template_param_here);
5485 // Cannot refer to non-static data members
5486 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
5487 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
5488 << Entity << Arg->getSourceRange();
5489 S.Diag(Param->getLocation(), diag::note_template_param_here);
5493 // Cannot refer to non-static member functions
5494 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
5495 if (!Method->isStatic()) {
5496 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
5497 << Method << Arg->getSourceRange();
5498 S.Diag(Param->getLocation(), diag::note_template_param_here);
5503 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
5504 VarDecl *Var = dyn_cast<VarDecl>(Entity);
5506 // A non-type template argument must refer to an object or function.
5507 if (!Func && !Var) {
5508 // We found something, but we don't know specifically what it is.
5509 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
5510 << Arg->getSourceRange();
5511 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5515 // Address / reference template args must have external linkage in C++98.
5516 if (Entity->getFormalLinkage() == InternalLinkage) {
5517 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
5518 diag::warn_cxx98_compat_template_arg_object_internal :
5519 diag::ext_template_arg_object_internal)
5520 << !Func << Entity << Arg->getSourceRange();
5521 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5523 } else if (!Entity->hasLinkage()) {
5524 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
5525 << !Func << Entity << Arg->getSourceRange();
5526 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
5532 // If the template parameter has pointer type, the function decays.
5533 if (ParamType->isPointerType() && !AddressTaken)
5534 ArgType = S.Context.getPointerType(Func->getType());
5535 else if (AddressTaken && ParamType->isReferenceType()) {
5536 // If we originally had an address-of operator, but the
5537 // parameter has reference type, complain and (if things look
5538 // like they will work) drop the address-of operator.
5539 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
5540 ParamType.getNonReferenceType())) {
5541 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5543 S.Diag(Param->getLocation(), diag::note_template_param_here);
5547 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5549 << FixItHint::CreateRemoval(AddrOpLoc);
5550 S.Diag(Param->getLocation(), diag::note_template_param_here);
5552 ArgType = Func->getType();
5555 // A value of reference type is not an object.
5556 if (Var->getType()->isReferenceType()) {
5557 S.Diag(Arg->getLocStart(),
5558 diag::err_template_arg_reference_var)
5559 << Var->getType() << Arg->getSourceRange();
5560 S.Diag(Param->getLocation(), diag::note_template_param_here);
5564 // A template argument must have static storage duration.
5565 if (Var->getTLSKind()) {
5566 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
5567 << Arg->getSourceRange();
5568 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
5572 // If the template parameter has pointer type, we must have taken
5573 // the address of this object.
5574 if (ParamType->isReferenceType()) {
5576 // If we originally had an address-of operator, but the
5577 // parameter has reference type, complain and (if things look
5578 // like they will work) drop the address-of operator.
5579 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
5580 ParamType.getNonReferenceType())) {
5581 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5583 S.Diag(Param->getLocation(), diag::note_template_param_here);
5587 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
5589 << FixItHint::CreateRemoval(AddrOpLoc);
5590 S.Diag(Param->getLocation(), diag::note_template_param_here);
5592 ArgType = Var->getType();
5594 } else if (!AddressTaken && ParamType->isPointerType()) {
5595 if (Var->getType()->isArrayType()) {
5596 // Array-to-pointer decay.
5597 ArgType = S.Context.getArrayDecayedType(Var->getType());
5599 // If the template parameter has pointer type but the address of
5600 // this object was not taken, complain and (possibly) recover by
5601 // taking the address of the entity.
5602 ArgType = S.Context.getPointerType(Var->getType());
5603 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
5604 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5606 S.Diag(Param->getLocation(), diag::note_template_param_here);
5610 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
5612 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
5614 S.Diag(Param->getLocation(), diag::note_template_param_here);
5619 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
5623 // Create the template argument.
5625 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
5626 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
5630 /// \brief Checks whether the given template argument is a pointer to
5631 /// member constant according to C++ [temp.arg.nontype]p1.
5632 static bool CheckTemplateArgumentPointerToMember(Sema &S,
5633 NonTypeTemplateParmDecl *Param,
5636 TemplateArgument &Converted) {
5637 bool Invalid = false;
5639 // Check for a null pointer value.
5640 Expr *Arg = ResultArg;
5641 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
5644 case NPV_NullPointer:
5645 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5646 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
5649 case NPV_NotNullPointer:
5653 bool ObjCLifetimeConversion;
5654 if (S.IsQualificationConversion(Arg->getType(),
5655 ParamType.getNonReferenceType(),
5656 false, ObjCLifetimeConversion)) {
5657 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
5658 Arg->getValueKind()).get();
5660 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
5661 ParamType.getNonReferenceType())) {
5662 // We can't perform this conversion.
5663 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
5664 << Arg->getType() << ParamType << Arg->getSourceRange();
5665 S.Diag(Param->getLocation(), diag::note_template_param_here);
5669 // See through any implicit casts we added to fix the type.
5670 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
5671 Arg = Cast->getSubExpr();
5673 // C++ [temp.arg.nontype]p1:
5675 // A template-argument for a non-type, non-template
5676 // template-parameter shall be one of: [...]
5678 // -- a pointer to member expressed as described in 5.3.1.
5679 DeclRefExpr *DRE = nullptr;
5681 // In C++98/03 mode, give an extension warning on any extra parentheses.
5682 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
5683 bool ExtraParens = false;
5684 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
5685 if (!Invalid && !ExtraParens) {
5686 S.Diag(Arg->getLocStart(),
5687 S.getLangOpts().CPlusPlus11 ?
5688 diag::warn_cxx98_compat_template_arg_extra_parens :
5689 diag::ext_template_arg_extra_parens)
5690 << Arg->getSourceRange();
5694 Arg = Parens->getSubExpr();
5697 while (SubstNonTypeTemplateParmExpr *subst =
5698 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
5699 Arg = subst->getReplacement()->IgnoreImpCasts();
5701 // A pointer-to-member constant written &Class::member.
5702 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
5703 if (UnOp->getOpcode() == UO_AddrOf) {
5704 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
5705 if (DRE && !DRE->getQualifier())
5709 // A constant of pointer-to-member type.
5710 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
5711 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
5712 if (VD->getType()->isMemberPointerType()) {
5713 if (isa<NonTypeTemplateParmDecl>(VD)) {
5714 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5715 Converted = TemplateArgument(Arg);
5717 VD = cast<ValueDecl>(VD->getCanonicalDecl());
5718 Converted = TemplateArgument(VD, ParamType);
5729 return S.Diag(Arg->getLocStart(),
5730 diag::err_template_arg_not_pointer_to_member_form)
5731 << Arg->getSourceRange();
5733 if (isa<FieldDecl>(DRE->getDecl()) ||
5734 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5735 isa<CXXMethodDecl>(DRE->getDecl())) {
5736 assert((isa<FieldDecl>(DRE->getDecl()) ||
5737 isa<IndirectFieldDecl>(DRE->getDecl()) ||
5738 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
5739 "Only non-static member pointers can make it here");
5741 // Okay: this is the address of a non-static member, and therefore
5742 // a member pointer constant.
5743 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5744 Converted = TemplateArgument(Arg);
5746 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
5747 Converted = TemplateArgument(D, ParamType);
5752 // We found something else, but we don't know specifically what it is.
5753 S.Diag(Arg->getLocStart(),
5754 diag::err_template_arg_not_pointer_to_member_form)
5755 << Arg->getSourceRange();
5756 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
5760 /// \brief Check a template argument against its corresponding
5761 /// non-type template parameter.
5763 /// This routine implements the semantics of C++ [temp.arg.nontype].
5764 /// If an error occurred, it returns ExprError(); otherwise, it
5765 /// returns the converted template argument. \p ParamType is the
5766 /// type of the non-type template parameter after it has been instantiated.
5767 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
5768 QualType ParamType, Expr *Arg,
5769 TemplateArgument &Converted,
5770 CheckTemplateArgumentKind CTAK) {
5771 SourceLocation StartLoc = Arg->getLocStart();
5773 // If the parameter type somehow involves auto, deduce the type now.
5774 if (getLangOpts().CPlusPlus1z && ParamType->isUndeducedType()) {
5775 // During template argument deduction, we allow 'decltype(auto)' to
5776 // match an arbitrary dependent argument.
5777 // FIXME: The language rules don't say what happens in this case.
5778 // FIXME: We get an opaque dependent type out of decltype(auto) if the
5779 // expression is merely instantiation-dependent; is this enough?
5780 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
5781 auto *AT = dyn_cast<AutoType>(ParamType);
5782 if (AT && AT->isDecltypeAuto()) {
5783 Converted = TemplateArgument(Arg);
5788 // When checking a deduced template argument, deduce from its type even if
5789 // the type is dependent, in order to check the types of non-type template
5790 // arguments line up properly in partial ordering.
5791 Optional<unsigned> Depth;
5792 if (CTAK != CTAK_Specified)
5793 Depth = Param->getDepth() + 1;
5795 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()),
5796 Arg, ParamType, Depth) == DAR_Failed) {
5797 Diag(Arg->getExprLoc(),
5798 diag::err_non_type_template_parm_type_deduction_failure)
5799 << Param->getDeclName() << Param->getType() << Arg->getType()
5800 << Arg->getSourceRange();
5801 Diag(Param->getLocation(), diag::note_template_param_here);
5804 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
5805 // an error. The error message normally references the parameter
5806 // declaration, but here we'll pass the argument location because that's
5807 // where the parameter type is deduced.
5808 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());
5809 if (ParamType.isNull()) {
5810 Diag(Param->getLocation(), diag::note_template_param_here);
5815 // We should have already dropped all cv-qualifiers by now.
5816 assert(!ParamType.hasQualifiers() &&
5817 "non-type template parameter type cannot be qualified");
5819 if (CTAK == CTAK_Deduced &&
5820 !Context.hasSameType(ParamType.getNonLValueExprType(Context),
5822 // FIXME: If either type is dependent, we skip the check. This isn't
5823 // correct, since during deduction we're supposed to have replaced each
5824 // template parameter with some unique (non-dependent) placeholder.
5825 // FIXME: If the argument type contains 'auto', we carry on and fail the
5826 // type check in order to force specific types to be more specialized than
5827 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
5829 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
5830 !Arg->getType()->getContainedAutoType()) {
5831 Converted = TemplateArgument(Arg);
5834 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
5835 // we should actually be checking the type of the template argument in P,
5836 // not the type of the template argument deduced from A, against the
5837 // template parameter type.
5838 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
5840 << ParamType.getUnqualifiedType();
5841 Diag(Param->getLocation(), diag::note_template_param_here);
5845 // If either the parameter has a dependent type or the argument is
5846 // type-dependent, there's nothing we can check now.
5847 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
5848 // FIXME: Produce a cloned, canonical expression?
5849 Converted = TemplateArgument(Arg);
5853 // The initialization of the parameter from the argument is
5854 // a constant-evaluated context.
5855 EnterExpressionEvaluationContext ConstantEvaluated(
5856 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5858 if (getLangOpts().CPlusPlus1z) {
5859 // C++1z [temp.arg.nontype]p1:
5860 // A template-argument for a non-type template parameter shall be
5861 // a converted constant expression of the type of the template-parameter.
5863 ExprResult ArgResult = CheckConvertedConstantExpression(
5864 Arg, ParamType, Value, CCEK_TemplateArg);
5865 if (ArgResult.isInvalid())
5868 // For a value-dependent argument, CheckConvertedConstantExpression is
5869 // permitted (and expected) to be unable to determine a value.
5870 if (ArgResult.get()->isValueDependent()) {
5871 Converted = TemplateArgument(ArgResult.get());
5875 QualType CanonParamType = Context.getCanonicalType(ParamType);
5877 // Convert the APValue to a TemplateArgument.
5878 switch (Value.getKind()) {
5879 case APValue::Uninitialized:
5880 assert(ParamType->isNullPtrType());
5881 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
5884 assert(ParamType->isIntegralOrEnumerationType());
5885 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
5887 case APValue::MemberPointer: {
5888 assert(ParamType->isMemberPointerType());
5890 // FIXME: We need TemplateArgument representation and mangling for these.
5891 if (!Value.getMemberPointerPath().empty()) {
5892 Diag(Arg->getLocStart(),
5893 diag::err_template_arg_member_ptr_base_derived_not_supported)
5894 << Value.getMemberPointerDecl() << ParamType
5895 << Arg->getSourceRange();
5899 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
5900 Converted = VD ? TemplateArgument(VD, CanonParamType)
5901 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
5904 case APValue::LValue: {
5905 // For a non-type template-parameter of pointer or reference type,
5906 // the value of the constant expression shall not refer to
5907 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
5908 ParamType->isNullPtrType());
5909 // -- a temporary object
5910 // -- a string literal
5911 // -- the result of a typeid expression, or
5912 // -- a predefined __func__ variable
5913 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
5914 if (isa<CXXUuidofExpr>(E)) {
5915 Converted = TemplateArgument(const_cast<Expr*>(E));
5918 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
5919 << Arg->getSourceRange();
5922 auto *VD = const_cast<ValueDecl *>(
5923 Value.getLValueBase().dyn_cast<const ValueDecl *>());
5925 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
5926 VD && VD->getType()->isArrayType() &&
5927 Value.getLValuePath()[0].ArrayIndex == 0 &&
5928 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
5929 // Per defect report (no number yet):
5930 // ... other than a pointer to the first element of a complete array
5932 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
5933 Value.isLValueOnePastTheEnd()) {
5934 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
5935 << Value.getAsString(Context, ParamType);
5938 assert((VD || !ParamType->isReferenceType()) &&
5939 "null reference should not be a constant expression");
5940 assert((!VD || !ParamType->isNullPtrType()) &&
5941 "non-null value of type nullptr_t?");
5942 Converted = VD ? TemplateArgument(VD, CanonParamType)
5943 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
5946 case APValue::AddrLabelDiff:
5947 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
5948 case APValue::Float:
5949 case APValue::ComplexInt:
5950 case APValue::ComplexFloat:
5951 case APValue::Vector:
5952 case APValue::Array:
5953 case APValue::Struct:
5954 case APValue::Union:
5955 llvm_unreachable("invalid kind for template argument");
5958 return ArgResult.get();
5961 // C++ [temp.arg.nontype]p5:
5962 // The following conversions are performed on each expression used
5963 // as a non-type template-argument. If a non-type
5964 // template-argument cannot be converted to the type of the
5965 // corresponding template-parameter then the program is
5967 if (ParamType->isIntegralOrEnumerationType()) {
5969 // -- for a non-type template-parameter of integral or
5970 // enumeration type, conversions permitted in a converted
5971 // constant expression are applied.
5974 // -- for a non-type template-parameter of integral or
5975 // enumeration type, integral promotions (4.5) and integral
5976 // conversions (4.7) are applied.
5978 if (getLangOpts().CPlusPlus11) {
5979 // C++ [temp.arg.nontype]p1:
5980 // A template-argument for a non-type, non-template template-parameter
5983 // -- for a non-type template-parameter of integral or enumeration
5984 // type, a converted constant expression of the type of the
5985 // template-parameter; or
5987 ExprResult ArgResult =
5988 CheckConvertedConstantExpression(Arg, ParamType, Value,
5990 if (ArgResult.isInvalid())
5993 // We can't check arbitrary value-dependent arguments.
5994 if (ArgResult.get()->isValueDependent()) {
5995 Converted = TemplateArgument(ArgResult.get());
5999 // Widen the argument value to sizeof(parameter type). This is almost
6000 // always a no-op, except when the parameter type is bool. In
6001 // that case, this may extend the argument from 1 bit to 8 bits.
6002 QualType IntegerType = ParamType;
6003 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6004 IntegerType = Enum->getDecl()->getIntegerType();
6005 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
6007 Converted = TemplateArgument(Context, Value,
6008 Context.getCanonicalType(ParamType));
6012 ExprResult ArgResult = DefaultLvalueConversion(Arg);
6013 if (ArgResult.isInvalid())
6015 Arg = ArgResult.get();
6017 QualType ArgType = Arg->getType();
6019 // C++ [temp.arg.nontype]p1:
6020 // A template-argument for a non-type, non-template
6021 // template-parameter shall be one of:
6023 // -- an integral constant-expression of integral or enumeration
6025 // -- the name of a non-type template-parameter; or
6026 SourceLocation NonConstantLoc;
6028 if (!ArgType->isIntegralOrEnumerationType()) {
6029 Diag(Arg->getLocStart(),
6030 diag::err_template_arg_not_integral_or_enumeral)
6031 << ArgType << Arg->getSourceRange();
6032 Diag(Param->getLocation(), diag::note_template_param_here);
6034 } else if (!Arg->isValueDependent()) {
6035 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
6039 TmplArgICEDiagnoser(QualType T) : T(T) { }
6041 void diagnoseNotICE(Sema &S, SourceLocation Loc,
6042 SourceRange SR) override {
6043 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
6045 } Diagnoser(ArgType);
6047 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
6053 // From here on out, all we care about is the unqualified form
6054 // of the argument type.
6055 ArgType = ArgType.getUnqualifiedType();
6057 // Try to convert the argument to the parameter's type.
6058 if (Context.hasSameType(ParamType, ArgType)) {
6059 // Okay: no conversion necessary
6060 } else if (ParamType->isBooleanType()) {
6061 // This is an integral-to-boolean conversion.
6062 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
6063 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
6064 !ParamType->isEnumeralType()) {
6065 // This is an integral promotion or conversion.
6066 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
6068 // We can't perform this conversion.
6069 Diag(Arg->getLocStart(),
6070 diag::err_template_arg_not_convertible)
6071 << Arg->getType() << ParamType << Arg->getSourceRange();
6072 Diag(Param->getLocation(), diag::note_template_param_here);
6076 // Add the value of this argument to the list of converted
6077 // arguments. We use the bitwidth and signedness of the template
6079 if (Arg->isValueDependent()) {
6080 // The argument is value-dependent. Create a new
6081 // TemplateArgument with the converted expression.
6082 Converted = TemplateArgument(Arg);
6086 QualType IntegerType = Context.getCanonicalType(ParamType);
6087 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
6088 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
6090 if (ParamType->isBooleanType()) {
6091 // Value must be zero or one.
6093 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6094 if (Value.getBitWidth() != AllowedBits)
6095 Value = Value.extOrTrunc(AllowedBits);
6096 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6098 llvm::APSInt OldValue = Value;
6100 // Coerce the template argument's value to the value it will have
6101 // based on the template parameter's type.
6102 unsigned AllowedBits = Context.getTypeSize(IntegerType);
6103 if (Value.getBitWidth() != AllowedBits)
6104 Value = Value.extOrTrunc(AllowedBits);
6105 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
6107 // Complain if an unsigned parameter received a negative value.
6108 if (IntegerType->isUnsignedIntegerOrEnumerationType()
6109 && (OldValue.isSigned() && OldValue.isNegative())) {
6110 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
6111 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6112 << Arg->getSourceRange();
6113 Diag(Param->getLocation(), diag::note_template_param_here);
6116 // Complain if we overflowed the template parameter's type.
6117 unsigned RequiredBits;
6118 if (IntegerType->isUnsignedIntegerOrEnumerationType())
6119 RequiredBits = OldValue.getActiveBits();
6120 else if (OldValue.isUnsigned())
6121 RequiredBits = OldValue.getActiveBits() + 1;
6123 RequiredBits = OldValue.getMinSignedBits();
6124 if (RequiredBits > AllowedBits) {
6125 Diag(Arg->getLocStart(),
6126 diag::warn_template_arg_too_large)
6127 << OldValue.toString(10) << Value.toString(10) << Param->getType()
6128 << Arg->getSourceRange();
6129 Diag(Param->getLocation(), diag::note_template_param_here);
6133 Converted = TemplateArgument(Context, Value,
6134 ParamType->isEnumeralType()
6135 ? Context.getCanonicalType(ParamType)
6140 QualType ArgType = Arg->getType();
6141 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
6143 // Handle pointer-to-function, reference-to-function, and
6144 // pointer-to-member-function all in (roughly) the same way.
6145 if (// -- For a non-type template-parameter of type pointer to
6146 // function, only the function-to-pointer conversion (4.3) is
6147 // applied. If the template-argument represents a set of
6148 // overloaded functions (or a pointer to such), the matching
6149 // function is selected from the set (13.4).
6150 (ParamType->isPointerType() &&
6151 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
6152 // -- For a non-type template-parameter of type reference to
6153 // function, no conversions apply. If the template-argument
6154 // represents a set of overloaded functions, the matching
6155 // function is selected from the set (13.4).
6156 (ParamType->isReferenceType() &&
6157 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
6158 // -- For a non-type template-parameter of type pointer to
6159 // member function, no conversions apply. If the
6160 // template-argument represents a set of overloaded member
6161 // functions, the matching member function is selected from
6163 (ParamType->isMemberPointerType() &&
6164 ParamType->getAs<MemberPointerType>()->getPointeeType()
6165 ->isFunctionType())) {
6167 if (Arg->getType() == Context.OverloadTy) {
6168 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
6171 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6174 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6175 ArgType = Arg->getType();
6180 if (!ParamType->isMemberPointerType()) {
6181 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6188 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6194 if (ParamType->isPointerType()) {
6195 // -- for a non-type template-parameter of type pointer to
6196 // object, qualification conversions (4.4) and the
6197 // array-to-pointer conversion (4.2) are applied.
6198 // C++0x also allows a value of std::nullptr_t.
6199 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
6200 "Only object pointers allowed here");
6202 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6209 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
6210 // -- For a non-type template-parameter of type reference to
6211 // object, no conversions apply. The type referred to by the
6212 // reference may be more cv-qualified than the (otherwise
6213 // identical) type of the template-argument. The
6214 // template-parameter is bound directly to the
6215 // template-argument, which must be an lvalue.
6216 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
6217 "Only object references allowed here");
6219 if (Arg->getType() == Context.OverloadTy) {
6220 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
6221 ParamRefType->getPointeeType(),
6224 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
6227 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
6228 ArgType = Arg->getType();
6233 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
6240 // Deal with parameters of type std::nullptr_t.
6241 if (ParamType->isNullPtrType()) {
6242 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6243 Converted = TemplateArgument(Arg);
6247 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
6248 case NPV_NotNullPointer:
6249 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
6250 << Arg->getType() << ParamType;
6251 Diag(Param->getLocation(), diag::note_template_param_here);
6257 case NPV_NullPointer:
6258 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
6259 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
6265 // -- For a non-type template-parameter of type pointer to data
6266 // member, qualification conversions (4.4) are applied.
6267 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
6269 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
6275 static void DiagnoseTemplateParameterListArityMismatch(
6276 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
6277 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
6279 /// \brief Check a template argument against its corresponding
6280 /// template template parameter.
6282 /// This routine implements the semantics of C++ [temp.arg.template].
6283 /// It returns true if an error occurred, and false otherwise.
6284 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
6285 TemplateArgumentLoc &Arg,
6286 unsigned ArgumentPackIndex) {
6287 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
6288 TemplateDecl *Template = Name.getAsTemplateDecl();
6290 // Any dependent template name is fine.
6291 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
6295 if (Template->isInvalidDecl())
6298 // C++0x [temp.arg.template]p1:
6299 // A template-argument for a template template-parameter shall be
6300 // the name of a class template or an alias template, expressed as an
6301 // id-expression. When the template-argument names a class template, only
6302 // primary class templates are considered when matching the
6303 // template template argument with the corresponding parameter;
6304 // partial specializations are not considered even if their
6305 // parameter lists match that of the template template parameter.
6307 // Note that we also allow template template parameters here, which
6308 // will happen when we are dealing with, e.g., class template
6309 // partial specializations.
6310 if (!isa<ClassTemplateDecl>(Template) &&
6311 !isa<TemplateTemplateParmDecl>(Template) &&
6312 !isa<TypeAliasTemplateDecl>(Template) &&
6313 !isa<BuiltinTemplateDecl>(Template)) {
6314 assert(isa<FunctionTemplateDecl>(Template) &&
6315 "Only function templates are possible here");
6316 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
6317 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
6321 TemplateParameterList *Params = Param->getTemplateParameters();
6322 if (Param->isExpandedParameterPack())
6323 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
6325 // C++1z [temp.arg.template]p3: (DR 150)
6326 // A template-argument matches a template template-parameter P when P
6327 // is at least as specialized as the template-argument A.
6328 if (getLangOpts().RelaxedTemplateTemplateArgs) {
6329 // Quick check for the common case:
6330 // If P contains a parameter pack, then A [...] matches P if each of A's
6331 // template parameters matches the corresponding template parameter in
6332 // the template-parameter-list of P.
6333 if (TemplateParameterListsAreEqual(
6334 Template->getTemplateParameters(), Params, false,
6335 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()))
6338 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template,
6341 // FIXME: Produce better diagnostics for deduction failures.
6344 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
6347 TPL_TemplateTemplateArgumentMatch,
6351 /// \brief Given a non-type template argument that refers to a
6352 /// declaration and the type of its corresponding non-type template
6353 /// parameter, produce an expression that properly refers to that
6356 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
6358 SourceLocation Loc) {
6359 // C++ [temp.param]p8:
6361 // A non-type template-parameter of type "array of T" or
6362 // "function returning T" is adjusted to be of type "pointer to
6363 // T" or "pointer to function returning T", respectively.
6364 if (ParamType->isArrayType())
6365 ParamType = Context.getArrayDecayedType(ParamType);
6366 else if (ParamType->isFunctionType())
6367 ParamType = Context.getPointerType(ParamType);
6369 // For a NULL non-type template argument, return nullptr casted to the
6370 // parameter's type.
6371 if (Arg.getKind() == TemplateArgument::NullPtr) {
6372 return ImpCastExprToType(
6373 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
6375 ParamType->getAs<MemberPointerType>()
6376 ? CK_NullToMemberPointer
6377 : CK_NullToPointer);
6379 assert(Arg.getKind() == TemplateArgument::Declaration &&
6380 "Only declaration template arguments permitted here");
6382 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
6384 if (VD->getDeclContext()->isRecord() &&
6385 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
6386 isa<IndirectFieldDecl>(VD))) {
6387 // If the value is a class member, we might have a pointer-to-member.
6388 // Determine whether the non-type template template parameter is of
6389 // pointer-to-member type. If so, we need to build an appropriate
6390 // expression for a pointer-to-member, since a "normal" DeclRefExpr
6391 // would refer to the member itself.
6392 if (ParamType->isMemberPointerType()) {
6394 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
6395 NestedNameSpecifier *Qualifier
6396 = NestedNameSpecifier::Create(Context, nullptr, false,
6397 ClassType.getTypePtr());
6399 SS.MakeTrivial(Context, Qualifier, Loc);
6401 // The actual value-ness of this is unimportant, but for
6402 // internal consistency's sake, references to instance methods
6404 ExprValueKind VK = VK_LValue;
6405 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
6408 ExprResult RefExpr = BuildDeclRefExpr(VD,
6409 VD->getType().getNonReferenceType(),
6413 if (RefExpr.isInvalid())
6416 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6418 // We might need to perform a trailing qualification conversion, since
6419 // the element type on the parameter could be more qualified than the
6420 // element type in the expression we constructed.
6421 bool ObjCLifetimeConversion;
6422 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
6423 ParamType.getUnqualifiedType(), false,
6424 ObjCLifetimeConversion))
6425 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
6427 assert(!RefExpr.isInvalid() &&
6428 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
6429 ParamType.getUnqualifiedType()));
6434 QualType T = VD->getType().getNonReferenceType();
6436 if (ParamType->isPointerType()) {
6437 // When the non-type template parameter is a pointer, take the
6438 // address of the declaration.
6439 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
6440 if (RefExpr.isInvalid())
6443 if (!Context.hasSameUnqualifiedType(ParamType->getPointeeType(), T) &&
6444 (T->isFunctionType() || T->isArrayType())) {
6445 // Decay functions and arrays unless we're forming a pointer to array.
6446 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
6447 if (RefExpr.isInvalid())
6453 // Take the address of everything else
6454 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
6457 ExprValueKind VK = VK_RValue;
6459 // If the non-type template parameter has reference type, qualify the
6460 // resulting declaration reference with the extra qualifiers on the
6461 // type that the reference refers to.
6462 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
6464 T = Context.getQualifiedType(T,
6465 TargetRef->getPointeeType().getQualifiers());
6466 } else if (isa<FunctionDecl>(VD)) {
6467 // References to functions are always lvalues.
6471 return BuildDeclRefExpr(VD, T, VK, Loc);
6474 /// \brief Construct a new expression that refers to the given
6475 /// integral template argument with the given source-location
6478 /// This routine takes care of the mapping from an integral template
6479 /// argument (which may have any integral type) to the appropriate
6482 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
6483 SourceLocation Loc) {
6484 assert(Arg.getKind() == TemplateArgument::Integral &&
6485 "Operation is only valid for integral template arguments");
6486 QualType OrigT = Arg.getIntegralType();
6488 // If this is an enum type that we're instantiating, we need to use an integer
6489 // type the same size as the enumerator. We don't want to build an
6490 // IntegerLiteral with enum type. The integer type of an enum type can be of
6491 // any integral type with C++11 enum classes, make sure we create the right
6492 // type of literal for it.
6494 if (const EnumType *ET = OrigT->getAs<EnumType>())
6495 T = ET->getDecl()->getIntegerType();
6498 if (T->isAnyCharacterType()) {
6499 // This does not need to handle u8 character literals because those are
6500 // of type char, and so can also be covered by an ASCII character literal.
6501 CharacterLiteral::CharacterKind Kind;
6502 if (T->isWideCharType())
6503 Kind = CharacterLiteral::Wide;
6504 else if (T->isChar16Type())
6505 Kind = CharacterLiteral::UTF16;
6506 else if (T->isChar32Type())
6507 Kind = CharacterLiteral::UTF32;
6509 Kind = CharacterLiteral::Ascii;
6511 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
6513 } else if (T->isBooleanType()) {
6514 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
6516 } else if (T->isNullPtrType()) {
6517 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
6519 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
6522 if (OrigT->isEnumeralType()) {
6523 // FIXME: This is a hack. We need a better way to handle substituted
6524 // non-type template parameters.
6525 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
6527 Context.getTrivialTypeSourceInfo(OrigT, Loc),
6534 /// \brief Match two template parameters within template parameter lists.
6535 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
6537 Sema::TemplateParameterListEqualKind Kind,
6538 SourceLocation TemplateArgLoc) {
6539 // Check the actual kind (type, non-type, template).
6540 if (Old->getKind() != New->getKind()) {
6542 unsigned NextDiag = diag::err_template_param_different_kind;
6543 if (TemplateArgLoc.isValid()) {
6544 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6545 NextDiag = diag::note_template_param_different_kind;
6547 S.Diag(New->getLocation(), NextDiag)
6548 << (Kind != Sema::TPL_TemplateMatch);
6549 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
6550 << (Kind != Sema::TPL_TemplateMatch);
6556 // Check that both are parameter packs or neither are parameter packs.
6557 // However, if we are matching a template template argument to a
6558 // template template parameter, the template template parameter can have
6559 // a parameter pack where the template template argument does not.
6560 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
6561 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6562 Old->isTemplateParameterPack())) {
6564 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
6565 if (TemplateArgLoc.isValid()) {
6566 S.Diag(TemplateArgLoc,
6567 diag::err_template_arg_template_params_mismatch);
6568 NextDiag = diag::note_template_parameter_pack_non_pack;
6571 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
6572 : isa<NonTypeTemplateParmDecl>(New)? 1
6574 S.Diag(New->getLocation(), NextDiag)
6575 << ParamKind << New->isParameterPack();
6576 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
6577 << ParamKind << Old->isParameterPack();
6583 // For non-type template parameters, check the type of the parameter.
6584 if (NonTypeTemplateParmDecl *OldNTTP
6585 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
6586 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
6588 // If we are matching a template template argument to a template
6589 // template parameter and one of the non-type template parameter types
6590 // is dependent, then we must wait until template instantiation time
6591 // to actually compare the arguments.
6592 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
6593 (OldNTTP->getType()->isDependentType() ||
6594 NewNTTP->getType()->isDependentType()))
6597 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
6599 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
6600 if (TemplateArgLoc.isValid()) {
6601 S.Diag(TemplateArgLoc,
6602 diag::err_template_arg_template_params_mismatch);
6603 NextDiag = diag::note_template_nontype_parm_different_type;
6605 S.Diag(NewNTTP->getLocation(), NextDiag)
6606 << NewNTTP->getType()
6607 << (Kind != Sema::TPL_TemplateMatch);
6608 S.Diag(OldNTTP->getLocation(),
6609 diag::note_template_nontype_parm_prev_declaration)
6610 << OldNTTP->getType();
6619 // For template template parameters, check the template parameter types.
6620 // The template parameter lists of template template
6621 // parameters must agree.
6622 if (TemplateTemplateParmDecl *OldTTP
6623 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
6624 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
6625 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
6626 OldTTP->getTemplateParameters(),
6628 (Kind == Sema::TPL_TemplateMatch
6629 ? Sema::TPL_TemplateTemplateParmMatch
6637 /// \brief Diagnose a known arity mismatch when comparing template argument
6640 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
6641 TemplateParameterList *New,
6642 TemplateParameterList *Old,
6643 Sema::TemplateParameterListEqualKind Kind,
6644 SourceLocation TemplateArgLoc) {
6645 unsigned NextDiag = diag::err_template_param_list_different_arity;
6646 if (TemplateArgLoc.isValid()) {
6647 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
6648 NextDiag = diag::note_template_param_list_different_arity;
6650 S.Diag(New->getTemplateLoc(), NextDiag)
6651 << (New->size() > Old->size())
6652 << (Kind != Sema::TPL_TemplateMatch)
6653 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
6654 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
6655 << (Kind != Sema::TPL_TemplateMatch)
6656 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
6659 /// \brief Determine whether the given template parameter lists are
6662 /// \param New The new template parameter list, typically written in the
6663 /// source code as part of a new template declaration.
6665 /// \param Old The old template parameter list, typically found via
6666 /// name lookup of the template declared with this template parameter
6669 /// \param Complain If true, this routine will produce a diagnostic if
6670 /// the template parameter lists are not equivalent.
6672 /// \param Kind describes how we are to match the template parameter lists.
6674 /// \param TemplateArgLoc If this source location is valid, then we
6675 /// are actually checking the template parameter list of a template
6676 /// argument (New) against the template parameter list of its
6677 /// corresponding template template parameter (Old). We produce
6678 /// slightly different diagnostics in this scenario.
6680 /// \returns True if the template parameter lists are equal, false
6683 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
6684 TemplateParameterList *Old,
6686 TemplateParameterListEqualKind Kind,
6687 SourceLocation TemplateArgLoc) {
6688 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
6690 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6696 // C++0x [temp.arg.template]p3:
6697 // A template-argument matches a template template-parameter (call it P)
6698 // when each of the template parameters in the template-parameter-list of
6699 // the template-argument's corresponding class template or alias template
6700 // (call it A) matches the corresponding template parameter in the
6701 // template-parameter-list of P. [...]
6702 TemplateParameterList::iterator NewParm = New->begin();
6703 TemplateParameterList::iterator NewParmEnd = New->end();
6704 for (TemplateParameterList::iterator OldParm = Old->begin(),
6705 OldParmEnd = Old->end();
6706 OldParm != OldParmEnd; ++OldParm) {
6707 if (Kind != TPL_TemplateTemplateArgumentMatch ||
6708 !(*OldParm)->isTemplateParameterPack()) {
6709 if (NewParm == NewParmEnd) {
6711 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6717 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6718 Kind, TemplateArgLoc))
6725 // C++0x [temp.arg.template]p3:
6726 // [...] When P's template- parameter-list contains a template parameter
6727 // pack (14.5.3), the template parameter pack will match zero or more
6728 // template parameters or template parameter packs in the
6729 // template-parameter-list of A with the same type and form as the
6730 // template parameter pack in P (ignoring whether those template
6731 // parameters are template parameter packs).
6732 for (; NewParm != NewParmEnd; ++NewParm) {
6733 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
6734 Kind, TemplateArgLoc))
6739 // Make sure we exhausted all of the arguments.
6740 if (NewParm != NewParmEnd) {
6742 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
6751 /// \brief Check whether a template can be declared within this scope.
6753 /// If the template declaration is valid in this scope, returns
6754 /// false. Otherwise, issues a diagnostic and returns true.
6756 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
6760 // Find the nearest enclosing declaration scope.
6761 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6762 (S->getFlags() & Scope::TemplateParamScope) != 0)
6766 // A template [...] shall not have C linkage.
6767 DeclContext *Ctx = S->getEntity();
6768 if (Ctx && Ctx->isExternCContext()) {
6769 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
6770 << TemplateParams->getSourceRange();
6771 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
6772 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
6775 Ctx = Ctx->getRedeclContext();
6778 // A template-declaration can appear only as a namespace scope or
6779 // class scope declaration.
6781 if (Ctx->isFileContext())
6783 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
6784 // C++ [temp.mem]p2:
6785 // A local class shall not have member templates.
6786 if (RD->isLocalClass())
6787 return Diag(TemplateParams->getTemplateLoc(),
6788 diag::err_template_inside_local_class)
6789 << TemplateParams->getSourceRange();
6795 return Diag(TemplateParams->getTemplateLoc(),
6796 diag::err_template_outside_namespace_or_class_scope)
6797 << TemplateParams->getSourceRange();
6800 /// \brief Determine what kind of template specialization the given declaration
6802 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
6804 return TSK_Undeclared;
6806 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
6807 return Record->getTemplateSpecializationKind();
6808 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
6809 return Function->getTemplateSpecializationKind();
6810 if (VarDecl *Var = dyn_cast<VarDecl>(D))
6811 return Var->getTemplateSpecializationKind();
6813 return TSK_Undeclared;
6816 /// \brief Check whether a specialization is well-formed in the current
6819 /// This routine determines whether a template specialization can be declared
6820 /// in the current context (C++ [temp.expl.spec]p2).
6822 /// \param S the semantic analysis object for which this check is being
6825 /// \param Specialized the entity being specialized or instantiated, which
6826 /// may be a kind of template (class template, function template, etc.) or
6827 /// a member of a class template (member function, static data member,
6830 /// \param PrevDecl the previous declaration of this entity, if any.
6832 /// \param Loc the location of the explicit specialization or instantiation of
6835 /// \param IsPartialSpecialization whether this is a partial specialization of
6836 /// a class template.
6838 /// \returns true if there was an error that we cannot recover from, false
6840 static bool CheckTemplateSpecializationScope(Sema &S,
6841 NamedDecl *Specialized,
6842 NamedDecl *PrevDecl,
6844 bool IsPartialSpecialization) {
6845 // Keep these "kind" numbers in sync with the %select statements in the
6846 // various diagnostics emitted by this routine.
6848 if (isa<ClassTemplateDecl>(Specialized))
6849 EntityKind = IsPartialSpecialization? 1 : 0;
6850 else if (isa<VarTemplateDecl>(Specialized))
6851 EntityKind = IsPartialSpecialization ? 3 : 2;
6852 else if (isa<FunctionTemplateDecl>(Specialized))
6854 else if (isa<CXXMethodDecl>(Specialized))
6856 else if (isa<VarDecl>(Specialized))
6858 else if (isa<RecordDecl>(Specialized))
6860 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
6863 S.Diag(Loc, diag::err_template_spec_unknown_kind)
6864 << S.getLangOpts().CPlusPlus11;
6865 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6869 // C++ [temp.expl.spec]p2:
6870 // An explicit specialization shall be declared in the namespace
6871 // of which the template is a member, or, for member templates, in
6872 // the namespace of which the enclosing class or enclosing class
6873 // template is a member. An explicit specialization of a member
6874 // function, member class or static data member of a class
6875 // template shall be declared in the namespace of which the class
6876 // template is a member. Such a declaration may also be a
6877 // definition. If the declaration is not a definition, the
6878 // specialization may be defined later in the name- space in which
6879 // the explicit specialization was declared, or in a namespace
6880 // that encloses the one in which the explicit specialization was
6882 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6883 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
6888 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
6889 if (S.getLangOpts().MicrosoftExt) {
6890 // Do not warn for class scope explicit specialization during
6891 // instantiation, warning was already emitted during pattern
6892 // semantic analysis.
6893 if (!S.inTemplateInstantiation())
6894 S.Diag(Loc, diag::ext_function_specialization_in_class)
6897 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6903 if (S.CurContext->isRecord() &&
6904 !S.CurContext->Equals(Specialized->getDeclContext())) {
6905 // Make sure that we're specializing in the right record context.
6906 // Otherwise, things can go horribly wrong.
6907 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
6912 // C++ [temp.class.spec]p6:
6913 // A class template partial specialization may be declared or redeclared
6914 // in any namespace scope in which its definition may be defined (14.5.1
6916 DeclContext *SpecializedContext
6917 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
6918 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
6920 // Make sure that this redeclaration (or definition) occurs in an enclosing
6922 // Note that HandleDeclarator() performs this check for explicit
6923 // specializations of function templates, static data members, and member
6924 // functions, so we skip the check here for those kinds of entities.
6925 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
6926 // Should we refactor that check, so that it occurs later?
6927 if (!DC->Encloses(SpecializedContext) &&
6928 !(isa<FunctionTemplateDecl>(Specialized) ||
6929 isa<FunctionDecl>(Specialized) ||
6930 isa<VarTemplateDecl>(Specialized) ||
6931 isa<VarDecl>(Specialized))) {
6932 if (isa<TranslationUnitDecl>(SpecializedContext))
6933 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
6934 << EntityKind << Specialized;
6935 else if (isa<NamespaceDecl>(SpecializedContext)) {
6936 int Diag = diag::err_template_spec_redecl_out_of_scope;
6937 if (S.getLangOpts().MicrosoftExt)
6938 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
6939 S.Diag(Loc, Diag) << EntityKind << Specialized
6940 << cast<NamedDecl>(SpecializedContext);
6942 llvm_unreachable("unexpected namespace context for specialization");
6944 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6945 } else if ((!PrevDecl ||
6946 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
6947 getTemplateSpecializationKind(PrevDecl) ==
6948 TSK_ImplicitInstantiation)) {
6949 // C++ [temp.exp.spec]p2:
6950 // An explicit specialization shall be declared in the namespace of which
6951 // the template is a member, or, for member templates, in the namespace
6952 // of which the enclosing class or enclosing class template is a member.
6953 // An explicit specialization of a member function, member class or
6954 // static data member of a class template shall be declared in the
6955 // namespace of which the class template is a member.
6957 // C++11 [temp.expl.spec]p2:
6958 // An explicit specialization shall be declared in a namespace enclosing
6959 // the specialized template.
6960 // C++11 [temp.explicit]p3:
6961 // An explicit instantiation shall appear in an enclosing namespace of its
6963 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
6964 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
6965 if (isa<TranslationUnitDecl>(SpecializedContext)) {
6966 assert(!IsCPlusPlus11Extension &&
6967 "DC encloses TU but isn't in enclosing namespace set");
6968 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
6969 << EntityKind << Specialized;
6970 } else if (isa<NamespaceDecl>(SpecializedContext)) {
6972 if (!IsCPlusPlus11Extension)
6973 Diag = diag::err_template_spec_decl_out_of_scope;
6974 else if (!S.getLangOpts().CPlusPlus11)
6975 Diag = diag::ext_template_spec_decl_out_of_scope;
6977 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
6979 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
6982 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
6989 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
6990 if (!E->isTypeDependent())
6991 return SourceLocation();
6992 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
6993 Checker.TraverseStmt(E);
6994 if (Checker.MatchLoc.isInvalid())
6995 return E->getSourceRange();
6996 return Checker.MatchLoc;
6999 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
7000 if (!TL.getType()->isDependentType())
7001 return SourceLocation();
7002 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
7003 Checker.TraverseTypeLoc(TL);
7004 if (Checker.MatchLoc.isInvalid())
7005 return TL.getSourceRange();
7006 return Checker.MatchLoc;
7009 /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
7010 /// that checks non-type template partial specialization arguments.
7011 static bool CheckNonTypeTemplatePartialSpecializationArgs(
7012 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
7013 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
7014 for (unsigned I = 0; I != NumArgs; ++I) {
7015 if (Args[I].getKind() == TemplateArgument::Pack) {
7016 if (CheckNonTypeTemplatePartialSpecializationArgs(
7017 S, TemplateNameLoc, Param, Args[I].pack_begin(),
7018 Args[I].pack_size(), IsDefaultArgument))
7024 if (Args[I].getKind() != TemplateArgument::Expression)
7027 Expr *ArgExpr = Args[I].getAsExpr();
7029 // We can have a pack expansion of any of the bullets below.
7030 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
7031 ArgExpr = Expansion->getPattern();
7033 // Strip off any implicit casts we added as part of type checking.
7034 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
7035 ArgExpr = ICE->getSubExpr();
7037 // C++ [temp.class.spec]p8:
7038 // A non-type argument is non-specialized if it is the name of a
7039 // non-type parameter. All other non-type arguments are
7042 // Below, we check the two conditions that only apply to
7043 // specialized non-type arguments, so skip any non-specialized
7045 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
7046 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
7049 // C++ [temp.class.spec]p9:
7050 // Within the argument list of a class template partial
7051 // specialization, the following restrictions apply:
7052 // -- A partially specialized non-type argument expression
7053 // shall not involve a template parameter of the partial
7054 // specialization except when the argument expression is a
7055 // simple identifier.
7056 // -- The type of a template parameter corresponding to a
7057 // specialized non-type argument shall not be dependent on a
7058 // parameter of the specialization.
7059 // DR1315 removes the first bullet, leaving an incoherent set of rules.
7060 // We implement a compromise between the original rules and DR1315:
7061 // -- A specialized non-type template argument shall not be
7062 // type-dependent and the corresponding template parameter
7063 // shall have a non-dependent type.
7064 SourceRange ParamUseRange =
7065 findTemplateParameterInType(Param->getDepth(), ArgExpr);
7066 if (ParamUseRange.isValid()) {
7067 if (IsDefaultArgument) {
7068 S.Diag(TemplateNameLoc,
7069 diag::err_dependent_non_type_arg_in_partial_spec);
7070 S.Diag(ParamUseRange.getBegin(),
7071 diag::note_dependent_non_type_default_arg_in_partial_spec)
7074 S.Diag(ParamUseRange.getBegin(),
7075 diag::err_dependent_non_type_arg_in_partial_spec)
7081 ParamUseRange = findTemplateParameter(
7082 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
7083 if (ParamUseRange.isValid()) {
7084 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
7085 diag::err_dependent_typed_non_type_arg_in_partial_spec)
7086 << Param->getType();
7087 S.Diag(Param->getLocation(), diag::note_template_param_here)
7088 << (IsDefaultArgument ? ParamUseRange : SourceRange())
7097 /// \brief Check the non-type template arguments of a class template
7098 /// partial specialization according to C++ [temp.class.spec]p9.
7100 /// \param TemplateNameLoc the location of the template name.
7101 /// \param PrimaryTemplate the template parameters of the primary class
7103 /// \param NumExplicit the number of explicitly-specified template arguments.
7104 /// \param TemplateArgs the template arguments of the class template
7105 /// partial specialization.
7107 /// \returns \c true if there was an error, \c false otherwise.
7108 bool Sema::CheckTemplatePartialSpecializationArgs(
7109 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
7110 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
7111 // We have to be conservative when checking a template in a dependent
7113 if (PrimaryTemplate->getDeclContext()->isDependentContext())
7116 TemplateParameterList *TemplateParams =
7117 PrimaryTemplate->getTemplateParameters();
7118 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7119 NonTypeTemplateParmDecl *Param
7120 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
7124 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,
7125 Param, &TemplateArgs[I],
7126 1, I >= NumExplicit))
7134 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
7136 SourceLocation KWLoc,
7137 SourceLocation ModulePrivateLoc,
7138 TemplateIdAnnotation &TemplateId,
7139 AttributeList *Attr,
7140 MultiTemplateParamsArg
7141 TemplateParameterLists,
7142 SkipBodyInfo *SkipBody) {
7143 assert(TUK != TUK_Reference && "References are not specializations");
7145 CXXScopeSpec &SS = TemplateId.SS;
7147 // NOTE: KWLoc is the location of the tag keyword. This will instead
7148 // store the location of the outermost template keyword in the declaration.
7149 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
7150 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
7151 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
7152 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
7153 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
7155 // Find the class template we're specializing
7156 TemplateName Name = TemplateId.Template.get();
7157 ClassTemplateDecl *ClassTemplate
7158 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
7160 if (!ClassTemplate) {
7161 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
7162 << (Name.getAsTemplateDecl() &&
7163 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
7167 bool isMemberSpecialization = false;
7168 bool isPartialSpecialization = false;
7170 // Check the validity of the template headers that introduce this
7172 // FIXME: We probably shouldn't complain about these headers for
7173 // friend declarations.
7174 bool Invalid = false;
7175 TemplateParameterList *TemplateParams =
7176 MatchTemplateParametersToScopeSpecifier(
7177 KWLoc, TemplateNameLoc, SS, &TemplateId,
7178 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization,
7183 if (TemplateParams && TemplateParams->size() > 0) {
7184 isPartialSpecialization = true;
7186 if (TUK == TUK_Friend) {
7187 Diag(KWLoc, diag::err_partial_specialization_friend)
7188 << SourceRange(LAngleLoc, RAngleLoc);
7192 // C++ [temp.class.spec]p10:
7193 // The template parameter list of a specialization shall not
7194 // contain default template argument values.
7195 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
7196 Decl *Param = TemplateParams->getParam(I);
7197 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
7198 if (TTP->hasDefaultArgument()) {
7199 Diag(TTP->getDefaultArgumentLoc(),
7200 diag::err_default_arg_in_partial_spec);
7201 TTP->removeDefaultArgument();
7203 } else if (NonTypeTemplateParmDecl *NTTP
7204 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
7205 if (Expr *DefArg = NTTP->getDefaultArgument()) {
7206 Diag(NTTP->getDefaultArgumentLoc(),
7207 diag::err_default_arg_in_partial_spec)
7208 << DefArg->getSourceRange();
7209 NTTP->removeDefaultArgument();
7212 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
7213 if (TTP->hasDefaultArgument()) {
7214 Diag(TTP->getDefaultArgument().getLocation(),
7215 diag::err_default_arg_in_partial_spec)
7216 << TTP->getDefaultArgument().getSourceRange();
7217 TTP->removeDefaultArgument();
7221 } else if (TemplateParams) {
7222 if (TUK == TUK_Friend)
7223 Diag(KWLoc, diag::err_template_spec_friend)
7224 << FixItHint::CreateRemoval(
7225 SourceRange(TemplateParams->getTemplateLoc(),
7226 TemplateParams->getRAngleLoc()))
7227 << SourceRange(LAngleLoc, RAngleLoc);
7229 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
7232 // Check that the specialization uses the same tag kind as the
7233 // original template.
7234 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7235 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
7236 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7237 Kind, TUK == TUK_Definition, KWLoc,
7238 ClassTemplate->getIdentifier())) {
7239 Diag(KWLoc, diag::err_use_with_wrong_tag)
7241 << FixItHint::CreateReplacement(KWLoc,
7242 ClassTemplate->getTemplatedDecl()->getKindName());
7243 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7244 diag::note_previous_use);
7245 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7248 // Translate the parser's template argument list in our AST format.
7249 TemplateArgumentListInfo TemplateArgs =
7250 makeTemplateArgumentListInfo(*this, TemplateId);
7252 // Check for unexpanded parameter packs in any of the template arguments.
7253 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7254 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
7255 UPPC_PartialSpecialization))
7258 // Check that the template argument list is well-formed for this
7260 SmallVector<TemplateArgument, 4> Converted;
7261 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7262 TemplateArgs, false, Converted))
7265 // Find the class template (partial) specialization declaration that
7266 // corresponds to these arguments.
7267 if (isPartialSpecialization) {
7268 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
7269 TemplateArgs.size(), Converted))
7272 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
7273 // also do it during instantiation.
7274 bool InstantiationDependent;
7275 if (!Name.isDependent() &&
7276 !TemplateSpecializationType::anyDependentTemplateArguments(
7277 TemplateArgs.arguments(), InstantiationDependent)) {
7278 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
7279 << ClassTemplate->getDeclName();
7280 isPartialSpecialization = false;
7284 void *InsertPos = nullptr;
7285 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
7287 if (isPartialSpecialization)
7288 // FIXME: Template parameter list matters, too
7289 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
7291 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
7293 ClassTemplateSpecializationDecl *Specialization = nullptr;
7295 // Check whether we can declare a class template specialization in
7296 // the current scope.
7297 if (TUK != TUK_Friend &&
7298 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
7300 isPartialSpecialization))
7303 // The canonical type
7305 if (isPartialSpecialization) {
7306 // Build the canonical type that describes the converted template
7307 // arguments of the class template partial specialization.
7308 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7309 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
7312 if (Context.hasSameType(CanonType,
7313 ClassTemplate->getInjectedClassNameSpecialization())) {
7314 // C++ [temp.class.spec]p9b3:
7316 // -- The argument list of the specialization shall not be identical
7317 // to the implicit argument list of the primary template.
7319 // This rule has since been removed, because it's redundant given DR1495,
7320 // but we keep it because it produces better diagnostics and recovery.
7321 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
7322 << /*class template*/0 << (TUK == TUK_Definition)
7323 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
7324 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
7325 ClassTemplate->getIdentifier(),
7329 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
7330 /*FriendLoc*/SourceLocation(),
7331 TemplateParameterLists.size() - 1,
7332 TemplateParameterLists.data());
7335 // Create a new class template partial specialization declaration node.
7336 ClassTemplatePartialSpecializationDecl *PrevPartial
7337 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
7338 ClassTemplatePartialSpecializationDecl *Partial
7339 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
7340 ClassTemplate->getDeclContext(),
7341 KWLoc, TemplateNameLoc,
7348 SetNestedNameSpecifier(Partial, SS);
7349 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
7350 Partial->setTemplateParameterListsInfo(
7351 Context, TemplateParameterLists.drop_back(1));
7355 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
7356 Specialization = Partial;
7358 // If we are providing an explicit specialization of a member class
7359 // template specialization, make a note of that.
7360 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
7361 PrevPartial->setMemberSpecialization();
7363 CheckTemplatePartialSpecialization(Partial);
7365 // Create a new class template specialization declaration node for
7366 // this explicit specialization or friend declaration.
7368 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7369 ClassTemplate->getDeclContext(),
7370 KWLoc, TemplateNameLoc,
7374 SetNestedNameSpecifier(Specialization, SS);
7375 if (TemplateParameterLists.size() > 0) {
7376 Specialization->setTemplateParameterListsInfo(Context,
7377 TemplateParameterLists);
7381 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7383 if (CurContext->isDependentContext()) {
7384 // -fms-extensions permits specialization of nested classes without
7385 // fully specializing the outer class(es).
7386 assert(getLangOpts().MicrosoftExt &&
7387 "Only possible with -fms-extensions!");
7388 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
7389 CanonType = Context.getTemplateSpecializationType(
7390 CanonTemplate, Converted);
7392 CanonType = Context.getTypeDeclType(Specialization);
7396 // C++ [temp.expl.spec]p6:
7397 // If a template, a member template or the member of a class template is
7398 // explicitly specialized then that specialization shall be declared
7399 // before the first use of that specialization that would cause an implicit
7400 // instantiation to take place, in every translation unit in which such a
7401 // use occurs; no diagnostic is required.
7402 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
7404 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7405 // Is there any previous explicit specialization declaration?
7406 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7413 SourceRange Range(TemplateNameLoc, RAngleLoc);
7414 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
7415 << Context.getTypeDeclType(Specialization) << Range;
7417 Diag(PrevDecl->getPointOfInstantiation(),
7418 diag::note_instantiation_required_here)
7419 << (PrevDecl->getTemplateSpecializationKind()
7420 != TSK_ImplicitInstantiation);
7425 // If this is not a friend, note that this is an explicit specialization.
7426 if (TUK != TUK_Friend)
7427 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
7429 // Check that this isn't a redefinition of this specialization.
7430 if (TUK == TUK_Definition) {
7431 RecordDecl *Def = Specialization->getDefinition();
7432 NamedDecl *Hidden = nullptr;
7433 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
7434 SkipBody->ShouldSkip = true;
7435 makeMergedDefinitionVisible(Hidden);
7436 // From here on out, treat this as just a redeclaration.
7437 TUK = TUK_Declaration;
7439 SourceRange Range(TemplateNameLoc, RAngleLoc);
7440 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
7441 Diag(Def->getLocation(), diag::note_previous_definition);
7442 Specialization->setInvalidDecl();
7448 ProcessDeclAttributeList(S, Specialization, Attr);
7450 // Add alignment attributes if necessary; these attributes are checked when
7451 // the ASTContext lays out the structure.
7452 if (TUK == TUK_Definition) {
7453 AddAlignmentAttributesForRecord(Specialization);
7454 AddMsStructLayoutForRecord(Specialization);
7457 if (ModulePrivateLoc.isValid())
7458 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
7459 << (isPartialSpecialization? 1 : 0)
7460 << FixItHint::CreateRemoval(ModulePrivateLoc);
7462 // Build the fully-sugared type for this class template
7463 // specialization as the user wrote in the specialization
7464 // itself. This means that we'll pretty-print the type retrieved
7465 // from the specialization's declaration the way that the user
7466 // actually wrote the specialization, rather than formatting the
7467 // name based on the "canonical" representation used to store the
7468 // template arguments in the specialization.
7469 TypeSourceInfo *WrittenTy
7470 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7471 TemplateArgs, CanonType);
7472 if (TUK != TUK_Friend) {
7473 Specialization->setTypeAsWritten(WrittenTy);
7474 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
7477 // C++ [temp.expl.spec]p9:
7478 // A template explicit specialization is in the scope of the
7479 // namespace in which the template was defined.
7481 // We actually implement this paragraph where we set the semantic
7482 // context (in the creation of the ClassTemplateSpecializationDecl),
7483 // but we also maintain the lexical context where the actual
7484 // definition occurs.
7485 Specialization->setLexicalDeclContext(CurContext);
7487 // We may be starting the definition of this specialization.
7488 if (TUK == TUK_Definition)
7489 Specialization->startDefinition();
7491 if (TUK == TUK_Friend) {
7492 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
7496 Friend->setAccess(AS_public);
7497 CurContext->addDecl(Friend);
7499 // Add the specialization into its lexical context, so that it can
7500 // be seen when iterating through the list of declarations in that
7501 // context. However, specializations are not found by name lookup.
7502 CurContext->addDecl(Specialization);
7504 return Specialization;
7507 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
7508 MultiTemplateParamsArg TemplateParameterLists,
7510 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
7511 ActOnDocumentableDecl(NewDecl);
7515 /// \brief Strips various properties off an implicit instantiation
7516 /// that has just been explicitly specialized.
7517 static void StripImplicitInstantiation(NamedDecl *D) {
7518 D->dropAttr<DLLImportAttr>();
7519 D->dropAttr<DLLExportAttr>();
7521 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
7522 FD->setInlineSpecified(false);
7525 /// \brief Compute the diagnostic location for an explicit instantiation
7526 // declaration or definition.
7527 static SourceLocation DiagLocForExplicitInstantiation(
7528 NamedDecl* D, SourceLocation PointOfInstantiation) {
7529 // Explicit instantiations following a specialization have no effect and
7530 // hence no PointOfInstantiation. In that case, walk decl backwards
7531 // until a valid name loc is found.
7532 SourceLocation PrevDiagLoc = PointOfInstantiation;
7533 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
7534 Prev = Prev->getPreviousDecl()) {
7535 PrevDiagLoc = Prev->getLocation();
7537 assert(PrevDiagLoc.isValid() &&
7538 "Explicit instantiation without point of instantiation?");
7542 /// \brief Diagnose cases where we have an explicit template specialization
7543 /// before/after an explicit template instantiation, producing diagnostics
7544 /// for those cases where they are required and determining whether the
7545 /// new specialization/instantiation will have any effect.
7547 /// \param NewLoc the location of the new explicit specialization or
7550 /// \param NewTSK the kind of the new explicit specialization or instantiation.
7552 /// \param PrevDecl the previous declaration of the entity.
7554 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
7556 /// \param PrevPointOfInstantiation if valid, indicates where the previus
7557 /// declaration was instantiated (either implicitly or explicitly).
7559 /// \param HasNoEffect will be set to true to indicate that the new
7560 /// specialization or instantiation has no effect and should be ignored.
7562 /// \returns true if there was an error that should prevent the introduction of
7563 /// the new declaration into the AST, false otherwise.
7565 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7566 TemplateSpecializationKind NewTSK,
7567 NamedDecl *PrevDecl,
7568 TemplateSpecializationKind PrevTSK,
7569 SourceLocation PrevPointOfInstantiation,
7570 bool &HasNoEffect) {
7571 HasNoEffect = false;
7574 case TSK_Undeclared:
7575 case TSK_ImplicitInstantiation:
7577 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
7578 "previous declaration must be implicit!");
7581 case TSK_ExplicitSpecialization:
7583 case TSK_Undeclared:
7584 case TSK_ExplicitSpecialization:
7585 // Okay, we're just specializing something that is either already
7586 // explicitly specialized or has merely been mentioned without any
7590 case TSK_ImplicitInstantiation:
7591 if (PrevPointOfInstantiation.isInvalid()) {
7592 // The declaration itself has not actually been instantiated, so it is
7593 // still okay to specialize it.
7594 StripImplicitInstantiation(PrevDecl);
7600 case TSK_ExplicitInstantiationDeclaration:
7601 case TSK_ExplicitInstantiationDefinition:
7602 assert((PrevTSK == TSK_ImplicitInstantiation ||
7603 PrevPointOfInstantiation.isValid()) &&
7604 "Explicit instantiation without point of instantiation?");
7606 // C++ [temp.expl.spec]p6:
7607 // If a template, a member template or the member of a class template
7608 // is explicitly specialized then that specialization shall be declared
7609 // before the first use of that specialization that would cause an
7610 // implicit instantiation to take place, in every translation unit in
7611 // which such a use occurs; no diagnostic is required.
7612 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7613 // Is there any previous explicit specialization declaration?
7614 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
7618 Diag(NewLoc, diag::err_specialization_after_instantiation)
7620 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
7621 << (PrevTSK != TSK_ImplicitInstantiation);
7625 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
7627 case TSK_ExplicitInstantiationDeclaration:
7629 case TSK_ExplicitInstantiationDeclaration:
7630 // This explicit instantiation declaration is redundant (that's okay).
7634 case TSK_Undeclared:
7635 case TSK_ImplicitInstantiation:
7636 // We're explicitly instantiating something that may have already been
7637 // implicitly instantiated; that's fine.
7640 case TSK_ExplicitSpecialization:
7641 // C++0x [temp.explicit]p4:
7642 // For a given set of template parameters, if an explicit instantiation
7643 // of a template appears after a declaration of an explicit
7644 // specialization for that template, the explicit instantiation has no
7649 case TSK_ExplicitInstantiationDefinition:
7650 // C++0x [temp.explicit]p10:
7651 // If an entity is the subject of both an explicit instantiation
7652 // declaration and an explicit instantiation definition in the same
7653 // translation unit, the definition shall follow the declaration.
7655 diag::err_explicit_instantiation_declaration_after_definition);
7657 // Explicit instantiations following a specialization have no effect and
7658 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
7659 // until a valid name loc is found.
7660 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7661 diag::note_explicit_instantiation_definition_here);
7666 case TSK_ExplicitInstantiationDefinition:
7668 case TSK_Undeclared:
7669 case TSK_ImplicitInstantiation:
7670 // We're explicitly instantiating something that may have already been
7671 // implicitly instantiated; that's fine.
7674 case TSK_ExplicitSpecialization:
7675 // C++ DR 259, C++0x [temp.explicit]p4:
7676 // For a given set of template parameters, if an explicit
7677 // instantiation of a template appears after a declaration of
7678 // an explicit specialization for that template, the explicit
7679 // instantiation has no effect.
7680 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
7682 Diag(PrevDecl->getLocation(),
7683 diag::note_previous_template_specialization);
7687 case TSK_ExplicitInstantiationDeclaration:
7688 // We're explicity instantiating a definition for something for which we
7689 // were previously asked to suppress instantiations. That's fine.
7691 // C++0x [temp.explicit]p4:
7692 // For a given set of template parameters, if an explicit instantiation
7693 // of a template appears after a declaration of an explicit
7694 // specialization for that template, the explicit instantiation has no
7696 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
7697 // Is there any previous explicit specialization declaration?
7698 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
7706 case TSK_ExplicitInstantiationDefinition:
7707 // C++0x [temp.spec]p5:
7708 // For a given template and a given set of template-arguments,
7709 // - an explicit instantiation definition shall appear at most once
7712 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
7713 Diag(NewLoc, (getLangOpts().MSVCCompat)
7714 ? diag::ext_explicit_instantiation_duplicate
7715 : diag::err_explicit_instantiation_duplicate)
7717 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
7718 diag::note_previous_explicit_instantiation);
7724 llvm_unreachable("Missing specialization/instantiation case?");
7727 /// \brief Perform semantic analysis for the given dependent function
7728 /// template specialization.
7730 /// The only possible way to get a dependent function template specialization
7731 /// is with a friend declaration, like so:
7734 /// template \<class T> void foo(T);
7735 /// template \<class T> class A {
7736 /// friend void foo<>(T);
7740 /// There really isn't any useful analysis we can do here, so we
7741 /// just store the information.
7743 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7744 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7745 LookupResult &Previous) {
7746 // Remove anything from Previous that isn't a function template in
7747 // the correct context.
7748 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
7749 LookupResult::Filter F = Previous.makeFilter();
7750 while (F.hasNext()) {
7751 NamedDecl *D = F.next()->getUnderlyingDecl();
7752 if (!isa<FunctionTemplateDecl>(D) ||
7753 !FDLookupContext->InEnclosingNamespaceSetOf(
7754 D->getDeclContext()->getRedeclContext()))
7759 // Should this be diagnosed here?
7760 if (Previous.empty()) return true;
7762 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
7763 ExplicitTemplateArgs);
7767 /// \brief Perform semantic analysis for the given function template
7770 /// This routine performs all of the semantic analysis required for an
7771 /// explicit function template specialization. On successful completion,
7772 /// the function declaration \p FD will become a function template
7775 /// \param FD the function declaration, which will be updated to become a
7776 /// function template specialization.
7778 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
7779 /// if any. Note that this may be valid info even when 0 arguments are
7780 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
7781 /// as it anyway contains info on the angle brackets locations.
7783 /// \param Previous the set of declarations that may be specialized by
7784 /// this function specialization.
7785 bool Sema::CheckFunctionTemplateSpecialization(
7786 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7787 LookupResult &Previous) {
7788 // The set of function template specializations that could match this
7789 // explicit function template specialization.
7790 UnresolvedSet<8> Candidates;
7791 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
7792 /*ForTakingAddress=*/false);
7794 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
7795 ConvertedTemplateArgs;
7797 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
7798 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7800 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
7801 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
7802 // Only consider templates found within the same semantic lookup scope as
7804 if (!FDLookupContext->InEnclosingNamespaceSetOf(
7805 Ovl->getDeclContext()->getRedeclContext()))
7808 // When matching a constexpr member function template specialization
7809 // against the primary template, we don't yet know whether the
7810 // specialization has an implicit 'const' (because we don't know whether
7811 // it will be a static member function until we know which template it
7812 // specializes), so adjust it now assuming it specializes this template.
7813 QualType FT = FD->getType();
7814 if (FD->isConstexpr()) {
7815 CXXMethodDecl *OldMD =
7816 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
7817 if (OldMD && OldMD->isConst()) {
7818 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
7819 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7820 EPI.TypeQuals |= Qualifiers::Const;
7821 FT = Context.getFunctionType(FPT->getReturnType(),
7822 FPT->getParamTypes(), EPI);
7826 TemplateArgumentListInfo Args;
7827 if (ExplicitTemplateArgs)
7828 Args = *ExplicitTemplateArgs;
7830 // C++ [temp.expl.spec]p11:
7831 // A trailing template-argument can be left unspecified in the
7832 // template-id naming an explicit function template specialization
7833 // provided it can be deduced from the function argument type.
7834 // Perform template argument deduction to determine whether we may be
7835 // specializing this template.
7836 // FIXME: It is somewhat wasteful to build
7837 TemplateDeductionInfo Info(FailedCandidates.getLocation());
7838 FunctionDecl *Specialization = nullptr;
7839 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
7840 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
7841 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization,
7843 // Template argument deduction failed; record why it failed, so
7844 // that we can provide nifty diagnostics.
7845 FailedCandidates.addCandidate().set(
7846 I.getPair(), FunTmpl->getTemplatedDecl(),
7847 MakeDeductionFailureInfo(Context, TDK, Info));
7852 // Target attributes are part of the cuda function signature, so
7853 // the deduced template's cuda target must match that of the
7854 // specialization. Given that C++ template deduction does not
7855 // take target attributes into account, we reject candidates
7856 // here that have a different target.
7857 if (LangOpts.CUDA &&
7858 IdentifyCUDATarget(Specialization,
7859 /* IgnoreImplicitHDAttributes = */ true) !=
7860 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttributes = */ true)) {
7861 FailedCandidates.addCandidate().set(
7862 I.getPair(), FunTmpl->getTemplatedDecl(),
7863 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
7867 // Record this candidate.
7868 if (ExplicitTemplateArgs)
7869 ConvertedTemplateArgs[Specialization] = std::move(Args);
7870 Candidates.addDecl(Specialization, I.getAccess());
7874 // Find the most specialized function template.
7875 UnresolvedSetIterator Result = getMostSpecialized(
7876 Candidates.begin(), Candidates.end(), FailedCandidates,
7878 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
7879 PDiag(diag::err_function_template_spec_ambiguous)
7880 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
7881 PDiag(diag::note_function_template_spec_matched));
7883 if (Result == Candidates.end())
7886 // Ignore access information; it doesn't figure into redeclaration checking.
7887 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
7889 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
7890 // an explicit specialization (14.8.3) [...] of a concept definition.
7891 if (Specialization->getPrimaryTemplate()->isConcept()) {
7892 Diag(FD->getLocation(), diag::err_concept_specialized)
7893 << 0 /*function*/ << 1 /*explicitly specialized*/;
7894 Diag(Specialization->getLocation(), diag::note_previous_declaration);
7898 FunctionTemplateSpecializationInfo *SpecInfo
7899 = Specialization->getTemplateSpecializationInfo();
7900 assert(SpecInfo && "Function template specialization info missing?");
7902 // Note: do not overwrite location info if previous template
7903 // specialization kind was explicit.
7904 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
7905 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
7906 Specialization->setLocation(FD->getLocation());
7907 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
7908 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
7909 // function can differ from the template declaration with respect to
7910 // the constexpr specifier.
7911 // FIXME: We need an update record for this AST mutation.
7912 // FIXME: What if there are multiple such prior declarations (for instance,
7913 // from different modules)?
7914 Specialization->setConstexpr(FD->isConstexpr());
7917 // FIXME: Check if the prior specialization has a point of instantiation.
7918 // If so, we have run afoul of .
7920 // If this is a friend declaration, then we're not really declaring
7921 // an explicit specialization.
7922 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
7924 // Check the scope of this explicit specialization.
7926 CheckTemplateSpecializationScope(*this,
7927 Specialization->getPrimaryTemplate(),
7928 Specialization, FD->getLocation(),
7932 // C++ [temp.expl.spec]p6:
7933 // If a template, a member template or the member of a class template is
7934 // explicitly specialized then that specialization shall be declared
7935 // before the first use of that specialization that would cause an implicit
7936 // instantiation to take place, in every translation unit in which such a
7937 // use occurs; no diagnostic is required.
7938 bool HasNoEffect = false;
7940 CheckSpecializationInstantiationRedecl(FD->getLocation(),
7941 TSK_ExplicitSpecialization,
7943 SpecInfo->getTemplateSpecializationKind(),
7944 SpecInfo->getPointOfInstantiation(),
7948 // Mark the prior declaration as an explicit specialization, so that later
7949 // clients know that this is an explicit specialization.
7951 // Since explicit specializations do not inherit '=delete' from their
7952 // primary function template - check if the 'specialization' that was
7953 // implicitly generated (during template argument deduction for partial
7954 // ordering) from the most specialized of all the function templates that
7955 // 'FD' could have been specializing, has a 'deleted' definition. If so,
7956 // first check that it was implicitly generated during template argument
7957 // deduction by making sure it wasn't referenced, and then reset the deleted
7958 // flag to not-deleted, so that we can inherit that information from 'FD'.
7959 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
7960 !Specialization->getCanonicalDecl()->isReferenced()) {
7961 // FIXME: This assert will not hold in the presence of modules.
7963 Specialization->getCanonicalDecl() == Specialization &&
7964 "This must be the only existing declaration of this specialization");
7965 // FIXME: We need an update record for this AST mutation.
7966 Specialization->setDeletedAsWritten(false);
7968 // FIXME: We need an update record for this AST mutation.
7969 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
7970 MarkUnusedFileScopedDecl(Specialization);
7973 // Turn the given function declaration into a function template
7974 // specialization, with the template arguments from the previous
7976 // Take copies of (semantic and syntactic) template argument lists.
7977 const TemplateArgumentList* TemplArgs = new (Context)
7978 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
7979 FD->setFunctionTemplateSpecialization(
7980 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,
7981 SpecInfo->getTemplateSpecializationKind(),
7982 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
7984 // A function template specialization inherits the target attributes
7985 // of its template. (We require the attributes explicitly in the
7986 // code to match, but a template may have implicit attributes by
7987 // virtue e.g. of being constexpr, and it passes these implicit
7988 // attributes on to its specializations.)
7990 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate());
7992 // The "previous declaration" for this function template specialization is
7993 // the prior function template specialization.
7995 Previous.addDecl(Specialization);
7999 /// \brief Perform semantic analysis for the given non-template member
8002 /// This routine performs all of the semantic analysis required for an
8003 /// explicit member function specialization. On successful completion,
8004 /// the function declaration \p FD will become a member function
8007 /// \param Member the member declaration, which will be updated to become a
8010 /// \param Previous the set of declarations, one of which may be specialized
8011 /// by this function specialization; the set will be modified to contain the
8012 /// redeclared member.
8014 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
8015 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
8017 // Try to find the member we are instantiating.
8018 NamedDecl *FoundInstantiation = nullptr;
8019 NamedDecl *Instantiation = nullptr;
8020 NamedDecl *InstantiatedFrom = nullptr;
8021 MemberSpecializationInfo *MSInfo = nullptr;
8023 if (Previous.empty()) {
8024 // Nowhere to look anyway.
8025 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
8026 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8028 NamedDecl *D = (*I)->getUnderlyingDecl();
8029 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
8030 QualType Adjusted = Function->getType();
8031 if (!hasExplicitCallingConv(Adjusted))
8032 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
8033 if (Context.hasSameType(Adjusted, Method->getType())) {
8034 FoundInstantiation = *I;
8035 Instantiation = Method;
8036 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
8037 MSInfo = Method->getMemberSpecializationInfo();
8042 } else if (isa<VarDecl>(Member)) {
8044 if (Previous.isSingleResult() &&
8045 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
8046 if (PrevVar->isStaticDataMember()) {
8047 FoundInstantiation = Previous.getRepresentativeDecl();
8048 Instantiation = PrevVar;
8049 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
8050 MSInfo = PrevVar->getMemberSpecializationInfo();
8052 } else if (isa<RecordDecl>(Member)) {
8053 CXXRecordDecl *PrevRecord;
8054 if (Previous.isSingleResult() &&
8055 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
8056 FoundInstantiation = Previous.getRepresentativeDecl();
8057 Instantiation = PrevRecord;
8058 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
8059 MSInfo = PrevRecord->getMemberSpecializationInfo();
8061 } else if (isa<EnumDecl>(Member)) {
8063 if (Previous.isSingleResult() &&
8064 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
8065 FoundInstantiation = Previous.getRepresentativeDecl();
8066 Instantiation = PrevEnum;
8067 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
8068 MSInfo = PrevEnum->getMemberSpecializationInfo();
8072 if (!Instantiation) {
8073 // There is no previous declaration that matches. Since member
8074 // specializations are always out-of-line, the caller will complain about
8075 // this mismatch later.
8079 // A member specialization in a friend declaration isn't really declaring
8080 // an explicit specialization, just identifying a specific (possibly implicit)
8081 // specialization. Don't change the template specialization kind.
8083 // FIXME: Is this really valid? Other compilers reject.
8084 if (Member->getFriendObjectKind() != Decl::FOK_None) {
8085 // Preserve instantiation information.
8086 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
8087 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
8088 cast<CXXMethodDecl>(InstantiatedFrom),
8089 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
8090 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
8091 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
8092 cast<CXXRecordDecl>(InstantiatedFrom),
8093 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
8097 Previous.addDecl(FoundInstantiation);
8101 // Make sure that this is a specialization of a member.
8102 if (!InstantiatedFrom) {
8103 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
8105 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
8109 // C++ [temp.expl.spec]p6:
8110 // If a template, a member template or the member of a class template is
8111 // explicitly specialized then that specialization shall be declared
8112 // before the first use of that specialization that would cause an implicit
8113 // instantiation to take place, in every translation unit in which such a
8114 // use occurs; no diagnostic is required.
8115 assert(MSInfo && "Member specialization info missing?");
8117 bool HasNoEffect = false;
8118 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
8119 TSK_ExplicitSpecialization,
8121 MSInfo->getTemplateSpecializationKind(),
8122 MSInfo->getPointOfInstantiation(),
8126 // Check the scope of this explicit specialization.
8127 if (CheckTemplateSpecializationScope(*this,
8129 Instantiation, Member->getLocation(),
8133 // Note that this member specialization is an "instantiation of" the
8134 // corresponding member of the original template.
8135 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {
8136 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
8137 if (InstantiationFunction->getTemplateSpecializationKind() ==
8138 TSK_ImplicitInstantiation) {
8139 // Explicit specializations of member functions of class templates do not
8140 // inherit '=delete' from the member function they are specializing.
8141 if (InstantiationFunction->isDeleted()) {
8142 // FIXME: This assert will not hold in the presence of modules.
8143 assert(InstantiationFunction->getCanonicalDecl() ==
8144 InstantiationFunction);
8145 // FIXME: We need an update record for this AST mutation.
8146 InstantiationFunction->setDeletedAsWritten(false);
8150 MemberFunction->setInstantiationOfMemberFunction(
8151 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8152 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {
8153 MemberVar->setInstantiationOfStaticDataMember(
8154 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8155 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {
8156 MemberClass->setInstantiationOfMemberClass(
8157 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8158 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {
8159 MemberEnum->setInstantiationOfMemberEnum(
8160 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
8162 llvm_unreachable("unknown member specialization kind");
8165 // Save the caller the trouble of having to figure out which declaration
8166 // this specialization matches.
8168 Previous.addDecl(FoundInstantiation);
8172 /// Complete the explicit specialization of a member of a class template by
8173 /// updating the instantiated member to be marked as an explicit specialization.
8175 /// \param OrigD The member declaration instantiated from the template.
8176 /// \param Loc The location of the explicit specialization of the member.
8177 template<typename DeclT>
8178 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
8179 SourceLocation Loc) {
8180 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
8183 // FIXME: Inform AST mutation listeners of this AST mutation.
8184 // FIXME: If there are multiple in-class declarations of the member (from
8185 // multiple modules, or a declaration and later definition of a member type),
8186 // should we update all of them?
8187 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
8188 OrigD->setLocation(Loc);
8191 void Sema::CompleteMemberSpecialization(NamedDecl *Member,
8192 LookupResult &Previous) {
8193 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
8194 if (Instantiation == Member)
8197 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
8198 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
8199 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
8200 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
8201 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
8202 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
8203 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
8204 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
8206 llvm_unreachable("unknown member specialization kind");
8209 /// \brief Check the scope of an explicit instantiation.
8211 /// \returns true if a serious error occurs, false otherwise.
8212 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
8213 SourceLocation InstLoc,
8214 bool WasQualifiedName) {
8215 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
8216 DeclContext *CurContext = S.CurContext->getRedeclContext();
8218 if (CurContext->isRecord()) {
8219 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
8224 // C++11 [temp.explicit]p3:
8225 // An explicit instantiation shall appear in an enclosing namespace of its
8226 // template. If the name declared in the explicit instantiation is an
8227 // unqualified name, the explicit instantiation shall appear in the
8228 // namespace where its template is declared or, if that namespace is inline
8229 // (7.3.1), any namespace from its enclosing namespace set.
8231 // This is DR275, which we do not retroactively apply to C++98/03.
8232 if (WasQualifiedName) {
8233 if (CurContext->Encloses(OrigContext))
8236 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
8240 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
8241 if (WasQualifiedName)
8243 S.getLangOpts().CPlusPlus11?
8244 diag::err_explicit_instantiation_out_of_scope :
8245 diag::warn_explicit_instantiation_out_of_scope_0x)
8249 S.getLangOpts().CPlusPlus11?
8250 diag::err_explicit_instantiation_unqualified_wrong_namespace :
8251 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
8255 S.getLangOpts().CPlusPlus11?
8256 diag::err_explicit_instantiation_must_be_global :
8257 diag::warn_explicit_instantiation_must_be_global_0x)
8259 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
8263 /// \brief Determine whether the given scope specifier has a template-id in it.
8264 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
8268 // C++11 [temp.explicit]p3:
8269 // If the explicit instantiation is for a member function, a member class
8270 // or a static data member of a class template specialization, the name of
8271 // the class template specialization in the qualified-id for the member
8272 // name shall be a simple-template-id.
8274 // C++98 has the same restriction, just worded differently.
8275 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
8276 NNS = NNS->getPrefix())
8277 if (const Type *T = NNS->getAsType())
8278 if (isa<TemplateSpecializationType>(T))
8284 /// Make a dllexport or dllimport attr on a class template specialization take
8286 static void dllExportImportClassTemplateSpecialization(
8287 Sema &S, ClassTemplateSpecializationDecl *Def) {
8288 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));
8289 assert(A && "dllExportImportClassTemplateSpecialization called "
8290 "on Def without dllexport or dllimport");
8292 // We reject explicit instantiations in class scope, so there should
8293 // never be any delayed exported classes to worry about.
8294 assert(S.DelayedDllExportClasses.empty() &&
8295 "delayed exports present at explicit instantiation");
8296 S.checkClassLevelDLLAttribute(Def);
8298 // Propagate attribute to base class templates.
8299 for (auto &B : Def->bases()) {
8300 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
8301 B.getType()->getAsCXXRecordDecl()))
8302 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
8305 S.referenceDLLExportedClassMethods();
8308 // Explicit instantiation of a class template specialization
8310 Sema::ActOnExplicitInstantiation(Scope *S,
8311 SourceLocation ExternLoc,
8312 SourceLocation TemplateLoc,
8314 SourceLocation KWLoc,
8315 const CXXScopeSpec &SS,
8316 TemplateTy TemplateD,
8317 SourceLocation TemplateNameLoc,
8318 SourceLocation LAngleLoc,
8319 ASTTemplateArgsPtr TemplateArgsIn,
8320 SourceLocation RAngleLoc,
8321 AttributeList *Attr) {
8322 // Find the class template we're specializing
8323 TemplateName Name = TemplateD.get();
8324 TemplateDecl *TD = Name.getAsTemplateDecl();
8325 // Check that the specialization uses the same tag kind as the
8326 // original template.
8327 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
8328 assert(Kind != TTK_Enum &&
8329 "Invalid enum tag in class template explicit instantiation!");
8331 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);
8333 if (!ClassTemplate) {
8334 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
8335 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;
8336 Diag(TD->getLocation(), diag::note_previous_use);
8340 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
8341 Kind, /*isDefinition*/false, KWLoc,
8342 ClassTemplate->getIdentifier())) {
8343 Diag(KWLoc, diag::err_use_with_wrong_tag)
8345 << FixItHint::CreateReplacement(KWLoc,
8346 ClassTemplate->getTemplatedDecl()->getKindName());
8347 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
8348 diag::note_previous_use);
8349 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8352 // C++0x [temp.explicit]p2:
8353 // There are two forms of explicit instantiation: an explicit instantiation
8354 // definition and an explicit instantiation declaration. An explicit
8355 // instantiation declaration begins with the extern keyword. [...]
8356 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
8357 ? TSK_ExplicitInstantiationDefinition
8358 : TSK_ExplicitInstantiationDeclaration;
8360 if (TSK == TSK_ExplicitInstantiationDeclaration) {
8361 // Check for dllexport class template instantiation declarations.
8362 for (AttributeList *A = Attr; A; A = A->getNext()) {
8363 if (A->getKind() == AttributeList::AT_DLLExport) {
8365 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8366 Diag(A->getLoc(), diag::note_attribute);
8371 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
8373 diag::warn_attribute_dllexport_explicit_instantiation_decl);
8374 Diag(A->getLocation(), diag::note_attribute);
8378 // In MSVC mode, dllimported explicit instantiation definitions are treated as
8379 // instantiation declarations for most purposes.
8380 bool DLLImportExplicitInstantiationDef = false;
8381 if (TSK == TSK_ExplicitInstantiationDefinition &&
8382 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8383 // Check for dllimport class template instantiation definitions.
8385 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
8386 for (AttributeList *A = Attr; A; A = A->getNext()) {
8387 if (A->getKind() == AttributeList::AT_DLLImport)
8389 if (A->getKind() == AttributeList::AT_DLLExport) {
8390 // dllexport trumps dllimport here.
8396 TSK = TSK_ExplicitInstantiationDeclaration;
8397 DLLImportExplicitInstantiationDef = true;
8401 // Translate the parser's template argument list in our AST format.
8402 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
8403 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
8405 // Check that the template argument list is well-formed for this
8407 SmallVector<TemplateArgument, 4> Converted;
8408 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
8409 TemplateArgs, false, Converted))
8412 // Find the class template specialization declaration that
8413 // corresponds to these arguments.
8414 void *InsertPos = nullptr;
8415 ClassTemplateSpecializationDecl *PrevDecl
8416 = ClassTemplate->findSpecialization(Converted, InsertPos);
8418 TemplateSpecializationKind PrevDecl_TSK
8419 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
8421 // C++0x [temp.explicit]p2:
8422 // [...] An explicit instantiation shall appear in an enclosing
8423 // namespace of its template. [...]
8425 // This is C++ DR 275.
8426 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
8430 ClassTemplateSpecializationDecl *Specialization = nullptr;
8432 bool HasNoEffect = false;
8434 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
8435 PrevDecl, PrevDecl_TSK,
8436 PrevDecl->getPointOfInstantiation(),
8440 // Even though HasNoEffect == true means that this explicit instantiation
8441 // has no effect on semantics, we go on to put its syntax in the AST.
8443 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
8444 PrevDecl_TSK == TSK_Undeclared) {
8445 // Since the only prior class template specialization with these
8446 // arguments was referenced but not declared, reuse that
8447 // declaration node as our own, updating the source location
8448 // for the template name to reflect our new declaration.
8449 // (Other source locations will be updated later.)
8450 Specialization = PrevDecl;
8451 Specialization->setLocation(TemplateNameLoc);
8455 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
8456 DLLImportExplicitInstantiationDef) {
8457 // The new specialization might add a dllimport attribute.
8458 HasNoEffect = false;
8462 if (!Specialization) {
8463 // Create a new class template specialization declaration node for
8464 // this explicit specialization.
8466 = ClassTemplateSpecializationDecl::Create(Context, Kind,
8467 ClassTemplate->getDeclContext(),
8468 KWLoc, TemplateNameLoc,
8472 SetNestedNameSpecifier(Specialization, SS);
8474 if (!HasNoEffect && !PrevDecl) {
8475 // Insert the new specialization.
8476 ClassTemplate->AddSpecialization(Specialization, InsertPos);
8480 // Build the fully-sugared type for this explicit instantiation as
8481 // the user wrote in the explicit instantiation itself. This means
8482 // that we'll pretty-print the type retrieved from the
8483 // specialization's declaration the way that the user actually wrote
8484 // the explicit instantiation, rather than formatting the name based
8485 // on the "canonical" representation used to store the template
8486 // arguments in the specialization.
8487 TypeSourceInfo *WrittenTy
8488 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
8490 Context.getTypeDeclType(Specialization));
8491 Specialization->setTypeAsWritten(WrittenTy);
8493 // Set source locations for keywords.
8494 Specialization->setExternLoc(ExternLoc);
8495 Specialization->setTemplateKeywordLoc(TemplateLoc);
8496 Specialization->setBraceRange(SourceRange());
8498 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
8500 ProcessDeclAttributeList(S, Specialization, Attr);
8502 // Add the explicit instantiation into its lexical context. However,
8503 // since explicit instantiations are never found by name lookup, we
8504 // just put it into the declaration context directly.
8505 Specialization->setLexicalDeclContext(CurContext);
8506 CurContext->addDecl(Specialization);
8508 // Syntax is now OK, so return if it has no other effect on semantics.
8510 // Set the template specialization kind.
8511 Specialization->setTemplateSpecializationKind(TSK);
8512 return Specialization;
8515 // C++ [temp.explicit]p3:
8516 // A definition of a class template or class member template
8517 // shall be in scope at the point of the explicit instantiation of
8518 // the class template or class member template.
8520 // This check comes when we actually try to perform the
8522 ClassTemplateSpecializationDecl *Def
8523 = cast_or_null<ClassTemplateSpecializationDecl>(
8524 Specialization->getDefinition());
8526 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
8527 else if (TSK == TSK_ExplicitInstantiationDefinition) {
8528 MarkVTableUsed(TemplateNameLoc, Specialization, true);
8529 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
8532 // Instantiate the members of this class template specialization.
8533 Def = cast_or_null<ClassTemplateSpecializationDecl>(
8534 Specialization->getDefinition());
8536 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
8537 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
8538 // TSK_ExplicitInstantiationDefinition
8539 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
8540 (TSK == TSK_ExplicitInstantiationDefinition ||
8541 DLLImportExplicitInstantiationDef)) {
8542 // FIXME: Need to notify the ASTMutationListener that we did this.
8543 Def->setTemplateSpecializationKind(TSK);
8545 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
8546 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8547 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8548 // In the MS ABI, an explicit instantiation definition can add a dll
8549 // attribute to a template with a previous instantiation declaration.
8550 // MinGW doesn't allow this.
8551 auto *A = cast<InheritableAttr>(
8552 getDLLAttr(Specialization)->clone(getASTContext()));
8553 A->setInherited(true);
8555 dllExportImportClassTemplateSpecialization(*this, Def);
8559 // Fix a TSK_ImplicitInstantiation followed by a
8560 // TSK_ExplicitInstantiationDefinition
8561 bool NewlyDLLExported =
8562 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
8563 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
8564 (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
8565 Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())) {
8566 // In the MS ABI, an explicit instantiation definition can add a dll
8567 // attribute to a template with a previous implicit instantiation.
8568 // MinGW doesn't allow this. We limit clang to only adding dllexport, to
8569 // avoid potentially strange codegen behavior. For example, if we extend
8570 // this conditional to dllimport, and we have a source file calling a
8571 // method on an implicitly instantiated template class instance and then
8572 // declaring a dllimport explicit instantiation definition for the same
8573 // template class, the codegen for the method call will not respect the
8574 // dllimport, while it will with cl. The Def will already have the DLL
8575 // attribute, since the Def and Specialization will be the same in the
8576 // case of Old_TSK == TSK_ImplicitInstantiation, and we already added the
8577 // attribute to the Specialization; we just need to make it take effect.
8578 assert(Def == Specialization &&
8579 "Def and Specialization should match for implicit instantiation");
8580 dllExportImportClassTemplateSpecialization(*this, Def);
8583 // Set the template specialization kind. Make sure it is set before
8584 // instantiating the members which will trigger ASTConsumer callbacks.
8585 Specialization->setTemplateSpecializationKind(TSK);
8586 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
8589 // Set the template specialization kind.
8590 Specialization->setTemplateSpecializationKind(TSK);
8593 return Specialization;
8596 // Explicit instantiation of a member class of a class template.
8598 Sema::ActOnExplicitInstantiation(Scope *S,
8599 SourceLocation ExternLoc,
8600 SourceLocation TemplateLoc,
8602 SourceLocation KWLoc,
8604 IdentifierInfo *Name,
8605 SourceLocation NameLoc,
8606 AttributeList *Attr) {
8609 bool IsDependent = false;
8610 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
8611 KWLoc, SS, Name, NameLoc, Attr, AS_none,
8612 /*ModulePrivateLoc=*/SourceLocation(),
8613 MultiTemplateParamsArg(), Owned, IsDependent,
8614 SourceLocation(), false, TypeResult(),
8615 /*IsTypeSpecifier*/false);
8616 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
8621 TagDecl *Tag = cast<TagDecl>(TagD);
8622 assert(!Tag->isEnum() && "shouldn't see enumerations here");
8624 if (Tag->isInvalidDecl())
8627 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
8628 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
8630 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
8631 << Context.getTypeDeclType(Record);
8632 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
8636 // C++0x [temp.explicit]p2:
8637 // If the explicit instantiation is for a class or member class, the
8638 // elaborated-type-specifier in the declaration shall include a
8639 // simple-template-id.
8641 // C++98 has the same restriction, just worded differently.
8642 if (!ScopeSpecifierHasTemplateId(SS))
8643 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
8644 << Record << SS.getRange();
8646 // C++0x [temp.explicit]p2:
8647 // There are two forms of explicit instantiation: an explicit instantiation
8648 // definition and an explicit instantiation declaration. An explicit
8649 // instantiation declaration begins with the extern keyword. [...]
8650 TemplateSpecializationKind TSK
8651 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8652 : TSK_ExplicitInstantiationDeclaration;
8654 // C++0x [temp.explicit]p2:
8655 // [...] An explicit instantiation shall appear in an enclosing
8656 // namespace of its template. [...]
8658 // This is C++ DR 275.
8659 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
8661 // Verify that it is okay to explicitly instantiate here.
8662 CXXRecordDecl *PrevDecl
8663 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
8664 if (!PrevDecl && Record->getDefinition())
8667 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
8668 bool HasNoEffect = false;
8669 assert(MSInfo && "No member specialization information?");
8670 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
8672 MSInfo->getTemplateSpecializationKind(),
8673 MSInfo->getPointOfInstantiation(),
8680 CXXRecordDecl *RecordDef
8681 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8683 // C++ [temp.explicit]p3:
8684 // A definition of a member class of a class template shall be in scope
8685 // at the point of an explicit instantiation of the member class.
8687 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
8689 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
8690 << 0 << Record->getDeclName() << Record->getDeclContext();
8691 Diag(Pattern->getLocation(), diag::note_forward_declaration)
8695 if (InstantiateClass(NameLoc, Record, Def,
8696 getTemplateInstantiationArgs(Record),
8700 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
8706 // Instantiate all of the members of the class.
8707 InstantiateClassMembers(NameLoc, RecordDef,
8708 getTemplateInstantiationArgs(Record), TSK);
8710 if (TSK == TSK_ExplicitInstantiationDefinition)
8711 MarkVTableUsed(NameLoc, RecordDef, true);
8713 // FIXME: We don't have any representation for explicit instantiations of
8714 // member classes. Such a representation is not needed for compilation, but it
8715 // should be available for clients that want to see all of the declarations in
8720 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
8721 SourceLocation ExternLoc,
8722 SourceLocation TemplateLoc,
8724 // Explicit instantiations always require a name.
8725 // TODO: check if/when DNInfo should replace Name.
8726 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8727 DeclarationName Name = NameInfo.getName();
8729 if (!D.isInvalidType())
8730 Diag(D.getDeclSpec().getLocStart(),
8731 diag::err_explicit_instantiation_requires_name)
8732 << D.getDeclSpec().getSourceRange()
8733 << D.getSourceRange();
8738 // The scope passed in may not be a decl scope. Zip up the scope tree until
8739 // we find one that is.
8740 while ((S->getFlags() & Scope::DeclScope) == 0 ||
8741 (S->getFlags() & Scope::TemplateParamScope) != 0)
8744 // Determine the type of the declaration.
8745 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
8746 QualType R = T->getType();
8751 // A storage-class-specifier shall not be specified in [...] an explicit
8752 // instantiation (14.7.2) directive.
8753 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
8754 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
8757 } else if (D.getDeclSpec().getStorageClassSpec()
8758 != DeclSpec::SCS_unspecified) {
8759 // Complain about then remove the storage class specifier.
8760 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
8761 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8763 D.getMutableDeclSpec().ClearStorageClassSpecs();
8766 // C++0x [temp.explicit]p1:
8767 // [...] An explicit instantiation of a function template shall not use the
8768 // inline or constexpr specifiers.
8769 // Presumably, this also applies to member functions of class templates as
8771 if (D.getDeclSpec().isInlineSpecified())
8772 Diag(D.getDeclSpec().getInlineSpecLoc(),
8773 getLangOpts().CPlusPlus11 ?
8774 diag::err_explicit_instantiation_inline :
8775 diag::warn_explicit_instantiation_inline_0x)
8776 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8777 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
8778 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
8779 // not already specified.
8780 Diag(D.getDeclSpec().getConstexprSpecLoc(),
8781 diag::err_explicit_instantiation_constexpr);
8783 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8784 // applied only to the definition of a function template or variable template,
8785 // declared in namespace scope.
8786 if (D.getDeclSpec().isConceptSpecified()) {
8787 Diag(D.getDeclSpec().getConceptSpecLoc(),
8788 diag::err_concept_specified_specialization) << 0;
8792 // A deduction guide is not on the list of entities that can be explicitly
8794 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8795 Diag(D.getDeclSpec().getLocStart(), diag::err_deduction_guide_specialized)
8796 << /*explicit instantiation*/ 0;
8800 // C++0x [temp.explicit]p2:
8801 // There are two forms of explicit instantiation: an explicit instantiation
8802 // definition and an explicit instantiation declaration. An explicit
8803 // instantiation declaration begins with the extern keyword. [...]
8804 TemplateSpecializationKind TSK
8805 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
8806 : TSK_ExplicitInstantiationDeclaration;
8808 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
8809 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
8811 if (!R->isFunctionType()) {
8812 // C++ [temp.explicit]p1:
8813 // A [...] static data member of a class template can be explicitly
8814 // instantiated from the member definition associated with its class
8816 // C++1y [temp.explicit]p1:
8817 // A [...] variable [...] template specialization can be explicitly
8818 // instantiated from its template.
8819 if (Previous.isAmbiguous())
8822 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
8823 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
8825 if (!PrevTemplate) {
8826 if (!Prev || !Prev->isStaticDataMember()) {
8827 // We expect to see a data data member here.
8828 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
8830 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8832 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
8836 if (!Prev->getInstantiatedFromStaticDataMember()) {
8837 // FIXME: Check for explicit specialization?
8838 Diag(D.getIdentifierLoc(),
8839 diag::err_explicit_instantiation_data_member_not_instantiated)
8841 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
8842 // FIXME: Can we provide a note showing where this was declared?
8846 // Explicitly instantiate a variable template.
8848 // C++1y [dcl.spec.auto]p6:
8849 // ... A program that uses auto or decltype(auto) in a context not
8850 // explicitly allowed in this section is ill-formed.
8852 // This includes auto-typed variable template instantiations.
8853 if (R->isUndeducedType()) {
8854 Diag(T->getTypeLoc().getLocStart(),
8855 diag::err_auto_not_allowed_var_inst);
8859 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8860 // C++1y [temp.explicit]p3:
8861 // If the explicit instantiation is for a variable, the unqualified-id
8862 // in the declaration shall be a template-id.
8863 Diag(D.getIdentifierLoc(),
8864 diag::err_explicit_instantiation_without_template_id)
8866 Diag(PrevTemplate->getLocation(),
8867 diag::note_explicit_instantiation_here);
8871 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
8872 // explicit instantiation (14.8.2) [...] of a concept definition.
8873 if (PrevTemplate->isConcept()) {
8874 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
8875 << 1 /*variable*/ << 0 /*explicitly instantiated*/;
8876 Diag(PrevTemplate->getLocation(), diag::note_previous_declaration);
8880 // Translate the parser's template argument list into our AST format.
8881 TemplateArgumentListInfo TemplateArgs =
8882 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
8884 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
8885 D.getIdentifierLoc(), TemplateArgs);
8886 if (Res.isInvalid())
8889 // Ignore access control bits, we don't need them for redeclaration
8891 Prev = cast<VarDecl>(Res.get());
8894 // C++0x [temp.explicit]p2:
8895 // If the explicit instantiation is for a member function, a member class
8896 // or a static data member of a class template specialization, the name of
8897 // the class template specialization in the qualified-id for the member
8898 // name shall be a simple-template-id.
8900 // C++98 has the same restriction, just worded differently.
8902 // This does not apply to variable template specializations, where the
8903 // template-id is in the unqualified-id instead.
8904 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
8905 Diag(D.getIdentifierLoc(),
8906 diag::ext_explicit_instantiation_without_qualified_id)
8907 << Prev << D.getCXXScopeSpec().getRange();
8909 // Check the scope of this explicit instantiation.
8910 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
8912 // Verify that it is okay to explicitly instantiate here.
8913 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
8914 SourceLocation POI = Prev->getPointOfInstantiation();
8915 bool HasNoEffect = false;
8916 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
8917 PrevTSK, POI, HasNoEffect))
8921 // Instantiate static data member or variable template.
8923 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
8925 // Merge attributes.
8926 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
8927 ProcessDeclAttributeList(S, Prev, Attr);
8929 if (TSK == TSK_ExplicitInstantiationDefinition)
8930 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
8933 // Check the new variable specialization against the parsed input.
8934 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
8935 Diag(T->getTypeLoc().getLocStart(),
8936 diag::err_invalid_var_template_spec_type)
8937 << 0 << PrevTemplate << R << Prev->getType();
8938 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
8939 << 2 << PrevTemplate->getDeclName();
8943 // FIXME: Create an ExplicitInstantiation node?
8944 return (Decl*) nullptr;
8947 // If the declarator is a template-id, translate the parser's template
8948 // argument list into our AST format.
8949 bool HasExplicitTemplateArgs = false;
8950 TemplateArgumentListInfo TemplateArgs;
8951 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8952 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
8953 HasExplicitTemplateArgs = true;
8956 // C++ [temp.explicit]p1:
8957 // A [...] function [...] can be explicitly instantiated from its template.
8958 // A member function [...] of a class template can be explicitly
8959 // instantiated from the member definition associated with its class
8961 UnresolvedSet<8> TemplateMatches;
8962 FunctionDecl *NonTemplateMatch = nullptr;
8963 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
8964 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
8965 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
8967 NamedDecl *Prev = *P;
8968 if (!HasExplicitTemplateArgs) {
8969 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
8970 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),
8971 /*AdjustExceptionSpec*/true);
8972 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
8973 if (Method->getPrimaryTemplate()) {
8974 TemplateMatches.addDecl(Method, P.getAccess());
8976 // FIXME: Can this assert ever happen? Needs a test.
8977 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
8978 NonTemplateMatch = Method;
8984 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
8988 TemplateDeductionInfo Info(FailedCandidates.getLocation());
8989 FunctionDecl *Specialization = nullptr;
8990 if (TemplateDeductionResult TDK
8991 = DeduceTemplateArguments(FunTmpl,
8992 (HasExplicitTemplateArgs ? &TemplateArgs
8994 R, Specialization, Info)) {
8995 // Keep track of almost-matches.
8996 FailedCandidates.addCandidate()
8997 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
8998 MakeDeductionFailureInfo(Context, TDK, Info));
9003 // Target attributes are part of the cuda function signature, so
9004 // the cuda target of the instantiated function must match that of its
9005 // template. Given that C++ template deduction does not take
9006 // target attributes into account, we reject candidates here that
9007 // have a different target.
9008 if (LangOpts.CUDA &&
9009 IdentifyCUDATarget(Specialization,
9010 /* IgnoreImplicitHDAttributes = */ true) !=
9011 IdentifyCUDATarget(Attr)) {
9012 FailedCandidates.addCandidate().set(
9013 P.getPair(), FunTmpl->getTemplatedDecl(),
9014 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info));
9018 TemplateMatches.addDecl(Specialization, P.getAccess());
9021 FunctionDecl *Specialization = NonTemplateMatch;
9022 if (!Specialization) {
9023 // Find the most specialized function template specialization.
9024 UnresolvedSetIterator Result = getMostSpecialized(
9025 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
9026 D.getIdentifierLoc(),
9027 PDiag(diag::err_explicit_instantiation_not_known) << Name,
9028 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
9029 PDiag(diag::note_explicit_instantiation_candidate));
9031 if (Result == TemplateMatches.end())
9034 // Ignore access control bits, we don't need them for redeclaration checking.
9035 Specialization = cast<FunctionDecl>(*Result);
9038 // C++11 [except.spec]p4
9039 // In an explicit instantiation an exception-specification may be specified,
9040 // but is not required.
9041 // If an exception-specification is specified in an explicit instantiation
9042 // directive, it shall be compatible with the exception-specifications of
9043 // other declarations of that function.
9044 if (auto *FPT = R->getAs<FunctionProtoType>())
9045 if (FPT->hasExceptionSpec()) {
9047 diag::err_mismatched_exception_spec_explicit_instantiation;
9048 if (getLangOpts().MicrosoftExt)
9049 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
9050 bool Result = CheckEquivalentExceptionSpec(
9051 PDiag(DiagID) << Specialization->getType(),
9052 PDiag(diag::note_explicit_instantiation_here),
9053 Specialization->getType()->getAs<FunctionProtoType>(),
9054 Specialization->getLocation(), FPT, D.getLocStart());
9055 // In Microsoft mode, mismatching exception specifications just cause a
9057 if (!getLangOpts().MicrosoftExt && Result)
9061 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
9062 Diag(D.getIdentifierLoc(),
9063 diag::err_explicit_instantiation_member_function_not_instantiated)
9065 << (Specialization->getTemplateSpecializationKind() ==
9066 TSK_ExplicitSpecialization);
9067 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
9071 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
9072 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
9073 PrevDecl = Specialization;
9076 bool HasNoEffect = false;
9077 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
9079 PrevDecl->getTemplateSpecializationKind(),
9080 PrevDecl->getPointOfInstantiation(),
9084 // FIXME: We may still want to build some representation of this
9085 // explicit specialization.
9087 return (Decl*) nullptr;
9090 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
9092 ProcessDeclAttributeList(S, Specialization, Attr);
9094 if (Specialization->isDefined()) {
9095 // Let the ASTConsumer know that this function has been explicitly
9096 // instantiated now, and its linkage might have changed.
9097 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
9098 } else if (TSK == TSK_ExplicitInstantiationDefinition)
9099 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
9101 // C++0x [temp.explicit]p2:
9102 // If the explicit instantiation is for a member function, a member class
9103 // or a static data member of a class template specialization, the name of
9104 // the class template specialization in the qualified-id for the member
9105 // name shall be a simple-template-id.
9107 // C++98 has the same restriction, just worded differently.
9108 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
9109 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
9110 D.getCXXScopeSpec().isSet() &&
9111 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
9112 Diag(D.getIdentifierLoc(),
9113 diag::ext_explicit_instantiation_without_qualified_id)
9114 << Specialization << D.getCXXScopeSpec().getRange();
9116 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare an
9117 // explicit instantiation (14.8.2) [...] of a concept definition.
9118 if (FunTmpl && FunTmpl->isConcept() &&
9119 !D.getDeclSpec().isConceptSpecified()) {
9120 Diag(D.getIdentifierLoc(), diag::err_concept_specialized)
9121 << 0 /*function*/ << 0 /*explicitly instantiated*/;
9122 Diag(FunTmpl->getLocation(), diag::note_previous_declaration);
9126 CheckExplicitInstantiationScope(*this,
9127 FunTmpl? (NamedDecl *)FunTmpl
9128 : Specialization->getInstantiatedFromMemberFunction(),
9129 D.getIdentifierLoc(),
9130 D.getCXXScopeSpec().isSet());
9132 // FIXME: Create some kind of ExplicitInstantiationDecl here.
9133 return (Decl*) nullptr;
9137 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
9138 const CXXScopeSpec &SS, IdentifierInfo *Name,
9139 SourceLocation TagLoc, SourceLocation NameLoc) {
9140 // This has to hold, because SS is expected to be defined.
9141 assert(Name && "Expected a name in a dependent tag");
9143 NestedNameSpecifier *NNS = SS.getScopeRep();
9147 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
9149 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
9150 Diag(NameLoc, diag::err_dependent_tag_decl)
9151 << (TUK == TUK_Definition) << Kind << SS.getRange();
9155 // Create the resulting type.
9156 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
9157 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
9159 // Create type-source location information for this type.
9161 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
9162 TL.setElaboratedKeywordLoc(TagLoc);
9163 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9164 TL.setNameLoc(NameLoc);
9165 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
9169 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
9170 const CXXScopeSpec &SS, const IdentifierInfo &II,
9171 SourceLocation IdLoc) {
9175 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9177 getLangOpts().CPlusPlus11 ?
9178 diag::warn_cxx98_compat_typename_outside_of_template :
9179 diag::ext_typename_outside_of_template)
9180 << FixItHint::CreateRemoval(TypenameLoc);
9182 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9183 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
9184 TypenameLoc, QualifierLoc, II, IdLoc);
9188 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
9189 if (isa<DependentNameType>(T)) {
9190 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
9191 TL.setElaboratedKeywordLoc(TypenameLoc);
9192 TL.setQualifierLoc(QualifierLoc);
9193 TL.setNameLoc(IdLoc);
9195 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
9196 TL.setElaboratedKeywordLoc(TypenameLoc);
9197 TL.setQualifierLoc(QualifierLoc);
9198 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
9201 return CreateParsedType(T, TSI);
9205 Sema::ActOnTypenameType(Scope *S,
9206 SourceLocation TypenameLoc,
9207 const CXXScopeSpec &SS,
9208 SourceLocation TemplateKWLoc,
9209 TemplateTy TemplateIn,
9210 IdentifierInfo *TemplateII,
9211 SourceLocation TemplateIILoc,
9212 SourceLocation LAngleLoc,
9213 ASTTemplateArgsPtr TemplateArgsIn,
9214 SourceLocation RAngleLoc) {
9215 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
9217 getLangOpts().CPlusPlus11 ?
9218 diag::warn_cxx98_compat_typename_outside_of_template :
9219 diag::ext_typename_outside_of_template)
9220 << FixItHint::CreateRemoval(TypenameLoc);
9222 // Strangely, non-type results are not ignored by this lookup, so the
9223 // program is ill-formed if it finds an injected-class-name.
9224 if (TypenameLoc.isValid()) {
9226 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));
9227 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
9229 diag::ext_out_of_line_qualified_id_type_names_constructor)
9230 << TemplateII << 0 /*injected-class-name used as template name*/
9231 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
9235 // Translate the parser's template argument list in our AST format.
9236 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
9237 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
9239 TemplateName Template = TemplateIn.get();
9240 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
9241 // Construct a dependent template specialization type.
9242 assert(DTN && "dependent template has non-dependent name?");
9243 assert(DTN->getQualifier() == SS.getScopeRep());
9244 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
9245 DTN->getQualifier(),
9246 DTN->getIdentifier(),
9249 // Create source-location information for this type.
9250 TypeLocBuilder Builder;
9251 DependentTemplateSpecializationTypeLoc SpecTL
9252 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
9253 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
9254 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
9255 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9256 SpecTL.setTemplateNameLoc(TemplateIILoc);
9257 SpecTL.setLAngleLoc(LAngleLoc);
9258 SpecTL.setRAngleLoc(RAngleLoc);
9259 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9260 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9261 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
9264 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
9268 // Provide source-location information for the template specialization type.
9269 TypeLocBuilder Builder;
9270 TemplateSpecializationTypeLoc SpecTL
9271 = Builder.push<TemplateSpecializationTypeLoc>(T);
9272 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
9273 SpecTL.setTemplateNameLoc(TemplateIILoc);
9274 SpecTL.setLAngleLoc(LAngleLoc);
9275 SpecTL.setRAngleLoc(RAngleLoc);
9276 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9277 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
9279 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
9280 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
9281 TL.setElaboratedKeywordLoc(TypenameLoc);
9282 TL.setQualifierLoc(SS.getWithLocInContext(Context));
9284 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
9285 return CreateParsedType(T, TSI);
9289 /// Determine whether this failed name lookup should be treated as being
9290 /// disabled by a usage of std::enable_if.
9291 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
9292 SourceRange &CondRange) {
9293 // We must be looking for a ::type...
9294 if (!II.isStr("type"))
9297 // ... within an explicitly-written template specialization...
9298 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
9300 TypeLoc EnableIfTy = NNS.getTypeLoc();
9301 TemplateSpecializationTypeLoc EnableIfTSTLoc =
9302 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
9303 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
9305 const TemplateSpecializationType *EnableIfTST =
9306 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
9308 // ... which names a complete class template declaration...
9309 const TemplateDecl *EnableIfDecl =
9310 EnableIfTST->getTemplateName().getAsTemplateDecl();
9311 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
9314 // ... called "enable_if".
9315 const IdentifierInfo *EnableIfII =
9316 EnableIfDecl->getDeclName().getAsIdentifierInfo();
9317 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
9320 // Assume the first template argument is the condition.
9321 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
9325 /// \brief Build the type that describes a C++ typename specifier,
9326 /// e.g., "typename T::type".
9328 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
9329 SourceLocation KeywordLoc,
9330 NestedNameSpecifierLoc QualifierLoc,
9331 const IdentifierInfo &II,
9332 SourceLocation IILoc) {
9334 SS.Adopt(QualifierLoc);
9336 DeclContext *Ctx = computeDeclContext(SS);
9338 // If the nested-name-specifier is dependent and couldn't be
9339 // resolved to a type, build a typename type.
9340 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
9341 return Context.getDependentNameType(Keyword,
9342 QualifierLoc.getNestedNameSpecifier(),
9346 // If the nested-name-specifier refers to the current instantiation,
9347 // the "typename" keyword itself is superfluous. In C++03, the
9348 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
9349 // allows such extraneous "typename" keywords, and we retroactively
9350 // apply this DR to C++03 code with only a warning. In any case we continue.
9352 if (RequireCompleteDeclContext(SS, Ctx))
9355 DeclarationName Name(&II);
9356 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
9357 LookupQualifiedName(Result, Ctx, SS);
9358 unsigned DiagID = 0;
9359 Decl *Referenced = nullptr;
9360 switch (Result.getResultKind()) {
9361 case LookupResult::NotFound: {
9362 // If we're looking up 'type' within a template named 'enable_if', produce
9363 // a more specific diagnostic.
9364 SourceRange CondRange;
9365 if (isEnableIf(QualifierLoc, II, CondRange)) {
9366 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
9367 << Ctx << CondRange;
9371 DiagID = diag::err_typename_nested_not_found;
9375 case LookupResult::FoundUnresolvedValue: {
9376 // We found a using declaration that is a value. Most likely, the using
9377 // declaration itself is meant to have the 'typename' keyword.
9378 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9380 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
9381 << Name << Ctx << FullRange;
9382 if (UnresolvedUsingValueDecl *Using
9383 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
9384 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
9385 Diag(Loc, diag::note_using_value_decl_missing_typename)
9386 << FixItHint::CreateInsertion(Loc, "typename ");
9389 // Fall through to create a dependent typename type, from which we can recover
9393 case LookupResult::NotFoundInCurrentInstantiation:
9394 // Okay, it's a member of an unknown instantiation.
9395 return Context.getDependentNameType(Keyword,
9396 QualifierLoc.getNestedNameSpecifier(),
9399 case LookupResult::Found:
9400 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
9401 // C++ [class.qual]p2:
9402 // In a lookup in which function names are not ignored and the
9403 // nested-name-specifier nominates a class C, if the name specified
9404 // after the nested-name-specifier, when looked up in C, is the
9405 // injected-class-name of C [...] then the name is instead considered
9406 // to name the constructor of class C.
9408 // Unlike in an elaborated-type-specifier, function names are not ignored
9409 // in typename-specifier lookup. However, they are ignored in all the
9410 // contexts where we form a typename type with no keyword (that is, in
9411 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
9413 // FIXME: That's not strictly true: mem-initializer-id lookup does not
9414 // ignore functions, but that appears to be an oversight.
9415 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx);
9416 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type);
9417 if (Keyword == ETK_Typename && LookupRD && FoundRD &&
9418 FoundRD->isInjectedClassName() &&
9419 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
9420 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
9421 << &II << 1 << 0 /*'typename' keyword used*/;
9423 // We found a type. Build an ElaboratedType, since the
9424 // typename-specifier was just sugar.
9425 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
9426 return Context.getElaboratedType(Keyword,
9427 QualifierLoc.getNestedNameSpecifier(),
9428 Context.getTypeDeclType(Type));
9431 // C++ [dcl.type.simple]p2:
9432 // A type-specifier of the form
9433 // typename[opt] nested-name-specifier[opt] template-name
9434 // is a placeholder for a deduced class type [...].
9435 if (getLangOpts().CPlusPlus1z) {
9436 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
9437 return Context.getElaboratedType(
9438 Keyword, QualifierLoc.getNestedNameSpecifier(),
9439 Context.getDeducedTemplateSpecializationType(TemplateName(TD),
9440 QualType(), false));
9444 DiagID = diag::err_typename_nested_not_type;
9445 Referenced = Result.getFoundDecl();
9448 case LookupResult::FoundOverloaded:
9449 DiagID = diag::err_typename_nested_not_type;
9450 Referenced = *Result.begin();
9453 case LookupResult::Ambiguous:
9457 // If we get here, it's because name lookup did not find a
9458 // type. Emit an appropriate diagnostic and return an error.
9459 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
9461 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
9463 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
9469 // See Sema::RebuildTypeInCurrentInstantiation
9470 class CurrentInstantiationRebuilder
9471 : public TreeTransform<CurrentInstantiationRebuilder> {
9473 DeclarationName Entity;
9476 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
9478 CurrentInstantiationRebuilder(Sema &SemaRef,
9480 DeclarationName Entity)
9481 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
9482 Loc(Loc), Entity(Entity) { }
9484 /// \brief Determine whether the given type \p T has already been
9487 /// For the purposes of type reconstruction, a type has already been
9488 /// transformed if it is NULL or if it is not dependent.
9489 bool AlreadyTransformed(QualType T) {
9490 return T.isNull() || !T->isDependentType();
9493 /// \brief Returns the location of the entity whose type is being
9495 SourceLocation getBaseLocation() { return Loc; }
9497 /// \brief Returns the name of the entity whose type is being rebuilt.
9498 DeclarationName getBaseEntity() { return Entity; }
9500 /// \brief Sets the "base" location and entity when that
9501 /// information is known based on another transformation.
9502 void setBase(SourceLocation Loc, DeclarationName Entity) {
9504 this->Entity = Entity;
9507 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9508 // Lambdas never need to be transformed.
9512 } // end anonymous namespace
9514 /// \brief Rebuilds a type within the context of the current instantiation.
9516 /// The type \p T is part of the type of an out-of-line member definition of
9517 /// a class template (or class template partial specialization) that was parsed
9518 /// and constructed before we entered the scope of the class template (or
9519 /// partial specialization thereof). This routine will rebuild that type now
9520 /// that we have entered the declarator's scope, which may produce different
9521 /// canonical types, e.g.,
9524 /// template<typename T>
9526 /// typedef T* pointer;
9530 /// template<typename T>
9531 /// typename X<T>::pointer X<T>::data() { ... }
9534 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
9535 /// since we do not know that we can look into X<T> when we parsed the type.
9536 /// This function will rebuild the type, performing the lookup of "pointer"
9537 /// in X<T> and returning an ElaboratedType whose canonical type is the same
9538 /// as the canonical type of T*, allowing the return types of the out-of-line
9539 /// definition and the declaration to match.
9540 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
9542 DeclarationName Name) {
9543 if (!T || !T->getType()->isDependentType())
9546 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
9547 return Rebuilder.TransformType(T);
9550 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
9551 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
9553 return Rebuilder.TransformExpr(E);
9556 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
9560 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9561 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
9563 NestedNameSpecifierLoc Rebuilt
9564 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
9572 /// \brief Rebuild the template parameters now that we know we're in a current
9574 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
9575 TemplateParameterList *Params) {
9576 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9577 Decl *Param = Params->getParam(I);
9579 // There is nothing to rebuild in a type parameter.
9580 if (isa<TemplateTypeParmDecl>(Param))
9583 // Rebuild the template parameter list of a template template parameter.
9584 if (TemplateTemplateParmDecl *TTP
9585 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
9586 if (RebuildTemplateParamsInCurrentInstantiation(
9587 TTP->getTemplateParameters()))
9593 // Rebuild the type of a non-type template parameter.
9594 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
9595 TypeSourceInfo *NewTSI
9596 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
9597 NTTP->getLocation(),
9598 NTTP->getDeclName());
9602 if (NewTSI != NTTP->getTypeSourceInfo()) {
9603 NTTP->setTypeSourceInfo(NewTSI);
9604 NTTP->setType(NewTSI->getType());
9611 /// \brief Produces a formatted string that describes the binding of
9612 /// template parameters to template arguments.
9614 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9615 const TemplateArgumentList &Args) {
9616 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
9620 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
9621 const TemplateArgument *Args,
9623 SmallString<128> Str;
9624 llvm::raw_svector_ostream Out(Str);
9626 if (!Params || Params->size() == 0 || NumArgs == 0)
9627 return std::string();
9629 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
9638 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
9639 Out << Id->getName();
9645 Args[I].print(getPrintingPolicy(), Out);
9652 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
9653 CachedTokens &Toks) {
9657 auto LPT = llvm::make_unique<LateParsedTemplate>();
9659 // Take tokens to avoid allocations
9660 LPT->Toks.swap(Toks);
9662 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));
9664 FD->setLateTemplateParsed(true);
9667 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
9670 FD->setLateTemplateParsed(false);
9673 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
9674 DeclContext *DC = CurContext;
9677 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
9678 const FunctionDecl *FD = RD->isLocalClass();
9679 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
9680 } else if (DC->isTranslationUnit() || DC->isNamespace())
9683 DC = DC->getParent();
9689 /// \brief Walk the path from which a declaration was instantiated, and check
9690 /// that every explicit specialization along that path is visible. This enforces
9691 /// C++ [temp.expl.spec]/6:
9693 /// If a template, a member template or a member of a class template is
9694 /// explicitly specialized then that specialization shall be declared before
9695 /// the first use of that specialization that would cause an implicit
9696 /// instantiation to take place, in every translation unit in which such a
9697 /// use occurs; no diagnostic is required.
9699 /// and also C++ [temp.class.spec]/1:
9701 /// A partial specialization shall be declared before the first use of a
9702 /// class template specialization that would make use of the partial
9703 /// specialization as the result of an implicit or explicit instantiation
9704 /// in every translation unit in which such a use occurs; no diagnostic is
9706 class ExplicitSpecializationVisibilityChecker {
9709 llvm::SmallVector<Module *, 8> Modules;
9712 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc)
9715 void check(NamedDecl *ND) {
9716 if (auto *FD = dyn_cast<FunctionDecl>(ND))
9717 return checkImpl(FD);
9718 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))
9719 return checkImpl(RD);
9720 if (auto *VD = dyn_cast<VarDecl>(ND))
9721 return checkImpl(VD);
9722 if (auto *ED = dyn_cast<EnumDecl>(ND))
9723 return checkImpl(ED);
9727 void diagnose(NamedDecl *D, bool IsPartialSpec) {
9728 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
9729 : Sema::MissingImportKind::ExplicitSpecialization;
9730 const bool Recover = true;
9732 // If we got a custom set of modules (because only a subset of the
9733 // declarations are interesting), use them, otherwise let
9734 // diagnoseMissingImport intelligently pick some.
9735 if (Modules.empty())
9736 S.diagnoseMissingImport(Loc, D, Kind, Recover);
9738 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
9741 // Check a specific declaration. There are three problematic cases:
9743 // 1) The declaration is an explicit specialization of a template
9745 // 2) The declaration is an explicit specialization of a member of an
9747 // 3) The declaration is an instantiation of a template, and that template
9748 // is an explicit specialization of a member of a templated class.
9750 // We don't need to go any deeper than that, as the instantiation of the
9751 // surrounding class / etc is not triggered by whatever triggered this
9752 // instantiation, and thus should be checked elsewhere.
9753 template<typename SpecDecl>
9754 void checkImpl(SpecDecl *Spec) {
9755 bool IsHiddenExplicitSpecialization = false;
9756 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
9757 IsHiddenExplicitSpecialization =
9758 Spec->getMemberSpecializationInfo()
9759 ? !S.hasVisibleMemberSpecialization(Spec, &Modules)
9760 : !S.hasVisibleExplicitSpecialization(Spec, &Modules);
9762 checkInstantiated(Spec);
9765 if (IsHiddenExplicitSpecialization)
9766 diagnose(Spec->getMostRecentDecl(), false);
9769 void checkInstantiated(FunctionDecl *FD) {
9770 if (auto *TD = FD->getPrimaryTemplate())
9774 void checkInstantiated(CXXRecordDecl *RD) {
9775 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);
9779 auto From = SD->getSpecializedTemplateOrPartial();
9780 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
9783 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
9784 if (!S.hasVisibleDeclaration(TD))
9790 void checkInstantiated(VarDecl *RD) {
9791 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);
9795 auto From = SD->getSpecializedTemplateOrPartial();
9796 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
9799 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
9800 if (!S.hasVisibleDeclaration(TD))
9806 void checkInstantiated(EnumDecl *FD) {}
9808 template<typename TemplDecl>
9809 void checkTemplate(TemplDecl *TD) {
9810 if (TD->isMemberSpecialization()) {
9811 if (!S.hasVisibleMemberSpecialization(TD, &Modules))
9812 diagnose(TD->getMostRecentDecl(), false);
9816 } // end anonymous namespace
9818 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
9819 if (!getLangOpts().Modules)
9822 ExplicitSpecializationVisibilityChecker(*this, Loc).check(Spec);
9825 /// \brief Check whether a template partial specialization that we've discovered
9826 /// is hidden, and produce suitable diagnostics if so.
9827 void Sema::checkPartialSpecializationVisibility(SourceLocation Loc,
9829 llvm::SmallVector<Module *, 8> Modules;
9830 if (!hasVisibleDeclaration(Spec, &Modules))
9831 diagnoseMissingImport(Loc, Spec, Spec->getLocation(), Modules,
9832 MissingImportKind::PartialSpecialization,