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/LangOptions.h"
22 #include "clang/Basic/PartialDiagnostic.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Sema/DeclSpec.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/ParsedTemplate.h"
27 #include "clang/Sema/Scope.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/SmallBitVector.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/StringExtras.h"
34 using namespace clang;
37 // Exported for use by Parser.
39 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
41 if (!N) return SourceRange();
42 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
45 /// \brief Determine whether the declaration found is acceptable as the name
46 /// of a template and, if so, return that template declaration. Otherwise,
48 static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
50 bool AllowFunctionTemplates) {
51 NamedDecl *D = Orig->getUnderlyingDecl();
53 if (isa<TemplateDecl>(D)) {
54 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
60 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
61 // C++ [temp.local]p1:
62 // Like normal (non-template) classes, class templates have an
63 // injected-class-name (Clause 9). The injected-class-name
64 // can be used with or without a template-argument-list. When
65 // it is used without a template-argument-list, it is
66 // equivalent to the injected-class-name followed by the
67 // template-parameters of the class template enclosed in
68 // <>. When it is used with a template-argument-list, it
69 // refers to the specified class template specialization,
70 // which could be the current specialization or another
72 if (Record->isInjectedClassName()) {
73 Record = cast<CXXRecordDecl>(Record->getDeclContext());
74 if (Record->getDescribedClassTemplate())
75 return Record->getDescribedClassTemplate();
77 if (ClassTemplateSpecializationDecl *Spec
78 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
79 return Spec->getSpecializedTemplate();
88 void Sema::FilterAcceptableTemplateNames(LookupResult &R,
89 bool AllowFunctionTemplates) {
90 // The set of class templates we've already seen.
91 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
92 LookupResult::Filter filter = R.makeFilter();
93 while (filter.hasNext()) {
94 NamedDecl *Orig = filter.next();
95 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig,
96 AllowFunctionTemplates);
99 else if (Repl != Orig) {
101 // C++ [temp.local]p3:
102 // A lookup that finds an injected-class-name (10.2) can result in an
103 // ambiguity in certain cases (for example, if it is found in more than
104 // one base class). If all of the injected-class-names that are found
105 // refer to specializations of the same class template, and if the name
106 // is used as a template-name, the reference refers to the class
107 // template itself and not a specialization thereof, and is not
109 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
110 if (!ClassTemplates.insert(ClassTmpl).second) {
115 // FIXME: we promote access to public here as a workaround to
116 // the fact that LookupResult doesn't let us remember that we
117 // found this template through a particular injected class name,
118 // which means we end up doing nasty things to the invariants.
119 // Pretending that access is public is *much* safer.
120 filter.replace(Repl, AS_public);
126 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
127 bool AllowFunctionTemplates) {
128 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
129 if (isAcceptableTemplateName(Context, *I, AllowFunctionTemplates))
135 TemplateNameKind Sema::isTemplateName(Scope *S,
137 bool hasTemplateKeyword,
139 ParsedType ObjectTypePtr,
140 bool EnteringContext,
141 TemplateTy &TemplateResult,
142 bool &MemberOfUnknownSpecialization) {
143 assert(getLangOpts().CPlusPlus && "No template names in C!");
145 DeclarationName TName;
146 MemberOfUnknownSpecialization = false;
148 switch (Name.getKind()) {
149 case UnqualifiedId::IK_Identifier:
150 TName = DeclarationName(Name.Identifier);
153 case UnqualifiedId::IK_OperatorFunctionId:
154 TName = Context.DeclarationNames.getCXXOperatorName(
155 Name.OperatorFunctionId.Operator);
158 case UnqualifiedId::IK_LiteralOperatorId:
159 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
163 return TNK_Non_template;
166 QualType ObjectType = ObjectTypePtr.get();
168 LookupResult R(*this, TName, Name.getLocStart(), LookupOrdinaryName);
169 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
170 MemberOfUnknownSpecialization);
171 if (R.empty()) return TNK_Non_template;
172 if (R.isAmbiguous()) {
173 // Suppress diagnostics; we'll redo this lookup later.
174 R.suppressDiagnostics();
176 // FIXME: we might have ambiguous templates, in which case we
177 // should at least parse them properly!
178 return TNK_Non_template;
181 TemplateName Template;
182 TemplateNameKind TemplateKind;
184 unsigned ResultCount = R.end() - R.begin();
185 if (ResultCount > 1) {
186 // We assume that we'll preserve the qualifier from a function
187 // template name in other ways.
188 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
189 TemplateKind = TNK_Function_template;
191 // We'll do this lookup again later.
192 R.suppressDiagnostics();
194 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
196 if (SS.isSet() && !SS.isInvalid()) {
197 NestedNameSpecifier *Qualifier = SS.getScopeRep();
198 Template = Context.getQualifiedTemplateName(Qualifier,
199 hasTemplateKeyword, TD);
201 Template = TemplateName(TD);
204 if (isa<FunctionTemplateDecl>(TD)) {
205 TemplateKind = TNK_Function_template;
207 // We'll do this lookup again later.
208 R.suppressDiagnostics();
210 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
211 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD));
213 isa<VarTemplateDecl>(TD) ? TNK_Var_template : TNK_Type_template;
217 TemplateResult = TemplateTy::make(Template);
221 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
222 SourceLocation IILoc,
224 const CXXScopeSpec *SS,
225 TemplateTy &SuggestedTemplate,
226 TemplateNameKind &SuggestedKind) {
227 // We can't recover unless there's a dependent scope specifier preceding the
229 // FIXME: Typo correction?
230 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
231 computeDeclContext(*SS))
234 // The code is missing a 'template' keyword prior to the dependent template
236 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
237 Diag(IILoc, diag::err_template_kw_missing)
238 << Qualifier << II.getName()
239 << FixItHint::CreateInsertion(IILoc, "template ");
241 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
242 SuggestedKind = TNK_Dependent_template_name;
246 void Sema::LookupTemplateName(LookupResult &Found,
247 Scope *S, CXXScopeSpec &SS,
249 bool EnteringContext,
250 bool &MemberOfUnknownSpecialization) {
251 // Determine where to perform name lookup
252 MemberOfUnknownSpecialization = false;
253 DeclContext *LookupCtx = nullptr;
254 bool isDependent = false;
255 if (!ObjectType.isNull()) {
256 // This nested-name-specifier occurs in a member access expression, e.g.,
257 // x->B::f, and we are looking into the type of the object.
258 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
259 LookupCtx = computeDeclContext(ObjectType);
260 isDependent = ObjectType->isDependentType();
261 assert((isDependent || !ObjectType->isIncompleteType() ||
262 ObjectType->castAs<TagType>()->isBeingDefined()) &&
263 "Caller should have completed object type");
265 // Template names cannot appear inside an Objective-C class or object type.
266 if (ObjectType->isObjCObjectOrInterfaceType()) {
270 } else if (SS.isSet()) {
271 // This nested-name-specifier occurs after another nested-name-specifier,
272 // so long into the context associated with the prior nested-name-specifier.
273 LookupCtx = computeDeclContext(SS, EnteringContext);
274 isDependent = isDependentScopeSpecifier(SS);
276 // The declaration context must be complete.
277 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
281 bool ObjectTypeSearchedInScope = false;
282 bool AllowFunctionTemplatesInLookup = true;
284 // Perform "qualified" name lookup into the declaration context we
285 // computed, which is either the type of the base of a member access
286 // expression or the declaration context associated with a prior
287 // nested-name-specifier.
288 LookupQualifiedName(Found, LookupCtx);
289 if (!ObjectType.isNull() && Found.empty()) {
290 // C++ [basic.lookup.classref]p1:
291 // In a class member access expression (5.2.5), if the . or -> token is
292 // immediately followed by an identifier followed by a <, the
293 // identifier must be looked up to determine whether the < is the
294 // beginning of a template argument list (14.2) or a less-than operator.
295 // The identifier is first looked up in the class of the object
296 // expression. If the identifier is not found, it is then looked up in
297 // the context of the entire postfix-expression and shall name a class
298 // or function template.
299 if (S) LookupName(Found, S);
300 ObjectTypeSearchedInScope = true;
301 AllowFunctionTemplatesInLookup = false;
303 } else if (isDependent && (!S || ObjectType.isNull())) {
304 // We cannot look into a dependent object type or nested nme
306 MemberOfUnknownSpecialization = true;
309 // Perform unqualified name lookup in the current scope.
310 LookupName(Found, S);
312 if (!ObjectType.isNull())
313 AllowFunctionTemplatesInLookup = false;
316 if (Found.empty() && !isDependent) {
317 // If we did not find any names, attempt to correct any typos.
318 DeclarationName Name = Found.getLookupName();
320 // Simple filter callback that, for keywords, only accepts the C++ *_cast
321 auto FilterCCC = llvm::make_unique<CorrectionCandidateCallback>();
322 FilterCCC->WantTypeSpecifiers = false;
323 FilterCCC->WantExpressionKeywords = false;
324 FilterCCC->WantRemainingKeywords = false;
325 FilterCCC->WantCXXNamedCasts = true;
326 if (TypoCorrection Corrected = CorrectTypo(
327 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS,
328 std::move(FilterCCC), CTK_ErrorRecovery, LookupCtx)) {
329 Found.setLookupName(Corrected.getCorrection());
330 if (Corrected.getCorrectionDecl())
331 Found.addDecl(Corrected.getCorrectionDecl());
332 FilterAcceptableTemplateNames(Found);
333 if (!Found.empty()) {
335 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
336 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
337 Name.getAsString() == CorrectedStr;
338 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
339 << Name << LookupCtx << DroppedSpecifier
342 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
346 Found.setLookupName(Name);
350 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
353 MemberOfUnknownSpecialization = true;
357 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
358 !getLangOpts().CPlusPlus11) {
359 // C++03 [basic.lookup.classref]p1:
360 // [...] If the lookup in the class of the object expression finds a
361 // template, the name is also looked up in the context of the entire
362 // postfix-expression and [...]
364 // Note: C++11 does not perform this second lookup.
365 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
367 LookupName(FoundOuter, S);
368 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
370 if (FoundOuter.empty()) {
371 // - if the name is not found, the name found in the class of the
372 // object expression is used, otherwise
373 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
374 FoundOuter.isAmbiguous()) {
375 // - if the name is found in the context of the entire
376 // postfix-expression and does not name a class template, the name
377 // found in the class of the object expression is used, otherwise
379 } else if (!Found.isSuppressingDiagnostics()) {
380 // - if the name found is a class template, it must refer to the same
381 // entity as the one found in the class of the object expression,
382 // otherwise the program is ill-formed.
383 if (!Found.isSingleResult() ||
384 Found.getFoundDecl()->getCanonicalDecl()
385 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
386 Diag(Found.getNameLoc(),
387 diag::ext_nested_name_member_ref_lookup_ambiguous)
388 << Found.getLookupName()
390 Diag(Found.getRepresentativeDecl()->getLocation(),
391 diag::note_ambig_member_ref_object_type)
393 Diag(FoundOuter.getFoundDecl()->getLocation(),
394 diag::note_ambig_member_ref_scope);
396 // Recover by taking the template that we found in the object
397 // expression's type.
403 /// ActOnDependentIdExpression - Handle a dependent id-expression that
404 /// was just parsed. This is only possible with an explicit scope
405 /// specifier naming a dependent type.
407 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
408 SourceLocation TemplateKWLoc,
409 const DeclarationNameInfo &NameInfo,
410 bool isAddressOfOperand,
411 const TemplateArgumentListInfo *TemplateArgs) {
412 DeclContext *DC = getFunctionLevelDeclContext();
414 if (!isAddressOfOperand &&
415 isa<CXXMethodDecl>(DC) &&
416 cast<CXXMethodDecl>(DC)->isInstance()) {
417 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
419 // Since the 'this' expression is synthesized, we don't need to
420 // perform the double-lookup check.
421 NamedDecl *FirstQualifierInScope = nullptr;
423 return CXXDependentScopeMemberExpr::Create(
424 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
425 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
426 FirstQualifierInScope, NameInfo, TemplateArgs);
429 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
433 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
434 SourceLocation TemplateKWLoc,
435 const DeclarationNameInfo &NameInfo,
436 const TemplateArgumentListInfo *TemplateArgs) {
437 return DependentScopeDeclRefExpr::Create(
438 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
442 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
443 /// that the template parameter 'PrevDecl' is being shadowed by a new
444 /// declaration at location Loc. Returns true to indicate that this is
445 /// an error, and false otherwise.
446 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
447 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
449 // Microsoft Visual C++ permits template parameters to be shadowed.
450 if (getLangOpts().MicrosoftExt)
453 // C++ [temp.local]p4:
454 // A template-parameter shall not be redeclared within its
455 // scope (including nested scopes).
456 Diag(Loc, diag::err_template_param_shadow)
457 << cast<NamedDecl>(PrevDecl)->getDeclName();
458 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
462 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
463 /// the parameter D to reference the templated declaration and return a pointer
464 /// to the template declaration. Otherwise, do nothing to D and return null.
465 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
466 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
467 D = Temp->getTemplatedDecl();
473 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
474 SourceLocation EllipsisLoc) const {
475 assert(Kind == Template &&
476 "Only template template arguments can be pack expansions here");
477 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
478 "Template template argument pack expansion without packs");
479 ParsedTemplateArgument Result(*this);
480 Result.EllipsisLoc = EllipsisLoc;
484 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
485 const ParsedTemplateArgument &Arg) {
487 switch (Arg.getKind()) {
488 case ParsedTemplateArgument::Type: {
490 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
492 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
493 return TemplateArgumentLoc(TemplateArgument(T), DI);
496 case ParsedTemplateArgument::NonType: {
497 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
498 return TemplateArgumentLoc(TemplateArgument(E), E);
501 case ParsedTemplateArgument::Template: {
502 TemplateName Template = Arg.getAsTemplate().get();
503 TemplateArgument TArg;
504 if (Arg.getEllipsisLoc().isValid())
505 TArg = TemplateArgument(Template, Optional<unsigned int>());
508 return TemplateArgumentLoc(TArg,
509 Arg.getScopeSpec().getWithLocInContext(
512 Arg.getEllipsisLoc());
516 llvm_unreachable("Unhandled parsed template argument");
519 /// \brief Translates template arguments as provided by the parser
520 /// into template arguments used by semantic analysis.
521 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
522 TemplateArgumentListInfo &TemplateArgs) {
523 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
524 TemplateArgs.addArgument(translateTemplateArgument(*this,
528 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
530 IdentifierInfo *Name) {
531 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
532 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
533 if (PrevDecl && PrevDecl->isTemplateParameter())
534 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
537 /// ActOnTypeParameter - Called when a C++ template type parameter
538 /// (e.g., "typename T") has been parsed. Typename specifies whether
539 /// the keyword "typename" was used to declare the type parameter
540 /// (otherwise, "class" was used), and KeyLoc is the location of the
541 /// "class" or "typename" keyword. ParamName is the name of the
542 /// parameter (NULL indicates an unnamed template parameter) and
543 /// ParamNameLoc is the location of the parameter name (if any).
544 /// If the type parameter has a default argument, it will be added
545 /// later via ActOnTypeParameterDefault.
546 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
547 SourceLocation EllipsisLoc,
548 SourceLocation KeyLoc,
549 IdentifierInfo *ParamName,
550 SourceLocation ParamNameLoc,
551 unsigned Depth, unsigned Position,
552 SourceLocation EqualLoc,
553 ParsedType DefaultArg) {
554 assert(S->isTemplateParamScope() &&
555 "Template type parameter not in template parameter scope!");
556 bool Invalid = false;
558 SourceLocation Loc = ParamNameLoc;
562 bool IsParameterPack = EllipsisLoc.isValid();
563 TemplateTypeParmDecl *Param
564 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
565 KeyLoc, Loc, Depth, Position, ParamName,
566 Typename, IsParameterPack);
567 Param->setAccess(AS_public);
569 Param->setInvalidDecl();
572 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
574 // Add the template parameter into the current scope.
576 IdResolver.AddDecl(Param);
579 // C++0x [temp.param]p9:
580 // A default template-argument may be specified for any kind of
581 // template-parameter that is not a template parameter pack.
582 if (DefaultArg && IsParameterPack) {
583 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
584 DefaultArg = ParsedType();
587 // Handle the default argument, if provided.
589 TypeSourceInfo *DefaultTInfo;
590 GetTypeFromParser(DefaultArg, &DefaultTInfo);
592 assert(DefaultTInfo && "expected source information for type");
594 // Check for unexpanded parameter packs.
595 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
596 UPPC_DefaultArgument))
599 // Check the template argument itself.
600 if (CheckTemplateArgument(Param, DefaultTInfo)) {
601 Param->setInvalidDecl();
605 Param->setDefaultArgument(DefaultTInfo);
611 /// \brief Check that the type of a non-type template parameter is
614 /// \returns the (possibly-promoted) parameter type if valid;
615 /// otherwise, produces a diagnostic and returns a NULL type.
617 Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
618 // We don't allow variably-modified types as the type of non-type template
620 if (T->isVariablyModifiedType()) {
621 Diag(Loc, diag::err_variably_modified_nontype_template_param)
626 // C++ [temp.param]p4:
628 // A non-type template-parameter shall have one of the following
629 // (optionally cv-qualified) types:
631 // -- integral or enumeration type,
632 if (T->isIntegralOrEnumerationType() ||
633 // -- pointer to object or pointer to function,
634 T->isPointerType() ||
635 // -- reference to object or reference to function,
636 T->isReferenceType() ||
637 // -- pointer to member,
638 T->isMemberPointerType() ||
639 // -- std::nullptr_t.
640 T->isNullPtrType() ||
641 // If T is a dependent type, we can't do the check now, so we
642 // assume that it is well-formed.
643 T->isDependentType()) {
644 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
645 // are ignored when determining its type.
646 return T.getUnqualifiedType();
649 // C++ [temp.param]p8:
651 // A non-type template-parameter of type "array of T" or
652 // "function returning T" is adjusted to be of type "pointer to
653 // T" or "pointer to function returning T", respectively.
654 else if (T->isArrayType() || T->isFunctionType())
655 return Context.getDecayedType(T);
657 Diag(Loc, diag::err_template_nontype_parm_bad_type)
663 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
666 SourceLocation EqualLoc,
668 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
669 QualType T = TInfo->getType();
671 assert(S->isTemplateParamScope() &&
672 "Non-type template parameter not in template parameter scope!");
673 bool Invalid = false;
675 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
677 T = Context.IntTy; // Recover with an 'int' type.
681 IdentifierInfo *ParamName = D.getIdentifier();
682 bool IsParameterPack = D.hasEllipsis();
683 NonTypeTemplateParmDecl *Param
684 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
686 D.getIdentifierLoc(),
687 Depth, Position, ParamName, T,
688 IsParameterPack, TInfo);
689 Param->setAccess(AS_public);
692 Param->setInvalidDecl();
695 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
698 // Add the template parameter into the current scope.
700 IdResolver.AddDecl(Param);
703 // C++0x [temp.param]p9:
704 // A default template-argument may be specified for any kind of
705 // template-parameter that is not a template parameter pack.
706 if (Default && IsParameterPack) {
707 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
711 // Check the well-formedness of the default template argument, if provided.
713 // Check for unexpanded parameter packs.
714 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
717 TemplateArgument Converted;
718 ExprResult DefaultRes =
719 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
720 if (DefaultRes.isInvalid()) {
721 Param->setInvalidDecl();
724 Default = DefaultRes.get();
726 Param->setDefaultArgument(Default);
732 /// ActOnTemplateTemplateParameter - Called when a C++ template template
733 /// parameter (e.g. T in template <template \<typename> class T> class array)
734 /// has been parsed. S is the current scope.
735 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
736 SourceLocation TmpLoc,
737 TemplateParameterList *Params,
738 SourceLocation EllipsisLoc,
739 IdentifierInfo *Name,
740 SourceLocation NameLoc,
743 SourceLocation EqualLoc,
744 ParsedTemplateArgument Default) {
745 assert(S->isTemplateParamScope() &&
746 "Template template parameter not in template parameter scope!");
748 // Construct the parameter object.
749 bool IsParameterPack = EllipsisLoc.isValid();
750 TemplateTemplateParmDecl *Param =
751 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
752 NameLoc.isInvalid()? TmpLoc : NameLoc,
753 Depth, Position, IsParameterPack,
755 Param->setAccess(AS_public);
757 // If the template template parameter has a name, then link the identifier
758 // into the scope and lookup mechanisms.
760 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
763 IdResolver.AddDecl(Param);
766 if (Params->size() == 0) {
767 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
768 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
769 Param->setInvalidDecl();
772 // C++0x [temp.param]p9:
773 // A default template-argument may be specified for any kind of
774 // template-parameter that is not a template parameter pack.
775 if (IsParameterPack && !Default.isInvalid()) {
776 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
777 Default = ParsedTemplateArgument();
780 if (!Default.isInvalid()) {
781 // Check only that we have a template template argument. We don't want to
782 // try to check well-formedness now, because our template template parameter
783 // might have dependent types in its template parameters, which we wouldn't
784 // be able to match now.
786 // If none of the template template parameter's template arguments mention
787 // other template parameters, we could actually perform more checking here.
788 // However, it isn't worth doing.
789 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
790 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
791 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
792 << DefaultArg.getSourceRange();
796 // Check for unexpanded parameter packs.
797 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
798 DefaultArg.getArgument().getAsTemplate(),
799 UPPC_DefaultArgument))
802 Param->setDefaultArgument(Context, DefaultArg);
808 /// ActOnTemplateParameterList - Builds a TemplateParameterList that
809 /// contains the template parameters in Params/NumParams.
810 TemplateParameterList *
811 Sema::ActOnTemplateParameterList(unsigned Depth,
812 SourceLocation ExportLoc,
813 SourceLocation TemplateLoc,
814 SourceLocation LAngleLoc,
815 Decl **Params, unsigned NumParams,
816 SourceLocation RAngleLoc) {
817 if (ExportLoc.isValid())
818 Diag(ExportLoc, diag::warn_template_export_unsupported);
820 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
821 (NamedDecl**)Params, NumParams,
825 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
827 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
831 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
832 SourceLocation KWLoc, CXXScopeSpec &SS,
833 IdentifierInfo *Name, SourceLocation NameLoc,
835 TemplateParameterList *TemplateParams,
836 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
837 SourceLocation FriendLoc,
838 unsigned NumOuterTemplateParamLists,
839 TemplateParameterList** OuterTemplateParamLists,
840 SkipBodyInfo *SkipBody) {
841 assert(TemplateParams && TemplateParams->size() > 0 &&
842 "No template parameters");
843 assert(TUK != TUK_Reference && "Can only declare or define class templates");
844 bool Invalid = false;
846 // Check that we can declare a template here.
847 if (CheckTemplateDeclScope(S, TemplateParams))
850 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
851 assert(Kind != TTK_Enum && "can't build template of enumerated type");
853 // There is no such thing as an unnamed class template.
855 Diag(KWLoc, diag::err_template_unnamed_class);
859 // Find any previous declaration with this name. For a friend with no
860 // scope explicitly specified, we only look for tag declarations (per
861 // C++11 [basic.lookup.elab]p2).
862 DeclContext *SemanticContext;
863 LookupResult Previous(*this, Name, NameLoc,
864 (SS.isEmpty() && TUK == TUK_Friend)
865 ? LookupTagName : LookupOrdinaryName,
867 if (SS.isNotEmpty() && !SS.isInvalid()) {
868 SemanticContext = computeDeclContext(SS, true);
869 if (!SemanticContext) {
870 // FIXME: Horrible, horrible hack! We can't currently represent this
871 // in the AST, and historically we have just ignored such friend
872 // class templates, so don't complain here.
873 Diag(NameLoc, TUK == TUK_Friend
874 ? diag::warn_template_qualified_friend_ignored
875 : diag::err_template_qualified_declarator_no_match)
876 << SS.getScopeRep() << SS.getRange();
877 return TUK != TUK_Friend;
880 if (RequireCompleteDeclContext(SS, SemanticContext))
883 // If we're adding a template to a dependent context, we may need to
884 // rebuilding some of the types used within the template parameter list,
885 // now that we know what the current instantiation is.
886 if (SemanticContext->isDependentContext()) {
887 ContextRAII SavedContext(*this, SemanticContext);
888 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
890 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
891 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
893 LookupQualifiedName(Previous, SemanticContext);
895 SemanticContext = CurContext;
896 LookupName(Previous, S);
899 if (Previous.isAmbiguous())
902 NamedDecl *PrevDecl = nullptr;
903 if (Previous.begin() != Previous.end())
904 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
906 // If there is a previous declaration with the same name, check
907 // whether this is a valid redeclaration.
908 ClassTemplateDecl *PrevClassTemplate
909 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
911 // We may have found the injected-class-name of a class template,
912 // class template partial specialization, or class template specialization.
913 // In these cases, grab the template that is being defined or specialized.
914 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
915 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
916 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
918 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
919 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
921 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
922 ->getSpecializedTemplate();
926 if (TUK == TUK_Friend) {
927 // C++ [namespace.memdef]p3:
928 // [...] When looking for a prior declaration of a class or a function
929 // declared as a friend, and when the name of the friend class or
930 // function is neither a qualified name nor a template-id, scopes outside
931 // the innermost enclosing namespace scope are not considered.
933 DeclContext *OutermostContext = CurContext;
934 while (!OutermostContext->isFileContext())
935 OutermostContext = OutermostContext->getLookupParent();
938 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
939 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
940 SemanticContext = PrevDecl->getDeclContext();
942 // Declarations in outer scopes don't matter. However, the outermost
943 // context we computed is the semantic context for our new
945 PrevDecl = PrevClassTemplate = nullptr;
946 SemanticContext = OutermostContext;
948 // Check that the chosen semantic context doesn't already contain a
949 // declaration of this name as a non-tag type.
950 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
952 DeclContext *LookupContext = SemanticContext;
953 while (LookupContext->isTransparentContext())
954 LookupContext = LookupContext->getLookupParent();
955 LookupQualifiedName(Previous, LookupContext);
957 if (Previous.isAmbiguous())
960 if (Previous.begin() != Previous.end())
961 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
964 } else if (PrevDecl &&
965 !isDeclInScope(PrevDecl, SemanticContext, S, SS.isValid()))
966 PrevDecl = PrevClassTemplate = nullptr;
968 if (PrevClassTemplate) {
969 // Ensure that the template parameter lists are compatible. Skip this check
970 // for a friend in a dependent context: the template parameter list itself
971 // could be dependent.
972 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
973 !TemplateParameterListsAreEqual(TemplateParams,
974 PrevClassTemplate->getTemplateParameters(),
979 // C++ [temp.class]p4:
980 // In a redeclaration, partial specialization, explicit
981 // specialization or explicit instantiation of a class template,
982 // the class-key shall agree in kind with the original class
983 // template declaration (7.1.5.3).
984 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
985 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
986 TUK == TUK_Definition, KWLoc, *Name)) {
987 Diag(KWLoc, diag::err_use_with_wrong_tag)
989 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
990 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
991 Kind = PrevRecordDecl->getTagKind();
994 // Check for redefinition of this class template.
995 if (TUK == TUK_Definition) {
996 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
997 // If we have a prior definition that is not visible, treat this as
998 // simply making that previous definition visible.
999 NamedDecl *Hidden = nullptr;
1000 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1001 SkipBody->ShouldSkip = true;
1002 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1003 assert(Tmpl && "original definition of a class template is not a "
1005 makeMergedDefinitionVisible(Hidden, KWLoc);
1006 makeMergedDefinitionVisible(Tmpl, KWLoc);
1010 Diag(NameLoc, diag::err_redefinition) << Name;
1011 Diag(Def->getLocation(), diag::note_previous_definition);
1012 // FIXME: Would it make sense to try to "forget" the previous
1013 // definition, as part of error recovery?
1017 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1018 // Maybe we will complain about the shadowed template parameter.
1019 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1020 // Just pretend that we didn't see the previous declaration.
1022 } else if (PrevDecl) {
1024 // A class template shall not have the same name as any other
1025 // template, class, function, object, enumeration, enumerator,
1026 // namespace, or type in the same scope (3.3), except as specified
1028 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1029 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1033 // Check the template parameter list of this declaration, possibly
1034 // merging in the template parameter list from the previous class
1035 // template declaration. Skip this check for a friend in a dependent
1036 // context, because the template parameter list might be dependent.
1037 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1038 CheckTemplateParameterList(
1040 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1042 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1043 SemanticContext->isDependentContext())
1044 ? TPC_ClassTemplateMember
1045 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1046 : TPC_ClassTemplate))
1050 // If the name of the template was qualified, we must be defining the
1051 // template out-of-line.
1052 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1053 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1054 : diag::err_member_decl_does_not_match)
1055 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1060 CXXRecordDecl *NewClass =
1061 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1063 PrevClassTemplate->getTemplatedDecl() : nullptr,
1064 /*DelayTypeCreation=*/true);
1065 SetNestedNameSpecifier(NewClass, SS);
1066 if (NumOuterTemplateParamLists > 0)
1067 NewClass->setTemplateParameterListsInfo(Context,
1068 NumOuterTemplateParamLists,
1069 OuterTemplateParamLists);
1071 // Add alignment attributes if necessary; these attributes are checked when
1072 // the ASTContext lays out the structure.
1073 if (TUK == TUK_Definition) {
1074 AddAlignmentAttributesForRecord(NewClass);
1075 AddMsStructLayoutForRecord(NewClass);
1078 ClassTemplateDecl *NewTemplate
1079 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1080 DeclarationName(Name), TemplateParams,
1081 NewClass, PrevClassTemplate);
1082 NewClass->setDescribedClassTemplate(NewTemplate);
1084 if (ModulePrivateLoc.isValid())
1085 NewTemplate->setModulePrivate();
1087 // Build the type for the class template declaration now.
1088 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1089 T = Context.getInjectedClassNameType(NewClass, T);
1090 assert(T->isDependentType() && "Class template type is not dependent?");
1093 // If we are providing an explicit specialization of a member that is a
1094 // class template, make a note of that.
1095 if (PrevClassTemplate &&
1096 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1097 PrevClassTemplate->setMemberSpecialization();
1099 // Set the access specifier.
1100 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1101 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1103 // Set the lexical context of these templates
1104 NewClass->setLexicalDeclContext(CurContext);
1105 NewTemplate->setLexicalDeclContext(CurContext);
1107 if (TUK == TUK_Definition)
1108 NewClass->startDefinition();
1111 ProcessDeclAttributeList(S, NewClass, Attr);
1113 if (PrevClassTemplate)
1114 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1116 AddPushedVisibilityAttribute(NewClass);
1118 if (TUK != TUK_Friend) {
1119 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
1121 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
1122 Outer = Outer->getParent();
1123 PushOnScopeChains(NewTemplate, Outer);
1125 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1126 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1127 NewClass->setAccess(PrevClassTemplate->getAccess());
1130 NewTemplate->setObjectOfFriendDecl();
1132 // Friend templates are visible in fairly strange ways.
1133 if (!CurContext->isDependentContext()) {
1134 DeclContext *DC = SemanticContext->getRedeclContext();
1135 DC->makeDeclVisibleInContext(NewTemplate);
1136 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1137 PushOnScopeChains(NewTemplate, EnclosingScope,
1138 /* AddToContext = */ false);
1141 FriendDecl *Friend = FriendDecl::Create(
1142 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1143 Friend->setAccess(AS_public);
1144 CurContext->addDecl(Friend);
1148 NewTemplate->setInvalidDecl();
1149 NewClass->setInvalidDecl();
1152 ActOnDocumentableDecl(NewTemplate);
1157 /// \brief Diagnose the presence of a default template argument on a
1158 /// template parameter, which is ill-formed in certain contexts.
1160 /// \returns true if the default template argument should be dropped.
1161 static bool DiagnoseDefaultTemplateArgument(Sema &S,
1162 Sema::TemplateParamListContext TPC,
1163 SourceLocation ParamLoc,
1164 SourceRange DefArgRange) {
1166 case Sema::TPC_ClassTemplate:
1167 case Sema::TPC_VarTemplate:
1168 case Sema::TPC_TypeAliasTemplate:
1171 case Sema::TPC_FunctionTemplate:
1172 case Sema::TPC_FriendFunctionTemplateDefinition:
1173 // C++ [temp.param]p9:
1174 // A default template-argument shall not be specified in a
1175 // function template declaration or a function template
1177 // If a friend function template declaration specifies a default
1178 // template-argument, that declaration shall be a definition and shall be
1179 // the only declaration of the function template in the translation unit.
1180 // (C++98/03 doesn't have this wording; see DR226).
1181 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1182 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1183 : diag::ext_template_parameter_default_in_function_template)
1187 case Sema::TPC_ClassTemplateMember:
1188 // C++0x [temp.param]p9:
1189 // A default template-argument shall not be specified in the
1190 // template-parameter-lists of the definition of a member of a
1191 // class template that appears outside of the member's class.
1192 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1196 case Sema::TPC_FriendClassTemplate:
1197 case Sema::TPC_FriendFunctionTemplate:
1198 // C++ [temp.param]p9:
1199 // A default template-argument shall not be specified in a
1200 // friend template declaration.
1201 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1205 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1206 // for friend function templates if there is only a single
1207 // declaration (and it is a definition). Strange!
1210 llvm_unreachable("Invalid TemplateParamListContext!");
1213 /// \brief Check for unexpanded parameter packs within the template parameters
1214 /// of a template template parameter, recursively.
1215 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1216 TemplateTemplateParmDecl *TTP) {
1217 // A template template parameter which is a parameter pack is also a pack
1219 if (TTP->isParameterPack())
1222 TemplateParameterList *Params = TTP->getTemplateParameters();
1223 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1224 NamedDecl *P = Params->getParam(I);
1225 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1226 if (!NTTP->isParameterPack() &&
1227 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1228 NTTP->getTypeSourceInfo(),
1229 Sema::UPPC_NonTypeTemplateParameterType))
1235 if (TemplateTemplateParmDecl *InnerTTP
1236 = dyn_cast<TemplateTemplateParmDecl>(P))
1237 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1244 /// \brief Checks the validity of a template parameter list, possibly
1245 /// considering the template parameter list from a previous
1248 /// If an "old" template parameter list is provided, it must be
1249 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1250 /// template parameter list.
1252 /// \param NewParams Template parameter list for a new template
1253 /// declaration. This template parameter list will be updated with any
1254 /// default arguments that are carried through from the previous
1255 /// template parameter list.
1257 /// \param OldParams If provided, template parameter list from a
1258 /// previous declaration of the same template. Default template
1259 /// arguments will be merged from the old template parameter list to
1260 /// the new template parameter list.
1262 /// \param TPC Describes the context in which we are checking the given
1263 /// template parameter list.
1265 /// \returns true if an error occurred, false otherwise.
1266 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1267 TemplateParameterList *OldParams,
1268 TemplateParamListContext TPC) {
1269 bool Invalid = false;
1271 // C++ [temp.param]p10:
1272 // The set of default template-arguments available for use with a
1273 // template declaration or definition is obtained by merging the
1274 // default arguments from the definition (if in scope) and all
1275 // declarations in scope in the same way default function
1276 // arguments are (8.3.6).
1277 bool SawDefaultArgument = false;
1278 SourceLocation PreviousDefaultArgLoc;
1280 // Dummy initialization to avoid warnings.
1281 TemplateParameterList::iterator OldParam = NewParams->end();
1283 OldParam = OldParams->begin();
1285 bool RemoveDefaultArguments = false;
1286 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1287 NewParamEnd = NewParams->end();
1288 NewParam != NewParamEnd; ++NewParam) {
1289 // Variables used to diagnose redundant default arguments
1290 bool RedundantDefaultArg = false;
1291 SourceLocation OldDefaultLoc;
1292 SourceLocation NewDefaultLoc;
1294 // Variable used to diagnose missing default arguments
1295 bool MissingDefaultArg = false;
1297 // Variable used to diagnose non-final parameter packs
1298 bool SawParameterPack = false;
1300 if (TemplateTypeParmDecl *NewTypeParm
1301 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1302 // Check the presence of a default argument here.
1303 if (NewTypeParm->hasDefaultArgument() &&
1304 DiagnoseDefaultTemplateArgument(*this, TPC,
1305 NewTypeParm->getLocation(),
1306 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1308 NewTypeParm->removeDefaultArgument();
1310 // Merge default arguments for template type parameters.
1311 TemplateTypeParmDecl *OldTypeParm
1312 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
1313 if (NewTypeParm->isParameterPack()) {
1314 assert(!NewTypeParm->hasDefaultArgument() &&
1315 "Parameter packs can't have a default argument!");
1316 SawParameterPack = true;
1317 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
1318 NewTypeParm->hasDefaultArgument()) {
1319 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1320 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1321 SawDefaultArgument = true;
1322 RedundantDefaultArg = true;
1323 PreviousDefaultArgLoc = NewDefaultLoc;
1324 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1325 // Merge the default argument from the old declaration to the
1327 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
1328 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1329 } else if (NewTypeParm->hasDefaultArgument()) {
1330 SawDefaultArgument = true;
1331 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1332 } else if (SawDefaultArgument)
1333 MissingDefaultArg = true;
1334 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1335 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1336 // Check for unexpanded parameter packs.
1337 if (!NewNonTypeParm->isParameterPack() &&
1338 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1339 NewNonTypeParm->getTypeSourceInfo(),
1340 UPPC_NonTypeTemplateParameterType)) {
1345 // Check the presence of a default argument here.
1346 if (NewNonTypeParm->hasDefaultArgument() &&
1347 DiagnoseDefaultTemplateArgument(*this, TPC,
1348 NewNonTypeParm->getLocation(),
1349 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1350 NewNonTypeParm->removeDefaultArgument();
1353 // Merge default arguments for non-type template parameters
1354 NonTypeTemplateParmDecl *OldNonTypeParm
1355 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
1356 if (NewNonTypeParm->isParameterPack()) {
1357 assert(!NewNonTypeParm->hasDefaultArgument() &&
1358 "Parameter packs can't have a default argument!");
1359 if (!NewNonTypeParm->isPackExpansion())
1360 SawParameterPack = true;
1361 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
1362 NewNonTypeParm->hasDefaultArgument()) {
1363 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1364 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1365 SawDefaultArgument = true;
1366 RedundantDefaultArg = true;
1367 PreviousDefaultArgLoc = NewDefaultLoc;
1368 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1369 // Merge the default argument from the old declaration to the
1371 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
1372 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1373 } else if (NewNonTypeParm->hasDefaultArgument()) {
1374 SawDefaultArgument = true;
1375 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1376 } else if (SawDefaultArgument)
1377 MissingDefaultArg = true;
1379 TemplateTemplateParmDecl *NewTemplateParm
1380 = cast<TemplateTemplateParmDecl>(*NewParam);
1382 // Check for unexpanded parameter packs, recursively.
1383 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1388 // Check the presence of a default argument here.
1389 if (NewTemplateParm->hasDefaultArgument() &&
1390 DiagnoseDefaultTemplateArgument(*this, TPC,
1391 NewTemplateParm->getLocation(),
1392 NewTemplateParm->getDefaultArgument().getSourceRange()))
1393 NewTemplateParm->removeDefaultArgument();
1395 // Merge default arguments for template template parameters
1396 TemplateTemplateParmDecl *OldTemplateParm
1397 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
1398 if (NewTemplateParm->isParameterPack()) {
1399 assert(!NewTemplateParm->hasDefaultArgument() &&
1400 "Parameter packs can't have a default argument!");
1401 if (!NewTemplateParm->isPackExpansion())
1402 SawParameterPack = true;
1403 } else if (OldTemplateParm &&
1404 hasVisibleDefaultArgument(OldTemplateParm) &&
1405 NewTemplateParm->hasDefaultArgument()) {
1406 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1407 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1408 SawDefaultArgument = true;
1409 RedundantDefaultArg = true;
1410 PreviousDefaultArgLoc = NewDefaultLoc;
1411 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1412 // Merge the default argument from the old declaration to the
1414 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
1415 PreviousDefaultArgLoc
1416 = OldTemplateParm->getDefaultArgument().getLocation();
1417 } else if (NewTemplateParm->hasDefaultArgument()) {
1418 SawDefaultArgument = true;
1419 PreviousDefaultArgLoc
1420 = NewTemplateParm->getDefaultArgument().getLocation();
1421 } else if (SawDefaultArgument)
1422 MissingDefaultArg = true;
1425 // C++11 [temp.param]p11:
1426 // If a template parameter of a primary class template or alias template
1427 // is a template parameter pack, it shall be the last template parameter.
1428 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1429 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1430 TPC == TPC_TypeAliasTemplate)) {
1431 Diag((*NewParam)->getLocation(),
1432 diag::err_template_param_pack_must_be_last_template_parameter);
1436 if (RedundantDefaultArg) {
1437 // C++ [temp.param]p12:
1438 // A template-parameter shall not be given default arguments
1439 // by two different declarations in the same scope.
1440 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1441 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1443 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
1444 // C++ [temp.param]p11:
1445 // If a template-parameter of a class template has a default
1446 // template-argument, each subsequent template-parameter shall either
1447 // have a default template-argument supplied or be a template parameter
1449 Diag((*NewParam)->getLocation(),
1450 diag::err_template_param_default_arg_missing);
1451 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1453 RemoveDefaultArguments = true;
1456 // If we have an old template parameter list that we're merging
1457 // in, move on to the next parameter.
1462 // We were missing some default arguments at the end of the list, so remove
1463 // all of the default arguments.
1464 if (RemoveDefaultArguments) {
1465 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1466 NewParamEnd = NewParams->end();
1467 NewParam != NewParamEnd; ++NewParam) {
1468 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1469 TTP->removeDefaultArgument();
1470 else if (NonTypeTemplateParmDecl *NTTP
1471 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1472 NTTP->removeDefaultArgument();
1474 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1483 /// A class which looks for a use of a certain level of template
1485 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1486 typedef RecursiveASTVisitor<DependencyChecker> super;
1490 SourceLocation MatchLoc;
1492 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
1494 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1495 NamedDecl *ND = Params->getParam(0);
1496 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1497 Depth = PD->getDepth();
1498 } else if (NonTypeTemplateParmDecl *PD =
1499 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1500 Depth = PD->getDepth();
1502 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1506 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
1507 if (ParmDepth >= Depth) {
1515 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1516 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1519 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1520 return !Matches(T->getDepth());
1523 bool TraverseTemplateName(TemplateName N) {
1524 if (TemplateTemplateParmDecl *PD =
1525 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1526 if (Matches(PD->getDepth()))
1528 return super::TraverseTemplateName(N);
1531 bool VisitDeclRefExpr(DeclRefExpr *E) {
1532 if (NonTypeTemplateParmDecl *PD =
1533 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1534 if (Matches(PD->getDepth(), E->getExprLoc()))
1536 return super::VisitDeclRefExpr(E);
1539 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1540 return TraverseType(T->getReplacementType());
1544 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1545 return TraverseTemplateArgument(T->getArgumentPack());
1548 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1549 return TraverseType(T->getInjectedSpecializationType());
1554 /// Determines whether a given type depends on the given parameter
1557 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
1558 DependencyChecker Checker(Params);
1559 Checker.TraverseType(T);
1560 return Checker.Match;
1563 // Find the source range corresponding to the named type in the given
1564 // nested-name-specifier, if any.
1565 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1567 const CXXScopeSpec &SS) {
1568 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1569 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1570 if (const Type *CurType = NNS->getAsType()) {
1571 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1572 return NNSLoc.getTypeLoc().getSourceRange();
1576 NNSLoc = NNSLoc.getPrefix();
1579 return SourceRange();
1582 /// \brief Match the given template parameter lists to the given scope
1583 /// specifier, returning the template parameter list that applies to the
1586 /// \param DeclStartLoc the start of the declaration that has a scope
1587 /// specifier or a template parameter list.
1589 /// \param DeclLoc The location of the declaration itself.
1591 /// \param SS the scope specifier that will be matched to the given template
1592 /// parameter lists. This scope specifier precedes a qualified name that is
1595 /// \param TemplateId The template-id following the scope specifier, if there
1596 /// is one. Used to check for a missing 'template<>'.
1598 /// \param ParamLists the template parameter lists, from the outermost to the
1599 /// innermost template parameter lists.
1601 /// \param IsFriend Whether to apply the slightly different rules for
1602 /// matching template parameters to scope specifiers in friend
1605 /// \param IsExplicitSpecialization will be set true if the entity being
1606 /// declared is an explicit specialization, false otherwise.
1608 /// \returns the template parameter list, if any, that corresponds to the
1609 /// name that is preceded by the scope specifier @p SS. This template
1610 /// parameter list may have template parameters (if we're declaring a
1611 /// template) or may have no template parameters (if we're declaring a
1612 /// template specialization), or may be NULL (if what we're declaring isn't
1613 /// itself a template).
1614 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1615 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
1616 TemplateIdAnnotation *TemplateId,
1617 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1618 bool &IsExplicitSpecialization, bool &Invalid) {
1619 IsExplicitSpecialization = false;
1622 // The sequence of nested types to which we will match up the template
1623 // parameter lists. We first build this list by starting with the type named
1624 // by the nested-name-specifier and walking out until we run out of types.
1625 SmallVector<QualType, 4> NestedTypes;
1627 if (SS.getScopeRep()) {
1628 if (CXXRecordDecl *Record
1629 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1630 T = Context.getTypeDeclType(Record);
1632 T = QualType(SS.getScopeRep()->getAsType(), 0);
1635 // If we found an explicit specialization that prevents us from needing
1636 // 'template<>' headers, this will be set to the location of that
1637 // explicit specialization.
1638 SourceLocation ExplicitSpecLoc;
1640 while (!T.isNull()) {
1641 NestedTypes.push_back(T);
1643 // Retrieve the parent of a record type.
1644 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1645 // If this type is an explicit specialization, we're done.
1646 if (ClassTemplateSpecializationDecl *Spec
1647 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1648 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1649 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1650 ExplicitSpecLoc = Spec->getLocation();
1653 } else if (Record->getTemplateSpecializationKind()
1654 == TSK_ExplicitSpecialization) {
1655 ExplicitSpecLoc = Record->getLocation();
1659 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1660 T = Context.getTypeDeclType(Parent);
1666 if (const TemplateSpecializationType *TST
1667 = T->getAs<TemplateSpecializationType>()) {
1668 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1669 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1670 T = Context.getTypeDeclType(Parent);
1677 // Look one step prior in a dependent template specialization type.
1678 if (const DependentTemplateSpecializationType *DependentTST
1679 = T->getAs<DependentTemplateSpecializationType>()) {
1680 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1681 T = QualType(NNS->getAsType(), 0);
1687 // Look one step prior in a dependent name type.
1688 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1689 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1690 T = QualType(NNS->getAsType(), 0);
1696 // Retrieve the parent of an enumeration type.
1697 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1698 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1700 EnumDecl *Enum = EnumT->getDecl();
1702 // Get to the parent type.
1703 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1704 T = Context.getTypeDeclType(Parent);
1712 // Reverse the nested types list, since we want to traverse from the outermost
1713 // to the innermost while checking template-parameter-lists.
1714 std::reverse(NestedTypes.begin(), NestedTypes.end());
1716 // C++0x [temp.expl.spec]p17:
1717 // A member or a member template may be nested within many
1718 // enclosing class templates. In an explicit specialization for
1719 // such a member, the member declaration shall be preceded by a
1720 // template<> for each enclosing class template that is
1721 // explicitly specialized.
1722 bool SawNonEmptyTemplateParameterList = false;
1724 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
1725 if (SawNonEmptyTemplateParameterList) {
1726 Diag(DeclLoc, diag::err_specialize_member_of_template)
1727 << !Recovery << Range;
1729 IsExplicitSpecialization = false;
1736 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1737 // Check that we can have an explicit specialization here.
1738 if (CheckExplicitSpecialization(Range, true))
1741 // We don't have a template header, but we should.
1742 SourceLocation ExpectedTemplateLoc;
1743 if (!ParamLists.empty())
1744 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1746 ExpectedTemplateLoc = DeclStartLoc;
1748 Diag(DeclLoc, diag::err_template_spec_needs_header)
1750 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1754 unsigned ParamIdx = 0;
1755 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1757 T = NestedTypes[TypeIdx];
1759 // Whether we expect a 'template<>' header.
1760 bool NeedEmptyTemplateHeader = false;
1762 // Whether we expect a template header with parameters.
1763 bool NeedNonemptyTemplateHeader = false;
1765 // For a dependent type, the set of template parameters that we
1767 TemplateParameterList *ExpectedTemplateParams = nullptr;
1769 // C++0x [temp.expl.spec]p15:
1770 // A member or a member template may be nested within many enclosing
1771 // class templates. In an explicit specialization for such a member, the
1772 // member declaration shall be preceded by a template<> for each
1773 // enclosing class template that is explicitly specialized.
1774 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1775 if (ClassTemplatePartialSpecializationDecl *Partial
1776 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1777 ExpectedTemplateParams = Partial->getTemplateParameters();
1778 NeedNonemptyTemplateHeader = true;
1779 } else if (Record->isDependentType()) {
1780 if (Record->getDescribedClassTemplate()) {
1781 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1782 ->getTemplateParameters();
1783 NeedNonemptyTemplateHeader = true;
1785 } else if (ClassTemplateSpecializationDecl *Spec
1786 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1787 // C++0x [temp.expl.spec]p4:
1788 // Members of an explicitly specialized class template are defined
1789 // in the same manner as members of normal classes, and not using
1790 // the template<> syntax.
1791 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1792 NeedEmptyTemplateHeader = true;
1795 } else if (Record->getTemplateSpecializationKind()) {
1796 if (Record->getTemplateSpecializationKind()
1797 != TSK_ExplicitSpecialization &&
1798 TypeIdx == NumTypes - 1)
1799 IsExplicitSpecialization = true;
1803 } else if (const TemplateSpecializationType *TST
1804 = T->getAs<TemplateSpecializationType>()) {
1805 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1806 ExpectedTemplateParams = Template->getTemplateParameters();
1807 NeedNonemptyTemplateHeader = true;
1809 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1810 // FIXME: We actually could/should check the template arguments here
1811 // against the corresponding template parameter list.
1812 NeedNonemptyTemplateHeader = false;
1815 // C++ [temp.expl.spec]p16:
1816 // In an explicit specialization declaration for a member of a class
1817 // template or a member template that ap- pears in namespace scope, the
1818 // member template and some of its enclosing class templates may remain
1819 // unspecialized, except that the declaration shall not explicitly
1820 // specialize a class member template if its en- closing class templates
1821 // are not explicitly specialized as well.
1822 if (ParamIdx < ParamLists.size()) {
1823 if (ParamLists[ParamIdx]->size() == 0) {
1824 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1828 SawNonEmptyTemplateParameterList = true;
1831 if (NeedEmptyTemplateHeader) {
1832 // If we're on the last of the types, and we need a 'template<>' header
1833 // here, then it's an explicit specialization.
1834 if (TypeIdx == NumTypes - 1)
1835 IsExplicitSpecialization = true;
1837 if (ParamIdx < ParamLists.size()) {
1838 if (ParamLists[ParamIdx]->size() > 0) {
1839 // The header has template parameters when it shouldn't. Complain.
1840 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1841 diag::err_template_param_list_matches_nontemplate)
1843 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1844 ParamLists[ParamIdx]->getRAngleLoc())
1845 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1850 // Consume this template header.
1856 if (DiagnoseMissingExplicitSpecialization(
1857 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
1863 if (NeedNonemptyTemplateHeader) {
1864 // In friend declarations we can have template-ids which don't
1865 // depend on the corresponding template parameter lists. But
1866 // assume that empty parameter lists are supposed to match this
1868 if (IsFriend && T->isDependentType()) {
1869 if (ParamIdx < ParamLists.size() &&
1870 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1871 ExpectedTemplateParams = nullptr;
1876 if (ParamIdx < ParamLists.size()) {
1877 // Check the template parameter list, if we can.
1878 if (ExpectedTemplateParams &&
1879 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1880 ExpectedTemplateParams,
1881 true, TPL_TemplateMatch))
1885 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
1886 TPC_ClassTemplateMember))
1893 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1895 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1901 // If there were at least as many template-ids as there were template
1902 // parameter lists, then there are no template parameter lists remaining for
1903 // the declaration itself.
1904 if (ParamIdx >= ParamLists.size()) {
1905 if (TemplateId && !IsFriend) {
1906 // We don't have a template header for the declaration itself, but we
1908 IsExplicitSpecialization = true;
1909 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1910 TemplateId->RAngleLoc));
1912 // Fabricate an empty template parameter list for the invented header.
1913 return TemplateParameterList::Create(Context, SourceLocation(),
1914 SourceLocation(), nullptr, 0,
1921 // If there were too many template parameter lists, complain about that now.
1922 if (ParamIdx < ParamLists.size() - 1) {
1923 bool HasAnyExplicitSpecHeader = false;
1924 bool AllExplicitSpecHeaders = true;
1925 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
1926 if (ParamLists[I]->size() == 0)
1927 HasAnyExplicitSpecHeader = true;
1929 AllExplicitSpecHeaders = false;
1932 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1933 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1934 : diag::err_template_spec_extra_headers)
1935 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1936 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
1938 // If there was a specialization somewhere, such that 'template<>' is
1939 // not required, and there were any 'template<>' headers, note where the
1940 // specialization occurred.
1941 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1942 Diag(ExplicitSpecLoc,
1943 diag::note_explicit_template_spec_does_not_need_header)
1944 << NestedTypes.back();
1946 // We have a template parameter list with no corresponding scope, which
1947 // means that the resulting template declaration can't be instantiated
1948 // properly (we'll end up with dependent nodes when we shouldn't).
1949 if (!AllExplicitSpecHeaders)
1953 // C++ [temp.expl.spec]p16:
1954 // In an explicit specialization declaration for a member of a class
1955 // template or a member template that ap- pears in namespace scope, the
1956 // member template and some of its enclosing class templates may remain
1957 // unspecialized, except that the declaration shall not explicitly
1958 // specialize a class member template if its en- closing class templates
1959 // are not explicitly specialized as well.
1960 if (ParamLists.back()->size() == 0 &&
1961 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1965 // Return the last template parameter list, which corresponds to the
1966 // entity being declared.
1967 return ParamLists.back();
1970 void Sema::NoteAllFoundTemplates(TemplateName Name) {
1971 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1972 Diag(Template->getLocation(), diag::note_template_declared_here)
1973 << (isa<FunctionTemplateDecl>(Template)
1975 : isa<ClassTemplateDecl>(Template)
1977 : isa<VarTemplateDecl>(Template)
1979 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
1980 << Template->getDeclName();
1984 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1985 for (OverloadedTemplateStorage::iterator I = OST->begin(),
1988 Diag((*I)->getLocation(), diag::note_template_declared_here)
1989 << 0 << (*I)->getDeclName();
1995 QualType Sema::CheckTemplateIdType(TemplateName Name,
1996 SourceLocation TemplateLoc,
1997 TemplateArgumentListInfo &TemplateArgs) {
1998 DependentTemplateName *DTN
1999 = Name.getUnderlying().getAsDependentTemplateName();
2000 if (DTN && DTN->isIdentifier())
2001 // When building a template-id where the template-name is dependent,
2002 // assume the template is a type template. Either our assumption is
2003 // correct, or the code is ill-formed and will be diagnosed when the
2004 // dependent name is substituted.
2005 return Context.getDependentTemplateSpecializationType(ETK_None,
2006 DTN->getQualifier(),
2007 DTN->getIdentifier(),
2010 TemplateDecl *Template = Name.getAsTemplateDecl();
2011 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2012 isa<VarTemplateDecl>(Template)) {
2013 // We might have a substituted template template parameter pack. If so,
2014 // build a template specialization type for it.
2015 if (Name.getAsSubstTemplateTemplateParmPack())
2016 return Context.getTemplateSpecializationType(Name, TemplateArgs);
2018 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2020 NoteAllFoundTemplates(Name);
2024 // Check that the template argument list is well-formed for this
2026 SmallVector<TemplateArgument, 4> Converted;
2027 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2033 bool InstantiationDependent = false;
2034 if (TypeAliasTemplateDecl *AliasTemplate =
2035 dyn_cast<TypeAliasTemplateDecl>(Template)) {
2036 // Find the canonical type for this type alias template specialization.
2037 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2038 if (Pattern->isInvalidDecl())
2041 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2042 Converted.data(), Converted.size());
2044 // Only substitute for the innermost template argument list.
2045 MultiLevelTemplateArgumentList TemplateArgLists;
2046 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
2047 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2048 for (unsigned I = 0; I < Depth; ++I)
2049 TemplateArgLists.addOuterTemplateArguments(None);
2051 LocalInstantiationScope Scope(*this);
2052 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2053 if (Inst.isInvalid())
2056 CanonType = SubstType(Pattern->getUnderlyingType(),
2057 TemplateArgLists, AliasTemplate->getLocation(),
2058 AliasTemplate->getDeclName());
2059 if (CanonType.isNull())
2061 } else if (Name.isDependent() ||
2062 TemplateSpecializationType::anyDependentTemplateArguments(
2063 TemplateArgs, InstantiationDependent)) {
2064 // This class template specialization is a dependent
2065 // type. Therefore, its canonical type is another class template
2066 // specialization type that contains all of the converted
2067 // arguments in canonical form. This ensures that, e.g., A<T> and
2068 // A<T, T> have identical types when A is declared as:
2070 // template<typename T, typename U = T> struct A;
2071 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
2072 CanonType = Context.getTemplateSpecializationType(CanonName,
2076 // FIXME: CanonType is not actually the canonical type, and unfortunately
2077 // it is a TemplateSpecializationType that we will never use again.
2078 // In the future, we need to teach getTemplateSpecializationType to only
2079 // build the canonical type and return that to us.
2080 CanonType = Context.getCanonicalType(CanonType);
2082 // This might work out to be a current instantiation, in which
2083 // case the canonical type needs to be the InjectedClassNameType.
2085 // TODO: in theory this could be a simple hashtable lookup; most
2086 // changes to CurContext don't change the set of current
2088 if (isa<ClassTemplateDecl>(Template)) {
2089 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2090 // If we get out to a namespace, we're done.
2091 if (Ctx->isFileContext()) break;
2093 // If this isn't a record, keep looking.
2094 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2095 if (!Record) continue;
2097 // Look for one of the two cases with InjectedClassNameTypes
2098 // and check whether it's the same template.
2099 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2100 !Record->getDescribedClassTemplate())
2103 // Fetch the injected class name type and check whether its
2104 // injected type is equal to the type we just built.
2105 QualType ICNT = Context.getTypeDeclType(Record);
2106 QualType Injected = cast<InjectedClassNameType>(ICNT)
2107 ->getInjectedSpecializationType();
2109 if (CanonType != Injected->getCanonicalTypeInternal())
2112 // If so, the canonical type of this TST is the injected
2113 // class name type of the record we just found.
2114 assert(ICNT.isCanonical());
2119 } else if (ClassTemplateDecl *ClassTemplate
2120 = dyn_cast<ClassTemplateDecl>(Template)) {
2121 // Find the class template specialization declaration that
2122 // corresponds to these arguments.
2123 void *InsertPos = nullptr;
2124 ClassTemplateSpecializationDecl *Decl
2125 = ClassTemplate->findSpecialization(Converted, InsertPos);
2127 // This is the first time we have referenced this class template
2128 // specialization. Create the canonical declaration and add it to
2129 // the set of specializations.
2130 Decl = ClassTemplateSpecializationDecl::Create(Context,
2131 ClassTemplate->getTemplatedDecl()->getTagKind(),
2132 ClassTemplate->getDeclContext(),
2133 ClassTemplate->getTemplatedDecl()->getLocStart(),
2134 ClassTemplate->getLocation(),
2137 Converted.size(), nullptr);
2138 ClassTemplate->AddSpecialization(Decl, InsertPos);
2139 if (ClassTemplate->isOutOfLine())
2140 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2143 // Diagnose uses of this specialization.
2144 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2146 CanonType = Context.getTypeDeclType(Decl);
2147 assert(isa<RecordType>(CanonType) &&
2148 "type of non-dependent specialization is not a RecordType");
2151 // Build the fully-sugared type for this class template
2152 // specialization, which refers back to the class template
2153 // specialization we created or found.
2154 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2158 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2159 TemplateTy TemplateD, SourceLocation TemplateLoc,
2160 SourceLocation LAngleLoc,
2161 ASTTemplateArgsPtr TemplateArgsIn,
2162 SourceLocation RAngleLoc,
2163 bool IsCtorOrDtorName) {
2167 TemplateName Template = TemplateD.get();
2169 // Translate the parser's template argument list in our AST format.
2170 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2171 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2173 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2175 = Context.getDependentTemplateSpecializationType(ETK_None,
2176 DTN->getQualifier(),
2177 DTN->getIdentifier(),
2179 // Build type-source information.
2181 DependentTemplateSpecializationTypeLoc SpecTL
2182 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2183 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2184 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2185 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2186 SpecTL.setTemplateNameLoc(TemplateLoc);
2187 SpecTL.setLAngleLoc(LAngleLoc);
2188 SpecTL.setRAngleLoc(RAngleLoc);
2189 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2190 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2191 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2194 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2196 if (Result.isNull())
2199 // Build type-source information.
2201 TemplateSpecializationTypeLoc SpecTL
2202 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2203 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2204 SpecTL.setTemplateNameLoc(TemplateLoc);
2205 SpecTL.setLAngleLoc(LAngleLoc);
2206 SpecTL.setRAngleLoc(RAngleLoc);
2207 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2208 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2210 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2211 // constructor or destructor name (in such a case, the scope specifier
2212 // will be attached to the enclosing Decl or Expr node).
2213 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
2214 // Create an elaborated-type-specifier containing the nested-name-specifier.
2215 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2216 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2217 ElabTL.setElaboratedKeywordLoc(SourceLocation());
2218 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2221 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2224 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
2225 TypeSpecifierType TagSpec,
2226 SourceLocation TagLoc,
2228 SourceLocation TemplateKWLoc,
2229 TemplateTy TemplateD,
2230 SourceLocation TemplateLoc,
2231 SourceLocation LAngleLoc,
2232 ASTTemplateArgsPtr TemplateArgsIn,
2233 SourceLocation RAngleLoc) {
2234 TemplateName Template = TemplateD.get();
2236 // Translate the parser's template argument list in our AST format.
2237 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2238 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2240 // Determine the tag kind
2241 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
2242 ElaboratedTypeKeyword Keyword
2243 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
2245 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2246 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2247 DTN->getQualifier(),
2248 DTN->getIdentifier(),
2251 // Build type-source information.
2253 DependentTemplateSpecializationTypeLoc SpecTL
2254 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2255 SpecTL.setElaboratedKeywordLoc(TagLoc);
2256 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2257 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2258 SpecTL.setTemplateNameLoc(TemplateLoc);
2259 SpecTL.setLAngleLoc(LAngleLoc);
2260 SpecTL.setRAngleLoc(RAngleLoc);
2261 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2262 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2263 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2266 if (TypeAliasTemplateDecl *TAT =
2267 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2268 // C++0x [dcl.type.elab]p2:
2269 // If the identifier resolves to a typedef-name or the simple-template-id
2270 // resolves to an alias template specialization, the
2271 // elaborated-type-specifier is ill-formed.
2272 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2273 Diag(TAT->getLocation(), diag::note_declared_at);
2276 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2277 if (Result.isNull())
2278 return TypeResult(true);
2280 // Check the tag kind
2281 if (const RecordType *RT = Result->getAs<RecordType>()) {
2282 RecordDecl *D = RT->getDecl();
2284 IdentifierInfo *Id = D->getIdentifier();
2285 assert(Id && "templated class must have an identifier");
2287 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2289 Diag(TagLoc, diag::err_use_with_wrong_tag)
2291 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
2292 Diag(D->getLocation(), diag::note_previous_use);
2296 // Provide source-location information for the template specialization.
2298 TemplateSpecializationTypeLoc SpecTL
2299 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2300 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2301 SpecTL.setTemplateNameLoc(TemplateLoc);
2302 SpecTL.setLAngleLoc(LAngleLoc);
2303 SpecTL.setRAngleLoc(RAngleLoc);
2304 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2305 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2307 // Construct an elaborated type containing the nested-name-specifier (if any)
2309 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2310 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2311 ElabTL.setElaboratedKeywordLoc(TagLoc);
2312 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2313 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2316 static bool CheckTemplatePartialSpecializationArgs(
2317 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2318 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
2320 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2321 NamedDecl *PrevDecl,
2323 bool IsPartialSpecialization);
2325 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
2327 static bool isTemplateArgumentTemplateParameter(
2328 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2329 switch (Arg.getKind()) {
2330 case TemplateArgument::Null:
2331 case TemplateArgument::NullPtr:
2332 case TemplateArgument::Integral:
2333 case TemplateArgument::Declaration:
2334 case TemplateArgument::Pack:
2335 case TemplateArgument::TemplateExpansion:
2338 case TemplateArgument::Type: {
2339 QualType Type = Arg.getAsType();
2340 const TemplateTypeParmType *TPT =
2341 Arg.getAsType()->getAs<TemplateTypeParmType>();
2342 return TPT && !Type.hasQualifiers() &&
2343 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2346 case TemplateArgument::Expression: {
2347 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2348 if (!DRE || !DRE->getDecl())
2350 const NonTypeTemplateParmDecl *NTTP =
2351 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2352 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2355 case TemplateArgument::Template:
2356 const TemplateTemplateParmDecl *TTP =
2357 dyn_cast_or_null<TemplateTemplateParmDecl>(
2358 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2359 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2361 llvm_unreachable("unexpected kind of template argument");
2364 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2365 ArrayRef<TemplateArgument> Args) {
2366 if (Params->size() != Args.size())
2369 unsigned Depth = Params->getDepth();
2371 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2372 TemplateArgument Arg = Args[I];
2374 // If the parameter is a pack expansion, the argument must be a pack
2375 // whose only element is a pack expansion.
2376 if (Params->getParam(I)->isParameterPack()) {
2377 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2378 !Arg.pack_begin()->isPackExpansion())
2380 Arg = Arg.pack_begin()->getPackExpansionPattern();
2383 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2390 /// Convert the parser's template argument list representation into our form.
2391 static TemplateArgumentListInfo
2392 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2393 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2394 TemplateId.RAngleLoc);
2395 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2396 TemplateId.NumArgs);
2397 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2398 return TemplateArgs;
2401 DeclResult Sema::ActOnVarTemplateSpecialization(
2402 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
2403 TemplateParameterList *TemplateParams, StorageClass SC,
2404 bool IsPartialSpecialization) {
2405 // D must be variable template id.
2406 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2407 "Variable template specialization is declared with a template it.");
2409 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
2410 TemplateArgumentListInfo TemplateArgs =
2411 makeTemplateArgumentListInfo(*this, *TemplateId);
2412 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2413 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2414 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
2416 TemplateName Name = TemplateId->Template.get();
2418 // The template-id must name a variable template.
2419 VarTemplateDecl *VarTemplate =
2420 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2422 NamedDecl *FnTemplate;
2423 if (auto *OTS = Name.getAsOverloadedTemplate())
2424 FnTemplate = *OTS->begin();
2426 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2428 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2429 << FnTemplate->getDeclName();
2430 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2431 << IsPartialSpecialization;
2434 // Check for unexpanded parameter packs in any of the template arguments.
2435 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2436 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2437 UPPC_PartialSpecialization))
2440 // Check that the template argument list is well-formed for this
2442 SmallVector<TemplateArgument, 4> Converted;
2443 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2447 // Check that the type of this variable template specialization
2448 // matches the expected type.
2449 TypeSourceInfo *ExpectedDI;
2451 // Do substitution on the type of the declaration
2452 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2453 Converted.data(), Converted.size());
2454 InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate);
2455 if (Inst.isInvalid())
2457 VarDecl *Templated = VarTemplate->getTemplatedDecl();
2459 SubstType(Templated->getTypeSourceInfo(),
2460 MultiLevelTemplateArgumentList(TemplateArgList),
2461 Templated->getTypeSpecStartLoc(), Templated->getDeclName());
2466 // Find the variable template (partial) specialization declaration that
2467 // corresponds to these arguments.
2468 if (IsPartialSpecialization) {
2469 if (CheckTemplatePartialSpecializationArgs(
2470 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2471 TemplateArgs.size(), Converted))
2474 bool InstantiationDependent;
2475 if (!Name.isDependent() &&
2476 !TemplateSpecializationType::anyDependentTemplateArguments(
2477 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2478 InstantiationDependent)) {
2479 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2480 << VarTemplate->getDeclName();
2481 IsPartialSpecialization = false;
2484 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2486 // C++ [temp.class.spec]p9b3:
2488 // -- The argument list of the specialization shall not be identical
2489 // to the implicit argument list of the primary template.
2490 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2491 << /*variable template*/ 1
2492 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2493 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2494 // FIXME: Recover from this by treating the declaration as a redeclaration
2495 // of the primary template.
2500 void *InsertPos = nullptr;
2501 VarTemplateSpecializationDecl *PrevDecl = nullptr;
2503 if (IsPartialSpecialization)
2504 // FIXME: Template parameter list matters too
2505 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
2507 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
2509 VarTemplateSpecializationDecl *Specialization = nullptr;
2511 // Check whether we can declare a variable template specialization in
2512 // the current scope.
2513 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2515 IsPartialSpecialization))
2518 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2519 // Since the only prior variable template specialization with these
2520 // arguments was referenced but not declared, reuse that
2521 // declaration node as our own, updating its source location and
2522 // the list of outer template parameters to reflect our new declaration.
2523 Specialization = PrevDecl;
2524 Specialization->setLocation(TemplateNameLoc);
2526 } else if (IsPartialSpecialization) {
2527 // Create a new class template partial specialization declaration node.
2528 VarTemplatePartialSpecializationDecl *PrevPartial =
2529 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
2530 VarTemplatePartialSpecializationDecl *Partial =
2531 VarTemplatePartialSpecializationDecl::Create(
2532 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2533 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
2534 Converted.data(), Converted.size(), TemplateArgs);
2537 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2538 Specialization = Partial;
2540 // If we are providing an explicit specialization of a member variable
2541 // template specialization, make a note of that.
2542 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
2543 PrevPartial->setMemberSpecialization();
2545 // Check that all of the template parameters of the variable template
2546 // partial specialization are deducible from the template
2547 // arguments. If not, this variable template partial specialization
2548 // will never be used.
2549 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2550 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2551 TemplateParams->getDepth(), DeducibleParams);
2553 if (!DeducibleParams.all()) {
2554 unsigned NumNonDeducible =
2555 DeducibleParams.size() - DeducibleParams.count();
2556 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2557 << /*variable template*/ 1 << (NumNonDeducible > 1)
2558 << SourceRange(TemplateNameLoc, RAngleLoc);
2559 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2560 if (!DeducibleParams[I]) {
2561 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2562 if (Param->getDeclName())
2563 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2564 << Param->getDeclName();
2566 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2572 // Create a new class template specialization declaration node for
2573 // this explicit specialization or friend declaration.
2574 Specialization = VarTemplateSpecializationDecl::Create(
2575 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2576 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2577 Specialization->setTemplateArgsInfo(TemplateArgs);
2580 VarTemplate->AddSpecialization(Specialization, InsertPos);
2583 // C++ [temp.expl.spec]p6:
2584 // If a template, a member template or the member of a class template is
2585 // explicitly specialized then that specialization shall be declared
2586 // before the first use of that specialization that would cause an implicit
2587 // instantiation to take place, in every translation unit in which such a
2588 // use occurs; no diagnostic is required.
2589 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2591 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2592 // Is there any previous explicit specialization declaration?
2593 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2600 SourceRange Range(TemplateNameLoc, RAngleLoc);
2601 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2604 Diag(PrevDecl->getPointOfInstantiation(),
2605 diag::note_instantiation_required_here)
2606 << (PrevDecl->getTemplateSpecializationKind() !=
2607 TSK_ImplicitInstantiation);
2612 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2613 Specialization->setLexicalDeclContext(CurContext);
2615 // Add the specialization into its lexical context, so that it can
2616 // be seen when iterating through the list of declarations in that
2617 // context. However, specializations are not found by name lookup.
2618 CurContext->addDecl(Specialization);
2620 // Note that this is an explicit specialization.
2621 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2624 // Check that this isn't a redefinition of this specialization,
2625 // merging with previous declarations.
2626 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2628 PrevSpec.addDecl(PrevDecl);
2629 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
2630 } else if (Specialization->isStaticDataMember() &&
2631 Specialization->isOutOfLine()) {
2632 Specialization->setAccess(VarTemplate->getAccess());
2635 // Link instantiations of static data members back to the template from
2636 // which they were instantiated.
2637 if (Specialization->isStaticDataMember())
2638 Specialization->setInstantiationOfStaticDataMember(
2639 VarTemplate->getTemplatedDecl(),
2640 Specialization->getSpecializationKind());
2642 return Specialization;
2646 /// \brief A partial specialization whose template arguments have matched
2647 /// a given template-id.
2648 struct PartialSpecMatchResult {
2649 VarTemplatePartialSpecializationDecl *Partial;
2650 TemplateArgumentList *Args;
2655 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2656 SourceLocation TemplateNameLoc,
2657 const TemplateArgumentListInfo &TemplateArgs) {
2658 assert(Template && "A variable template id without template?");
2660 // Check that the template argument list is well-formed for this template.
2661 SmallVector<TemplateArgument, 4> Converted;
2662 if (CheckTemplateArgumentList(
2663 Template, TemplateNameLoc,
2664 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
2668 // Find the variable template specialization declaration that
2669 // corresponds to these arguments.
2670 void *InsertPos = nullptr;
2671 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
2672 Converted, InsertPos))
2673 // If we already have a variable template specialization, return it.
2676 // This is the first time we have referenced this variable template
2677 // specialization. Create the canonical declaration and add it to
2678 // the set of specializations, based on the closest partial specialization
2679 // that it represents. That is,
2680 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2681 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2682 Converted.data(), Converted.size());
2683 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2684 bool AmbiguousPartialSpec = false;
2685 typedef PartialSpecMatchResult MatchResult;
2686 SmallVector<MatchResult, 4> Matched;
2687 SourceLocation PointOfInstantiation = TemplateNameLoc;
2688 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2690 // 1. Attempt to find the closest partial specialization that this
2691 // specializes, if any.
2692 // If any of the template arguments is dependent, then this is probably
2693 // a placeholder for an incomplete declarative context; which must be
2694 // complete by instantiation time. Thus, do not search through the partial
2695 // specializations yet.
2696 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2697 // Perhaps better after unification of DeduceTemplateArguments() and
2698 // getMoreSpecializedPartialSpecialization().
2699 bool InstantiationDependent = false;
2700 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2701 TemplateArgs, InstantiationDependent)) {
2703 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2704 Template->getPartialSpecializations(PartialSpecs);
2706 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2707 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2708 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2710 if (TemplateDeductionResult Result =
2711 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2712 // Store the failed-deduction information for use in diagnostics, later.
2713 // TODO: Actually use the failed-deduction info?
2714 FailedCandidates.addCandidate()
2715 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2718 Matched.push_back(PartialSpecMatchResult());
2719 Matched.back().Partial = Partial;
2720 Matched.back().Args = Info.take();
2724 if (Matched.size() >= 1) {
2725 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2726 if (Matched.size() == 1) {
2727 // -- If exactly one matching specialization is found, the
2728 // instantiation is generated from that specialization.
2729 // We don't need to do anything for this.
2731 // -- If more than one matching specialization is found, the
2732 // partial order rules (14.5.4.2) are used to determine
2733 // whether one of the specializations is more specialized
2734 // than the others. If none of the specializations is more
2735 // specialized than all of the other matching
2736 // specializations, then the use of the variable template is
2737 // ambiguous and the program is ill-formed.
2738 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2739 PEnd = Matched.end();
2741 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2742 PointOfInstantiation) ==
2747 // Determine if the best partial specialization is more specialized than
2749 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2750 PEnd = Matched.end();
2752 if (P != Best && getMoreSpecializedPartialSpecialization(
2753 P->Partial, Best->Partial,
2754 PointOfInstantiation) != Best->Partial) {
2755 AmbiguousPartialSpec = true;
2761 // Instantiate using the best variable template partial specialization.
2762 InstantiationPattern = Best->Partial;
2763 InstantiationArgs = Best->Args;
2765 // -- If no match is found, the instantiation is generated
2766 // from the primary template.
2767 // InstantiationPattern = Template->getTemplatedDecl();
2771 // 2. Create the canonical declaration.
2772 // Note that we do not instantiate the variable just yet, since
2773 // instantiation is handled in DoMarkVarDeclReferenced().
2774 // FIXME: LateAttrs et al.?
2775 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2776 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2777 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2781 if (AmbiguousPartialSpec) {
2782 // Partial ordering did not produce a clear winner. Complain.
2783 Decl->setInvalidDecl();
2784 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2787 // Print the matching partial specializations.
2788 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2789 PEnd = Matched.end();
2791 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2792 << getTemplateArgumentBindingsText(
2793 P->Partial->getTemplateParameters(), *P->Args);
2797 if (VarTemplatePartialSpecializationDecl *D =
2798 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2799 Decl->setInstantiationOf(D, InstantiationArgs);
2801 assert(Decl && "No variable template specialization?");
2806 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2807 const DeclarationNameInfo &NameInfo,
2808 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2809 const TemplateArgumentListInfo *TemplateArgs) {
2811 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2813 if (Decl.isInvalid())
2816 VarDecl *Var = cast<VarDecl>(Decl.get());
2817 if (!Var->getTemplateSpecializationKind())
2818 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2821 // Build an ordinary singleton decl ref.
2822 return BuildDeclarationNameExpr(SS, NameInfo, Var,
2823 /*FoundD=*/nullptr, TemplateArgs);
2826 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
2827 SourceLocation TemplateKWLoc,
2830 const TemplateArgumentListInfo *TemplateArgs) {
2831 // FIXME: Can we do any checking at this point? I guess we could check the
2832 // template arguments that we have against the template name, if the template
2833 // name refers to a single template. That's not a terribly common case,
2835 // foo<int> could identify a single function unambiguously
2836 // This approach does NOT work, since f<int>(1);
2837 // gets resolved prior to resorting to overload resolution
2838 // i.e., template<class T> void f(double);
2839 // vs template<class T, class U> void f(U);
2841 // These should be filtered out by our callers.
2842 assert(!R.empty() && "empty lookup results when building templateid");
2843 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2845 // In C++1y, check variable template ids.
2846 bool InstantiationDependent;
2847 if (R.getAsSingle<VarTemplateDecl>() &&
2848 !TemplateSpecializationType::anyDependentTemplateArguments(
2849 *TemplateArgs, InstantiationDependent)) {
2850 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2851 R.getAsSingle<VarTemplateDecl>(),
2852 TemplateKWLoc, TemplateArgs);
2855 // We don't want lookup warnings at this point.
2856 R.suppressDiagnostics();
2858 UnresolvedLookupExpr *ULE
2859 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2860 SS.getWithLocInContext(Context),
2862 R.getLookupNameInfo(),
2863 RequiresADL, TemplateArgs,
2864 R.begin(), R.end());
2869 // We actually only call this from template instantiation.
2871 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
2872 SourceLocation TemplateKWLoc,
2873 const DeclarationNameInfo &NameInfo,
2874 const TemplateArgumentListInfo *TemplateArgs) {
2876 assert(TemplateArgs || TemplateKWLoc.isValid());
2878 if (!(DC = computeDeclContext(SS, false)) ||
2879 DC->isDependentContext() ||
2880 RequireCompleteDeclContext(SS, DC))
2881 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
2883 bool MemberOfUnknownSpecialization;
2884 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2885 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
2886 MemberOfUnknownSpecialization);
2888 if (R.isAmbiguous())
2892 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2893 << NameInfo.getName() << SS.getRange();
2897 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
2898 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2900 << NameInfo.getName().getAsString() << SS.getRange();
2901 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2905 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
2908 /// \brief Form a dependent template name.
2910 /// This action forms a dependent template name given the template
2911 /// name and its (presumably dependent) scope specifier. For
2912 /// example, given "MetaFun::template apply", the scope specifier \p
2913 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2914 /// of the "template" keyword, and "apply" is the \p Name.
2915 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
2917 SourceLocation TemplateKWLoc,
2918 UnqualifiedId &Name,
2919 ParsedType ObjectType,
2920 bool EnteringContext,
2921 TemplateTy &Result) {
2922 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2924 getLangOpts().CPlusPlus11 ?
2925 diag::warn_cxx98_compat_template_outside_of_template :
2926 diag::ext_template_outside_of_template)
2927 << FixItHint::CreateRemoval(TemplateKWLoc);
2929 DeclContext *LookupCtx = nullptr;
2931 LookupCtx = computeDeclContext(SS, EnteringContext);
2932 if (!LookupCtx && ObjectType)
2933 LookupCtx = computeDeclContext(ObjectType.get());
2935 // C++0x [temp.names]p5:
2936 // If a name prefixed by the keyword template is not the name of
2937 // a template, the program is ill-formed. [Note: the keyword
2938 // template may not be applied to non-template members of class
2939 // templates. -end note ] [ Note: as is the case with the
2940 // typename prefix, the template prefix is allowed in cases
2941 // where it is not strictly necessary; i.e., when the
2942 // nested-name-specifier or the expression on the left of the ->
2943 // or . is not dependent on a template-parameter, or the use
2944 // does not appear in the scope of a template. -end note]
2946 // Note: C++03 was more strict here, because it banned the use of
2947 // the "template" keyword prior to a template-name that was not a
2948 // dependent name. C++ DR468 relaxed this requirement (the
2949 // "template" keyword is now permitted). We follow the C++0x
2950 // rules, even in C++03 mode with a warning, retroactively applying the DR.
2951 bool MemberOfUnknownSpecialization;
2952 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
2953 ObjectType, EnteringContext, Result,
2954 MemberOfUnknownSpecialization);
2955 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2956 isa<CXXRecordDecl>(LookupCtx) &&
2957 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2958 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
2959 // This is a dependent template. Handle it below.
2960 } else if (TNK == TNK_Non_template) {
2961 Diag(Name.getLocStart(),
2962 diag::err_template_kw_refers_to_non_template)
2963 << GetNameFromUnqualifiedId(Name).getName()
2964 << Name.getSourceRange()
2966 return TNK_Non_template;
2968 // We found something; return it.
2973 NestedNameSpecifier *Qualifier = SS.getScopeRep();
2975 switch (Name.getKind()) {
2976 case UnqualifiedId::IK_Identifier:
2977 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2979 return TNK_Dependent_template_name;
2981 case UnqualifiedId::IK_OperatorFunctionId:
2982 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2983 Name.OperatorFunctionId.Operator));
2984 return TNK_Function_template;
2986 case UnqualifiedId::IK_LiteralOperatorId:
2987 llvm_unreachable("literal operator id cannot have a dependent scope");
2993 Diag(Name.getLocStart(),
2994 diag::err_template_kw_refers_to_non_template)
2995 << GetNameFromUnqualifiedId(Name).getName()
2996 << Name.getSourceRange()
2998 return TNK_Non_template;
3001 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
3002 TemplateArgumentLoc &AL,
3003 SmallVectorImpl<TemplateArgument> &Converted) {
3004 const TemplateArgument &Arg = AL.getArgument();
3006 TypeSourceInfo *TSI = nullptr;
3008 // Check template type parameter.
3009 switch(Arg.getKind()) {
3010 case TemplateArgument::Type:
3011 // C++ [temp.arg.type]p1:
3012 // A template-argument for a template-parameter which is a
3013 // type shall be a type-id.
3014 ArgType = Arg.getAsType();
3015 TSI = AL.getTypeSourceInfo();
3017 case TemplateArgument::Template: {
3018 // We have a template type parameter but the template argument
3019 // is a template without any arguments.
3020 SourceRange SR = AL.getSourceRange();
3021 TemplateName Name = Arg.getAsTemplate();
3022 Diag(SR.getBegin(), diag::err_template_missing_args)
3024 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3025 Diag(Decl->getLocation(), diag::note_template_decl_here);
3029 case TemplateArgument::Expression: {
3030 // We have a template type parameter but the template argument is an
3031 // expression; see if maybe it is missing the "typename" keyword.
3033 DeclarationNameInfo NameInfo;
3035 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3036 SS.Adopt(ArgExpr->getQualifierLoc());
3037 NameInfo = ArgExpr->getNameInfo();
3038 } else if (DependentScopeDeclRefExpr *ArgExpr =
3039 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3040 SS.Adopt(ArgExpr->getQualifierLoc());
3041 NameInfo = ArgExpr->getNameInfo();
3042 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3043 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
3044 if (ArgExpr->isImplicitAccess()) {
3045 SS.Adopt(ArgExpr->getQualifierLoc());
3046 NameInfo = ArgExpr->getMemberNameInfo();
3050 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
3051 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3052 LookupParsedName(Result, CurScope, &SS);
3054 if (Result.getAsSingle<TypeDecl>() ||
3055 Result.getResultKind() ==
3056 LookupResult::NotFoundInCurrentInstantiation) {
3057 // Suggest that the user add 'typename' before the NNS.
3058 SourceLocation Loc = AL.getSourceRange().getBegin();
3059 Diag(Loc, getLangOpts().MSVCCompat
3060 ? diag::ext_ms_template_type_arg_missing_typename
3061 : diag::err_template_arg_must_be_type_suggest)
3062 << FixItHint::CreateInsertion(Loc, "typename ");
3063 Diag(Param->getLocation(), diag::note_template_param_here);
3065 // Recover by synthesizing a type using the location information that we
3068 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3070 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3071 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3072 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3073 TL.setNameLoc(NameInfo.getLoc());
3074 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3076 // Overwrite our input TemplateArgumentLoc so that we can recover
3078 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3079 TemplateArgumentLocInfo(TSI));
3087 // We have a template type parameter but the template argument
3089 SourceRange SR = AL.getSourceRange();
3090 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
3091 Diag(Param->getLocation(), diag::note_template_param_here);
3097 if (CheckTemplateArgument(Param, TSI))
3100 // Add the converted template type argument.
3101 ArgType = Context.getCanonicalType(ArgType);
3104 // If an explicitly-specified template argument type is a lifetime type
3105 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
3106 if (getLangOpts().ObjCAutoRefCount &&
3107 ArgType->isObjCLifetimeType() &&
3108 !ArgType.getObjCLifetime()) {
3110 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3111 ArgType = Context.getQualifiedType(ArgType, Qs);
3114 Converted.push_back(TemplateArgument(ArgType));
3118 /// \brief Substitute template arguments into the default template argument for
3119 /// the given template type parameter.
3121 /// \param SemaRef the semantic analysis object for which we are performing
3122 /// the substitution.
3124 /// \param Template the template that we are synthesizing template arguments
3127 /// \param TemplateLoc the location of the template name that started the
3128 /// template-id we are checking.
3130 /// \param RAngleLoc the location of the right angle bracket ('>') that
3131 /// terminates the template-id.
3133 /// \param Param the template template parameter whose default we are
3134 /// substituting into.
3136 /// \param Converted the list of template arguments provided for template
3137 /// parameters that precede \p Param in the template parameter list.
3138 /// \returns the substituted template argument, or NULL if an error occurred.
3139 static TypeSourceInfo *
3140 SubstDefaultTemplateArgument(Sema &SemaRef,
3141 TemplateDecl *Template,
3142 SourceLocation TemplateLoc,
3143 SourceLocation RAngleLoc,
3144 TemplateTypeParmDecl *Param,
3145 SmallVectorImpl<TemplateArgument> &Converted) {
3146 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
3148 // If the argument type is dependent, instantiate it now based
3149 // on the previously-computed template arguments.
3150 if (ArgType->getType()->isDependentType()) {
3151 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3152 Template, Converted,
3153 SourceRange(TemplateLoc, RAngleLoc));
3154 if (Inst.isInvalid())
3157 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3158 Converted.data(), Converted.size());
3160 // Only substitute for the innermost template argument list.
3161 MultiLevelTemplateArgumentList TemplateArgLists;
3162 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3163 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3164 TemplateArgLists.addOuterTemplateArguments(None);
3166 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3168 SemaRef.SubstType(ArgType, TemplateArgLists,
3169 Param->getDefaultArgumentLoc(), Param->getDeclName());
3175 /// \brief Substitute template arguments into the default template argument for
3176 /// the given non-type template parameter.
3178 /// \param SemaRef the semantic analysis object for which we are performing
3179 /// the substitution.
3181 /// \param Template the template that we are synthesizing template arguments
3184 /// \param TemplateLoc the location of the template name that started the
3185 /// template-id we are checking.
3187 /// \param RAngleLoc the location of the right angle bracket ('>') that
3188 /// terminates the template-id.
3190 /// \param Param the non-type template parameter whose default we are
3191 /// substituting into.
3193 /// \param Converted the list of template arguments provided for template
3194 /// parameters that precede \p Param in the template parameter list.
3196 /// \returns the substituted template argument, or NULL if an error occurred.
3198 SubstDefaultTemplateArgument(Sema &SemaRef,
3199 TemplateDecl *Template,
3200 SourceLocation TemplateLoc,
3201 SourceLocation RAngleLoc,
3202 NonTypeTemplateParmDecl *Param,
3203 SmallVectorImpl<TemplateArgument> &Converted) {
3204 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3205 Template, Converted,
3206 SourceRange(TemplateLoc, RAngleLoc));
3207 if (Inst.isInvalid())
3210 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3211 Converted.data(), Converted.size());
3213 // Only substitute for the innermost template argument list.
3214 MultiLevelTemplateArgumentList TemplateArgLists;
3215 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3216 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3217 TemplateArgLists.addOuterTemplateArguments(None);
3219 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3220 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
3221 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
3224 /// \brief Substitute template arguments into the default template argument for
3225 /// the given template template parameter.
3227 /// \param SemaRef the semantic analysis object for which we are performing
3228 /// the substitution.
3230 /// \param Template the template that we are synthesizing template arguments
3233 /// \param TemplateLoc the location of the template name that started the
3234 /// template-id we are checking.
3236 /// \param RAngleLoc the location of the right angle bracket ('>') that
3237 /// terminates the template-id.
3239 /// \param Param the template template parameter whose default we are
3240 /// substituting into.
3242 /// \param Converted the list of template arguments provided for template
3243 /// parameters that precede \p Param in the template parameter list.
3245 /// \param QualifierLoc Will be set to the nested-name-specifier (with
3246 /// source-location information) that precedes the template name.
3248 /// \returns the substituted template argument, or NULL if an error occurred.
3250 SubstDefaultTemplateArgument(Sema &SemaRef,
3251 TemplateDecl *Template,
3252 SourceLocation TemplateLoc,
3253 SourceLocation RAngleLoc,
3254 TemplateTemplateParmDecl *Param,
3255 SmallVectorImpl<TemplateArgument> &Converted,
3256 NestedNameSpecifierLoc &QualifierLoc) {
3257 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
3258 SourceRange(TemplateLoc, RAngleLoc));
3259 if (Inst.isInvalid())
3260 return TemplateName();
3262 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3263 Converted.data(), Converted.size());
3265 // Only substitute for the innermost template argument list.
3266 MultiLevelTemplateArgumentList TemplateArgLists;
3267 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3268 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3269 TemplateArgLists.addOuterTemplateArguments(None);
3271 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3272 // Substitute into the nested-name-specifier first,
3273 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
3276 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
3278 return TemplateName();
3281 return SemaRef.SubstTemplateName(
3283 Param->getDefaultArgument().getArgument().getAsTemplate(),
3284 Param->getDefaultArgument().getTemplateNameLoc(),
3288 /// \brief If the given template parameter has a default template
3289 /// argument, substitute into that default template argument and
3290 /// return the corresponding template argument.
3292 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3293 SourceLocation TemplateLoc,
3294 SourceLocation RAngleLoc,
3296 SmallVectorImpl<TemplateArgument>
3298 bool &HasDefaultArg) {
3299 HasDefaultArg = false;
3301 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
3302 if (!hasVisibleDefaultArgument(TypeParm))
3303 return TemplateArgumentLoc();
3305 HasDefaultArg = true;
3306 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
3312 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3314 return TemplateArgumentLoc();
3317 if (NonTypeTemplateParmDecl *NonTypeParm
3318 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3319 if (!hasVisibleDefaultArgument(NonTypeParm))
3320 return TemplateArgumentLoc();
3322 HasDefaultArg = true;
3323 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
3328 if (Arg.isInvalid())
3329 return TemplateArgumentLoc();
3331 Expr *ArgE = Arg.getAs<Expr>();
3332 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3335 TemplateTemplateParmDecl *TempTempParm
3336 = cast<TemplateTemplateParmDecl>(Param);
3337 if (!hasVisibleDefaultArgument(TempTempParm))
3338 return TemplateArgumentLoc();
3340 HasDefaultArg = true;
3341 NestedNameSpecifierLoc QualifierLoc;
3342 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
3349 return TemplateArgumentLoc();
3351 return TemplateArgumentLoc(TemplateArgument(TName),
3352 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
3353 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3356 /// \brief Check that the given template argument corresponds to the given
3357 /// template parameter.
3359 /// \param Param The template parameter against which the argument will be
3362 /// \param Arg The template argument, which may be updated due to conversions.
3364 /// \param Template The template in which the template argument resides.
3366 /// \param TemplateLoc The location of the template name for the template
3367 /// whose argument list we're matching.
3369 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
3370 /// the template argument list.
3372 /// \param ArgumentPackIndex The index into the argument pack where this
3373 /// argument will be placed. Only valid if the parameter is a parameter pack.
3375 /// \param Converted The checked, converted argument will be added to the
3376 /// end of this small vector.
3378 /// \param CTAK Describes how we arrived at this particular template argument:
3379 /// explicitly written, deduced, etc.
3381 /// \returns true on error, false otherwise.
3382 bool Sema::CheckTemplateArgument(NamedDecl *Param,
3383 TemplateArgumentLoc &Arg,
3384 NamedDecl *Template,
3385 SourceLocation TemplateLoc,
3386 SourceLocation RAngleLoc,
3387 unsigned ArgumentPackIndex,
3388 SmallVectorImpl<TemplateArgument> &Converted,
3389 CheckTemplateArgumentKind CTAK) {
3390 // Check template type parameters.
3391 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3392 return CheckTemplateTypeArgument(TTP, Arg, Converted);
3394 // Check non-type template parameters.
3395 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3396 // Do substitution on the type of the non-type template parameter
3397 // with the template arguments we've seen thus far. But if the
3398 // template has a dependent context then we cannot substitute yet.
3399 QualType NTTPType = NTTP->getType();
3400 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3401 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
3403 if (NTTPType->isDependentType() &&
3404 !isa<TemplateTemplateParmDecl>(Template) &&
3405 !Template->getDeclContext()->isDependentContext()) {
3406 // Do substitution on the type of the non-type template parameter.
3407 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3409 SourceRange(TemplateLoc, RAngleLoc));
3410 if (Inst.isInvalid())
3413 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3414 Converted.data(), Converted.size());
3415 NTTPType = SubstType(NTTPType,
3416 MultiLevelTemplateArgumentList(TemplateArgs),
3417 NTTP->getLocation(),
3418 NTTP->getDeclName());
3419 // If that worked, check the non-type template parameter type
3421 if (!NTTPType.isNull())
3422 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3423 NTTP->getLocation());
3424 if (NTTPType.isNull())
3428 switch (Arg.getArgument().getKind()) {
3429 case TemplateArgument::Null:
3430 llvm_unreachable("Should never see a NULL template argument here");
3432 case TemplateArgument::Expression: {
3433 TemplateArgument Result;
3435 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3437 if (Res.isInvalid())
3440 // If the resulting expression is new, then use it in place of the
3441 // old expression in the template argument.
3442 if (Res.get() != Arg.getArgument().getAsExpr()) {
3443 TemplateArgument TA(Res.get());
3444 Arg = TemplateArgumentLoc(TA, Res.get());
3447 Converted.push_back(Result);
3451 case TemplateArgument::Declaration:
3452 case TemplateArgument::Integral:
3453 case TemplateArgument::NullPtr:
3454 // We've already checked this template argument, so just copy
3455 // it to the list of converted arguments.
3456 Converted.push_back(Arg.getArgument());
3459 case TemplateArgument::Template:
3460 case TemplateArgument::TemplateExpansion:
3461 // We were given a template template argument. It may not be ill-formed;
3463 if (DependentTemplateName *DTN
3464 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3465 .getAsDependentTemplateName()) {
3466 // We have a template argument such as \c T::template X, which we
3467 // parsed as a template template argument. However, since we now
3468 // know that we need a non-type template argument, convert this
3469 // template name into an expression.
3471 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3472 Arg.getTemplateNameLoc());
3475 SS.Adopt(Arg.getTemplateQualifierLoc());
3476 // FIXME: the template-template arg was a DependentTemplateName,
3477 // so it was provided with a template keyword. However, its source
3478 // location is not stored in the template argument structure.
3479 SourceLocation TemplateKWLoc;
3480 ExprResult E = DependentScopeDeclRefExpr::Create(
3481 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3484 // If we parsed the template argument as a pack expansion, create a
3485 // pack expansion expression.
3486 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
3487 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
3492 TemplateArgument Result;
3493 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
3497 Converted.push_back(Result);
3501 // We have a template argument that actually does refer to a class
3502 // template, alias template, or template template parameter, and
3503 // therefore cannot be a non-type template argument.
3504 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3505 << Arg.getSourceRange();
3507 Diag(Param->getLocation(), diag::note_template_param_here);
3510 case TemplateArgument::Type: {
3511 // We have a non-type template parameter but the template
3512 // argument is a type.
3514 // C++ [temp.arg]p2:
3515 // In a template-argument, an ambiguity between a type-id and
3516 // an expression is resolved to a type-id, regardless of the
3517 // form of the corresponding template-parameter.
3519 // We warn specifically about this case, since it can be rather
3520 // confusing for users.
3521 QualType T = Arg.getArgument().getAsType();
3522 SourceRange SR = Arg.getSourceRange();
3523 if (T->isFunctionType())
3524 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3526 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3527 Diag(Param->getLocation(), diag::note_template_param_here);
3531 case TemplateArgument::Pack:
3532 llvm_unreachable("Caller must expand template argument packs");
3539 // Check template template parameters.
3540 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
3542 // Substitute into the template parameter list of the template
3543 // template parameter, since previously-supplied template arguments
3544 // may appear within the template template parameter.
3546 // Set up a template instantiation context.
3547 LocalInstantiationScope Scope(*this);
3548 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3549 TempParm, Converted,
3550 SourceRange(TemplateLoc, RAngleLoc));
3551 if (Inst.isInvalid())
3554 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3555 Converted.data(), Converted.size());
3556 TempParm = cast_or_null<TemplateTemplateParmDecl>(
3557 SubstDecl(TempParm, CurContext,
3558 MultiLevelTemplateArgumentList(TemplateArgs)));
3563 switch (Arg.getArgument().getKind()) {
3564 case TemplateArgument::Null:
3565 llvm_unreachable("Should never see a NULL template argument here");
3567 case TemplateArgument::Template:
3568 case TemplateArgument::TemplateExpansion:
3569 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
3572 Converted.push_back(Arg.getArgument());
3575 case TemplateArgument::Expression:
3576 case TemplateArgument::Type:
3577 // We have a template template parameter but the template
3578 // argument does not refer to a template.
3579 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
3580 << getLangOpts().CPlusPlus11;
3583 case TemplateArgument::Declaration:
3584 llvm_unreachable("Declaration argument with template template parameter");
3585 case TemplateArgument::Integral:
3586 llvm_unreachable("Integral argument with template template parameter");
3587 case TemplateArgument::NullPtr:
3588 llvm_unreachable("Null pointer argument with template template parameter");
3590 case TemplateArgument::Pack:
3591 llvm_unreachable("Caller must expand template argument packs");
3597 /// \brief Diagnose an arity mismatch in the
3598 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3599 SourceLocation TemplateLoc,
3600 TemplateArgumentListInfo &TemplateArgs) {
3601 TemplateParameterList *Params = Template->getTemplateParameters();
3602 unsigned NumParams = Params->size();
3603 unsigned NumArgs = TemplateArgs.size();
3606 if (NumArgs > NumParams)
3607 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3608 TemplateArgs.getRAngleLoc());
3609 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3610 << (NumArgs > NumParams)
3611 << (isa<ClassTemplateDecl>(Template)? 0 :
3612 isa<FunctionTemplateDecl>(Template)? 1 :
3613 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3614 << Template << Range;
3615 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3616 << Params->getSourceRange();
3620 /// \brief Check whether the template parameter is a pack expansion, and if so,
3621 /// determine the number of parameters produced by that expansion. For instance:
3624 /// template<typename ...Ts> struct A {
3625 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3629 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3630 /// is not a pack expansion, so returns an empty Optional.
3631 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
3632 if (NonTypeTemplateParmDecl *NTTP
3633 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3634 if (NTTP->isExpandedParameterPack())
3635 return NTTP->getNumExpansionTypes();
3638 if (TemplateTemplateParmDecl *TTP
3639 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3640 if (TTP->isExpandedParameterPack())
3641 return TTP->getNumExpansionTemplateParameters();
3647 /// Diagnose a missing template argument.
3648 template<typename TemplateParmDecl>
3649 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
3651 const TemplateParmDecl *D,
3652 TemplateArgumentListInfo &Args) {
3653 // Dig out the most recent declaration of the template parameter; there may be
3654 // declarations of the template that are more recent than TD.
3655 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
3656 ->getTemplateParameters()
3657 ->getParam(D->getIndex()));
3659 // If there's a default argument that's not visible, diagnose that we're
3660 // missing a module import.
3661 llvm::SmallVector<Module*, 8> Modules;
3662 if (D->hasDefaultArgument() && !S.hasVisibleDefaultArgument(D, &Modules)) {
3663 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
3664 D->getDefaultArgumentLoc(), Modules,
3665 Sema::MissingImportKind::DefaultArgument,
3670 // FIXME: If there's a more recent default argument that *is* visible,
3671 // diagnose that it was declared too late.
3673 return diagnoseArityMismatch(S, TD, Loc, Args);
3676 /// \brief Check that the given template argument list is well-formed
3677 /// for specializing the given template.
3678 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3679 SourceLocation TemplateLoc,
3680 TemplateArgumentListInfo &TemplateArgs,
3681 bool PartialTemplateArgs,
3682 SmallVectorImpl<TemplateArgument> &Converted) {
3683 // Make a copy of the template arguments for processing. Only make the
3684 // changes at the end when successful in matching the arguments to the
3686 TemplateArgumentListInfo NewArgs = TemplateArgs;
3688 TemplateParameterList *Params = Template->getTemplateParameters();
3690 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
3692 // C++ [temp.arg]p1:
3693 // [...] The type and form of each template-argument specified in
3694 // a template-id shall match the type and form specified for the
3695 // corresponding parameter declared by the template in its
3696 // template-parameter-list.
3697 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
3698 SmallVector<TemplateArgument, 2> ArgumentPack;
3699 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
3700 LocalInstantiationScope InstScope(*this, true);
3701 for (TemplateParameterList::iterator Param = Params->begin(),
3702 ParamEnd = Params->end();
3703 Param != ParamEnd; /* increment in loop */) {
3704 // If we have an expanded parameter pack, make sure we don't have too
3706 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
3707 if (*Expansions == ArgumentPack.size()) {
3708 // We're done with this parameter pack. Pack up its arguments and add
3709 // them to the list.
3710 Converted.push_back(
3711 TemplateArgument::CreatePackCopy(Context,
3712 ArgumentPack.data(),
3713 ArgumentPack.size()));
3714 ArgumentPack.clear();
3716 // This argument is assigned to the next parameter.
3719 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3720 // Not enough arguments for this parameter pack.
3721 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3723 << (isa<ClassTemplateDecl>(Template)? 0 :
3724 isa<FunctionTemplateDecl>(Template)? 1 :
3725 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3727 Diag(Template->getLocation(), diag::note_template_decl_here)
3728 << Params->getSourceRange();
3733 if (ArgIdx < NumArgs) {
3734 // Check the template argument we were given.
3735 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
3736 TemplateLoc, RAngleLoc,
3737 ArgumentPack.size(), Converted))
3740 bool PackExpansionIntoNonPack =
3741 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
3742 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3743 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
3744 // Core issue 1430: we have a pack expansion as an argument to an
3745 // alias template, and it's not part of a parameter pack. This
3746 // can't be canonicalized, so reject it now.
3747 Diag(NewArgs[ArgIdx].getLocation(),
3748 diag::err_alias_template_expansion_into_fixed_list)
3749 << NewArgs[ArgIdx].getSourceRange();
3750 Diag((*Param)->getLocation(), diag::note_template_param_here);
3754 // We're now done with this argument.
3757 if ((*Param)->isTemplateParameterPack()) {
3758 // The template parameter was a template parameter pack, so take the
3759 // deduced argument and place it on the argument pack. Note that we
3760 // stay on the same template parameter so that we can deduce more
3762 ArgumentPack.push_back(Converted.pop_back_val());
3764 // Move to the next template parameter.
3768 // If we just saw a pack expansion into a non-pack, then directly convert
3769 // the remaining arguments, because we don't know what parameters they'll
3771 if (PackExpansionIntoNonPack) {
3772 if (!ArgumentPack.empty()) {
3773 // If we were part way through filling in an expanded parameter pack,
3774 // fall back to just producing individual arguments.
3775 Converted.insert(Converted.end(),
3776 ArgumentPack.begin(), ArgumentPack.end());
3777 ArgumentPack.clear();
3780 while (ArgIdx < NumArgs) {
3781 Converted.push_back(NewArgs[ArgIdx].getArgument());
3791 // If we're checking a partial template argument list, we're done.
3792 if (PartialTemplateArgs) {
3793 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3794 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3795 ArgumentPack.data(),
3796 ArgumentPack.size()));
3801 // If we have a template parameter pack with no more corresponding
3802 // arguments, just break out now and we'll fill in the argument pack below.
3803 if ((*Param)->isTemplateParameterPack()) {
3804 assert(!getExpandedPackSize(*Param) &&
3805 "Should have dealt with this already");
3807 // A non-expanded parameter pack before the end of the parameter list
3808 // only occurs for an ill-formed template parameter list, unless we've
3809 // got a partial argument list for a function template, so just bail out.
3810 if (Param + 1 != ParamEnd)
3813 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3814 ArgumentPack.data(),
3815 ArgumentPack.size()));
3816 ArgumentPack.clear();
3822 // Check whether we have a default argument.
3823 TemplateArgumentLoc Arg;
3825 // Retrieve the default template argument from the template
3826 // parameter. For each kind of template parameter, we substitute the
3827 // template arguments provided thus far and any "outer" template arguments
3828 // (when the template parameter was part of a nested template) into
3829 // the default argument.
3830 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
3831 if (!hasVisibleDefaultArgument(TTP))
3832 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
3835 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
3844 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3846 } else if (NonTypeTemplateParmDecl *NTTP
3847 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
3848 if (!hasVisibleDefaultArgument(NTTP))
3849 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
3852 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
3860 Expr *Ex = E.getAs<Expr>();
3861 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3863 TemplateTemplateParmDecl *TempParm
3864 = cast<TemplateTemplateParmDecl>(*Param);
3866 if (!hasVisibleDefaultArgument(TempParm))
3867 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
3870 NestedNameSpecifierLoc QualifierLoc;
3871 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
3880 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3881 TempParm->getDefaultArgument().getTemplateNameLoc());
3884 // Introduce an instantiation record that describes where we are using
3885 // the default template argument.
3886 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3887 SourceRange(TemplateLoc, RAngleLoc));
3888 if (Inst.isInvalid())
3891 // Check the default template argument.
3892 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
3893 RAngleLoc, 0, Converted))
3896 // Core issue 150 (assumed resolution): if this is a template template
3897 // parameter, keep track of the default template arguments from the
3898 // template definition.
3899 if (isTemplateTemplateParameter)
3900 NewArgs.addArgument(Arg);
3902 // Move to the next template parameter and argument.
3907 // If we're performing a partial argument substitution, allow any trailing
3908 // pack expansions; they might be empty. This can happen even if
3909 // PartialTemplateArgs is false (the list of arguments is complete but
3910 // still dependent).
3911 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3912 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
3913 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
3914 Converted.push_back(NewArgs[ArgIdx++].getArgument());
3917 // If we have any leftover arguments, then there were too many arguments.
3918 // Complain and fail.
3919 if (ArgIdx < NumArgs)
3920 return diagnoseArityMismatch(*this, Template, TemplateLoc, NewArgs);
3922 // No problems found with the new argument list, propagate changes back
3924 TemplateArgs = NewArgs;
3930 class UnnamedLocalNoLinkageFinder
3931 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
3936 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
3939 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3941 bool Visit(QualType T) {
3942 return inherited::Visit(T.getTypePtr());
3945 #define TYPE(Class, Parent) \
3946 bool Visit##Class##Type(const Class##Type *);
3947 #define ABSTRACT_TYPE(Class, Parent) \
3948 bool Visit##Class##Type(const Class##Type *) { return false; }
3949 #define NON_CANONICAL_TYPE(Class, Parent) \
3950 bool Visit##Class##Type(const Class##Type *) { return false; }
3951 #include "clang/AST/TypeNodes.def"
3953 bool VisitTagDecl(const TagDecl *Tag);
3954 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3958 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
3962 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3963 return Visit(T->getElementType());
3966 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
3967 return Visit(T->getPointeeType());
3970 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
3971 const BlockPointerType* T) {
3972 return Visit(T->getPointeeType());
3975 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
3976 const LValueReferenceType* T) {
3977 return Visit(T->getPointeeType());
3980 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
3981 const RValueReferenceType* T) {
3982 return Visit(T->getPointeeType());
3985 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
3986 const MemberPointerType* T) {
3987 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3990 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
3991 const ConstantArrayType* T) {
3992 return Visit(T->getElementType());
3995 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
3996 const IncompleteArrayType* T) {
3997 return Visit(T->getElementType());
4000 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
4001 const VariableArrayType* T) {
4002 return Visit(T->getElementType());
4005 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
4006 const DependentSizedArrayType* T) {
4007 return Visit(T->getElementType());
4010 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
4011 const DependentSizedExtVectorType* T) {
4012 return Visit(T->getElementType());
4015 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
4016 return Visit(T->getElementType());
4019 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
4020 return Visit(T->getElementType());
4023 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
4024 const FunctionProtoType* T) {
4025 for (const auto &A : T->param_types()) {
4030 return Visit(T->getReturnType());
4033 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
4034 const FunctionNoProtoType* T) {
4035 return Visit(T->getReturnType());
4038 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
4039 const UnresolvedUsingType*) {
4043 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
4047 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4048 return Visit(T->getUnderlyingType());
4051 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4055 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4056 const UnaryTransformType*) {
4060 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4061 return Visit(T->getDeducedType());
4064 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4065 return VisitTagDecl(T->getDecl());
4068 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4069 return VisitTagDecl(T->getDecl());
4072 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4073 const TemplateTypeParmType*) {
4077 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4078 const SubstTemplateTypeParmPackType *) {
4082 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4083 const TemplateSpecializationType*) {
4087 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4088 const InjectedClassNameType* T) {
4089 return VisitTagDecl(T->getDecl());
4092 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4093 const DependentNameType* T) {
4094 return VisitNestedNameSpecifier(T->getQualifier());
4097 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4098 const DependentTemplateSpecializationType* T) {
4099 return VisitNestedNameSpecifier(T->getQualifier());
4102 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4103 const PackExpansionType* T) {
4104 return Visit(T->getPattern());
4107 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4111 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4112 const ObjCInterfaceType *) {
4116 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4117 const ObjCObjectPointerType *) {
4121 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4122 return Visit(T->getValueType());
4125 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4126 if (Tag->getDeclContext()->isFunctionOrMethod()) {
4127 S.Diag(SR.getBegin(),
4128 S.getLangOpts().CPlusPlus11 ?
4129 diag::warn_cxx98_compat_template_arg_local_type :
4130 diag::ext_template_arg_local_type)
4131 << S.Context.getTypeDeclType(Tag) << SR;
4135 if (!Tag->hasNameForLinkage()) {
4136 S.Diag(SR.getBegin(),
4137 S.getLangOpts().CPlusPlus11 ?
4138 diag::warn_cxx98_compat_template_arg_unnamed_type :
4139 diag::ext_template_arg_unnamed_type) << SR;
4140 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4147 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4148 NestedNameSpecifier *NNS) {
4149 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4152 switch (NNS->getKind()) {
4153 case NestedNameSpecifier::Identifier:
4154 case NestedNameSpecifier::Namespace:
4155 case NestedNameSpecifier::NamespaceAlias:
4156 case NestedNameSpecifier::Global:
4157 case NestedNameSpecifier::Super:
4160 case NestedNameSpecifier::TypeSpec:
4161 case NestedNameSpecifier::TypeSpecWithTemplate:
4162 return Visit(QualType(NNS->getAsType(), 0));
4164 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4168 /// \brief Check a template argument against its corresponding
4169 /// template type parameter.
4171 /// This routine implements the semantics of C++ [temp.arg.type]. It
4172 /// returns true if an error occurred, and false otherwise.
4173 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
4174 TypeSourceInfo *ArgInfo) {
4175 assert(ArgInfo && "invalid TypeSourceInfo");
4176 QualType Arg = ArgInfo->getType();
4177 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
4179 if (Arg->isVariablyModifiedType()) {
4180 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
4181 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
4182 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
4185 // C++03 [temp.arg.type]p2:
4186 // A local type, a type with no linkage, an unnamed type or a type
4187 // compounded from any of these types shall not be used as a
4188 // template-argument for a template type-parameter.
4190 // C++11 allows these, and even in C++03 we allow them as an extension with
4193 if (LangOpts.CPlusPlus11)
4195 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4197 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4200 NeedsCheck = Arg->hasUnnamedOrLocalType();
4203 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4204 (void)Finder.Visit(Context.getCanonicalType(Arg));
4210 enum NullPointerValueKind {
4216 /// \brief Determine whether the given template argument is a null pointer
4217 /// value of the appropriate type.
4218 static NullPointerValueKind
4219 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4220 QualType ParamType, Expr *Arg) {
4221 if (Arg->isValueDependent() || Arg->isTypeDependent())
4222 return NPV_NotNullPointer;
4224 if (!S.getLangOpts().CPlusPlus11)
4225 return NPV_NotNullPointer;
4227 // Determine whether we have a constant expression.
4228 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4229 if (ArgRV.isInvalid())
4233 Expr::EvalResult EvalResult;
4234 SmallVector<PartialDiagnosticAt, 8> Notes;
4235 EvalResult.Diag = &Notes;
4236 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
4237 EvalResult.HasSideEffects) {
4238 SourceLocation DiagLoc = Arg->getExprLoc();
4240 // If our only note is the usual "invalid subexpression" note, just point
4241 // the caret at its location rather than producing an essentially
4243 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4244 diag::note_invalid_subexpr_in_const_expr) {
4245 DiagLoc = Notes[0].first;
4249 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4250 << Arg->getType() << Arg->getSourceRange();
4251 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4252 S.Diag(Notes[I].first, Notes[I].second);
4254 S.Diag(Param->getLocation(), diag::note_template_param_here);
4258 // C++11 [temp.arg.nontype]p1:
4259 // - an address constant expression of type std::nullptr_t
4260 if (Arg->getType()->isNullPtrType())
4261 return NPV_NullPointer;
4263 // - a constant expression that evaluates to a null pointer value (4.10); or
4264 // - a constant expression that evaluates to a null member pointer value
4266 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4267 (EvalResult.Val.isMemberPointer() &&
4268 !EvalResult.Val.getMemberPointerDecl())) {
4269 // If our expression has an appropriate type, we've succeeded.
4270 bool ObjCLifetimeConversion;
4271 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4272 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4273 ObjCLifetimeConversion))
4274 return NPV_NullPointer;
4276 // The types didn't match, but we know we got a null pointer; complain,
4277 // then recover as if the types were correct.
4278 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4279 << Arg->getType() << ParamType << Arg->getSourceRange();
4280 S.Diag(Param->getLocation(), diag::note_template_param_here);
4281 return NPV_NullPointer;
4284 // If we don't have a null pointer value, but we do have a NULL pointer
4285 // constant, suggest a cast to the appropriate type.
4286 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4287 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4288 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
4289 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4290 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4292 S.Diag(Param->getLocation(), diag::note_template_param_here);
4293 return NPV_NullPointer;
4296 // FIXME: If we ever want to support general, address-constant expressions
4297 // as non-type template arguments, we should return the ExprResult here to
4298 // be interpreted by the caller.
4299 return NPV_NotNullPointer;
4302 /// \brief Checks whether the given template argument is compatible with its
4303 /// template parameter.
4304 static bool CheckTemplateArgumentIsCompatibleWithParameter(
4305 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4306 Expr *Arg, QualType ArgType) {
4307 bool ObjCLifetimeConversion;
4308 if (ParamType->isPointerType() &&
4309 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4310 S.IsQualificationConversion(ArgType, ParamType, false,
4311 ObjCLifetimeConversion)) {
4312 // For pointer-to-object types, qualification conversions are
4315 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4316 if (!ParamRef->getPointeeType()->isFunctionType()) {
4317 // C++ [temp.arg.nontype]p5b3:
4318 // For a non-type template-parameter of type reference to
4319 // object, no conversions apply. The type referred to by the
4320 // reference may be more cv-qualified than the (otherwise
4321 // identical) type of the template- argument. The
4322 // template-parameter is bound directly to the
4323 // template-argument, which shall be an lvalue.
4325 // FIXME: Other qualifiers?
4326 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4327 unsigned ArgQuals = ArgType.getCVRQualifiers();
4329 if ((ParamQuals | ArgQuals) != ParamQuals) {
4330 S.Diag(Arg->getLocStart(),
4331 diag::err_template_arg_ref_bind_ignores_quals)
4332 << ParamType << Arg->getType() << Arg->getSourceRange();
4333 S.Diag(Param->getLocation(), diag::note_template_param_here);
4339 // At this point, the template argument refers to an object or
4340 // function with external linkage. We now need to check whether the
4341 // argument and parameter types are compatible.
4342 if (!S.Context.hasSameUnqualifiedType(ArgType,
4343 ParamType.getNonReferenceType())) {
4344 // We can't perform this conversion or binding.
4345 if (ParamType->isReferenceType())
4346 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4347 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4349 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4350 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4351 S.Diag(Param->getLocation(), diag::note_template_param_here);
4359 /// \brief Checks whether the given template argument is the address
4360 /// of an object or function according to C++ [temp.arg.nontype]p1.
4362 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4363 NonTypeTemplateParmDecl *Param,
4366 TemplateArgument &Converted) {
4367 bool Invalid = false;
4369 QualType ArgType = Arg->getType();
4371 bool AddressTaken = false;
4372 SourceLocation AddrOpLoc;
4373 if (S.getLangOpts().MicrosoftExt) {
4374 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4375 // dereference and address-of operators.
4376 Arg = Arg->IgnoreParenCasts();
4378 bool ExtWarnMSTemplateArg = false;
4379 UnaryOperatorKind FirstOpKind;
4380 SourceLocation FirstOpLoc;
4381 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4382 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4383 if (UnOpKind == UO_Deref)
4384 ExtWarnMSTemplateArg = true;
4385 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4386 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4387 if (!AddrOpLoc.isValid()) {
4388 FirstOpKind = UnOpKind;
4389 FirstOpLoc = UnOp->getOperatorLoc();
4394 if (FirstOpLoc.isValid()) {
4395 if (ExtWarnMSTemplateArg)
4396 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4397 << ArgIn->getSourceRange();
4399 if (FirstOpKind == UO_AddrOf)
4400 AddressTaken = true;
4401 else if (Arg->getType()->isPointerType()) {
4402 // We cannot let pointers get dereferenced here, that is obviously not a
4403 // constant expression.
4404 assert(FirstOpKind == UO_Deref);
4405 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4406 << Arg->getSourceRange();
4410 // See through any implicit casts we added to fix the type.
4411 Arg = Arg->IgnoreImpCasts();
4413 // C++ [temp.arg.nontype]p1:
4415 // A template-argument for a non-type, non-template
4416 // template-parameter shall be one of: [...]
4418 // -- the address of an object or function with external
4419 // linkage, including function templates and function
4420 // template-ids but excluding non-static class members,
4421 // expressed as & id-expression where the & is optional if
4422 // the name refers to a function or array, or if the
4423 // corresponding template-parameter is a reference; or
4425 // In C++98/03 mode, give an extension warning on any extra parentheses.
4426 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4427 bool ExtraParens = false;
4428 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4429 if (!Invalid && !ExtraParens) {
4430 S.Diag(Arg->getLocStart(),
4431 S.getLangOpts().CPlusPlus11
4432 ? diag::warn_cxx98_compat_template_arg_extra_parens
4433 : diag::ext_template_arg_extra_parens)
4434 << Arg->getSourceRange();
4438 Arg = Parens->getSubExpr();
4441 while (SubstNonTypeTemplateParmExpr *subst =
4442 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4443 Arg = subst->getReplacement()->IgnoreImpCasts();
4445 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4446 if (UnOp->getOpcode() == UO_AddrOf) {
4447 Arg = UnOp->getSubExpr();
4448 AddressTaken = true;
4449 AddrOpLoc = UnOp->getOperatorLoc();
4453 while (SubstNonTypeTemplateParmExpr *subst =
4454 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4455 Arg = subst->getReplacement()->IgnoreImpCasts();
4458 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4459 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4461 // If our parameter has pointer type, check for a null template value.
4462 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4463 NullPointerValueKind NPV;
4464 // dllimport'd entities aren't constant but are available inside of template
4466 if (Entity && Entity->hasAttr<DLLImportAttr>())
4467 NPV = NPV_NotNullPointer;
4469 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4471 case NPV_NullPointer:
4472 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4473 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4474 /*isNullPtr=*/true);
4480 case NPV_NotNullPointer:
4485 // Stop checking the precise nature of the argument if it is value dependent,
4486 // it should be checked when instantiated.
4487 if (Arg->isValueDependent()) {
4488 Converted = TemplateArgument(ArgIn);
4492 if (isa<CXXUuidofExpr>(Arg)) {
4493 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4494 ArgIn, Arg, ArgType))
4497 Converted = TemplateArgument(ArgIn);
4502 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4503 << Arg->getSourceRange();
4504 S.Diag(Param->getLocation(), diag::note_template_param_here);
4508 // Cannot refer to non-static data members
4509 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
4510 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
4511 << Entity << Arg->getSourceRange();
4512 S.Diag(Param->getLocation(), diag::note_template_param_here);
4516 // Cannot refer to non-static member functions
4517 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
4518 if (!Method->isStatic()) {
4519 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
4520 << Method << Arg->getSourceRange();
4521 S.Diag(Param->getLocation(), diag::note_template_param_here);
4526 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4527 VarDecl *Var = dyn_cast<VarDecl>(Entity);
4529 // A non-type template argument must refer to an object or function.
4530 if (!Func && !Var) {
4531 // We found something, but we don't know specifically what it is.
4532 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4533 << Arg->getSourceRange();
4534 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4538 // Address / reference template args must have external linkage in C++98.
4539 if (Entity->getFormalLinkage() == InternalLinkage) {
4540 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
4541 diag::warn_cxx98_compat_template_arg_object_internal :
4542 diag::ext_template_arg_object_internal)
4543 << !Func << Entity << Arg->getSourceRange();
4544 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4546 } else if (!Entity->hasLinkage()) {
4547 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4548 << !Func << Entity << Arg->getSourceRange();
4549 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4555 // If the template parameter has pointer type, the function decays.
4556 if (ParamType->isPointerType() && !AddressTaken)
4557 ArgType = S.Context.getPointerType(Func->getType());
4558 else if (AddressTaken && ParamType->isReferenceType()) {
4559 // If we originally had an address-of operator, but the
4560 // parameter has reference type, complain and (if things look
4561 // like they will work) drop the address-of operator.
4562 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4563 ParamType.getNonReferenceType())) {
4564 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4566 S.Diag(Param->getLocation(), diag::note_template_param_here);
4570 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4572 << FixItHint::CreateRemoval(AddrOpLoc);
4573 S.Diag(Param->getLocation(), diag::note_template_param_here);
4575 ArgType = Func->getType();
4578 // A value of reference type is not an object.
4579 if (Var->getType()->isReferenceType()) {
4580 S.Diag(Arg->getLocStart(),
4581 diag::err_template_arg_reference_var)
4582 << Var->getType() << Arg->getSourceRange();
4583 S.Diag(Param->getLocation(), diag::note_template_param_here);
4587 // A template argument must have static storage duration.
4588 if (Var->getTLSKind()) {
4589 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4590 << Arg->getSourceRange();
4591 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4595 // If the template parameter has pointer type, we must have taken
4596 // the address of this object.
4597 if (ParamType->isReferenceType()) {
4599 // If we originally had an address-of operator, but the
4600 // parameter has reference type, complain and (if things look
4601 // like they will work) drop the address-of operator.
4602 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4603 ParamType.getNonReferenceType())) {
4604 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4606 S.Diag(Param->getLocation(), diag::note_template_param_here);
4610 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4612 << FixItHint::CreateRemoval(AddrOpLoc);
4613 S.Diag(Param->getLocation(), diag::note_template_param_here);
4615 ArgType = Var->getType();
4617 } else if (!AddressTaken && ParamType->isPointerType()) {
4618 if (Var->getType()->isArrayType()) {
4619 // Array-to-pointer decay.
4620 ArgType = S.Context.getArrayDecayedType(Var->getType());
4622 // If the template parameter has pointer type but the address of
4623 // this object was not taken, complain and (possibly) recover by
4624 // taking the address of the entity.
4625 ArgType = S.Context.getPointerType(Var->getType());
4626 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4627 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4629 S.Diag(Param->getLocation(), diag::note_template_param_here);
4633 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4635 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4637 S.Diag(Param->getLocation(), diag::note_template_param_here);
4642 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4646 // Create the template argument.
4648 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), ParamType);
4649 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
4653 /// \brief Checks whether the given template argument is a pointer to
4654 /// member constant according to C++ [temp.arg.nontype]p1.
4655 static bool CheckTemplateArgumentPointerToMember(Sema &S,
4656 NonTypeTemplateParmDecl *Param,
4659 TemplateArgument &Converted) {
4660 bool Invalid = false;
4662 // Check for a null pointer value.
4663 Expr *Arg = ResultArg;
4664 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4667 case NPV_NullPointer:
4668 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4669 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4671 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft())
4672 S.RequireCompleteType(Arg->getExprLoc(), ParamType, 0);
4674 case NPV_NotNullPointer:
4678 bool ObjCLifetimeConversion;
4679 if (S.IsQualificationConversion(Arg->getType(),
4680 ParamType.getNonReferenceType(),
4681 false, ObjCLifetimeConversion)) {
4682 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
4683 Arg->getValueKind()).get();
4685 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4686 ParamType.getNonReferenceType())) {
4687 // We can't perform this conversion.
4688 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4689 << Arg->getType() << ParamType << Arg->getSourceRange();
4690 S.Diag(Param->getLocation(), diag::note_template_param_here);
4694 // See through any implicit casts we added to fix the type.
4695 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
4696 Arg = Cast->getSubExpr();
4698 // C++ [temp.arg.nontype]p1:
4700 // A template-argument for a non-type, non-template
4701 // template-parameter shall be one of: [...]
4703 // -- a pointer to member expressed as described in 5.3.1.
4704 DeclRefExpr *DRE = nullptr;
4706 // In C++98/03 mode, give an extension warning on any extra parentheses.
4707 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4708 bool ExtraParens = false;
4709 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4710 if (!Invalid && !ExtraParens) {
4711 S.Diag(Arg->getLocStart(),
4712 S.getLangOpts().CPlusPlus11 ?
4713 diag::warn_cxx98_compat_template_arg_extra_parens :
4714 diag::ext_template_arg_extra_parens)
4715 << Arg->getSourceRange();
4719 Arg = Parens->getSubExpr();
4722 while (SubstNonTypeTemplateParmExpr *subst =
4723 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4724 Arg = subst->getReplacement()->IgnoreImpCasts();
4726 // A pointer-to-member constant written &Class::member.
4727 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4728 if (UnOp->getOpcode() == UO_AddrOf) {
4729 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4730 if (DRE && !DRE->getQualifier())
4734 // A constant of pointer-to-member type.
4735 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4736 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4737 if (VD->getType()->isMemberPointerType()) {
4738 if (isa<NonTypeTemplateParmDecl>(VD)) {
4739 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4740 Converted = TemplateArgument(Arg);
4742 VD = cast<ValueDecl>(VD->getCanonicalDecl());
4743 Converted = TemplateArgument(VD, ParamType);
4754 return S.Diag(Arg->getLocStart(),
4755 diag::err_template_arg_not_pointer_to_member_form)
4756 << Arg->getSourceRange();
4758 if (isa<FieldDecl>(DRE->getDecl()) ||
4759 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4760 isa<CXXMethodDecl>(DRE->getDecl())) {
4761 assert((isa<FieldDecl>(DRE->getDecl()) ||
4762 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4763 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4764 "Only non-static member pointers can make it here");
4766 // Okay: this is the address of a non-static member, and therefore
4767 // a member pointer constant.
4768 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4769 Converted = TemplateArgument(Arg);
4771 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4772 Converted = TemplateArgument(D, ParamType);
4777 // We found something else, but we don't know specifically what it is.
4778 S.Diag(Arg->getLocStart(),
4779 diag::err_template_arg_not_pointer_to_member_form)
4780 << Arg->getSourceRange();
4781 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4785 /// \brief Check a template argument against its corresponding
4786 /// non-type template parameter.
4788 /// This routine implements the semantics of C++ [temp.arg.nontype].
4789 /// If an error occurred, it returns ExprError(); otherwise, it
4790 /// returns the converted template argument. \p ParamType is the
4791 /// type of the non-type template parameter after it has been instantiated.
4792 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4793 QualType ParamType, Expr *Arg,
4794 TemplateArgument &Converted,
4795 CheckTemplateArgumentKind CTAK) {
4796 SourceLocation StartLoc = Arg->getLocStart();
4798 // If either the parameter has a dependent type or the argument is
4799 // type-dependent, there's nothing we can check now.
4800 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
4801 // FIXME: Produce a cloned, canonical expression?
4802 Converted = TemplateArgument(Arg);
4806 // We should have already dropped all cv-qualifiers by now.
4807 assert(!ParamType.hasQualifiers() &&
4808 "non-type template parameter type cannot be qualified");
4810 if (CTAK == CTAK_Deduced &&
4811 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4812 // C++ [temp.deduct.type]p17:
4813 // If, in the declaration of a function template with a non-type
4814 // template-parameter, the non-type template-parameter is used
4815 // in an expression in the function parameter-list and, if the
4816 // corresponding template-argument is deduced, the
4817 // template-argument type shall match the type of the
4818 // template-parameter exactly, except that a template-argument
4819 // deduced from an array bound may be of any integral type.
4820 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4821 << Arg->getType().getUnqualifiedType()
4822 << ParamType.getUnqualifiedType();
4823 Diag(Param->getLocation(), diag::note_template_param_here);
4827 if (getLangOpts().CPlusPlus1z) {
4828 // FIXME: We can do some limited checking for a value-dependent but not
4829 // type-dependent argument.
4830 if (Arg->isValueDependent()) {
4831 Converted = TemplateArgument(Arg);
4835 // C++1z [temp.arg.nontype]p1:
4836 // A template-argument for a non-type template parameter shall be
4837 // a converted constant expression of the type of the template-parameter.
4839 ExprResult ArgResult = CheckConvertedConstantExpression(
4840 Arg, ParamType, Value, CCEK_TemplateArg);
4841 if (ArgResult.isInvalid())
4844 QualType CanonParamType = Context.getCanonicalType(ParamType);
4846 // Convert the APValue to a TemplateArgument.
4847 switch (Value.getKind()) {
4848 case APValue::Uninitialized:
4849 assert(ParamType->isNullPtrType());
4850 Converted = TemplateArgument(CanonParamType, /*isNullPtr*/true);
4853 assert(ParamType->isIntegralOrEnumerationType());
4854 Converted = TemplateArgument(Context, Value.getInt(), CanonParamType);
4856 case APValue::MemberPointer: {
4857 assert(ParamType->isMemberPointerType());
4859 // FIXME: We need TemplateArgument representation and mangling for these.
4860 if (!Value.getMemberPointerPath().empty()) {
4861 Diag(Arg->getLocStart(),
4862 diag::err_template_arg_member_ptr_base_derived_not_supported)
4863 << Value.getMemberPointerDecl() << ParamType
4864 << Arg->getSourceRange();
4868 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl());
4869 Converted = VD ? TemplateArgument(VD, CanonParamType)
4870 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4873 case APValue::LValue: {
4874 // For a non-type template-parameter of pointer or reference type,
4875 // the value of the constant expression shall not refer to
4876 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
4877 ParamType->isNullPtrType());
4878 // -- a temporary object
4879 // -- a string literal
4880 // -- the result of a typeid expression, or
4881 // -- a predefind __func__ variable
4882 if (auto *E = Value.getLValueBase().dyn_cast<const Expr*>()) {
4883 if (isa<CXXUuidofExpr>(E)) {
4884 Converted = TemplateArgument(const_cast<Expr*>(E));
4887 Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4888 << Arg->getSourceRange();
4891 auto *VD = const_cast<ValueDecl *>(
4892 Value.getLValueBase().dyn_cast<const ValueDecl *>());
4894 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 &&
4895 VD && VD->getType()->isArrayType() &&
4896 Value.getLValuePath()[0].ArrayIndex == 0 &&
4897 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
4898 // Per defect report (no number yet):
4899 // ... other than a pointer to the first element of a complete array
4901 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
4902 Value.isLValueOnePastTheEnd()) {
4903 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
4904 << Value.getAsString(Context, ParamType);
4907 assert((VD || !ParamType->isReferenceType()) &&
4908 "null reference should not be a constant expression");
4909 assert((!VD || !ParamType->isNullPtrType()) &&
4910 "non-null value of type nullptr_t?");
4911 Converted = VD ? TemplateArgument(VD, CanonParamType)
4912 : TemplateArgument(CanonParamType, /*isNullPtr*/true);
4915 case APValue::AddrLabelDiff:
4916 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
4917 case APValue::Float:
4918 case APValue::ComplexInt:
4919 case APValue::ComplexFloat:
4920 case APValue::Vector:
4921 case APValue::Array:
4922 case APValue::Struct:
4923 case APValue::Union:
4924 llvm_unreachable("invalid kind for template argument");
4927 return ArgResult.get();
4930 // C++ [temp.arg.nontype]p5:
4931 // The following conversions are performed on each expression used
4932 // as a non-type template-argument. If a non-type
4933 // template-argument cannot be converted to the type of the
4934 // corresponding template-parameter then the program is
4936 if (ParamType->isIntegralOrEnumerationType()) {
4938 // -- for a non-type template-parameter of integral or
4939 // enumeration type, conversions permitted in a converted
4940 // constant expression are applied.
4943 // -- for a non-type template-parameter of integral or
4944 // enumeration type, integral promotions (4.5) and integral
4945 // conversions (4.7) are applied.
4947 if (getLangOpts().CPlusPlus11) {
4948 // We can't check arbitrary value-dependent arguments.
4949 // FIXME: If there's no viable conversion to the template parameter type,
4950 // we should be able to diagnose that prior to instantiation.
4951 if (Arg->isValueDependent()) {
4952 Converted = TemplateArgument(Arg);
4956 // C++ [temp.arg.nontype]p1:
4957 // A template-argument for a non-type, non-template template-parameter
4960 // -- for a non-type template-parameter of integral or enumeration
4961 // type, a converted constant expression of the type of the
4962 // template-parameter; or
4964 ExprResult ArgResult =
4965 CheckConvertedConstantExpression(Arg, ParamType, Value,
4967 if (ArgResult.isInvalid())
4970 // Widen the argument value to sizeof(parameter type). This is almost
4971 // always a no-op, except when the parameter type is bool. In
4972 // that case, this may extend the argument from 1 bit to 8 bits.
4973 QualType IntegerType = ParamType;
4974 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4975 IntegerType = Enum->getDecl()->getIntegerType();
4976 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4978 Converted = TemplateArgument(Context, Value,
4979 Context.getCanonicalType(ParamType));
4983 ExprResult ArgResult = DefaultLvalueConversion(Arg);
4984 if (ArgResult.isInvalid())
4986 Arg = ArgResult.get();
4988 QualType ArgType = Arg->getType();
4990 // C++ [temp.arg.nontype]p1:
4991 // A template-argument for a non-type, non-template
4992 // template-parameter shall be one of:
4994 // -- an integral constant-expression of integral or enumeration
4996 // -- the name of a non-type template-parameter; or
4997 SourceLocation NonConstantLoc;
4999 if (!ArgType->isIntegralOrEnumerationType()) {
5000 Diag(Arg->getLocStart(),
5001 diag::err_template_arg_not_integral_or_enumeral)
5002 << ArgType << Arg->getSourceRange();
5003 Diag(Param->getLocation(), diag::note_template_param_here);
5005 } else if (!Arg->isValueDependent()) {
5006 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
5010 TmplArgICEDiagnoser(QualType T) : T(T) { }
5012 void diagnoseNotICE(Sema &S, SourceLocation Loc,
5013 SourceRange SR) override {
5014 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
5016 } Diagnoser(ArgType);
5018 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
5024 // From here on out, all we care about is the unqualified form
5025 // of the argument type.
5026 ArgType = ArgType.getUnqualifiedType();
5028 // Try to convert the argument to the parameter's type.
5029 if (Context.hasSameType(ParamType, ArgType)) {
5030 // Okay: no conversion necessary
5031 } else if (ParamType->isBooleanType()) {
5032 // This is an integral-to-boolean conversion.
5033 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
5034 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
5035 !ParamType->isEnumeralType()) {
5036 // This is an integral promotion or conversion.
5037 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
5039 // We can't perform this conversion.
5040 Diag(Arg->getLocStart(),
5041 diag::err_template_arg_not_convertible)
5042 << Arg->getType() << ParamType << Arg->getSourceRange();
5043 Diag(Param->getLocation(), diag::note_template_param_here);
5047 // Add the value of this argument to the list of converted
5048 // arguments. We use the bitwidth and signedness of the template
5050 if (Arg->isValueDependent()) {
5051 // The argument is value-dependent. Create a new
5052 // TemplateArgument with the converted expression.
5053 Converted = TemplateArgument(Arg);
5057 QualType IntegerType = Context.getCanonicalType(ParamType);
5058 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
5059 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
5061 if (ParamType->isBooleanType()) {
5062 // Value must be zero or one.
5064 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5065 if (Value.getBitWidth() != AllowedBits)
5066 Value = Value.extOrTrunc(AllowedBits);
5067 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5069 llvm::APSInt OldValue = Value;
5071 // Coerce the template argument's value to the value it will have
5072 // based on the template parameter's type.
5073 unsigned AllowedBits = Context.getTypeSize(IntegerType);
5074 if (Value.getBitWidth() != AllowedBits)
5075 Value = Value.extOrTrunc(AllowedBits);
5076 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
5078 // Complain if an unsigned parameter received a negative value.
5079 if (IntegerType->isUnsignedIntegerOrEnumerationType()
5080 && (OldValue.isSigned() && OldValue.isNegative())) {
5081 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
5082 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5083 << Arg->getSourceRange();
5084 Diag(Param->getLocation(), diag::note_template_param_here);
5087 // Complain if we overflowed the template parameter's type.
5088 unsigned RequiredBits;
5089 if (IntegerType->isUnsignedIntegerOrEnumerationType())
5090 RequiredBits = OldValue.getActiveBits();
5091 else if (OldValue.isUnsigned())
5092 RequiredBits = OldValue.getActiveBits() + 1;
5094 RequiredBits = OldValue.getMinSignedBits();
5095 if (RequiredBits > AllowedBits) {
5096 Diag(Arg->getLocStart(),
5097 diag::warn_template_arg_too_large)
5098 << OldValue.toString(10) << Value.toString(10) << Param->getType()
5099 << Arg->getSourceRange();
5100 Diag(Param->getLocation(), diag::note_template_param_here);
5104 Converted = TemplateArgument(Context, Value,
5105 ParamType->isEnumeralType()
5106 ? Context.getCanonicalType(ParamType)
5111 QualType ArgType = Arg->getType();
5112 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
5114 // Handle pointer-to-function, reference-to-function, and
5115 // pointer-to-member-function all in (roughly) the same way.
5116 if (// -- For a non-type template-parameter of type pointer to
5117 // function, only the function-to-pointer conversion (4.3) is
5118 // applied. If the template-argument represents a set of
5119 // overloaded functions (or a pointer to such), the matching
5120 // function is selected from the set (13.4).
5121 (ParamType->isPointerType() &&
5122 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
5123 // -- For a non-type template-parameter of type reference to
5124 // function, no conversions apply. If the template-argument
5125 // represents a set of overloaded functions, the matching
5126 // function is selected from the set (13.4).
5127 (ParamType->isReferenceType() &&
5128 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
5129 // -- For a non-type template-parameter of type pointer to
5130 // member function, no conversions apply. If the
5131 // template-argument represents a set of overloaded member
5132 // functions, the matching member function is selected from
5134 (ParamType->isMemberPointerType() &&
5135 ParamType->getAs<MemberPointerType>()->getPointeeType()
5136 ->isFunctionType())) {
5138 if (Arg->getType() == Context.OverloadTy) {
5139 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
5142 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5145 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5146 ArgType = Arg->getType();
5151 if (!ParamType->isMemberPointerType()) {
5152 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5159 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5165 if (ParamType->isPointerType()) {
5166 // -- for a non-type template-parameter of type pointer to
5167 // object, qualification conversions (4.4) and the
5168 // array-to-pointer conversion (4.2) are applied.
5169 // C++0x also allows a value of std::nullptr_t.
5170 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
5171 "Only object pointers allowed here");
5173 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5180 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
5181 // -- For a non-type template-parameter of type reference to
5182 // object, no conversions apply. The type referred to by the
5183 // reference may be more cv-qualified than the (otherwise
5184 // identical) type of the template-argument. The
5185 // template-parameter is bound directly to the
5186 // template-argument, which must be an lvalue.
5187 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
5188 "Only object references allowed here");
5190 if (Arg->getType() == Context.OverloadTy) {
5191 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5192 ParamRefType->getPointeeType(),
5195 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5198 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5199 ArgType = Arg->getType();
5204 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5211 // Deal with parameters of type std::nullptr_t.
5212 if (ParamType->isNullPtrType()) {
5213 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5214 Converted = TemplateArgument(Arg);
5218 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5219 case NPV_NotNullPointer:
5220 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5221 << Arg->getType() << ParamType;
5222 Diag(Param->getLocation(), diag::note_template_param_here);
5228 case NPV_NullPointer:
5229 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5230 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5236 // -- For a non-type template-parameter of type pointer to data
5237 // member, qualification conversions (4.4) are applied.
5238 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5240 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5246 /// \brief Check a template argument against its corresponding
5247 /// template template parameter.
5249 /// This routine implements the semantics of C++ [temp.arg.template].
5250 /// It returns true if an error occurred, and false otherwise.
5251 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5252 TemplateArgumentLoc &Arg,
5253 unsigned ArgumentPackIndex) {
5254 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
5255 TemplateDecl *Template = Name.getAsTemplateDecl();
5257 // Any dependent template name is fine.
5258 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5262 // C++0x [temp.arg.template]p1:
5263 // A template-argument for a template template-parameter shall be
5264 // the name of a class template or an alias template, expressed as an
5265 // id-expression. When the template-argument names a class template, only
5266 // primary class templates are considered when matching the
5267 // template template argument with the corresponding parameter;
5268 // partial specializations are not considered even if their
5269 // parameter lists match that of the template template parameter.
5271 // Note that we also allow template template parameters here, which
5272 // will happen when we are dealing with, e.g., class template
5273 // partial specializations.
5274 if (!isa<ClassTemplateDecl>(Template) &&
5275 !isa<TemplateTemplateParmDecl>(Template) &&
5276 !isa<TypeAliasTemplateDecl>(Template)) {
5277 assert(isa<FunctionTemplateDecl>(Template) &&
5278 "Only function templates are possible here");
5279 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
5280 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5284 TemplateParameterList *Params = Param->getTemplateParameters();
5285 if (Param->isExpandedParameterPack())
5286 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5288 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
5291 TPL_TemplateTemplateArgumentMatch,
5295 /// \brief Given a non-type template argument that refers to a
5296 /// declaration and the type of its corresponding non-type template
5297 /// parameter, produce an expression that properly refers to that
5300 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5302 SourceLocation Loc) {
5303 // C++ [temp.param]p8:
5305 // A non-type template-parameter of type "array of T" or
5306 // "function returning T" is adjusted to be of type "pointer to
5307 // T" or "pointer to function returning T", respectively.
5308 if (ParamType->isArrayType())
5309 ParamType = Context.getArrayDecayedType(ParamType);
5310 else if (ParamType->isFunctionType())
5311 ParamType = Context.getPointerType(ParamType);
5313 // For a NULL non-type template argument, return nullptr casted to the
5314 // parameter's type.
5315 if (Arg.getKind() == TemplateArgument::NullPtr) {
5316 return ImpCastExprToType(
5317 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5319 ParamType->getAs<MemberPointerType>()
5320 ? CK_NullToMemberPointer
5321 : CK_NullToPointer);
5323 assert(Arg.getKind() == TemplateArgument::Declaration &&
5324 "Only declaration template arguments permitted here");
5326 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5328 if (VD->getDeclContext()->isRecord() &&
5329 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5330 isa<IndirectFieldDecl>(VD))) {
5331 // If the value is a class member, we might have a pointer-to-member.
5332 // Determine whether the non-type template template parameter is of
5333 // pointer-to-member type. If so, we need to build an appropriate
5334 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5335 // would refer to the member itself.
5336 if (ParamType->isMemberPointerType()) {
5338 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5339 NestedNameSpecifier *Qualifier
5340 = NestedNameSpecifier::Create(Context, nullptr, false,
5341 ClassType.getTypePtr());
5343 SS.MakeTrivial(Context, Qualifier, Loc);
5345 // The actual value-ness of this is unimportant, but for
5346 // internal consistency's sake, references to instance methods
5348 ExprValueKind VK = VK_LValue;
5349 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5352 ExprResult RefExpr = BuildDeclRefExpr(VD,
5353 VD->getType().getNonReferenceType(),
5357 if (RefExpr.isInvalid())
5360 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5362 // We might need to perform a trailing qualification conversion, since
5363 // the element type on the parameter could be more qualified than the
5364 // element type in the expression we constructed.
5365 bool ObjCLifetimeConversion;
5366 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
5367 ParamType.getUnqualifiedType(), false,
5368 ObjCLifetimeConversion))
5369 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
5371 assert(!RefExpr.isInvalid() &&
5372 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
5373 ParamType.getUnqualifiedType()));
5378 QualType T = VD->getType().getNonReferenceType();
5380 if (ParamType->isPointerType()) {
5381 // When the non-type template parameter is a pointer, take the
5382 // address of the declaration.
5383 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
5384 if (RefExpr.isInvalid())
5387 if (T->isFunctionType() || T->isArrayType()) {
5388 // Decay functions and arrays.
5389 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
5390 if (RefExpr.isInvalid())
5396 // Take the address of everything else
5397 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5400 ExprValueKind VK = VK_RValue;
5402 // If the non-type template parameter has reference type, qualify the
5403 // resulting declaration reference with the extra qualifiers on the
5404 // type that the reference refers to.
5405 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5407 T = Context.getQualifiedType(T,
5408 TargetRef->getPointeeType().getQualifiers());
5409 } else if (isa<FunctionDecl>(VD)) {
5410 // References to functions are always lvalues.
5414 return BuildDeclRefExpr(VD, T, VK, Loc);
5417 /// \brief Construct a new expression that refers to the given
5418 /// integral template argument with the given source-location
5421 /// This routine takes care of the mapping from an integral template
5422 /// argument (which may have any integral type) to the appropriate
5425 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5426 SourceLocation Loc) {
5427 assert(Arg.getKind() == TemplateArgument::Integral &&
5428 "Operation is only valid for integral template arguments");
5429 QualType OrigT = Arg.getIntegralType();
5431 // If this is an enum type that we're instantiating, we need to use an integer
5432 // type the same size as the enumerator. We don't want to build an
5433 // IntegerLiteral with enum type. The integer type of an enum type can be of
5434 // any integral type with C++11 enum classes, make sure we create the right
5435 // type of literal for it.
5437 if (const EnumType *ET = OrigT->getAs<EnumType>())
5438 T = ET->getDecl()->getIntegerType();
5441 if (T->isAnyCharacterType()) {
5442 CharacterLiteral::CharacterKind Kind;
5443 if (T->isWideCharType())
5444 Kind = CharacterLiteral::Wide;
5445 else if (T->isChar16Type())
5446 Kind = CharacterLiteral::UTF16;
5447 else if (T->isChar32Type())
5448 Kind = CharacterLiteral::UTF32;
5450 Kind = CharacterLiteral::Ascii;
5452 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5454 } else if (T->isBooleanType()) {
5455 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5457 } else if (T->isNullPtrType()) {
5458 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5460 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
5463 if (OrigT->isEnumeralType()) {
5464 // FIXME: This is a hack. We need a better way to handle substituted
5465 // non-type template parameters.
5466 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5468 Context.getTrivialTypeSourceInfo(OrigT, Loc),
5475 /// \brief Match two template parameters within template parameter lists.
5476 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5478 Sema::TemplateParameterListEqualKind Kind,
5479 SourceLocation TemplateArgLoc) {
5480 // Check the actual kind (type, non-type, template).
5481 if (Old->getKind() != New->getKind()) {
5483 unsigned NextDiag = diag::err_template_param_different_kind;
5484 if (TemplateArgLoc.isValid()) {
5485 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5486 NextDiag = diag::note_template_param_different_kind;
5488 S.Diag(New->getLocation(), NextDiag)
5489 << (Kind != Sema::TPL_TemplateMatch);
5490 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5491 << (Kind != Sema::TPL_TemplateMatch);
5497 // Check that both are parameter packs are neither are parameter packs.
5498 // However, if we are matching a template template argument to a
5499 // template template parameter, the template template parameter can have
5500 // a parameter pack where the template template argument does not.
5501 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5502 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5503 Old->isTemplateParameterPack())) {
5505 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5506 if (TemplateArgLoc.isValid()) {
5507 S.Diag(TemplateArgLoc,
5508 diag::err_template_arg_template_params_mismatch);
5509 NextDiag = diag::note_template_parameter_pack_non_pack;
5512 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5513 : isa<NonTypeTemplateParmDecl>(New)? 1
5515 S.Diag(New->getLocation(), NextDiag)
5516 << ParamKind << New->isParameterPack();
5517 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5518 << ParamKind << Old->isParameterPack();
5524 // For non-type template parameters, check the type of the parameter.
5525 if (NonTypeTemplateParmDecl *OldNTTP
5526 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5527 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
5529 // If we are matching a template template argument to a template
5530 // template parameter and one of the non-type template parameter types
5531 // is dependent, then we must wait until template instantiation time
5532 // to actually compare the arguments.
5533 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5534 (OldNTTP->getType()->isDependentType() ||
5535 NewNTTP->getType()->isDependentType()))
5538 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5540 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5541 if (TemplateArgLoc.isValid()) {
5542 S.Diag(TemplateArgLoc,
5543 diag::err_template_arg_template_params_mismatch);
5544 NextDiag = diag::note_template_nontype_parm_different_type;
5546 S.Diag(NewNTTP->getLocation(), NextDiag)
5547 << NewNTTP->getType()
5548 << (Kind != Sema::TPL_TemplateMatch);
5549 S.Diag(OldNTTP->getLocation(),
5550 diag::note_template_nontype_parm_prev_declaration)
5551 << OldNTTP->getType();
5560 // For template template parameters, check the template parameter types.
5561 // The template parameter lists of template template
5562 // parameters must agree.
5563 if (TemplateTemplateParmDecl *OldTTP
5564 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
5565 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
5566 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5567 OldTTP->getTemplateParameters(),
5569 (Kind == Sema::TPL_TemplateMatch
5570 ? Sema::TPL_TemplateTemplateParmMatch
5578 /// \brief Diagnose a known arity mismatch when comparing template argument
5581 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
5582 TemplateParameterList *New,
5583 TemplateParameterList *Old,
5584 Sema::TemplateParameterListEqualKind Kind,
5585 SourceLocation TemplateArgLoc) {
5586 unsigned NextDiag = diag::err_template_param_list_different_arity;
5587 if (TemplateArgLoc.isValid()) {
5588 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5589 NextDiag = diag::note_template_param_list_different_arity;
5591 S.Diag(New->getTemplateLoc(), NextDiag)
5592 << (New->size() > Old->size())
5593 << (Kind != Sema::TPL_TemplateMatch)
5594 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5595 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5596 << (Kind != Sema::TPL_TemplateMatch)
5597 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5600 /// \brief Determine whether the given template parameter lists are
5603 /// \param New The new template parameter list, typically written in the
5604 /// source code as part of a new template declaration.
5606 /// \param Old The old template parameter list, typically found via
5607 /// name lookup of the template declared with this template parameter
5610 /// \param Complain If true, this routine will produce a diagnostic if
5611 /// the template parameter lists are not equivalent.
5613 /// \param Kind describes how we are to match the template parameter lists.
5615 /// \param TemplateArgLoc If this source location is valid, then we
5616 /// are actually checking the template parameter list of a template
5617 /// argument (New) against the template parameter list of its
5618 /// corresponding template template parameter (Old). We produce
5619 /// slightly different diagnostics in this scenario.
5621 /// \returns True if the template parameter lists are equal, false
5624 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5625 TemplateParameterList *Old,
5627 TemplateParameterListEqualKind Kind,
5628 SourceLocation TemplateArgLoc) {
5629 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5631 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5637 // C++0x [temp.arg.template]p3:
5638 // A template-argument matches a template template-parameter (call it P)
5639 // when each of the template parameters in the template-parameter-list of
5640 // the template-argument's corresponding class template or alias template
5641 // (call it A) matches the corresponding template parameter in the
5642 // template-parameter-list of P. [...]
5643 TemplateParameterList::iterator NewParm = New->begin();
5644 TemplateParameterList::iterator NewParmEnd = New->end();
5645 for (TemplateParameterList::iterator OldParm = Old->begin(),
5646 OldParmEnd = Old->end();
5647 OldParm != OldParmEnd; ++OldParm) {
5648 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5649 !(*OldParm)->isTemplateParameterPack()) {
5650 if (NewParm == NewParmEnd) {
5652 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5658 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5659 Kind, TemplateArgLoc))
5666 // C++0x [temp.arg.template]p3:
5667 // [...] When P's template- parameter-list contains a template parameter
5668 // pack (14.5.3), the template parameter pack will match zero or more
5669 // template parameters or template parameter packs in the
5670 // template-parameter-list of A with the same type and form as the
5671 // template parameter pack in P (ignoring whether those template
5672 // parameters are template parameter packs).
5673 for (; NewParm != NewParmEnd; ++NewParm) {
5674 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5675 Kind, TemplateArgLoc))
5680 // Make sure we exhausted all of the arguments.
5681 if (NewParm != NewParmEnd) {
5683 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5692 /// \brief Check whether a template can be declared within this scope.
5694 /// If the template declaration is valid in this scope, returns
5695 /// false. Otherwise, issues a diagnostic and returns true.
5697 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
5701 // Find the nearest enclosing declaration scope.
5702 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5703 (S->getFlags() & Scope::TemplateParamScope) != 0)
5707 // A template [...] shall not have C linkage.
5708 DeclContext *Ctx = S->getEntity();
5709 if (Ctx && Ctx->isExternCContext())
5710 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
5711 << TemplateParams->getSourceRange();
5713 while (Ctx && isa<LinkageSpecDecl>(Ctx))
5714 Ctx = Ctx->getParent();
5717 // A template-declaration can appear only as a namespace scope or
5718 // class scope declaration.
5720 if (Ctx->isFileContext())
5722 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5723 // C++ [temp.mem]p2:
5724 // A local class shall not have member templates.
5725 if (RD->isLocalClass())
5726 return Diag(TemplateParams->getTemplateLoc(),
5727 diag::err_template_inside_local_class)
5728 << TemplateParams->getSourceRange();
5734 return Diag(TemplateParams->getTemplateLoc(),
5735 diag::err_template_outside_namespace_or_class_scope)
5736 << TemplateParams->getSourceRange();
5739 /// \brief Determine what kind of template specialization the given declaration
5741 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
5743 return TSK_Undeclared;
5745 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5746 return Record->getTemplateSpecializationKind();
5747 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5748 return Function->getTemplateSpecializationKind();
5749 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5750 return Var->getTemplateSpecializationKind();
5752 return TSK_Undeclared;
5755 /// \brief Check whether a specialization is well-formed in the current
5758 /// This routine determines whether a template specialization can be declared
5759 /// in the current context (C++ [temp.expl.spec]p2).
5761 /// \param S the semantic analysis object for which this check is being
5764 /// \param Specialized the entity being specialized or instantiated, which
5765 /// may be a kind of template (class template, function template, etc.) or
5766 /// a member of a class template (member function, static data member,
5769 /// \param PrevDecl the previous declaration of this entity, if any.
5771 /// \param Loc the location of the explicit specialization or instantiation of
5774 /// \param IsPartialSpecialization whether this is a partial specialization of
5775 /// a class template.
5777 /// \returns true if there was an error that we cannot recover from, false
5779 static bool CheckTemplateSpecializationScope(Sema &S,
5780 NamedDecl *Specialized,
5781 NamedDecl *PrevDecl,
5783 bool IsPartialSpecialization) {
5784 // Keep these "kind" numbers in sync with the %select statements in the
5785 // various diagnostics emitted by this routine.
5787 if (isa<ClassTemplateDecl>(Specialized))
5788 EntityKind = IsPartialSpecialization? 1 : 0;
5789 else if (isa<VarTemplateDecl>(Specialized))
5790 EntityKind = IsPartialSpecialization ? 3 : 2;
5791 else if (isa<FunctionTemplateDecl>(Specialized))
5793 else if (isa<CXXMethodDecl>(Specialized))
5795 else if (isa<VarDecl>(Specialized))
5797 else if (isa<RecordDecl>(Specialized))
5799 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5802 S.Diag(Loc, diag::err_template_spec_unknown_kind)
5803 << S.getLangOpts().CPlusPlus11;
5804 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5808 // C++ [temp.expl.spec]p2:
5809 // An explicit specialization shall be declared in the namespace
5810 // of which the template is a member, or, for member templates, in
5811 // the namespace of which the enclosing class or enclosing class
5812 // template is a member. An explicit specialization of a member
5813 // function, member class or static data member of a class
5814 // template shall be declared in the namespace of which the class
5815 // template is a member. Such a declaration may also be a
5816 // definition. If the declaration is not a definition, the
5817 // specialization may be defined later in the name- space in which
5818 // the explicit specialization was declared, or in a namespace
5819 // that encloses the one in which the explicit specialization was
5821 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5822 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
5827 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
5828 if (S.getLangOpts().MicrosoftExt) {
5829 // Do not warn for class scope explicit specialization during
5830 // instantiation, warning was already emitted during pattern
5831 // semantic analysis.
5832 if (!S.ActiveTemplateInstantiations.size())
5833 S.Diag(Loc, diag::ext_function_specialization_in_class)
5836 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5842 if (S.CurContext->isRecord() &&
5843 !S.CurContext->Equals(Specialized->getDeclContext())) {
5844 // Make sure that we're specializing in the right record context.
5845 // Otherwise, things can go horribly wrong.
5846 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5851 // C++ [temp.class.spec]p6:
5852 // A class template partial specialization may be declared or redeclared
5853 // in any namespace scope in which its definition may be defined (14.5.1
5855 DeclContext *SpecializedContext
5856 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
5857 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
5859 // Make sure that this redeclaration (or definition) occurs in an enclosing
5861 // Note that HandleDeclarator() performs this check for explicit
5862 // specializations of function templates, static data members, and member
5863 // functions, so we skip the check here for those kinds of entities.
5864 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5865 // Should we refactor that check, so that it occurs later?
5866 if (!DC->Encloses(SpecializedContext) &&
5867 !(isa<FunctionTemplateDecl>(Specialized) ||
5868 isa<FunctionDecl>(Specialized) ||
5869 isa<VarTemplateDecl>(Specialized) ||
5870 isa<VarDecl>(Specialized))) {
5871 if (isa<TranslationUnitDecl>(SpecializedContext))
5872 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5873 << EntityKind << Specialized;
5874 else if (isa<NamespaceDecl>(SpecializedContext)) {
5875 int Diag = diag::err_template_spec_redecl_out_of_scope;
5876 if (S.getLangOpts().MicrosoftExt)
5877 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
5878 S.Diag(Loc, Diag) << EntityKind << Specialized
5879 << cast<NamedDecl>(SpecializedContext);
5881 llvm_unreachable("unexpected namespace context for specialization");
5883 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5884 } else if ((!PrevDecl ||
5885 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5886 getTemplateSpecializationKind(PrevDecl) ==
5887 TSK_ImplicitInstantiation)) {
5888 // C++ [temp.exp.spec]p2:
5889 // An explicit specialization shall be declared in the namespace of which
5890 // the template is a member, or, for member templates, in the namespace
5891 // of which the enclosing class or enclosing class template is a member.
5892 // An explicit specialization of a member function, member class or
5893 // static data member of a class template shall be declared in the
5894 // namespace of which the class template is a member.
5896 // C++11 [temp.expl.spec]p2:
5897 // An explicit specialization shall be declared in a namespace enclosing
5898 // the specialized template.
5899 // C++11 [temp.explicit]p3:
5900 // An explicit instantiation shall appear in an enclosing namespace of its
5902 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
5903 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
5904 if (isa<TranslationUnitDecl>(SpecializedContext)) {
5905 assert(!IsCPlusPlus11Extension &&
5906 "DC encloses TU but isn't in enclosing namespace set");
5907 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
5908 << EntityKind << Specialized;
5909 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5911 if (!IsCPlusPlus11Extension)
5912 Diag = diag::err_template_spec_decl_out_of_scope;
5913 else if (!S.getLangOpts().CPlusPlus11)
5914 Diag = diag::ext_template_spec_decl_out_of_scope;
5916 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5918 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5921 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5928 static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5929 if (!E->isInstantiationDependent())
5930 return SourceLocation();
5931 DependencyChecker Checker(Depth);
5932 Checker.TraverseStmt(E);
5933 if (Checker.Match && Checker.MatchLoc.isInvalid())
5934 return E->getSourceRange();
5935 return Checker.MatchLoc;
5938 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
5939 if (!TL.getType()->isDependentType())
5940 return SourceLocation();
5941 DependencyChecker Checker(Depth);
5942 Checker.TraverseTypeLoc(TL);
5943 if (Checker.Match && Checker.MatchLoc.isInvalid())
5944 return TL.getSourceRange();
5945 return Checker.MatchLoc;
5948 /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
5949 /// that checks non-type template partial specialization arguments.
5950 static bool CheckNonTypeTemplatePartialSpecializationArgs(
5951 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
5952 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
5953 for (unsigned I = 0; I != NumArgs; ++I) {
5954 if (Args[I].getKind() == TemplateArgument::Pack) {
5955 if (CheckNonTypeTemplatePartialSpecializationArgs(
5956 S, TemplateNameLoc, Param, Args[I].pack_begin(),
5957 Args[I].pack_size(), IsDefaultArgument))
5963 if (Args[I].getKind() != TemplateArgument::Expression)
5966 Expr *ArgExpr = Args[I].getAsExpr();
5968 // We can have a pack expansion of any of the bullets below.
5969 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5970 ArgExpr = Expansion->getPattern();
5972 // Strip off any implicit casts we added as part of type checking.
5973 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5974 ArgExpr = ICE->getSubExpr();
5976 // C++ [temp.class.spec]p8:
5977 // A non-type argument is non-specialized if it is the name of a
5978 // non-type parameter. All other non-type arguments are
5981 // Below, we check the two conditions that only apply to
5982 // specialized non-type arguments, so skip any non-specialized
5984 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
5985 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
5988 // C++ [temp.class.spec]p9:
5989 // Within the argument list of a class template partial
5990 // specialization, the following restrictions apply:
5991 // -- A partially specialized non-type argument expression
5992 // shall not involve a template parameter of the partial
5993 // specialization except when the argument expression is a
5994 // simple identifier.
5995 SourceRange ParamUseRange =
5996 findTemplateParameter(Param->getDepth(), ArgExpr);
5997 if (ParamUseRange.isValid()) {
5998 if (IsDefaultArgument) {
5999 S.Diag(TemplateNameLoc,
6000 diag::err_dependent_non_type_arg_in_partial_spec);
6001 S.Diag(ParamUseRange.getBegin(),
6002 diag::note_dependent_non_type_default_arg_in_partial_spec)
6005 S.Diag(ParamUseRange.getBegin(),
6006 diag::err_dependent_non_type_arg_in_partial_spec)
6012 // -- The type of a template parameter corresponding to a
6013 // specialized non-type argument shall not be dependent on a
6014 // parameter of the specialization.
6016 // FIXME: We need to delay this check until instantiation in some cases:
6018 // template<template<typename> class X> struct A {
6019 // template<typename T, X<T> N> struct B;
6020 // template<typename T> struct B<T, 0>;
6022 // template<typename> using X = int;
6023 // A<X>::B<int, 0> b;
6024 ParamUseRange = findTemplateParameter(
6025 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
6026 if (ParamUseRange.isValid()) {
6027 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
6028 diag::err_dependent_typed_non_type_arg_in_partial_spec)
6029 << Param->getType() << ParamUseRange;
6030 S.Diag(Param->getLocation(), diag::note_template_param_here)
6031 << (IsDefaultArgument ? ParamUseRange : SourceRange());
6039 /// \brief Check the non-type template arguments of a class template
6040 /// partial specialization according to C++ [temp.class.spec]p9.
6042 /// \param TemplateNameLoc the location of the template name.
6043 /// \param TemplateParams the template parameters of the primary class
6045 /// \param NumExplicit the number of explicitly-specified template arguments.
6046 /// \param TemplateArgs the template arguments of the class template
6047 /// partial specialization.
6049 /// \returns \c true if there was an error, \c false otherwise.
6050 static bool CheckTemplatePartialSpecializationArgs(
6051 Sema &S, SourceLocation TemplateNameLoc,
6052 TemplateParameterList *TemplateParams, unsigned NumExplicit,
6053 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
6054 const TemplateArgument *ArgList = TemplateArgs.data();
6056 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6057 NonTypeTemplateParmDecl *Param
6058 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
6062 if (CheckNonTypeTemplatePartialSpecializationArgs(
6063 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
6071 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
6073 SourceLocation KWLoc,
6074 SourceLocation ModulePrivateLoc,
6075 TemplateIdAnnotation &TemplateId,
6076 AttributeList *Attr,
6077 MultiTemplateParamsArg
6078 TemplateParameterLists,
6079 SkipBodyInfo *SkipBody) {
6080 assert(TUK != TUK_Reference && "References are not specializations");
6082 CXXScopeSpec &SS = TemplateId.SS;
6084 // NOTE: KWLoc is the location of the tag keyword. This will instead
6085 // store the location of the outermost template keyword in the declaration.
6086 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
6087 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
6088 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
6089 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
6090 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
6092 // Find the class template we're specializing
6093 TemplateName Name = TemplateId.Template.get();
6094 ClassTemplateDecl *ClassTemplate
6095 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
6097 if (!ClassTemplate) {
6098 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
6099 << (Name.getAsTemplateDecl() &&
6100 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
6104 bool isExplicitSpecialization = false;
6105 bool isPartialSpecialization = false;
6107 // Check the validity of the template headers that introduce this
6109 // FIXME: We probably shouldn't complain about these headers for
6110 // friend declarations.
6111 bool Invalid = false;
6112 TemplateParameterList *TemplateParams =
6113 MatchTemplateParametersToScopeSpecifier(
6114 KWLoc, TemplateNameLoc, SS, &TemplateId,
6115 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
6120 if (TemplateParams && TemplateParams->size() > 0) {
6121 isPartialSpecialization = true;
6123 if (TUK == TUK_Friend) {
6124 Diag(KWLoc, diag::err_partial_specialization_friend)
6125 << SourceRange(LAngleLoc, RAngleLoc);
6129 // C++ [temp.class.spec]p10:
6130 // The template parameter list of a specialization shall not
6131 // contain default template argument values.
6132 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
6133 Decl *Param = TemplateParams->getParam(I);
6134 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
6135 if (TTP->hasDefaultArgument()) {
6136 Diag(TTP->getDefaultArgumentLoc(),
6137 diag::err_default_arg_in_partial_spec);
6138 TTP->removeDefaultArgument();
6140 } else if (NonTypeTemplateParmDecl *NTTP
6141 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
6142 if (Expr *DefArg = NTTP->getDefaultArgument()) {
6143 Diag(NTTP->getDefaultArgumentLoc(),
6144 diag::err_default_arg_in_partial_spec)
6145 << DefArg->getSourceRange();
6146 NTTP->removeDefaultArgument();
6149 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
6150 if (TTP->hasDefaultArgument()) {
6151 Diag(TTP->getDefaultArgument().getLocation(),
6152 diag::err_default_arg_in_partial_spec)
6153 << TTP->getDefaultArgument().getSourceRange();
6154 TTP->removeDefaultArgument();
6158 } else if (TemplateParams) {
6159 if (TUK == TUK_Friend)
6160 Diag(KWLoc, diag::err_template_spec_friend)
6161 << FixItHint::CreateRemoval(
6162 SourceRange(TemplateParams->getTemplateLoc(),
6163 TemplateParams->getRAngleLoc()))
6164 << SourceRange(LAngleLoc, RAngleLoc);
6166 isExplicitSpecialization = true;
6168 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
6171 // Check that the specialization uses the same tag kind as the
6172 // original template.
6173 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6174 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
6175 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
6176 Kind, TUK == TUK_Definition, KWLoc,
6177 *ClassTemplate->getIdentifier())) {
6178 Diag(KWLoc, diag::err_use_with_wrong_tag)
6180 << FixItHint::CreateReplacement(KWLoc,
6181 ClassTemplate->getTemplatedDecl()->getKindName());
6182 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
6183 diag::note_previous_use);
6184 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6187 // Translate the parser's template argument list in our AST format.
6188 TemplateArgumentListInfo TemplateArgs =
6189 makeTemplateArgumentListInfo(*this, TemplateId);
6191 // Check for unexpanded parameter packs in any of the template arguments.
6192 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6193 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
6194 UPPC_PartialSpecialization))
6197 // Check that the template argument list is well-formed for this
6199 SmallVector<TemplateArgument, 4> Converted;
6200 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6201 TemplateArgs, false, Converted))
6204 // Find the class template (partial) specialization declaration that
6205 // corresponds to these arguments.
6206 if (isPartialSpecialization) {
6207 if (CheckTemplatePartialSpecializationArgs(
6208 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6209 TemplateArgs.size(), Converted))
6212 bool InstantiationDependent;
6213 if (!Name.isDependent() &&
6214 !TemplateSpecializationType::anyDependentTemplateArguments(
6215 TemplateArgs.getArgumentArray(),
6216 TemplateArgs.size(),
6217 InstantiationDependent)) {
6218 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6219 << ClassTemplate->getDeclName();
6220 isPartialSpecialization = false;
6224 void *InsertPos = nullptr;
6225 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
6227 if (isPartialSpecialization)
6228 // FIXME: Template parameter list matters, too
6229 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
6231 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
6233 ClassTemplateSpecializationDecl *Specialization = nullptr;
6235 // Check whether we can declare a class template specialization in
6236 // the current scope.
6237 if (TUK != TUK_Friend &&
6238 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6240 isPartialSpecialization))
6243 // The canonical type
6245 if (isPartialSpecialization) {
6246 // Build the canonical type that describes the converted template
6247 // arguments of the class template partial specialization.
6248 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6249 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
6253 if (Context.hasSameType(CanonType,
6254 ClassTemplate->getInjectedClassNameSpecialization())) {
6255 // C++ [temp.class.spec]p9b3:
6257 // -- The argument list of the specialization shall not be identical
6258 // to the implicit argument list of the primary template.
6259 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
6260 << /*class template*/0 << (TUK == TUK_Definition)
6261 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
6262 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6263 ClassTemplate->getIdentifier(),
6267 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
6268 /*FriendLoc*/SourceLocation(),
6269 TemplateParameterLists.size() - 1,
6270 TemplateParameterLists.data());
6273 // Create a new class template partial specialization declaration node.
6274 ClassTemplatePartialSpecializationDecl *PrevPartial
6275 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
6276 ClassTemplatePartialSpecializationDecl *Partial
6277 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
6278 ClassTemplate->getDeclContext(),
6279 KWLoc, TemplateNameLoc,
6287 SetNestedNameSpecifier(Partial, SS);
6288 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
6289 Partial->setTemplateParameterListsInfo(Context,
6290 TemplateParameterLists.size() - 1,
6291 TemplateParameterLists.data());
6295 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
6296 Specialization = Partial;
6298 // If we are providing an explicit specialization of a member class
6299 // template specialization, make a note of that.
6300 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6301 PrevPartial->setMemberSpecialization();
6303 // Check that all of the template parameters of the class template
6304 // partial specialization are deducible from the template
6305 // arguments. If not, this class template partial specialization
6306 // will never be used.
6307 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
6308 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
6309 TemplateParams->getDepth(),
6312 if (!DeducibleParams.all()) {
6313 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
6314 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
6315 << /*class template*/0 << (NumNonDeducible > 1)
6316 << SourceRange(TemplateNameLoc, RAngleLoc);
6317 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6318 if (!DeducibleParams[I]) {
6319 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6320 if (Param->getDeclName())
6321 Diag(Param->getLocation(),
6322 diag::note_partial_spec_unused_parameter)
6323 << Param->getDeclName();
6325 Diag(Param->getLocation(),
6326 diag::note_partial_spec_unused_parameter)
6332 // Create a new class template specialization declaration node for
6333 // this explicit specialization or friend declaration.
6335 = ClassTemplateSpecializationDecl::Create(Context, Kind,
6336 ClassTemplate->getDeclContext(),
6337 KWLoc, TemplateNameLoc,
6342 SetNestedNameSpecifier(Specialization, SS);
6343 if (TemplateParameterLists.size() > 0) {
6344 Specialization->setTemplateParameterListsInfo(Context,
6345 TemplateParameterLists.size(),
6346 TemplateParameterLists.data());
6350 ClassTemplate->AddSpecialization(Specialization, InsertPos);
6352 CanonType = Context.getTypeDeclType(Specialization);
6355 // C++ [temp.expl.spec]p6:
6356 // If a template, a member template or the member of a class template is
6357 // explicitly specialized then that specialization shall be declared
6358 // before the first use of that specialization that would cause an implicit
6359 // instantiation to take place, in every translation unit in which such a
6360 // use occurs; no diagnostic is required.
6361 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
6363 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6364 // Is there any previous explicit specialization declaration?
6365 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6372 SourceRange Range(TemplateNameLoc, RAngleLoc);
6373 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6374 << Context.getTypeDeclType(Specialization) << Range;
6376 Diag(PrevDecl->getPointOfInstantiation(),
6377 diag::note_instantiation_required_here)
6378 << (PrevDecl->getTemplateSpecializationKind()
6379 != TSK_ImplicitInstantiation);
6384 // If this is not a friend, note that this is an explicit specialization.
6385 if (TUK != TUK_Friend)
6386 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
6388 // Check that this isn't a redefinition of this specialization.
6389 if (TUK == TUK_Definition) {
6390 RecordDecl *Def = Specialization->getDefinition();
6391 NamedDecl *Hidden = nullptr;
6392 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
6393 SkipBody->ShouldSkip = true;
6394 makeMergedDefinitionVisible(Hidden, KWLoc);
6395 // From here on out, treat this as just a redeclaration.
6396 TUK = TUK_Declaration;
6398 SourceRange Range(TemplateNameLoc, RAngleLoc);
6399 Diag(TemplateNameLoc, diag::err_redefinition)
6400 << Context.getTypeDeclType(Specialization) << Range;
6401 Diag(Def->getLocation(), diag::note_previous_definition);
6402 Specialization->setInvalidDecl();
6408 ProcessDeclAttributeList(S, Specialization, Attr);
6410 // Add alignment attributes if necessary; these attributes are checked when
6411 // the ASTContext lays out the structure.
6412 if (TUK == TUK_Definition) {
6413 AddAlignmentAttributesForRecord(Specialization);
6414 AddMsStructLayoutForRecord(Specialization);
6417 if (ModulePrivateLoc.isValid())
6418 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6419 << (isPartialSpecialization? 1 : 0)
6420 << FixItHint::CreateRemoval(ModulePrivateLoc);
6422 // Build the fully-sugared type for this class template
6423 // specialization as the user wrote in the specialization
6424 // itself. This means that we'll pretty-print the type retrieved
6425 // from the specialization's declaration the way that the user
6426 // actually wrote the specialization, rather than formatting the
6427 // name based on the "canonical" representation used to store the
6428 // template arguments in the specialization.
6429 TypeSourceInfo *WrittenTy
6430 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6431 TemplateArgs, CanonType);
6432 if (TUK != TUK_Friend) {
6433 Specialization->setTypeAsWritten(WrittenTy);
6434 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
6437 // C++ [temp.expl.spec]p9:
6438 // A template explicit specialization is in the scope of the
6439 // namespace in which the template was defined.
6441 // We actually implement this paragraph where we set the semantic
6442 // context (in the creation of the ClassTemplateSpecializationDecl),
6443 // but we also maintain the lexical context where the actual
6444 // definition occurs.
6445 Specialization->setLexicalDeclContext(CurContext);
6447 // We may be starting the definition of this specialization.
6448 if (TUK == TUK_Definition)
6449 Specialization->startDefinition();
6451 if (TUK == TUK_Friend) {
6452 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6456 Friend->setAccess(AS_public);
6457 CurContext->addDecl(Friend);
6459 // Add the specialization into its lexical context, so that it can
6460 // be seen when iterating through the list of declarations in that
6461 // context. However, specializations are not found by name lookup.
6462 CurContext->addDecl(Specialization);
6464 return Specialization;
6467 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
6468 MultiTemplateParamsArg TemplateParameterLists,
6470 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
6471 ActOnDocumentableDecl(NewDecl);
6475 Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
6476 MultiTemplateParamsArg TemplateParameterLists,
6478 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
6479 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6481 if (FTI.hasPrototype) {
6482 // FIXME: Diagnose arguments without names in C.
6485 Scope *ParentScope = FnBodyScope->getParent();
6487 D.setFunctionDefinitionKind(FDK_Definition);
6488 Decl *DP = HandleDeclarator(ParentScope, D,
6489 TemplateParameterLists);
6490 return ActOnStartOfFunctionDef(FnBodyScope, DP);
6493 /// \brief Strips various properties off an implicit instantiation
6494 /// that has just been explicitly specialized.
6495 static void StripImplicitInstantiation(NamedDecl *D) {
6496 D->dropAttr<DLLImportAttr>();
6497 D->dropAttr<DLLExportAttr>();
6499 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
6500 FD->setInlineSpecified(false);
6503 /// \brief Compute the diagnostic location for an explicit instantiation
6504 // declaration or definition.
6505 static SourceLocation DiagLocForExplicitInstantiation(
6506 NamedDecl* D, SourceLocation PointOfInstantiation) {
6507 // Explicit instantiations following a specialization have no effect and
6508 // hence no PointOfInstantiation. In that case, walk decl backwards
6509 // until a valid name loc is found.
6510 SourceLocation PrevDiagLoc = PointOfInstantiation;
6511 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6512 Prev = Prev->getPreviousDecl()) {
6513 PrevDiagLoc = Prev->getLocation();
6515 assert(PrevDiagLoc.isValid() &&
6516 "Explicit instantiation without point of instantiation?");
6520 /// \brief Diagnose cases where we have an explicit template specialization
6521 /// before/after an explicit template instantiation, producing diagnostics
6522 /// for those cases where they are required and determining whether the
6523 /// new specialization/instantiation will have any effect.
6525 /// \param NewLoc the location of the new explicit specialization or
6528 /// \param NewTSK the kind of the new explicit specialization or instantiation.
6530 /// \param PrevDecl the previous declaration of the entity.
6532 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6534 /// \param PrevPointOfInstantiation if valid, indicates where the previus
6535 /// declaration was instantiated (either implicitly or explicitly).
6537 /// \param HasNoEffect will be set to true to indicate that the new
6538 /// specialization or instantiation has no effect and should be ignored.
6540 /// \returns true if there was an error that should prevent the introduction of
6541 /// the new declaration into the AST, false otherwise.
6543 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6544 TemplateSpecializationKind NewTSK,
6545 NamedDecl *PrevDecl,
6546 TemplateSpecializationKind PrevTSK,
6547 SourceLocation PrevPointOfInstantiation,
6548 bool &HasNoEffect) {
6549 HasNoEffect = false;
6552 case TSK_Undeclared:
6553 case TSK_ImplicitInstantiation:
6555 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6556 "previous declaration must be implicit!");
6559 case TSK_ExplicitSpecialization:
6561 case TSK_Undeclared:
6562 case TSK_ExplicitSpecialization:
6563 // Okay, we're just specializing something that is either already
6564 // explicitly specialized or has merely been mentioned without any
6568 case TSK_ImplicitInstantiation:
6569 if (PrevPointOfInstantiation.isInvalid()) {
6570 // The declaration itself has not actually been instantiated, so it is
6571 // still okay to specialize it.
6572 StripImplicitInstantiation(PrevDecl);
6577 case TSK_ExplicitInstantiationDeclaration:
6578 case TSK_ExplicitInstantiationDefinition:
6579 assert((PrevTSK == TSK_ImplicitInstantiation ||
6580 PrevPointOfInstantiation.isValid()) &&
6581 "Explicit instantiation without point of instantiation?");
6583 // C++ [temp.expl.spec]p6:
6584 // If a template, a member template or the member of a class template
6585 // is explicitly specialized then that specialization shall be declared
6586 // before the first use of that specialization that would cause an
6587 // implicit instantiation to take place, in every translation unit in
6588 // which such a use occurs; no diagnostic is required.
6589 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6590 // Is there any previous explicit specialization declaration?
6591 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6595 Diag(NewLoc, diag::err_specialization_after_instantiation)
6597 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
6598 << (PrevTSK != TSK_ImplicitInstantiation);
6603 case TSK_ExplicitInstantiationDeclaration:
6605 case TSK_ExplicitInstantiationDeclaration:
6606 // This explicit instantiation declaration is redundant (that's okay).
6610 case TSK_Undeclared:
6611 case TSK_ImplicitInstantiation:
6612 // We're explicitly instantiating something that may have already been
6613 // implicitly instantiated; that's fine.
6616 case TSK_ExplicitSpecialization:
6617 // C++0x [temp.explicit]p4:
6618 // For a given set of template parameters, if an explicit instantiation
6619 // of a template appears after a declaration of an explicit
6620 // specialization for that template, the explicit instantiation has no
6625 case TSK_ExplicitInstantiationDefinition:
6626 // C++0x [temp.explicit]p10:
6627 // If an entity is the subject of both an explicit instantiation
6628 // declaration and an explicit instantiation definition in the same
6629 // translation unit, the definition shall follow the declaration.
6631 diag::err_explicit_instantiation_declaration_after_definition);
6633 // Explicit instantiations following a specialization have no effect and
6634 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6635 // until a valid name loc is found.
6636 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6637 diag::note_explicit_instantiation_definition_here);
6642 case TSK_ExplicitInstantiationDefinition:
6644 case TSK_Undeclared:
6645 case TSK_ImplicitInstantiation:
6646 // We're explicitly instantiating something that may have already been
6647 // implicitly instantiated; that's fine.
6650 case TSK_ExplicitSpecialization:
6651 // C++ DR 259, C++0x [temp.explicit]p4:
6652 // For a given set of template parameters, if an explicit
6653 // instantiation of a template appears after a declaration of
6654 // an explicit specialization for that template, the explicit
6655 // instantiation has no effect.
6657 // In C++98/03 mode, we only give an extension warning here, because it
6658 // is not harmful to try to explicitly instantiate something that
6659 // has been explicitly specialized.
6660 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
6661 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6662 diag::ext_explicit_instantiation_after_specialization)
6664 Diag(PrevDecl->getLocation(),
6665 diag::note_previous_template_specialization);
6669 case TSK_ExplicitInstantiationDeclaration:
6670 // We're explicity instantiating a definition for something for which we
6671 // were previously asked to suppress instantiations. That's fine.
6673 // C++0x [temp.explicit]p4:
6674 // For a given set of template parameters, if an explicit instantiation
6675 // of a template appears after a declaration of an explicit
6676 // specialization for that template, the explicit instantiation has no
6678 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6679 // Is there any previous explicit specialization declaration?
6680 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6688 case TSK_ExplicitInstantiationDefinition:
6689 // C++0x [temp.spec]p5:
6690 // For a given template and a given set of template-arguments,
6691 // - an explicit instantiation definition shall appear at most once
6694 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6695 Diag(NewLoc, (getLangOpts().MSVCCompat)
6696 ? diag::ext_explicit_instantiation_duplicate
6697 : diag::err_explicit_instantiation_duplicate)
6699 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6700 diag::note_previous_explicit_instantiation);
6706 llvm_unreachable("Missing specialization/instantiation case?");
6709 /// \brief Perform semantic analysis for the given dependent function
6710 /// template specialization.
6712 /// The only possible way to get a dependent function template specialization
6713 /// is with a friend declaration, like so:
6716 /// template \<class T> void foo(T);
6717 /// template \<class T> class A {
6718 /// friend void foo<>(T);
6722 /// There really isn't any useful analysis we can do here, so we
6723 /// just store the information.
6725 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6726 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6727 LookupResult &Previous) {
6728 // Remove anything from Previous that isn't a function template in
6729 // the correct context.
6730 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6731 LookupResult::Filter F = Previous.makeFilter();
6732 while (F.hasNext()) {
6733 NamedDecl *D = F.next()->getUnderlyingDecl();
6734 if (!isa<FunctionTemplateDecl>(D) ||
6735 !FDLookupContext->InEnclosingNamespaceSetOf(
6736 D->getDeclContext()->getRedeclContext()))
6741 // Should this be diagnosed here?
6742 if (Previous.empty()) return true;
6744 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6745 ExplicitTemplateArgs);
6749 /// \brief Perform semantic analysis for the given function template
6752 /// This routine performs all of the semantic analysis required for an
6753 /// explicit function template specialization. On successful completion,
6754 /// the function declaration \p FD will become a function template
6757 /// \param FD the function declaration, which will be updated to become a
6758 /// function template specialization.
6760 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6761 /// if any. Note that this may be valid info even when 0 arguments are
6762 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6763 /// as it anyway contains info on the angle brackets locations.
6765 /// \param Previous the set of declarations that may be specialized by
6766 /// this function specialization.
6767 bool Sema::CheckFunctionTemplateSpecialization(
6768 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6769 LookupResult &Previous) {
6770 // The set of function template specializations that could match this
6771 // explicit function template specialization.
6772 UnresolvedSet<8> Candidates;
6773 TemplateSpecCandidateSet FailedCandidates(FD->getLocation());
6775 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6776 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6778 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6779 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
6780 // Only consider templates found within the same semantic lookup scope as
6782 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6783 Ovl->getDeclContext()->getRedeclContext()))
6786 // When matching a constexpr member function template specialization
6787 // against the primary template, we don't yet know whether the
6788 // specialization has an implicit 'const' (because we don't know whether
6789 // it will be a static member function until we know which template it
6790 // specializes), so adjust it now assuming it specializes this template.
6791 QualType FT = FD->getType();
6792 if (FD->isConstexpr()) {
6793 CXXMethodDecl *OldMD =
6794 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
6795 if (OldMD && OldMD->isConst()) {
6796 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
6797 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6798 EPI.TypeQuals |= Qualifiers::Const;
6799 FT = Context.getFunctionType(FPT->getReturnType(),
6800 FPT->getParamTypes(), EPI);
6804 // C++ [temp.expl.spec]p11:
6805 // A trailing template-argument can be left unspecified in the
6806 // template-id naming an explicit function template specialization
6807 // provided it can be deduced from the function argument type.
6808 // Perform template argument deduction to determine whether we may be
6809 // specializing this template.
6810 // FIXME: It is somewhat wasteful to build
6811 TemplateDeductionInfo Info(FailedCandidates.getLocation());
6812 FunctionDecl *Specialization = nullptr;
6813 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6814 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6815 ExplicitTemplateArgs, FT, Specialization, Info)) {
6816 // Template argument deduction failed; record why it failed, so
6817 // that we can provide nifty diagnostics.
6818 FailedCandidates.addCandidate()
6819 .set(FunTmpl->getTemplatedDecl(),
6820 MakeDeductionFailureInfo(Context, TDK, Info));
6825 // Record this candidate.
6826 Candidates.addDecl(Specialization, I.getAccess());
6830 // Find the most specialized function template.
6831 UnresolvedSetIterator Result = getMostSpecialized(
6832 Candidates.begin(), Candidates.end(), FailedCandidates,
6834 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6835 PDiag(diag::err_function_template_spec_ambiguous)
6836 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
6837 PDiag(diag::note_function_template_spec_matched));
6839 if (Result == Candidates.end())
6842 // Ignore access information; it doesn't figure into redeclaration checking.
6843 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
6845 FunctionTemplateSpecializationInfo *SpecInfo
6846 = Specialization->getTemplateSpecializationInfo();
6847 assert(SpecInfo && "Function template specialization info missing?");
6849 // Note: do not overwrite location info if previous template
6850 // specialization kind was explicit.
6851 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
6852 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
6853 Specialization->setLocation(FD->getLocation());
6854 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6855 // function can differ from the template declaration with respect to
6856 // the constexpr specifier.
6857 Specialization->setConstexpr(FD->isConstexpr());
6860 // FIXME: Check if the prior specialization has a point of instantiation.
6861 // If so, we have run afoul of .
6863 // If this is a friend declaration, then we're not really declaring
6864 // an explicit specialization.
6865 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
6867 // Check the scope of this explicit specialization.
6869 CheckTemplateSpecializationScope(*this,
6870 Specialization->getPrimaryTemplate(),
6871 Specialization, FD->getLocation(),
6875 // C++ [temp.expl.spec]p6:
6876 // If a template, a member template or the member of a class template is
6877 // explicitly specialized then that specialization shall be declared
6878 // before the first use of that specialization that would cause an implicit
6879 // instantiation to take place, in every translation unit in which such a
6880 // use occurs; no diagnostic is required.
6881 bool HasNoEffect = false;
6883 CheckSpecializationInstantiationRedecl(FD->getLocation(),
6884 TSK_ExplicitSpecialization,
6886 SpecInfo->getTemplateSpecializationKind(),
6887 SpecInfo->getPointOfInstantiation(),
6891 // Mark the prior declaration as an explicit specialization, so that later
6892 // clients know that this is an explicit specialization.
6894 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
6895 MarkUnusedFileScopedDecl(Specialization);
6898 // Turn the given function declaration into a function template
6899 // specialization, with the template arguments from the previous
6901 // Take copies of (semantic and syntactic) template argument lists.
6902 const TemplateArgumentList* TemplArgs = new (Context)
6903 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
6904 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
6905 TemplArgs, /*InsertPos=*/nullptr,
6906 SpecInfo->getTemplateSpecializationKind(),
6907 ExplicitTemplateArgs);
6909 // The "previous declaration" for this function template specialization is
6910 // the prior function template specialization.
6912 Previous.addDecl(Specialization);
6916 /// \brief Perform semantic analysis for the given non-template member
6919 /// This routine performs all of the semantic analysis required for an
6920 /// explicit member function specialization. On successful completion,
6921 /// the function declaration \p FD will become a member function
6924 /// \param Member the member declaration, which will be updated to become a
6927 /// \param Previous the set of declarations, one of which may be specialized
6928 /// by this function specialization; the set will be modified to contain the
6929 /// redeclared member.
6931 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
6932 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
6934 // Try to find the member we are instantiating.
6935 NamedDecl *Instantiation = nullptr;
6936 NamedDecl *InstantiatedFrom = nullptr;
6937 MemberSpecializationInfo *MSInfo = nullptr;
6939 if (Previous.empty()) {
6940 // Nowhere to look anyway.
6941 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
6942 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6944 NamedDecl *D = (*I)->getUnderlyingDecl();
6945 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
6946 QualType Adjusted = Function->getType();
6947 if (!hasExplicitCallingConv(Adjusted))
6948 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
6949 if (Context.hasSameType(Adjusted, Method->getType())) {
6950 Instantiation = Method;
6951 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
6952 MSInfo = Method->getMemberSpecializationInfo();
6957 } else if (isa<VarDecl>(Member)) {
6959 if (Previous.isSingleResult() &&
6960 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
6961 if (PrevVar->isStaticDataMember()) {
6962 Instantiation = PrevVar;
6963 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
6964 MSInfo = PrevVar->getMemberSpecializationInfo();
6966 } else if (isa<RecordDecl>(Member)) {
6967 CXXRecordDecl *PrevRecord;
6968 if (Previous.isSingleResult() &&
6969 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6970 Instantiation = PrevRecord;
6971 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
6972 MSInfo = PrevRecord->getMemberSpecializationInfo();
6974 } else if (isa<EnumDecl>(Member)) {
6976 if (Previous.isSingleResult() &&
6977 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6978 Instantiation = PrevEnum;
6979 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6980 MSInfo = PrevEnum->getMemberSpecializationInfo();
6984 if (!Instantiation) {
6985 // There is no previous declaration that matches. Since member
6986 // specializations are always out-of-line, the caller will complain about
6987 // this mismatch later.
6991 // If this is a friend, just bail out here before we start turning
6992 // things into explicit specializations.
6993 if (Member->getFriendObjectKind() != Decl::FOK_None) {
6994 // Preserve instantiation information.
6995 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
6996 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
6997 cast<CXXMethodDecl>(InstantiatedFrom),
6998 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
6999 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
7000 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7001 cast<CXXRecordDecl>(InstantiatedFrom),
7002 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
7006 Previous.addDecl(Instantiation);
7010 // Make sure that this is a specialization of a member.
7011 if (!InstantiatedFrom) {
7012 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
7014 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
7018 // C++ [temp.expl.spec]p6:
7019 // If a template, a member template or the member of a class template is
7020 // explicitly specialized then that specialization shall be declared
7021 // before the first use of that specialization that would cause an implicit
7022 // instantiation to take place, in every translation unit in which such a
7023 // use occurs; no diagnostic is required.
7024 assert(MSInfo && "Member specialization info missing?");
7026 bool HasNoEffect = false;
7027 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
7028 TSK_ExplicitSpecialization,
7030 MSInfo->getTemplateSpecializationKind(),
7031 MSInfo->getPointOfInstantiation(),
7035 // Check the scope of this explicit specialization.
7036 if (CheckTemplateSpecializationScope(*this,
7038 Instantiation, Member->getLocation(),
7042 // Note that this is an explicit instantiation of a member.
7043 // the original declaration to note that it is an explicit specialization
7044 // (if it was previously an implicit instantiation). This latter step
7045 // makes bookkeeping easier.
7046 if (isa<FunctionDecl>(Member)) {
7047 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
7048 if (InstantiationFunction->getTemplateSpecializationKind() ==
7049 TSK_ImplicitInstantiation) {
7050 InstantiationFunction->setTemplateSpecializationKind(
7051 TSK_ExplicitSpecialization);
7052 InstantiationFunction->setLocation(Member->getLocation());
7055 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
7056 cast<CXXMethodDecl>(InstantiatedFrom),
7057 TSK_ExplicitSpecialization);
7058 MarkUnusedFileScopedDecl(InstantiationFunction);
7059 } else if (isa<VarDecl>(Member)) {
7060 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
7061 if (InstantiationVar->getTemplateSpecializationKind() ==
7062 TSK_ImplicitInstantiation) {
7063 InstantiationVar->setTemplateSpecializationKind(
7064 TSK_ExplicitSpecialization);
7065 InstantiationVar->setLocation(Member->getLocation());
7068 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
7069 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7070 MarkUnusedFileScopedDecl(InstantiationVar);
7071 } else if (isa<CXXRecordDecl>(Member)) {
7072 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
7073 if (InstantiationClass->getTemplateSpecializationKind() ==
7074 TSK_ImplicitInstantiation) {
7075 InstantiationClass->setTemplateSpecializationKind(
7076 TSK_ExplicitSpecialization);
7077 InstantiationClass->setLocation(Member->getLocation());
7080 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
7081 cast<CXXRecordDecl>(InstantiatedFrom),
7082 TSK_ExplicitSpecialization);
7084 assert(isa<EnumDecl>(Member) && "Only member enums remain");
7085 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
7086 if (InstantiationEnum->getTemplateSpecializationKind() ==
7087 TSK_ImplicitInstantiation) {
7088 InstantiationEnum->setTemplateSpecializationKind(
7089 TSK_ExplicitSpecialization);
7090 InstantiationEnum->setLocation(Member->getLocation());
7093 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
7094 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
7097 // Save the caller the trouble of having to figure out which declaration
7098 // this specialization matches.
7100 Previous.addDecl(Instantiation);
7104 /// \brief Check the scope of an explicit instantiation.
7106 /// \returns true if a serious error occurs, false otherwise.
7107 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
7108 SourceLocation InstLoc,
7109 bool WasQualifiedName) {
7110 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
7111 DeclContext *CurContext = S.CurContext->getRedeclContext();
7113 if (CurContext->isRecord()) {
7114 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
7119 // C++11 [temp.explicit]p3:
7120 // An explicit instantiation shall appear in an enclosing namespace of its
7121 // template. If the name declared in the explicit instantiation is an
7122 // unqualified name, the explicit instantiation shall appear in the
7123 // namespace where its template is declared or, if that namespace is inline
7124 // (7.3.1), any namespace from its enclosing namespace set.
7126 // This is DR275, which we do not retroactively apply to C++98/03.
7127 if (WasQualifiedName) {
7128 if (CurContext->Encloses(OrigContext))
7131 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
7135 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
7136 if (WasQualifiedName)
7138 S.getLangOpts().CPlusPlus11?
7139 diag::err_explicit_instantiation_out_of_scope :
7140 diag::warn_explicit_instantiation_out_of_scope_0x)
7144 S.getLangOpts().CPlusPlus11?
7145 diag::err_explicit_instantiation_unqualified_wrong_namespace :
7146 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
7150 S.getLangOpts().CPlusPlus11?
7151 diag::err_explicit_instantiation_must_be_global :
7152 diag::warn_explicit_instantiation_must_be_global_0x)
7154 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
7158 /// \brief Determine whether the given scope specifier has a template-id in it.
7159 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7163 // C++11 [temp.explicit]p3:
7164 // If the explicit instantiation is for a member function, a member class
7165 // or a static data member of a class template specialization, the name of
7166 // the class template specialization in the qualified-id for the member
7167 // name shall be a simple-template-id.
7169 // C++98 has the same restriction, just worded differently.
7170 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7171 NNS = NNS->getPrefix())
7172 if (const Type *T = NNS->getAsType())
7173 if (isa<TemplateSpecializationType>(T))
7179 // Explicit instantiation of a class template specialization
7181 Sema::ActOnExplicitInstantiation(Scope *S,
7182 SourceLocation ExternLoc,
7183 SourceLocation TemplateLoc,
7185 SourceLocation KWLoc,
7186 const CXXScopeSpec &SS,
7187 TemplateTy TemplateD,
7188 SourceLocation TemplateNameLoc,
7189 SourceLocation LAngleLoc,
7190 ASTTemplateArgsPtr TemplateArgsIn,
7191 SourceLocation RAngleLoc,
7192 AttributeList *Attr) {
7193 // Find the class template we're specializing
7194 TemplateName Name = TemplateD.get();
7195 TemplateDecl *TD = Name.getAsTemplateDecl();
7196 // Check that the specialization uses the same tag kind as the
7197 // original template.
7198 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7199 assert(Kind != TTK_Enum &&
7200 "Invalid enum tag in class template explicit instantiation!");
7202 if (isa<TypeAliasTemplateDecl>(TD)) {
7203 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7204 Diag(TD->getTemplatedDecl()->getLocation(),
7205 diag::note_previous_use);
7209 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7211 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7212 Kind, /*isDefinition*/false, KWLoc,
7213 *ClassTemplate->getIdentifier())) {
7214 Diag(KWLoc, diag::err_use_with_wrong_tag)
7216 << FixItHint::CreateReplacement(KWLoc,
7217 ClassTemplate->getTemplatedDecl()->getKindName());
7218 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7219 diag::note_previous_use);
7220 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7223 // C++0x [temp.explicit]p2:
7224 // There are two forms of explicit instantiation: an explicit instantiation
7225 // definition and an explicit instantiation declaration. An explicit
7226 // instantiation declaration begins with the extern keyword. [...]
7227 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
7228 ? TSK_ExplicitInstantiationDefinition
7229 : TSK_ExplicitInstantiationDeclaration;
7231 if (TSK == TSK_ExplicitInstantiationDeclaration) {
7232 // Check for dllexport class template instantiation declarations.
7233 for (AttributeList *A = Attr; A; A = A->getNext()) {
7234 if (A->getKind() == AttributeList::AT_DLLExport) {
7236 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7237 Diag(A->getLoc(), diag::note_attribute);
7242 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
7244 diag::warn_attribute_dllexport_explicit_instantiation_decl);
7245 Diag(A->getLocation(), diag::note_attribute);
7249 // Translate the parser's template argument list in our AST format.
7250 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7251 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7253 // Check that the template argument list is well-formed for this
7255 SmallVector<TemplateArgument, 4> Converted;
7256 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7257 TemplateArgs, false, Converted))
7260 // Find the class template specialization declaration that
7261 // corresponds to these arguments.
7262 void *InsertPos = nullptr;
7263 ClassTemplateSpecializationDecl *PrevDecl
7264 = ClassTemplate->findSpecialization(Converted, InsertPos);
7266 TemplateSpecializationKind PrevDecl_TSK
7267 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7269 // C++0x [temp.explicit]p2:
7270 // [...] An explicit instantiation shall appear in an enclosing
7271 // namespace of its template. [...]
7273 // This is C++ DR 275.
7274 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7278 ClassTemplateSpecializationDecl *Specialization = nullptr;
7280 bool HasNoEffect = false;
7282 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
7283 PrevDecl, PrevDecl_TSK,
7284 PrevDecl->getPointOfInstantiation(),
7288 // Even though HasNoEffect == true means that this explicit instantiation
7289 // has no effect on semantics, we go on to put its syntax in the AST.
7291 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7292 PrevDecl_TSK == TSK_Undeclared) {
7293 // Since the only prior class template specialization with these
7294 // arguments was referenced but not declared, reuse that
7295 // declaration node as our own, updating the source location
7296 // for the template name to reflect our new declaration.
7297 // (Other source locations will be updated later.)
7298 Specialization = PrevDecl;
7299 Specialization->setLocation(TemplateNameLoc);
7304 if (!Specialization) {
7305 // Create a new class template specialization declaration node for
7306 // this explicit specialization.
7308 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7309 ClassTemplate->getDeclContext(),
7310 KWLoc, TemplateNameLoc,
7315 SetNestedNameSpecifier(Specialization, SS);
7317 if (!HasNoEffect && !PrevDecl) {
7318 // Insert the new specialization.
7319 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7323 // Build the fully-sugared type for this explicit instantiation as
7324 // the user wrote in the explicit instantiation itself. This means
7325 // that we'll pretty-print the type retrieved from the
7326 // specialization's declaration the way that the user actually wrote
7327 // the explicit instantiation, rather than formatting the name based
7328 // on the "canonical" representation used to store the template
7329 // arguments in the specialization.
7330 TypeSourceInfo *WrittenTy
7331 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7333 Context.getTypeDeclType(Specialization));
7334 Specialization->setTypeAsWritten(WrittenTy);
7336 // Set source locations for keywords.
7337 Specialization->setExternLoc(ExternLoc);
7338 Specialization->setTemplateKeywordLoc(TemplateLoc);
7339 Specialization->setRBraceLoc(SourceLocation());
7342 ProcessDeclAttributeList(S, Specialization, Attr);
7344 // Add the explicit instantiation into its lexical context. However,
7345 // since explicit instantiations are never found by name lookup, we
7346 // just put it into the declaration context directly.
7347 Specialization->setLexicalDeclContext(CurContext);
7348 CurContext->addDecl(Specialization);
7350 // Syntax is now OK, so return if it has no other effect on semantics.
7352 // Set the template specialization kind.
7353 Specialization->setTemplateSpecializationKind(TSK);
7354 return Specialization;
7357 // C++ [temp.explicit]p3:
7358 // A definition of a class template or class member template
7359 // shall be in scope at the point of the explicit instantiation of
7360 // the class template or class member template.
7362 // This check comes when we actually try to perform the
7364 ClassTemplateSpecializationDecl *Def
7365 = cast_or_null<ClassTemplateSpecializationDecl>(
7366 Specialization->getDefinition());
7368 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
7369 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7370 MarkVTableUsed(TemplateNameLoc, Specialization, true);
7371 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7374 // Instantiate the members of this class template specialization.
7375 Def = cast_or_null<ClassTemplateSpecializationDecl>(
7376 Specialization->getDefinition());
7378 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7380 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7381 // TSK_ExplicitInstantiationDefinition
7382 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
7383 TSK == TSK_ExplicitInstantiationDefinition) {
7384 // FIXME: Need to notify the ASTMutationListener that we did this.
7385 Def->setTemplateSpecializationKind(TSK);
7387 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
7388 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7389 // In the MS ABI, an explicit instantiation definition can add a dll
7390 // attribute to a template with a previous instantiation declaration.
7391 // MinGW doesn't allow this.
7392 auto *A = cast<InheritableAttr>(
7393 getDLLAttr(Specialization)->clone(getASTContext()));
7394 A->setInherited(true);
7396 checkClassLevelDLLAttribute(Def);
7398 // Propagate attribute to base class templates.
7399 for (auto &B : Def->bases()) {
7400 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
7401 B.getType()->getAsCXXRecordDecl()))
7402 propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getLocStart());
7407 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
7410 // Set the template specialization kind.
7411 Specialization->setTemplateSpecializationKind(TSK);
7412 return Specialization;
7415 // Explicit instantiation of a member class of a class template.
7417 Sema::ActOnExplicitInstantiation(Scope *S,
7418 SourceLocation ExternLoc,
7419 SourceLocation TemplateLoc,
7421 SourceLocation KWLoc,
7423 IdentifierInfo *Name,
7424 SourceLocation NameLoc,
7425 AttributeList *Attr) {
7428 bool IsDependent = false;
7429 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
7430 KWLoc, SS, Name, NameLoc, Attr, AS_none,
7431 /*ModulePrivateLoc=*/SourceLocation(),
7432 MultiTemplateParamsArg(), Owned, IsDependent,
7433 SourceLocation(), false, TypeResult(),
7434 /*IsTypeSpecifier*/false);
7435 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7440 TagDecl *Tag = cast<TagDecl>(TagD);
7441 assert(!Tag->isEnum() && "shouldn't see enumerations here");
7443 if (Tag->isInvalidDecl())
7446 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7447 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7449 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7450 << Context.getTypeDeclType(Record);
7451 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7455 // C++0x [temp.explicit]p2:
7456 // If the explicit instantiation is for a class or member class, the
7457 // elaborated-type-specifier in the declaration shall include a
7458 // simple-template-id.
7460 // C++98 has the same restriction, just worded differently.
7461 if (!ScopeSpecifierHasTemplateId(SS))
7462 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
7463 << Record << SS.getRange();
7465 // C++0x [temp.explicit]p2:
7466 // There are two forms of explicit instantiation: an explicit instantiation
7467 // definition and an explicit instantiation declaration. An explicit
7468 // instantiation declaration begins with the extern keyword. [...]
7469 TemplateSpecializationKind TSK
7470 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7471 : TSK_ExplicitInstantiationDeclaration;
7473 // C++0x [temp.explicit]p2:
7474 // [...] An explicit instantiation shall appear in an enclosing
7475 // namespace of its template. [...]
7477 // This is C++ DR 275.
7478 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
7480 // Verify that it is okay to explicitly instantiate here.
7481 CXXRecordDecl *PrevDecl
7482 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
7483 if (!PrevDecl && Record->getDefinition())
7486 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
7487 bool HasNoEffect = false;
7488 assert(MSInfo && "No member specialization information?");
7489 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
7491 MSInfo->getTemplateSpecializationKind(),
7492 MSInfo->getPointOfInstantiation(),
7499 CXXRecordDecl *RecordDef
7500 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7502 // C++ [temp.explicit]p3:
7503 // A definition of a member class of a class template shall be in scope
7504 // at the point of an explicit instantiation of the member class.
7506 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
7508 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7509 << 0 << Record->getDeclName() << Record->getDeclContext();
7510 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7514 if (InstantiateClass(NameLoc, Record, Def,
7515 getTemplateInstantiationArgs(Record),
7519 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7525 // Instantiate all of the members of the class.
7526 InstantiateClassMembers(NameLoc, RecordDef,
7527 getTemplateInstantiationArgs(Record), TSK);
7529 if (TSK == TSK_ExplicitInstantiationDefinition)
7530 MarkVTableUsed(NameLoc, RecordDef, true);
7532 // FIXME: We don't have any representation for explicit instantiations of
7533 // member classes. Such a representation is not needed for compilation, but it
7534 // should be available for clients that want to see all of the declarations in
7539 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7540 SourceLocation ExternLoc,
7541 SourceLocation TemplateLoc,
7543 // Explicit instantiations always require a name.
7544 // TODO: check if/when DNInfo should replace Name.
7545 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7546 DeclarationName Name = NameInfo.getName();
7548 if (!D.isInvalidType())
7549 Diag(D.getDeclSpec().getLocStart(),
7550 diag::err_explicit_instantiation_requires_name)
7551 << D.getDeclSpec().getSourceRange()
7552 << D.getSourceRange();
7557 // The scope passed in may not be a decl scope. Zip up the scope tree until
7558 // we find one that is.
7559 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7560 (S->getFlags() & Scope::TemplateParamScope) != 0)
7563 // Determine the type of the declaration.
7564 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7565 QualType R = T->getType();
7570 // A storage-class-specifier shall not be specified in [...] an explicit
7571 // instantiation (14.7.2) directive.
7572 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
7573 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7576 } else if (D.getDeclSpec().getStorageClassSpec()
7577 != DeclSpec::SCS_unspecified) {
7578 // Complain about then remove the storage class specifier.
7579 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7580 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7582 D.getMutableDeclSpec().ClearStorageClassSpecs();
7585 // C++0x [temp.explicit]p1:
7586 // [...] An explicit instantiation of a function template shall not use the
7587 // inline or constexpr specifiers.
7588 // Presumably, this also applies to member functions of class templates as
7590 if (D.getDeclSpec().isInlineSpecified())
7591 Diag(D.getDeclSpec().getInlineSpecLoc(),
7592 getLangOpts().CPlusPlus11 ?
7593 diag::err_explicit_instantiation_inline :
7594 diag::warn_explicit_instantiation_inline_0x)
7595 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7596 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
7597 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7598 // not already specified.
7599 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7600 diag::err_explicit_instantiation_constexpr);
7602 // C++0x [temp.explicit]p2:
7603 // There are two forms of explicit instantiation: an explicit instantiation
7604 // definition and an explicit instantiation declaration. An explicit
7605 // instantiation declaration begins with the extern keyword. [...]
7606 TemplateSpecializationKind TSK
7607 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7608 : TSK_ExplicitInstantiationDeclaration;
7610 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
7611 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
7613 if (!R->isFunctionType()) {
7614 // C++ [temp.explicit]p1:
7615 // A [...] static data member of a class template can be explicitly
7616 // instantiated from the member definition associated with its class
7618 // C++1y [temp.explicit]p1:
7619 // A [...] variable [...] template specialization can be explicitly
7620 // instantiated from its template.
7621 if (Previous.isAmbiguous())
7624 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
7625 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
7627 if (!PrevTemplate) {
7628 if (!Prev || !Prev->isStaticDataMember()) {
7629 // We expect to see a data data member here.
7630 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7632 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7634 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7638 if (!Prev->getInstantiatedFromStaticDataMember()) {
7639 // FIXME: Check for explicit specialization?
7640 Diag(D.getIdentifierLoc(),
7641 diag::err_explicit_instantiation_data_member_not_instantiated)
7643 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7644 // FIXME: Can we provide a note showing where this was declared?
7648 // Explicitly instantiate a variable template.
7650 // C++1y [dcl.spec.auto]p6:
7651 // ... A program that uses auto or decltype(auto) in a context not
7652 // explicitly allowed in this section is ill-formed.
7654 // This includes auto-typed variable template instantiations.
7655 if (R->isUndeducedType()) {
7656 Diag(T->getTypeLoc().getLocStart(),
7657 diag::err_auto_not_allowed_var_inst);
7661 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7662 // C++1y [temp.explicit]p3:
7663 // If the explicit instantiation is for a variable, the unqualified-id
7664 // in the declaration shall be a template-id.
7665 Diag(D.getIdentifierLoc(),
7666 diag::err_explicit_instantiation_without_template_id)
7668 Diag(PrevTemplate->getLocation(),
7669 diag::note_explicit_instantiation_here);
7673 // Translate the parser's template argument list into our AST format.
7674 TemplateArgumentListInfo TemplateArgs =
7675 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7677 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7678 D.getIdentifierLoc(), TemplateArgs);
7679 if (Res.isInvalid())
7682 // Ignore access control bits, we don't need them for redeclaration
7684 Prev = cast<VarDecl>(Res.get());
7687 // C++0x [temp.explicit]p2:
7688 // If the explicit instantiation is for a member function, a member class
7689 // or a static data member of a class template specialization, the name of
7690 // the class template specialization in the qualified-id for the member
7691 // name shall be a simple-template-id.
7693 // C++98 has the same restriction, just worded differently.
7695 // This does not apply to variable template specializations, where the
7696 // template-id is in the unqualified-id instead.
7697 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
7698 Diag(D.getIdentifierLoc(),
7699 diag::ext_explicit_instantiation_without_qualified_id)
7700 << Prev << D.getCXXScopeSpec().getRange();
7702 // Check the scope of this explicit instantiation.
7703 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
7705 // Verify that it is okay to explicitly instantiate here.
7706 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7707 SourceLocation POI = Prev->getPointOfInstantiation();
7708 bool HasNoEffect = false;
7709 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
7710 PrevTSK, POI, HasNoEffect))
7714 // Instantiate static data member or variable template.
7716 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7718 // Merge attributes.
7719 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7720 ProcessDeclAttributeList(S, Prev, Attr);
7722 if (TSK == TSK_ExplicitInstantiationDefinition)
7723 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7726 // Check the new variable specialization against the parsed input.
7727 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7728 Diag(T->getTypeLoc().getLocStart(),
7729 diag::err_invalid_var_template_spec_type)
7730 << 0 << PrevTemplate << R << Prev->getType();
7731 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7732 << 2 << PrevTemplate->getDeclName();
7736 // FIXME: Create an ExplicitInstantiation node?
7737 return (Decl*) nullptr;
7740 // If the declarator is a template-id, translate the parser's template
7741 // argument list into our AST format.
7742 bool HasExplicitTemplateArgs = false;
7743 TemplateArgumentListInfo TemplateArgs;
7744 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7745 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7746 HasExplicitTemplateArgs = true;
7749 // C++ [temp.explicit]p1:
7750 // A [...] function [...] can be explicitly instantiated from its template.
7751 // A member function [...] of a class template can be explicitly
7752 // instantiated from the member definition associated with its class
7754 UnresolvedSet<8> Matches;
7755 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
7756 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7758 NamedDecl *Prev = *P;
7759 if (!HasExplicitTemplateArgs) {
7760 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
7761 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7762 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
7765 Matches.addDecl(Method, P.getAccess());
7766 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7772 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7776 TemplateDeductionInfo Info(FailedCandidates.getLocation());
7777 FunctionDecl *Specialization = nullptr;
7778 if (TemplateDeductionResult TDK
7779 = DeduceTemplateArguments(FunTmpl,
7780 (HasExplicitTemplateArgs ? &TemplateArgs
7782 R, Specialization, Info)) {
7783 // Keep track of almost-matches.
7784 FailedCandidates.addCandidate()
7785 .set(FunTmpl->getTemplatedDecl(),
7786 MakeDeductionFailureInfo(Context, TDK, Info));
7791 Matches.addDecl(Specialization, P.getAccess());
7794 // Find the most specialized function template specialization.
7795 UnresolvedSetIterator Result = getMostSpecialized(
7796 Matches.begin(), Matches.end(), FailedCandidates,
7797 D.getIdentifierLoc(),
7798 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7799 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7800 PDiag(diag::note_explicit_instantiation_candidate));
7802 if (Result == Matches.end())
7805 // Ignore access control bits, we don't need them for redeclaration checking.
7806 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
7808 // C++11 [except.spec]p4
7809 // In an explicit instantiation an exception-specification may be specified,
7810 // but is not required.
7811 // If an exception-specification is specified in an explicit instantiation
7812 // directive, it shall be compatible with the exception-specifications of
7813 // other declarations of that function.
7814 if (auto *FPT = R->getAs<FunctionProtoType>())
7815 if (FPT->hasExceptionSpec()) {
7817 diag::err_mismatched_exception_spec_explicit_instantiation;
7818 if (getLangOpts().MicrosoftExt)
7819 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
7820 bool Result = CheckEquivalentExceptionSpec(
7821 PDiag(DiagID) << Specialization->getType(),
7822 PDiag(diag::note_explicit_instantiation_here),
7823 Specialization->getType()->getAs<FunctionProtoType>(),
7824 Specialization->getLocation(), FPT, D.getLocStart());
7825 // In Microsoft mode, mismatching exception specifications just cause a
7827 if (!getLangOpts().MicrosoftExt && Result)
7831 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
7832 Diag(D.getIdentifierLoc(),
7833 diag::err_explicit_instantiation_member_function_not_instantiated)
7835 << (Specialization->getTemplateSpecializationKind() ==
7836 TSK_ExplicitSpecialization);
7837 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7841 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
7842 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7843 PrevDecl = Specialization;
7846 bool HasNoEffect = false;
7847 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
7849 PrevDecl->getTemplateSpecializationKind(),
7850 PrevDecl->getPointOfInstantiation(),
7854 // FIXME: We may still want to build some representation of this
7855 // explicit specialization.
7857 return (Decl*) nullptr;
7860 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7861 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7863 ProcessDeclAttributeList(S, Specialization, Attr);
7865 if (Specialization->isDefined()) {
7866 // Let the ASTConsumer know that this function has been explicitly
7867 // instantiated now, and its linkage might have changed.
7868 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7869 } else if (TSK == TSK_ExplicitInstantiationDefinition)
7870 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
7872 // C++0x [temp.explicit]p2:
7873 // If the explicit instantiation is for a member function, a member class
7874 // or a static data member of a class template specialization, the name of
7875 // the class template specialization in the qualified-id for the member
7876 // name shall be a simple-template-id.
7878 // C++98 has the same restriction, just worded differently.
7879 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
7880 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
7881 D.getCXXScopeSpec().isSet() &&
7882 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
7883 Diag(D.getIdentifierLoc(),
7884 diag::ext_explicit_instantiation_without_qualified_id)
7885 << Specialization << D.getCXXScopeSpec().getRange();
7887 CheckExplicitInstantiationScope(*this,
7888 FunTmpl? (NamedDecl *)FunTmpl
7889 : Specialization->getInstantiatedFromMemberFunction(),
7890 D.getIdentifierLoc(),
7891 D.getCXXScopeSpec().isSet());
7893 // FIXME: Create some kind of ExplicitInstantiationDecl here.
7894 return (Decl*) nullptr;
7898 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7899 const CXXScopeSpec &SS, IdentifierInfo *Name,
7900 SourceLocation TagLoc, SourceLocation NameLoc) {
7901 // This has to hold, because SS is expected to be defined.
7902 assert(Name && "Expected a name in a dependent tag");
7904 NestedNameSpecifier *NNS = SS.getScopeRep();
7908 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7910 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7911 Diag(NameLoc, diag::err_dependent_tag_decl)
7912 << (TUK == TUK_Definition) << Kind << SS.getRange();
7916 // Create the resulting type.
7917 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7918 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7920 // Create type-source location information for this type.
7922 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
7923 TL.setElaboratedKeywordLoc(TagLoc);
7924 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7925 TL.setNameLoc(NameLoc);
7926 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
7930 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7931 const CXXScopeSpec &SS, const IdentifierInfo &II,
7932 SourceLocation IdLoc) {
7936 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7938 getLangOpts().CPlusPlus11 ?
7939 diag::warn_cxx98_compat_typename_outside_of_template :
7940 diag::ext_typename_outside_of_template)
7941 << FixItHint::CreateRemoval(TypenameLoc);
7943 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7944 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
7945 TypenameLoc, QualifierLoc, II, IdLoc);
7949 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7950 if (isa<DependentNameType>(T)) {
7951 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
7952 TL.setElaboratedKeywordLoc(TypenameLoc);
7953 TL.setQualifierLoc(QualifierLoc);
7954 TL.setNameLoc(IdLoc);
7956 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
7957 TL.setElaboratedKeywordLoc(TypenameLoc);
7958 TL.setQualifierLoc(QualifierLoc);
7959 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
7962 return CreateParsedType(T, TSI);
7966 Sema::ActOnTypenameType(Scope *S,
7967 SourceLocation TypenameLoc,
7968 const CXXScopeSpec &SS,
7969 SourceLocation TemplateKWLoc,
7970 TemplateTy TemplateIn,
7971 SourceLocation TemplateNameLoc,
7972 SourceLocation LAngleLoc,
7973 ASTTemplateArgsPtr TemplateArgsIn,
7974 SourceLocation RAngleLoc) {
7975 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7977 getLangOpts().CPlusPlus11 ?
7978 diag::warn_cxx98_compat_typename_outside_of_template :
7979 diag::ext_typename_outside_of_template)
7980 << FixItHint::CreateRemoval(TypenameLoc);
7982 // Translate the parser's template argument list in our AST format.
7983 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7984 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7986 TemplateName Template = TemplateIn.get();
7987 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
7988 // Construct a dependent template specialization type.
7989 assert(DTN && "dependent template has non-dependent name?");
7990 assert(DTN->getQualifier() == SS.getScopeRep());
7991 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
7992 DTN->getQualifier(),
7993 DTN->getIdentifier(),
7996 // Create source-location information for this type.
7997 TypeLocBuilder Builder;
7998 DependentTemplateSpecializationTypeLoc SpecTL
7999 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
8000 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
8001 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
8002 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8003 SpecTL.setTemplateNameLoc(TemplateNameLoc);
8004 SpecTL.setLAngleLoc(LAngleLoc);
8005 SpecTL.setRAngleLoc(RAngleLoc);
8006 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8007 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8008 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
8011 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
8015 // Provide source-location information for the template specialization type.
8016 TypeLocBuilder Builder;
8017 TemplateSpecializationTypeLoc SpecTL
8018 = Builder.push<TemplateSpecializationTypeLoc>(T);
8019 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
8020 SpecTL.setTemplateNameLoc(TemplateNameLoc);
8021 SpecTL.setLAngleLoc(LAngleLoc);
8022 SpecTL.setRAngleLoc(RAngleLoc);
8023 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8024 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
8026 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
8027 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
8028 TL.setElaboratedKeywordLoc(TypenameLoc);
8029 TL.setQualifierLoc(SS.getWithLocInContext(Context));
8031 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
8032 return CreateParsedType(T, TSI);
8036 /// Determine whether this failed name lookup should be treated as being
8037 /// disabled by a usage of std::enable_if.
8038 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
8039 SourceRange &CondRange) {
8040 // We must be looking for a ::type...
8041 if (!II.isStr("type"))
8044 // ... within an explicitly-written template specialization...
8045 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
8047 TypeLoc EnableIfTy = NNS.getTypeLoc();
8048 TemplateSpecializationTypeLoc EnableIfTSTLoc =
8049 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
8050 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
8052 const TemplateSpecializationType *EnableIfTST =
8053 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
8055 // ... which names a complete class template declaration...
8056 const TemplateDecl *EnableIfDecl =
8057 EnableIfTST->getTemplateName().getAsTemplateDecl();
8058 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
8061 // ... called "enable_if".
8062 const IdentifierInfo *EnableIfII =
8063 EnableIfDecl->getDeclName().getAsIdentifierInfo();
8064 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
8067 // Assume the first template argument is the condition.
8068 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
8072 /// \brief Build the type that describes a C++ typename specifier,
8073 /// e.g., "typename T::type".
8075 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
8076 SourceLocation KeywordLoc,
8077 NestedNameSpecifierLoc QualifierLoc,
8078 const IdentifierInfo &II,
8079 SourceLocation IILoc) {
8081 SS.Adopt(QualifierLoc);
8083 DeclContext *Ctx = computeDeclContext(SS);
8085 // If the nested-name-specifier is dependent and couldn't be
8086 // resolved to a type, build a typename type.
8087 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
8088 return Context.getDependentNameType(Keyword,
8089 QualifierLoc.getNestedNameSpecifier(),
8093 // If the nested-name-specifier refers to the current instantiation,
8094 // the "typename" keyword itself is superfluous. In C++03, the
8095 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
8096 // allows such extraneous "typename" keywords, and we retroactively
8097 // apply this DR to C++03 code with only a warning. In any case we continue.
8099 if (RequireCompleteDeclContext(SS, Ctx))
8102 DeclarationName Name(&II);
8103 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
8104 LookupQualifiedName(Result, Ctx, SS);
8105 unsigned DiagID = 0;
8106 Decl *Referenced = nullptr;
8107 switch (Result.getResultKind()) {
8108 case LookupResult::NotFound: {
8109 // If we're looking up 'type' within a template named 'enable_if', produce
8110 // a more specific diagnostic.
8111 SourceRange CondRange;
8112 if (isEnableIf(QualifierLoc, II, CondRange)) {
8113 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
8114 << Ctx << CondRange;
8118 DiagID = diag::err_typename_nested_not_found;
8122 case LookupResult::FoundUnresolvedValue: {
8123 // We found a using declaration that is a value. Most likely, the using
8124 // declaration itself is meant to have the 'typename' keyword.
8125 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8127 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
8128 << Name << Ctx << FullRange;
8129 if (UnresolvedUsingValueDecl *Using
8130 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
8131 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
8132 Diag(Loc, diag::note_using_value_decl_missing_typename)
8133 << FixItHint::CreateInsertion(Loc, "typename ");
8136 // Fall through to create a dependent typename type, from which we can recover
8139 case LookupResult::NotFoundInCurrentInstantiation:
8140 // Okay, it's a member of an unknown instantiation.
8141 return Context.getDependentNameType(Keyword,
8142 QualifierLoc.getNestedNameSpecifier(),
8145 case LookupResult::Found:
8146 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
8147 // We found a type. Build an ElaboratedType, since the
8148 // typename-specifier was just sugar.
8149 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
8150 return Context.getElaboratedType(ETK_Typename,
8151 QualifierLoc.getNestedNameSpecifier(),
8152 Context.getTypeDeclType(Type));
8155 DiagID = diag::err_typename_nested_not_type;
8156 Referenced = Result.getFoundDecl();
8159 case LookupResult::FoundOverloaded:
8160 DiagID = diag::err_typename_nested_not_type;
8161 Referenced = *Result.begin();
8164 case LookupResult::Ambiguous:
8168 // If we get here, it's because name lookup did not find a
8169 // type. Emit an appropriate diagnostic and return an error.
8170 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
8172 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
8174 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
8180 // See Sema::RebuildTypeInCurrentInstantiation
8181 class CurrentInstantiationRebuilder
8182 : public TreeTransform<CurrentInstantiationRebuilder> {
8184 DeclarationName Entity;
8187 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
8189 CurrentInstantiationRebuilder(Sema &SemaRef,
8191 DeclarationName Entity)
8192 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
8193 Loc(Loc), Entity(Entity) { }
8195 /// \brief Determine whether the given type \p T has already been
8198 /// For the purposes of type reconstruction, a type has already been
8199 /// transformed if it is NULL or if it is not dependent.
8200 bool AlreadyTransformed(QualType T) {
8201 return T.isNull() || !T->isDependentType();
8204 /// \brief Returns the location of the entity whose type is being
8206 SourceLocation getBaseLocation() { return Loc; }
8208 /// \brief Returns the name of the entity whose type is being rebuilt.
8209 DeclarationName getBaseEntity() { return Entity; }
8211 /// \brief Sets the "base" location and entity when that
8212 /// information is known based on another transformation.
8213 void setBase(SourceLocation Loc, DeclarationName Entity) {
8215 this->Entity = Entity;
8218 ExprResult TransformLambdaExpr(LambdaExpr *E) {
8219 // Lambdas never need to be transformed.
8225 /// \brief Rebuilds a type within the context of the current instantiation.
8227 /// The type \p T is part of the type of an out-of-line member definition of
8228 /// a class template (or class template partial specialization) that was parsed
8229 /// and constructed before we entered the scope of the class template (or
8230 /// partial specialization thereof). This routine will rebuild that type now
8231 /// that we have entered the declarator's scope, which may produce different
8232 /// canonical types, e.g.,
8235 /// template<typename T>
8237 /// typedef T* pointer;
8241 /// template<typename T>
8242 /// typename X<T>::pointer X<T>::data() { ... }
8245 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
8246 /// since we do not know that we can look into X<T> when we parsed the type.
8247 /// This function will rebuild the type, performing the lookup of "pointer"
8248 /// in X<T> and returning an ElaboratedType whose canonical type is the same
8249 /// as the canonical type of T*, allowing the return types of the out-of-line
8250 /// definition and the declaration to match.
8251 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8253 DeclarationName Name) {
8254 if (!T || !T->getType()->isDependentType())
8257 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8258 return Rebuilder.TransformType(T);
8261 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
8262 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8264 return Rebuilder.TransformExpr(E);
8267 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
8271 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8272 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8274 NestedNameSpecifierLoc Rebuilt
8275 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8283 /// \brief Rebuild the template parameters now that we know we're in a current
8285 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8286 TemplateParameterList *Params) {
8287 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8288 Decl *Param = Params->getParam(I);
8290 // There is nothing to rebuild in a type parameter.
8291 if (isa<TemplateTypeParmDecl>(Param))
8294 // Rebuild the template parameter list of a template template parameter.
8295 if (TemplateTemplateParmDecl *TTP
8296 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8297 if (RebuildTemplateParamsInCurrentInstantiation(
8298 TTP->getTemplateParameters()))
8304 // Rebuild the type of a non-type template parameter.
8305 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8306 TypeSourceInfo *NewTSI
8307 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8308 NTTP->getLocation(),
8309 NTTP->getDeclName());
8313 if (NewTSI != NTTP->getTypeSourceInfo()) {
8314 NTTP->setTypeSourceInfo(NewTSI);
8315 NTTP->setType(NewTSI->getType());
8322 /// \brief Produces a formatted string that describes the binding of
8323 /// template parameters to template arguments.
8325 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8326 const TemplateArgumentList &Args) {
8327 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
8331 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8332 const TemplateArgument *Args,
8334 SmallString<128> Str;
8335 llvm::raw_svector_ostream Out(Str);
8337 if (!Params || Params->size() == 0 || NumArgs == 0)
8338 return std::string();
8340 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8349 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
8350 Out << Id->getName();
8356 Args[I].print(getPrintingPolicy(), Out);
8363 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8364 CachedTokens &Toks) {
8368 LateParsedTemplate *LPT = new LateParsedTemplate;
8370 // Take tokens to avoid allocations
8371 LPT->Toks.swap(Toks);
8373 LateParsedTemplateMap.insert(std::make_pair(FD, LPT));
8375 FD->setLateTemplateParsed(true);
8378 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8381 FD->setLateTemplateParsed(false);
8384 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8385 DeclContext *DC = CurContext;
8388 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8389 const FunctionDecl *FD = RD->isLocalClass();
8390 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8391 } else if (DC->isTranslationUnit() || DC->isNamespace())
8394 DC = DC->getParent();