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)) {
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 CorrectionCandidateCallback FilterCCC;
322 FilterCCC.WantTypeSpecifiers = false;
323 FilterCCC.WantExpressionKeywords = false;
324 FilterCCC.WantRemainingKeywords = false;
325 FilterCCC.WantCXXNamedCasts = true;
326 if (TypoCorrection Corrected = CorrectTypo(Found.getLookupNameInfo(),
327 Found.getLookupKind(), S, &SS,
328 FilterCCC, CTK_ErrorRecovery,
330 Found.setLookupName(Corrected.getCorrection());
331 if (Corrected.getCorrectionDecl())
332 Found.addDecl(Corrected.getCorrectionDecl());
333 FilterAcceptableTemplateNames(Found);
334 if (!Found.empty()) {
336 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
337 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
338 Name.getAsString() == CorrectedStr;
339 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
340 << Name << LookupCtx << DroppedSpecifier
343 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
347 Found.setLookupName(Name);
351 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
354 MemberOfUnknownSpecialization = true;
358 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
359 !getLangOpts().CPlusPlus11) {
360 // C++03 [basic.lookup.classref]p1:
361 // [...] If the lookup in the class of the object expression finds a
362 // template, the name is also looked up in the context of the entire
363 // postfix-expression and [...]
365 // Note: C++11 does not perform this second lookup.
366 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
368 LookupName(FoundOuter, S);
369 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
371 if (FoundOuter.empty()) {
372 // - if the name is not found, the name found in the class of the
373 // object expression is used, otherwise
374 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>() ||
375 FoundOuter.isAmbiguous()) {
376 // - if the name is found in the context of the entire
377 // postfix-expression and does not name a class template, the name
378 // found in the class of the object expression is used, otherwise
380 } else if (!Found.isSuppressingDiagnostics()) {
381 // - if the name found is a class template, it must refer to the same
382 // entity as the one found in the class of the object expression,
383 // otherwise the program is ill-formed.
384 if (!Found.isSingleResult() ||
385 Found.getFoundDecl()->getCanonicalDecl()
386 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
387 Diag(Found.getNameLoc(),
388 diag::ext_nested_name_member_ref_lookup_ambiguous)
389 << Found.getLookupName()
391 Diag(Found.getRepresentativeDecl()->getLocation(),
392 diag::note_ambig_member_ref_object_type)
394 Diag(FoundOuter.getFoundDecl()->getLocation(),
395 diag::note_ambig_member_ref_scope);
397 // Recover by taking the template that we found in the object
398 // expression's type.
404 /// ActOnDependentIdExpression - Handle a dependent id-expression that
405 /// was just parsed. This is only possible with an explicit scope
406 /// specifier naming a dependent type.
408 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
409 SourceLocation TemplateKWLoc,
410 const DeclarationNameInfo &NameInfo,
411 bool isAddressOfOperand,
412 const TemplateArgumentListInfo *TemplateArgs) {
413 DeclContext *DC = getFunctionLevelDeclContext();
415 if (!isAddressOfOperand &&
416 isa<CXXMethodDecl>(DC) &&
417 cast<CXXMethodDecl>(DC)->isInstance()) {
418 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
420 // Since the 'this' expression is synthesized, we don't need to
421 // perform the double-lookup check.
422 NamedDecl *FirstQualifierInScope = nullptr;
424 return CXXDependentScopeMemberExpr::Create(
425 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
426 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
427 FirstQualifierInScope, NameInfo, TemplateArgs);
430 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
434 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
435 SourceLocation TemplateKWLoc,
436 const DeclarationNameInfo &NameInfo,
437 const TemplateArgumentListInfo *TemplateArgs) {
438 return DependentScopeDeclRefExpr::Create(
439 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
443 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
444 /// that the template parameter 'PrevDecl' is being shadowed by a new
445 /// declaration at location Loc. Returns true to indicate that this is
446 /// an error, and false otherwise.
447 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
448 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
450 // Microsoft Visual C++ permits template parameters to be shadowed.
451 if (getLangOpts().MicrosoftExt)
454 // C++ [temp.local]p4:
455 // A template-parameter shall not be redeclared within its
456 // scope (including nested scopes).
457 Diag(Loc, diag::err_template_param_shadow)
458 << cast<NamedDecl>(PrevDecl)->getDeclName();
459 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
463 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
464 /// the parameter D to reference the templated declaration and return a pointer
465 /// to the template declaration. Otherwise, do nothing to D and return null.
466 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
467 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
468 D = Temp->getTemplatedDecl();
474 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
475 SourceLocation EllipsisLoc) const {
476 assert(Kind == Template &&
477 "Only template template arguments can be pack expansions here");
478 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
479 "Template template argument pack expansion without packs");
480 ParsedTemplateArgument Result(*this);
481 Result.EllipsisLoc = EllipsisLoc;
485 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
486 const ParsedTemplateArgument &Arg) {
488 switch (Arg.getKind()) {
489 case ParsedTemplateArgument::Type: {
491 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
493 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
494 return TemplateArgumentLoc(TemplateArgument(T), DI);
497 case ParsedTemplateArgument::NonType: {
498 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
499 return TemplateArgumentLoc(TemplateArgument(E), E);
502 case ParsedTemplateArgument::Template: {
503 TemplateName Template = Arg.getAsTemplate().get();
504 TemplateArgument TArg;
505 if (Arg.getEllipsisLoc().isValid())
506 TArg = TemplateArgument(Template, Optional<unsigned int>());
509 return TemplateArgumentLoc(TArg,
510 Arg.getScopeSpec().getWithLocInContext(
513 Arg.getEllipsisLoc());
517 llvm_unreachable("Unhandled parsed template argument");
520 /// \brief Translates template arguments as provided by the parser
521 /// into template arguments used by semantic analysis.
522 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
523 TemplateArgumentListInfo &TemplateArgs) {
524 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
525 TemplateArgs.addArgument(translateTemplateArgument(*this,
529 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
531 IdentifierInfo *Name) {
532 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
533 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForRedeclaration);
534 if (PrevDecl && PrevDecl->isTemplateParameter())
535 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
538 /// ActOnTypeParameter - Called when a C++ template type parameter
539 /// (e.g., "typename T") has been parsed. Typename specifies whether
540 /// the keyword "typename" was used to declare the type parameter
541 /// (otherwise, "class" was used), and KeyLoc is the location of the
542 /// "class" or "typename" keyword. ParamName is the name of the
543 /// parameter (NULL indicates an unnamed template parameter) and
544 /// ParamNameLoc is the location of the parameter name (if any).
545 /// If the type parameter has a default argument, it will be added
546 /// later via ActOnTypeParameterDefault.
547 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
548 SourceLocation EllipsisLoc,
549 SourceLocation KeyLoc,
550 IdentifierInfo *ParamName,
551 SourceLocation ParamNameLoc,
552 unsigned Depth, unsigned Position,
553 SourceLocation EqualLoc,
554 ParsedType DefaultArg) {
555 assert(S->isTemplateParamScope() &&
556 "Template type parameter not in template parameter scope!");
557 bool Invalid = false;
559 SourceLocation Loc = ParamNameLoc;
563 bool IsParameterPack = EllipsisLoc.isValid();
564 TemplateTypeParmDecl *Param
565 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
566 KeyLoc, Loc, Depth, Position, ParamName,
567 Typename, IsParameterPack);
568 Param->setAccess(AS_public);
570 Param->setInvalidDecl();
573 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
575 // Add the template parameter into the current scope.
577 IdResolver.AddDecl(Param);
580 // C++0x [temp.param]p9:
581 // A default template-argument may be specified for any kind of
582 // template-parameter that is not a template parameter pack.
583 if (DefaultArg && IsParameterPack) {
584 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
585 DefaultArg = ParsedType();
588 // Handle the default argument, if provided.
590 TypeSourceInfo *DefaultTInfo;
591 GetTypeFromParser(DefaultArg, &DefaultTInfo);
593 assert(DefaultTInfo && "expected source information for type");
595 // Check for unexpanded parameter packs.
596 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
597 UPPC_DefaultArgument))
600 // Check the template argument itself.
601 if (CheckTemplateArgument(Param, DefaultTInfo)) {
602 Param->setInvalidDecl();
606 Param->setDefaultArgument(DefaultTInfo, false);
612 /// \brief Check that the type of a non-type template parameter is
615 /// \returns the (possibly-promoted) parameter type if valid;
616 /// otherwise, produces a diagnostic and returns a NULL type.
618 Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
619 // We don't allow variably-modified types as the type of non-type template
621 if (T->isVariablyModifiedType()) {
622 Diag(Loc, diag::err_variably_modified_nontype_template_param)
627 // C++ [temp.param]p4:
629 // A non-type template-parameter shall have one of the following
630 // (optionally cv-qualified) types:
632 // -- integral or enumeration type,
633 if (T->isIntegralOrEnumerationType() ||
634 // -- pointer to object or pointer to function,
635 T->isPointerType() ||
636 // -- reference to object or reference to function,
637 T->isReferenceType() ||
638 // -- pointer to member,
639 T->isMemberPointerType() ||
640 // -- std::nullptr_t.
641 T->isNullPtrType() ||
642 // If T is a dependent type, we can't do the check now, so we
643 // assume that it is well-formed.
644 T->isDependentType()) {
645 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
646 // are ignored when determining its type.
647 return T.getUnqualifiedType();
650 // C++ [temp.param]p8:
652 // A non-type template-parameter of type "array of T" or
653 // "function returning T" is adjusted to be of type "pointer to
654 // T" or "pointer to function returning T", respectively.
655 else if (T->isArrayType())
656 // FIXME: Keep the type prior to promotion?
657 return Context.getArrayDecayedType(T);
658 else if (T->isFunctionType())
659 // FIXME: Keep the type prior to promotion?
660 return Context.getPointerType(T);
662 Diag(Loc, diag::err_template_nontype_parm_bad_type)
668 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
671 SourceLocation EqualLoc,
673 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
674 QualType T = TInfo->getType();
676 assert(S->isTemplateParamScope() &&
677 "Non-type template parameter not in template parameter scope!");
678 bool Invalid = false;
680 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
682 T = Context.IntTy; // Recover with an 'int' type.
686 IdentifierInfo *ParamName = D.getIdentifier();
687 bool IsParameterPack = D.hasEllipsis();
688 NonTypeTemplateParmDecl *Param
689 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
691 D.getIdentifierLoc(),
692 Depth, Position, ParamName, T,
693 IsParameterPack, TInfo);
694 Param->setAccess(AS_public);
697 Param->setInvalidDecl();
700 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
703 // Add the template parameter into the current scope.
705 IdResolver.AddDecl(Param);
708 // C++0x [temp.param]p9:
709 // A default template-argument may be specified for any kind of
710 // template-parameter that is not a template parameter pack.
711 if (Default && IsParameterPack) {
712 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
716 // Check the well-formedness of the default template argument, if provided.
718 // Check for unexpanded parameter packs.
719 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
722 TemplateArgument Converted;
723 ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted);
724 if (DefaultRes.isInvalid()) {
725 Param->setInvalidDecl();
728 Default = DefaultRes.get();
730 Param->setDefaultArgument(Default, false);
736 /// ActOnTemplateTemplateParameter - Called when a C++ template template
737 /// parameter (e.g. T in template <template \<typename> class T> class array)
738 /// has been parsed. S is the current scope.
739 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
740 SourceLocation TmpLoc,
741 TemplateParameterList *Params,
742 SourceLocation EllipsisLoc,
743 IdentifierInfo *Name,
744 SourceLocation NameLoc,
747 SourceLocation EqualLoc,
748 ParsedTemplateArgument Default) {
749 assert(S->isTemplateParamScope() &&
750 "Template template parameter not in template parameter scope!");
752 // Construct the parameter object.
753 bool IsParameterPack = EllipsisLoc.isValid();
754 TemplateTemplateParmDecl *Param =
755 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
756 NameLoc.isInvalid()? TmpLoc : NameLoc,
757 Depth, Position, IsParameterPack,
759 Param->setAccess(AS_public);
761 // If the template template parameter has a name, then link the identifier
762 // into the scope and lookup mechanisms.
764 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
767 IdResolver.AddDecl(Param);
770 if (Params->size() == 0) {
771 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
772 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
773 Param->setInvalidDecl();
776 // C++0x [temp.param]p9:
777 // A default template-argument may be specified for any kind of
778 // template-parameter that is not a template parameter pack.
779 if (IsParameterPack && !Default.isInvalid()) {
780 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
781 Default = ParsedTemplateArgument();
784 if (!Default.isInvalid()) {
785 // Check only that we have a template template argument. We don't want to
786 // try to check well-formedness now, because our template template parameter
787 // might have dependent types in its template parameters, which we wouldn't
788 // be able to match now.
790 // If none of the template template parameter's template arguments mention
791 // other template parameters, we could actually perform more checking here.
792 // However, it isn't worth doing.
793 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
794 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
795 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
796 << DefaultArg.getSourceRange();
800 // Check for unexpanded parameter packs.
801 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
802 DefaultArg.getArgument().getAsTemplate(),
803 UPPC_DefaultArgument))
806 Param->setDefaultArgument(DefaultArg, false);
812 /// ActOnTemplateParameterList - Builds a TemplateParameterList that
813 /// contains the template parameters in Params/NumParams.
814 TemplateParameterList *
815 Sema::ActOnTemplateParameterList(unsigned Depth,
816 SourceLocation ExportLoc,
817 SourceLocation TemplateLoc,
818 SourceLocation LAngleLoc,
819 Decl **Params, unsigned NumParams,
820 SourceLocation RAngleLoc) {
821 if (ExportLoc.isValid())
822 Diag(ExportLoc, diag::warn_template_export_unsupported);
824 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
825 (NamedDecl**)Params, NumParams,
829 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
831 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
835 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
836 SourceLocation KWLoc, CXXScopeSpec &SS,
837 IdentifierInfo *Name, SourceLocation NameLoc,
839 TemplateParameterList *TemplateParams,
840 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
841 SourceLocation FriendLoc,
842 unsigned NumOuterTemplateParamLists,
843 TemplateParameterList** OuterTemplateParamLists) {
844 assert(TemplateParams && TemplateParams->size() > 0 &&
845 "No template parameters");
846 assert(TUK != TUK_Reference && "Can only declare or define class templates");
847 bool Invalid = false;
849 // Check that we can declare a template here.
850 if (CheckTemplateDeclScope(S, TemplateParams))
853 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
854 assert(Kind != TTK_Enum && "can't build template of enumerated type");
856 // There is no such thing as an unnamed class template.
858 Diag(KWLoc, diag::err_template_unnamed_class);
862 // Find any previous declaration with this name. For a friend with no
863 // scope explicitly specified, we only look for tag declarations (per
864 // C++11 [basic.lookup.elab]p2).
865 DeclContext *SemanticContext;
866 LookupResult Previous(*this, Name, NameLoc,
867 (SS.isEmpty() && TUK == TUK_Friend)
868 ? LookupTagName : LookupOrdinaryName,
870 if (SS.isNotEmpty() && !SS.isInvalid()) {
871 SemanticContext = computeDeclContext(SS, true);
872 if (!SemanticContext) {
873 // FIXME: Horrible, horrible hack! We can't currently represent this
874 // in the AST, and historically we have just ignored such friend
875 // class templates, so don't complain here.
876 Diag(NameLoc, TUK == TUK_Friend
877 ? diag::warn_template_qualified_friend_ignored
878 : diag::err_template_qualified_declarator_no_match)
879 << SS.getScopeRep() << SS.getRange();
880 return TUK != TUK_Friend;
883 if (RequireCompleteDeclContext(SS, SemanticContext))
886 // If we're adding a template to a dependent context, we may need to
887 // rebuilding some of the types used within the template parameter list,
888 // now that we know what the current instantiation is.
889 if (SemanticContext->isDependentContext()) {
890 ContextRAII SavedContext(*this, SemanticContext);
891 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
893 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
894 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc);
896 LookupQualifiedName(Previous, SemanticContext);
898 SemanticContext = CurContext;
899 LookupName(Previous, S);
902 if (Previous.isAmbiguous())
905 NamedDecl *PrevDecl = nullptr;
906 if (Previous.begin() != Previous.end())
907 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
909 // If there is a previous declaration with the same name, check
910 // whether this is a valid redeclaration.
911 ClassTemplateDecl *PrevClassTemplate
912 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
914 // We may have found the injected-class-name of a class template,
915 // class template partial specialization, or class template specialization.
916 // In these cases, grab the template that is being defined or specialized.
917 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
918 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
919 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
921 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
922 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
924 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
925 ->getSpecializedTemplate();
929 if (TUK == TUK_Friend) {
930 // C++ [namespace.memdef]p3:
931 // [...] When looking for a prior declaration of a class or a function
932 // declared as a friend, and when the name of the friend class or
933 // function is neither a qualified name nor a template-id, scopes outside
934 // the innermost enclosing namespace scope are not considered.
936 DeclContext *OutermostContext = CurContext;
937 while (!OutermostContext->isFileContext())
938 OutermostContext = OutermostContext->getLookupParent();
941 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
942 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
943 SemanticContext = PrevDecl->getDeclContext();
945 // Declarations in outer scopes don't matter. However, the outermost
946 // context we computed is the semantic context for our new
948 PrevDecl = PrevClassTemplate = nullptr;
949 SemanticContext = OutermostContext;
951 // Check that the chosen semantic context doesn't already contain a
952 // declaration of this name as a non-tag type.
953 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
955 DeclContext *LookupContext = SemanticContext;
956 while (LookupContext->isTransparentContext())
957 LookupContext = LookupContext->getLookupParent();
958 LookupQualifiedName(Previous, LookupContext);
960 if (Previous.isAmbiguous())
963 if (Previous.begin() != Previous.end())
964 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
967 } else if (PrevDecl &&
968 !isDeclInScope(PrevDecl, SemanticContext, S, SS.isValid()))
969 PrevDecl = PrevClassTemplate = nullptr;
971 if (PrevClassTemplate) {
972 // Ensure that the template parameter lists are compatible. Skip this check
973 // for a friend in a dependent context: the template parameter list itself
974 // could be dependent.
975 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
976 !TemplateParameterListsAreEqual(TemplateParams,
977 PrevClassTemplate->getTemplateParameters(),
982 // C++ [temp.class]p4:
983 // In a redeclaration, partial specialization, explicit
984 // specialization or explicit instantiation of a class template,
985 // the class-key shall agree in kind with the original class
986 // template declaration (7.1.5.3).
987 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
988 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
989 TUK == TUK_Definition, KWLoc, *Name)) {
990 Diag(KWLoc, diag::err_use_with_wrong_tag)
992 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
993 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
994 Kind = PrevRecordDecl->getTagKind();
997 // Check for redefinition of this class template.
998 if (TUK == TUK_Definition) {
999 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1000 Diag(NameLoc, diag::err_redefinition) << Name;
1001 Diag(Def->getLocation(), diag::note_previous_definition);
1002 // FIXME: Would it make sense to try to "forget" the previous
1003 // definition, as part of error recovery?
1007 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
1008 // Maybe we will complain about the shadowed template parameter.
1009 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1010 // Just pretend that we didn't see the previous declaration.
1012 } else if (PrevDecl) {
1014 // A class template shall not have the same name as any other
1015 // template, class, function, object, enumeration, enumerator,
1016 // namespace, or type in the same scope (3.3), except as specified
1018 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1019 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1023 // Check the template parameter list of this declaration, possibly
1024 // merging in the template parameter list from the previous class
1025 // template declaration. Skip this check for a friend in a dependent
1026 // context, because the template parameter list might be dependent.
1027 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1028 CheckTemplateParameterList(
1030 PrevClassTemplate ? PrevClassTemplate->getTemplateParameters()
1032 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1033 SemanticContext->isDependentContext())
1034 ? TPC_ClassTemplateMember
1035 : TUK == TUK_Friend ? TPC_FriendClassTemplate
1036 : TPC_ClassTemplate))
1040 // If the name of the template was qualified, we must be defining the
1041 // template out-of-line.
1042 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1043 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1044 : diag::err_member_decl_does_not_match)
1045 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1050 CXXRecordDecl *NewClass =
1051 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1053 PrevClassTemplate->getTemplatedDecl() : nullptr,
1054 /*DelayTypeCreation=*/true);
1055 SetNestedNameSpecifier(NewClass, SS);
1056 if (NumOuterTemplateParamLists > 0)
1057 NewClass->setTemplateParameterListsInfo(Context,
1058 NumOuterTemplateParamLists,
1059 OuterTemplateParamLists);
1061 // Add alignment attributes if necessary; these attributes are checked when
1062 // the ASTContext lays out the structure.
1063 if (TUK == TUK_Definition) {
1064 AddAlignmentAttributesForRecord(NewClass);
1065 AddMsStructLayoutForRecord(NewClass);
1068 ClassTemplateDecl *NewTemplate
1069 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
1070 DeclarationName(Name), TemplateParams,
1071 NewClass, PrevClassTemplate);
1072 NewClass->setDescribedClassTemplate(NewTemplate);
1074 if (ModulePrivateLoc.isValid())
1075 NewTemplate->setModulePrivate();
1077 // Build the type for the class template declaration now.
1078 QualType T = NewTemplate->getInjectedClassNameSpecialization();
1079 T = Context.getInjectedClassNameType(NewClass, T);
1080 assert(T->isDependentType() && "Class template type is not dependent?");
1083 // If we are providing an explicit specialization of a member that is a
1084 // class template, make a note of that.
1085 if (PrevClassTemplate &&
1086 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1087 PrevClassTemplate->setMemberSpecialization();
1089 // Set the access specifier.
1090 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
1091 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1093 // Set the lexical context of these templates
1094 NewClass->setLexicalDeclContext(CurContext);
1095 NewTemplate->setLexicalDeclContext(CurContext);
1097 if (TUK == TUK_Definition)
1098 NewClass->startDefinition();
1101 ProcessDeclAttributeList(S, NewClass, Attr);
1103 if (PrevClassTemplate)
1104 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
1106 AddPushedVisibilityAttribute(NewClass);
1108 if (TUK != TUK_Friend)
1109 PushOnScopeChains(NewTemplate, S);
1111 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1112 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1113 NewClass->setAccess(PrevClassTemplate->getAccess());
1116 NewTemplate->setObjectOfFriendDecl();
1118 // Friend templates are visible in fairly strange ways.
1119 if (!CurContext->isDependentContext()) {
1120 DeclContext *DC = SemanticContext->getRedeclContext();
1121 DC->makeDeclVisibleInContext(NewTemplate);
1122 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1123 PushOnScopeChains(NewTemplate, EnclosingScope,
1124 /* AddToContext = */ false);
1127 FriendDecl *Friend = FriendDecl::Create(
1128 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
1129 Friend->setAccess(AS_public);
1130 CurContext->addDecl(Friend);
1134 NewTemplate->setInvalidDecl();
1135 NewClass->setInvalidDecl();
1138 ActOnDocumentableDecl(NewTemplate);
1143 /// \brief Diagnose the presence of a default template argument on a
1144 /// template parameter, which is ill-formed in certain contexts.
1146 /// \returns true if the default template argument should be dropped.
1147 static bool DiagnoseDefaultTemplateArgument(Sema &S,
1148 Sema::TemplateParamListContext TPC,
1149 SourceLocation ParamLoc,
1150 SourceRange DefArgRange) {
1152 case Sema::TPC_ClassTemplate:
1153 case Sema::TPC_VarTemplate:
1154 case Sema::TPC_TypeAliasTemplate:
1157 case Sema::TPC_FunctionTemplate:
1158 case Sema::TPC_FriendFunctionTemplateDefinition:
1159 // C++ [temp.param]p9:
1160 // A default template-argument shall not be specified in a
1161 // function template declaration or a function template
1163 // If a friend function template declaration specifies a default
1164 // template-argument, that declaration shall be a definition and shall be
1165 // the only declaration of the function template in the translation unit.
1166 // (C++98/03 doesn't have this wording; see DR226).
1167 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
1168 diag::warn_cxx98_compat_template_parameter_default_in_function_template
1169 : diag::ext_template_parameter_default_in_function_template)
1173 case Sema::TPC_ClassTemplateMember:
1174 // C++0x [temp.param]p9:
1175 // A default template-argument shall not be specified in the
1176 // template-parameter-lists of the definition of a member of a
1177 // class template that appears outside of the member's class.
1178 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1182 case Sema::TPC_FriendClassTemplate:
1183 case Sema::TPC_FriendFunctionTemplate:
1184 // C++ [temp.param]p9:
1185 // A default template-argument shall not be specified in a
1186 // friend template declaration.
1187 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1191 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1192 // for friend function templates if there is only a single
1193 // declaration (and it is a definition). Strange!
1196 llvm_unreachable("Invalid TemplateParamListContext!");
1199 /// \brief Check for unexpanded parameter packs within the template parameters
1200 /// of a template template parameter, recursively.
1201 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1202 TemplateTemplateParmDecl *TTP) {
1203 // A template template parameter which is a parameter pack is also a pack
1205 if (TTP->isParameterPack())
1208 TemplateParameterList *Params = TTP->getTemplateParameters();
1209 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1210 NamedDecl *P = Params->getParam(I);
1211 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1212 if (!NTTP->isParameterPack() &&
1213 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1214 NTTP->getTypeSourceInfo(),
1215 Sema::UPPC_NonTypeTemplateParameterType))
1221 if (TemplateTemplateParmDecl *InnerTTP
1222 = dyn_cast<TemplateTemplateParmDecl>(P))
1223 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1230 /// \brief Checks the validity of a template parameter list, possibly
1231 /// considering the template parameter list from a previous
1234 /// If an "old" template parameter list is provided, it must be
1235 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1236 /// template parameter list.
1238 /// \param NewParams Template parameter list for a new template
1239 /// declaration. This template parameter list will be updated with any
1240 /// default arguments that are carried through from the previous
1241 /// template parameter list.
1243 /// \param OldParams If provided, template parameter list from a
1244 /// previous declaration of the same template. Default template
1245 /// arguments will be merged from the old template parameter list to
1246 /// the new template parameter list.
1248 /// \param TPC Describes the context in which we are checking the given
1249 /// template parameter list.
1251 /// \returns true if an error occurred, false otherwise.
1252 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1253 TemplateParameterList *OldParams,
1254 TemplateParamListContext TPC) {
1255 bool Invalid = false;
1257 // C++ [temp.param]p10:
1258 // The set of default template-arguments available for use with a
1259 // template declaration or definition is obtained by merging the
1260 // default arguments from the definition (if in scope) and all
1261 // declarations in scope in the same way default function
1262 // arguments are (8.3.6).
1263 bool SawDefaultArgument = false;
1264 SourceLocation PreviousDefaultArgLoc;
1266 // Dummy initialization to avoid warnings.
1267 TemplateParameterList::iterator OldParam = NewParams->end();
1269 OldParam = OldParams->begin();
1271 bool RemoveDefaultArguments = false;
1272 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1273 NewParamEnd = NewParams->end();
1274 NewParam != NewParamEnd; ++NewParam) {
1275 // Variables used to diagnose redundant default arguments
1276 bool RedundantDefaultArg = false;
1277 SourceLocation OldDefaultLoc;
1278 SourceLocation NewDefaultLoc;
1280 // Variable used to diagnose missing default arguments
1281 bool MissingDefaultArg = false;
1283 // Variable used to diagnose non-final parameter packs
1284 bool SawParameterPack = false;
1286 if (TemplateTypeParmDecl *NewTypeParm
1287 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1288 // Check the presence of a default argument here.
1289 if (NewTypeParm->hasDefaultArgument() &&
1290 DiagnoseDefaultTemplateArgument(*this, TPC,
1291 NewTypeParm->getLocation(),
1292 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1294 NewTypeParm->removeDefaultArgument();
1296 // Merge default arguments for template type parameters.
1297 TemplateTypeParmDecl *OldTypeParm
1298 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
1300 if (NewTypeParm->isParameterPack()) {
1301 assert(!NewTypeParm->hasDefaultArgument() &&
1302 "Parameter packs can't have a default argument!");
1303 SawParameterPack = true;
1304 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
1305 NewTypeParm->hasDefaultArgument()) {
1306 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1307 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1308 SawDefaultArgument = true;
1309 RedundantDefaultArg = true;
1310 PreviousDefaultArgLoc = NewDefaultLoc;
1311 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1312 // Merge the default argument from the old declaration to the
1314 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
1316 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1317 } else if (NewTypeParm->hasDefaultArgument()) {
1318 SawDefaultArgument = true;
1319 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1320 } else if (SawDefaultArgument)
1321 MissingDefaultArg = true;
1322 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1323 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1324 // Check for unexpanded parameter packs.
1325 if (!NewNonTypeParm->isParameterPack() &&
1326 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1327 NewNonTypeParm->getTypeSourceInfo(),
1328 UPPC_NonTypeTemplateParameterType)) {
1333 // Check the presence of a default argument here.
1334 if (NewNonTypeParm->hasDefaultArgument() &&
1335 DiagnoseDefaultTemplateArgument(*this, TPC,
1336 NewNonTypeParm->getLocation(),
1337 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1338 NewNonTypeParm->removeDefaultArgument();
1341 // Merge default arguments for non-type template parameters
1342 NonTypeTemplateParmDecl *OldNonTypeParm
1343 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
1344 if (NewNonTypeParm->isParameterPack()) {
1345 assert(!NewNonTypeParm->hasDefaultArgument() &&
1346 "Parameter packs can't have a default argument!");
1347 if (!NewNonTypeParm->isPackExpansion())
1348 SawParameterPack = true;
1349 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
1350 NewNonTypeParm->hasDefaultArgument()) {
1351 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1352 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1353 SawDefaultArgument = true;
1354 RedundantDefaultArg = true;
1355 PreviousDefaultArgLoc = NewDefaultLoc;
1356 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1357 // Merge the default argument from the old declaration to the
1359 // FIXME: We need to create a new kind of "default argument"
1360 // expression that points to a previous non-type template
1362 NewNonTypeParm->setDefaultArgument(
1363 OldNonTypeParm->getDefaultArgument(),
1364 /*Inherited=*/ true);
1365 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1366 } else if (NewNonTypeParm->hasDefaultArgument()) {
1367 SawDefaultArgument = true;
1368 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1369 } else if (SawDefaultArgument)
1370 MissingDefaultArg = true;
1372 TemplateTemplateParmDecl *NewTemplateParm
1373 = cast<TemplateTemplateParmDecl>(*NewParam);
1375 // Check for unexpanded parameter packs, recursively.
1376 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1381 // Check the presence of a default argument here.
1382 if (NewTemplateParm->hasDefaultArgument() &&
1383 DiagnoseDefaultTemplateArgument(*this, TPC,
1384 NewTemplateParm->getLocation(),
1385 NewTemplateParm->getDefaultArgument().getSourceRange()))
1386 NewTemplateParm->removeDefaultArgument();
1388 // Merge default arguments for template template parameters
1389 TemplateTemplateParmDecl *OldTemplateParm
1390 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
1391 if (NewTemplateParm->isParameterPack()) {
1392 assert(!NewTemplateParm->hasDefaultArgument() &&
1393 "Parameter packs can't have a default argument!");
1394 if (!NewTemplateParm->isPackExpansion())
1395 SawParameterPack = true;
1396 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
1397 NewTemplateParm->hasDefaultArgument()) {
1398 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1399 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1400 SawDefaultArgument = true;
1401 RedundantDefaultArg = true;
1402 PreviousDefaultArgLoc = NewDefaultLoc;
1403 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1404 // Merge the default argument from the old declaration to the
1406 // FIXME: We need to create a new kind of "default argument" expression
1407 // that points to a previous template template parameter.
1408 NewTemplateParm->setDefaultArgument(
1409 OldTemplateParm->getDefaultArgument(),
1410 /*Inherited=*/ true);
1411 PreviousDefaultArgLoc
1412 = OldTemplateParm->getDefaultArgument().getLocation();
1413 } else if (NewTemplateParm->hasDefaultArgument()) {
1414 SawDefaultArgument = true;
1415 PreviousDefaultArgLoc
1416 = NewTemplateParm->getDefaultArgument().getLocation();
1417 } else if (SawDefaultArgument)
1418 MissingDefaultArg = true;
1421 // C++11 [temp.param]p11:
1422 // If a template parameter of a primary class template or alias template
1423 // is a template parameter pack, it shall be the last template parameter.
1424 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
1425 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
1426 TPC == TPC_TypeAliasTemplate)) {
1427 Diag((*NewParam)->getLocation(),
1428 diag::err_template_param_pack_must_be_last_template_parameter);
1432 if (RedundantDefaultArg) {
1433 // C++ [temp.param]p12:
1434 // A template-parameter shall not be given default arguments
1435 // by two different declarations in the same scope.
1436 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1437 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1439 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
1440 // C++ [temp.param]p11:
1441 // If a template-parameter of a class template has a default
1442 // template-argument, each subsequent template-parameter shall either
1443 // have a default template-argument supplied or be a template parameter
1445 Diag((*NewParam)->getLocation(),
1446 diag::err_template_param_default_arg_missing);
1447 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1449 RemoveDefaultArguments = true;
1452 // If we have an old template parameter list that we're merging
1453 // in, move on to the next parameter.
1458 // We were missing some default arguments at the end of the list, so remove
1459 // all of the default arguments.
1460 if (RemoveDefaultArguments) {
1461 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1462 NewParamEnd = NewParams->end();
1463 NewParam != NewParamEnd; ++NewParam) {
1464 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1465 TTP->removeDefaultArgument();
1466 else if (NonTypeTemplateParmDecl *NTTP
1467 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1468 NTTP->removeDefaultArgument();
1470 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1479 /// A class which looks for a use of a certain level of template
1481 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1482 typedef RecursiveASTVisitor<DependencyChecker> super;
1486 SourceLocation MatchLoc;
1488 DependencyChecker(unsigned Depth) : Depth(Depth), Match(false) {}
1490 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1491 NamedDecl *ND = Params->getParam(0);
1492 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1493 Depth = PD->getDepth();
1494 } else if (NonTypeTemplateParmDecl *PD =
1495 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1496 Depth = PD->getDepth();
1498 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1502 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
1503 if (ParmDepth >= Depth) {
1511 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
1512 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
1515 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1516 return !Matches(T->getDepth());
1519 bool TraverseTemplateName(TemplateName N) {
1520 if (TemplateTemplateParmDecl *PD =
1521 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1522 if (Matches(PD->getDepth()))
1524 return super::TraverseTemplateName(N);
1527 bool VisitDeclRefExpr(DeclRefExpr *E) {
1528 if (NonTypeTemplateParmDecl *PD =
1529 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
1530 if (Matches(PD->getDepth(), E->getExprLoc()))
1532 return super::VisitDeclRefExpr(E);
1535 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
1536 return TraverseType(T->getReplacementType());
1540 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
1541 return TraverseTemplateArgument(T->getArgumentPack());
1544 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1545 return TraverseType(T->getInjectedSpecializationType());
1550 /// Determines whether a given type depends on the given parameter
1553 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
1554 DependencyChecker Checker(Params);
1555 Checker.TraverseType(T);
1556 return Checker.Match;
1559 // Find the source range corresponding to the named type in the given
1560 // nested-name-specifier, if any.
1561 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1563 const CXXScopeSpec &SS) {
1564 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1565 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1566 if (const Type *CurType = NNS->getAsType()) {
1567 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1568 return NNSLoc.getTypeLoc().getSourceRange();
1572 NNSLoc = NNSLoc.getPrefix();
1575 return SourceRange();
1578 /// \brief Match the given template parameter lists to the given scope
1579 /// specifier, returning the template parameter list that applies to the
1582 /// \param DeclStartLoc the start of the declaration that has a scope
1583 /// specifier or a template parameter list.
1585 /// \param DeclLoc The location of the declaration itself.
1587 /// \param SS the scope specifier that will be matched to the given template
1588 /// parameter lists. This scope specifier precedes a qualified name that is
1591 /// \param TemplateId The template-id following the scope specifier, if there
1592 /// is one. Used to check for a missing 'template<>'.
1594 /// \param ParamLists the template parameter lists, from the outermost to the
1595 /// innermost template parameter lists.
1597 /// \param IsFriend Whether to apply the slightly different rules for
1598 /// matching template parameters to scope specifiers in friend
1601 /// \param IsExplicitSpecialization will be set true if the entity being
1602 /// declared is an explicit specialization, false otherwise.
1604 /// \returns the template parameter list, if any, that corresponds to the
1605 /// name that is preceded by the scope specifier @p SS. This template
1606 /// parameter list may have template parameters (if we're declaring a
1607 /// template) or may have no template parameters (if we're declaring a
1608 /// template specialization), or may be NULL (if what we're declaring isn't
1609 /// itself a template).
1610 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
1611 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
1612 TemplateIdAnnotation *TemplateId,
1613 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
1614 bool &IsExplicitSpecialization, bool &Invalid) {
1615 IsExplicitSpecialization = false;
1618 // The sequence of nested types to which we will match up the template
1619 // parameter lists. We first build this list by starting with the type named
1620 // by the nested-name-specifier and walking out until we run out of types.
1621 SmallVector<QualType, 4> NestedTypes;
1623 if (SS.getScopeRep()) {
1624 if (CXXRecordDecl *Record
1625 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1626 T = Context.getTypeDeclType(Record);
1628 T = QualType(SS.getScopeRep()->getAsType(), 0);
1631 // If we found an explicit specialization that prevents us from needing
1632 // 'template<>' headers, this will be set to the location of that
1633 // explicit specialization.
1634 SourceLocation ExplicitSpecLoc;
1636 while (!T.isNull()) {
1637 NestedTypes.push_back(T);
1639 // Retrieve the parent of a record type.
1640 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1641 // If this type is an explicit specialization, we're done.
1642 if (ClassTemplateSpecializationDecl *Spec
1643 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1644 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1645 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1646 ExplicitSpecLoc = Spec->getLocation();
1649 } else if (Record->getTemplateSpecializationKind()
1650 == TSK_ExplicitSpecialization) {
1651 ExplicitSpecLoc = Record->getLocation();
1655 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1656 T = Context.getTypeDeclType(Parent);
1662 if (const TemplateSpecializationType *TST
1663 = T->getAs<TemplateSpecializationType>()) {
1664 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1665 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1666 T = Context.getTypeDeclType(Parent);
1673 // Look one step prior in a dependent template specialization type.
1674 if (const DependentTemplateSpecializationType *DependentTST
1675 = T->getAs<DependentTemplateSpecializationType>()) {
1676 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1677 T = QualType(NNS->getAsType(), 0);
1683 // Look one step prior in a dependent name type.
1684 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1685 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1686 T = QualType(NNS->getAsType(), 0);
1692 // Retrieve the parent of an enumeration type.
1693 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1694 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1696 EnumDecl *Enum = EnumT->getDecl();
1698 // Get to the parent type.
1699 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1700 T = Context.getTypeDeclType(Parent);
1708 // Reverse the nested types list, since we want to traverse from the outermost
1709 // to the innermost while checking template-parameter-lists.
1710 std::reverse(NestedTypes.begin(), NestedTypes.end());
1712 // C++0x [temp.expl.spec]p17:
1713 // A member or a member template may be nested within many
1714 // enclosing class templates. In an explicit specialization for
1715 // such a member, the member declaration shall be preceded by a
1716 // template<> for each enclosing class template that is
1717 // explicitly specialized.
1718 bool SawNonEmptyTemplateParameterList = false;
1720 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
1721 if (SawNonEmptyTemplateParameterList) {
1722 Diag(DeclLoc, diag::err_specialize_member_of_template)
1723 << !Recovery << Range;
1725 IsExplicitSpecialization = false;
1732 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
1733 // Check that we can have an explicit specialization here.
1734 if (CheckExplicitSpecialization(Range, true))
1737 // We don't have a template header, but we should.
1738 SourceLocation ExpectedTemplateLoc;
1739 if (!ParamLists.empty())
1740 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1742 ExpectedTemplateLoc = DeclStartLoc;
1744 Diag(DeclLoc, diag::err_template_spec_needs_header)
1746 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1750 unsigned ParamIdx = 0;
1751 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1753 T = NestedTypes[TypeIdx];
1755 // Whether we expect a 'template<>' header.
1756 bool NeedEmptyTemplateHeader = false;
1758 // Whether we expect a template header with parameters.
1759 bool NeedNonemptyTemplateHeader = false;
1761 // For a dependent type, the set of template parameters that we
1763 TemplateParameterList *ExpectedTemplateParams = nullptr;
1765 // C++0x [temp.expl.spec]p15:
1766 // A member or a member template may be nested within many enclosing
1767 // class templates. In an explicit specialization for such a member, the
1768 // member declaration shall be preceded by a template<> for each
1769 // enclosing class template that is explicitly specialized.
1770 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1771 if (ClassTemplatePartialSpecializationDecl *Partial
1772 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1773 ExpectedTemplateParams = Partial->getTemplateParameters();
1774 NeedNonemptyTemplateHeader = true;
1775 } else if (Record->isDependentType()) {
1776 if (Record->getDescribedClassTemplate()) {
1777 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1778 ->getTemplateParameters();
1779 NeedNonemptyTemplateHeader = true;
1781 } else if (ClassTemplateSpecializationDecl *Spec
1782 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1783 // C++0x [temp.expl.spec]p4:
1784 // Members of an explicitly specialized class template are defined
1785 // in the same manner as members of normal classes, and not using
1786 // the template<> syntax.
1787 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1788 NeedEmptyTemplateHeader = true;
1791 } else if (Record->getTemplateSpecializationKind()) {
1792 if (Record->getTemplateSpecializationKind()
1793 != TSK_ExplicitSpecialization &&
1794 TypeIdx == NumTypes - 1)
1795 IsExplicitSpecialization = true;
1799 } else if (const TemplateSpecializationType *TST
1800 = T->getAs<TemplateSpecializationType>()) {
1801 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1802 ExpectedTemplateParams = Template->getTemplateParameters();
1803 NeedNonemptyTemplateHeader = true;
1805 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1806 // FIXME: We actually could/should check the template arguments here
1807 // against the corresponding template parameter list.
1808 NeedNonemptyTemplateHeader = false;
1811 // C++ [temp.expl.spec]p16:
1812 // In an explicit specialization declaration for a member of a class
1813 // template or a member template that ap- pears in namespace scope, the
1814 // member template and some of its enclosing class templates may remain
1815 // unspecialized, except that the declaration shall not explicitly
1816 // specialize a class member template if its en- closing class templates
1817 // are not explicitly specialized as well.
1818 if (ParamIdx < ParamLists.size()) {
1819 if (ParamLists[ParamIdx]->size() == 0) {
1820 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1824 SawNonEmptyTemplateParameterList = true;
1827 if (NeedEmptyTemplateHeader) {
1828 // If we're on the last of the types, and we need a 'template<>' header
1829 // here, then it's an explicit specialization.
1830 if (TypeIdx == NumTypes - 1)
1831 IsExplicitSpecialization = true;
1833 if (ParamIdx < ParamLists.size()) {
1834 if (ParamLists[ParamIdx]->size() > 0) {
1835 // The header has template parameters when it shouldn't. Complain.
1836 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1837 diag::err_template_param_list_matches_nontemplate)
1839 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1840 ParamLists[ParamIdx]->getRAngleLoc())
1841 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1846 // Consume this template header.
1852 if (DiagnoseMissingExplicitSpecialization(
1853 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
1859 if (NeedNonemptyTemplateHeader) {
1860 // In friend declarations we can have template-ids which don't
1861 // depend on the corresponding template parameter lists. But
1862 // assume that empty parameter lists are supposed to match this
1864 if (IsFriend && T->isDependentType()) {
1865 if (ParamIdx < ParamLists.size() &&
1866 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1867 ExpectedTemplateParams = nullptr;
1872 if (ParamIdx < ParamLists.size()) {
1873 // Check the template parameter list, if we can.
1874 if (ExpectedTemplateParams &&
1875 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1876 ExpectedTemplateParams,
1877 true, TPL_TemplateMatch))
1881 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
1882 TPC_ClassTemplateMember))
1889 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1891 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1897 // If there were at least as many template-ids as there were template
1898 // parameter lists, then there are no template parameter lists remaining for
1899 // the declaration itself.
1900 if (ParamIdx >= ParamLists.size()) {
1901 if (TemplateId && !IsFriend) {
1902 // We don't have a template header for the declaration itself, but we
1904 IsExplicitSpecialization = true;
1905 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
1906 TemplateId->RAngleLoc));
1908 // Fabricate an empty template parameter list for the invented header.
1909 return TemplateParameterList::Create(Context, SourceLocation(),
1910 SourceLocation(), nullptr, 0,
1917 // If there were too many template parameter lists, complain about that now.
1918 if (ParamIdx < ParamLists.size() - 1) {
1919 bool HasAnyExplicitSpecHeader = false;
1920 bool AllExplicitSpecHeaders = true;
1921 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
1922 if (ParamLists[I]->size() == 0)
1923 HasAnyExplicitSpecHeader = true;
1925 AllExplicitSpecHeaders = false;
1928 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1929 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
1930 : diag::err_template_spec_extra_headers)
1931 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1932 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
1934 // If there was a specialization somewhere, such that 'template<>' is
1935 // not required, and there were any 'template<>' headers, note where the
1936 // specialization occurred.
1937 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1938 Diag(ExplicitSpecLoc,
1939 diag::note_explicit_template_spec_does_not_need_header)
1940 << NestedTypes.back();
1942 // We have a template parameter list with no corresponding scope, which
1943 // means that the resulting template declaration can't be instantiated
1944 // properly (we'll end up with dependent nodes when we shouldn't).
1945 if (!AllExplicitSpecHeaders)
1949 // C++ [temp.expl.spec]p16:
1950 // In an explicit specialization declaration for a member of a class
1951 // template or a member template that ap- pears in namespace scope, the
1952 // member template and some of its enclosing class templates may remain
1953 // unspecialized, except that the declaration shall not explicitly
1954 // specialize a class member template if its en- closing class templates
1955 // are not explicitly specialized as well.
1956 if (ParamLists.back()->size() == 0 &&
1957 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
1961 // Return the last template parameter list, which corresponds to the
1962 // entity being declared.
1963 return ParamLists.back();
1966 void Sema::NoteAllFoundTemplates(TemplateName Name) {
1967 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1968 Diag(Template->getLocation(), diag::note_template_declared_here)
1969 << (isa<FunctionTemplateDecl>(Template)
1971 : isa<ClassTemplateDecl>(Template)
1973 : isa<VarTemplateDecl>(Template)
1975 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
1976 << Template->getDeclName();
1980 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1981 for (OverloadedTemplateStorage::iterator I = OST->begin(),
1984 Diag((*I)->getLocation(), diag::note_template_declared_here)
1985 << 0 << (*I)->getDeclName();
1991 QualType Sema::CheckTemplateIdType(TemplateName Name,
1992 SourceLocation TemplateLoc,
1993 TemplateArgumentListInfo &TemplateArgs) {
1994 DependentTemplateName *DTN
1995 = Name.getUnderlying().getAsDependentTemplateName();
1996 if (DTN && DTN->isIdentifier())
1997 // When building a template-id where the template-name is dependent,
1998 // assume the template is a type template. Either our assumption is
1999 // correct, or the code is ill-formed and will be diagnosed when the
2000 // dependent name is substituted.
2001 return Context.getDependentTemplateSpecializationType(ETK_None,
2002 DTN->getQualifier(),
2003 DTN->getIdentifier(),
2006 TemplateDecl *Template = Name.getAsTemplateDecl();
2007 if (!Template || isa<FunctionTemplateDecl>(Template) ||
2008 isa<VarTemplateDecl>(Template)) {
2009 // We might have a substituted template template parameter pack. If so,
2010 // build a template specialization type for it.
2011 if (Name.getAsSubstTemplateTemplateParmPack())
2012 return Context.getTemplateSpecializationType(Name, TemplateArgs);
2014 Diag(TemplateLoc, diag::err_template_id_not_a_type)
2016 NoteAllFoundTemplates(Name);
2020 // Check that the template argument list is well-formed for this
2022 SmallVector<TemplateArgument, 4> Converted;
2023 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
2029 bool InstantiationDependent = false;
2030 if (TypeAliasTemplateDecl *AliasTemplate =
2031 dyn_cast<TypeAliasTemplateDecl>(Template)) {
2032 // Find the canonical type for this type alias template specialization.
2033 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
2034 if (Pattern->isInvalidDecl())
2037 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2038 Converted.data(), Converted.size());
2040 // Only substitute for the innermost template argument list.
2041 MultiLevelTemplateArgumentList TemplateArgLists;
2042 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
2043 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
2044 for (unsigned I = 0; I < Depth; ++I)
2045 TemplateArgLists.addOuterTemplateArguments(None);
2047 LocalInstantiationScope Scope(*this);
2048 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
2049 if (Inst.isInvalid())
2052 CanonType = SubstType(Pattern->getUnderlyingType(),
2053 TemplateArgLists, AliasTemplate->getLocation(),
2054 AliasTemplate->getDeclName());
2055 if (CanonType.isNull())
2057 } else if (Name.isDependent() ||
2058 TemplateSpecializationType::anyDependentTemplateArguments(
2059 TemplateArgs, InstantiationDependent)) {
2060 // This class template specialization is a dependent
2061 // type. Therefore, its canonical type is another class template
2062 // specialization type that contains all of the converted
2063 // arguments in canonical form. This ensures that, e.g., A<T> and
2064 // A<T, T> have identical types when A is declared as:
2066 // template<typename T, typename U = T> struct A;
2067 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
2068 CanonType = Context.getTemplateSpecializationType(CanonName,
2072 // FIXME: CanonType is not actually the canonical type, and unfortunately
2073 // it is a TemplateSpecializationType that we will never use again.
2074 // In the future, we need to teach getTemplateSpecializationType to only
2075 // build the canonical type and return that to us.
2076 CanonType = Context.getCanonicalType(CanonType);
2078 // This might work out to be a current instantiation, in which
2079 // case the canonical type needs to be the InjectedClassNameType.
2081 // TODO: in theory this could be a simple hashtable lookup; most
2082 // changes to CurContext don't change the set of current
2084 if (isa<ClassTemplateDecl>(Template)) {
2085 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
2086 // If we get out to a namespace, we're done.
2087 if (Ctx->isFileContext()) break;
2089 // If this isn't a record, keep looking.
2090 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
2091 if (!Record) continue;
2093 // Look for one of the two cases with InjectedClassNameTypes
2094 // and check whether it's the same template.
2095 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
2096 !Record->getDescribedClassTemplate())
2099 // Fetch the injected class name type and check whether its
2100 // injected type is equal to the type we just built.
2101 QualType ICNT = Context.getTypeDeclType(Record);
2102 QualType Injected = cast<InjectedClassNameType>(ICNT)
2103 ->getInjectedSpecializationType();
2105 if (CanonType != Injected->getCanonicalTypeInternal())
2108 // If so, the canonical type of this TST is the injected
2109 // class name type of the record we just found.
2110 assert(ICNT.isCanonical());
2115 } else if (ClassTemplateDecl *ClassTemplate
2116 = dyn_cast<ClassTemplateDecl>(Template)) {
2117 // Find the class template specialization declaration that
2118 // corresponds to these arguments.
2119 void *InsertPos = nullptr;
2120 ClassTemplateSpecializationDecl *Decl
2121 = ClassTemplate->findSpecialization(Converted, InsertPos);
2123 // This is the first time we have referenced this class template
2124 // specialization. Create the canonical declaration and add it to
2125 // the set of specializations.
2126 Decl = ClassTemplateSpecializationDecl::Create(Context,
2127 ClassTemplate->getTemplatedDecl()->getTagKind(),
2128 ClassTemplate->getDeclContext(),
2129 ClassTemplate->getTemplatedDecl()->getLocStart(),
2130 ClassTemplate->getLocation(),
2133 Converted.size(), nullptr);
2134 ClassTemplate->AddSpecialization(Decl, InsertPos);
2135 if (ClassTemplate->isOutOfLine())
2136 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
2139 // Diagnose uses of this specialization.
2140 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
2142 CanonType = Context.getTypeDeclType(Decl);
2143 assert(isa<RecordType>(CanonType) &&
2144 "type of non-dependent specialization is not a RecordType");
2147 // Build the fully-sugared type for this class template
2148 // specialization, which refers back to the class template
2149 // specialization we created or found.
2150 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2154 Sema::ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
2155 TemplateTy TemplateD, SourceLocation TemplateLoc,
2156 SourceLocation LAngleLoc,
2157 ASTTemplateArgsPtr TemplateArgsIn,
2158 SourceLocation RAngleLoc,
2159 bool IsCtorOrDtorName) {
2163 TemplateName Template = TemplateD.get();
2165 // Translate the parser's template argument list in our AST format.
2166 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2167 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2169 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2171 = Context.getDependentTemplateSpecializationType(ETK_None,
2172 DTN->getQualifier(),
2173 DTN->getIdentifier(),
2175 // Build type-source information.
2177 DependentTemplateSpecializationTypeLoc SpecTL
2178 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2179 SpecTL.setElaboratedKeywordLoc(SourceLocation());
2180 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2181 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2182 SpecTL.setTemplateNameLoc(TemplateLoc);
2183 SpecTL.setLAngleLoc(LAngleLoc);
2184 SpecTL.setRAngleLoc(RAngleLoc);
2185 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2186 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2187 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2190 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2192 if (Result.isNull())
2195 // Build type-source information.
2197 TemplateSpecializationTypeLoc SpecTL
2198 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2199 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2200 SpecTL.setTemplateNameLoc(TemplateLoc);
2201 SpecTL.setLAngleLoc(LAngleLoc);
2202 SpecTL.setRAngleLoc(RAngleLoc);
2203 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2204 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2206 // NOTE: avoid constructing an ElaboratedTypeLoc if this is a
2207 // constructor or destructor name (in such a case, the scope specifier
2208 // will be attached to the enclosing Decl or Expr node).
2209 if (SS.isNotEmpty() && !IsCtorOrDtorName) {
2210 // Create an elaborated-type-specifier containing the nested-name-specifier.
2211 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2212 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2213 ElabTL.setElaboratedKeywordLoc(SourceLocation());
2214 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2217 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2220 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
2221 TypeSpecifierType TagSpec,
2222 SourceLocation TagLoc,
2224 SourceLocation TemplateKWLoc,
2225 TemplateTy TemplateD,
2226 SourceLocation TemplateLoc,
2227 SourceLocation LAngleLoc,
2228 ASTTemplateArgsPtr TemplateArgsIn,
2229 SourceLocation RAngleLoc) {
2230 TemplateName Template = TemplateD.get();
2232 // Translate the parser's template argument list in our AST format.
2233 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2234 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2236 // Determine the tag kind
2237 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
2238 ElaboratedTypeKeyword Keyword
2239 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
2241 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2242 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2243 DTN->getQualifier(),
2244 DTN->getIdentifier(),
2247 // Build type-source information.
2249 DependentTemplateSpecializationTypeLoc SpecTL
2250 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2251 SpecTL.setElaboratedKeywordLoc(TagLoc);
2252 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2253 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2254 SpecTL.setTemplateNameLoc(TemplateLoc);
2255 SpecTL.setLAngleLoc(LAngleLoc);
2256 SpecTL.setRAngleLoc(RAngleLoc);
2257 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2258 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2259 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2262 if (TypeAliasTemplateDecl *TAT =
2263 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2264 // C++0x [dcl.type.elab]p2:
2265 // If the identifier resolves to a typedef-name or the simple-template-id
2266 // resolves to an alias template specialization, the
2267 // elaborated-type-specifier is ill-formed.
2268 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2269 Diag(TAT->getLocation(), diag::note_declared_at);
2272 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2273 if (Result.isNull())
2274 return TypeResult(true);
2276 // Check the tag kind
2277 if (const RecordType *RT = Result->getAs<RecordType>()) {
2278 RecordDecl *D = RT->getDecl();
2280 IdentifierInfo *Id = D->getIdentifier();
2281 assert(Id && "templated class must have an identifier");
2283 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2285 Diag(TagLoc, diag::err_use_with_wrong_tag)
2287 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
2288 Diag(D->getLocation(), diag::note_previous_use);
2292 // Provide source-location information for the template specialization.
2294 TemplateSpecializationTypeLoc SpecTL
2295 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2296 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
2297 SpecTL.setTemplateNameLoc(TemplateLoc);
2298 SpecTL.setLAngleLoc(LAngleLoc);
2299 SpecTL.setRAngleLoc(RAngleLoc);
2300 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2301 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2303 // Construct an elaborated type containing the nested-name-specifier (if any)
2305 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2306 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2307 ElabTL.setElaboratedKeywordLoc(TagLoc);
2308 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2309 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2312 static bool CheckTemplatePartialSpecializationArgs(
2313 Sema &S, SourceLocation NameLoc, TemplateParameterList *TemplateParams,
2314 unsigned ExplicitArgs, SmallVectorImpl<TemplateArgument> &TemplateArgs);
2316 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
2317 NamedDecl *PrevDecl,
2319 bool IsPartialSpecialization);
2321 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
2323 static bool isTemplateArgumentTemplateParameter(
2324 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
2325 switch (Arg.getKind()) {
2326 case TemplateArgument::Null:
2327 case TemplateArgument::NullPtr:
2328 case TemplateArgument::Integral:
2329 case TemplateArgument::Declaration:
2330 case TemplateArgument::Pack:
2331 case TemplateArgument::TemplateExpansion:
2334 case TemplateArgument::Type: {
2335 QualType Type = Arg.getAsType();
2336 const TemplateTypeParmType *TPT =
2337 Arg.getAsType()->getAs<TemplateTypeParmType>();
2338 return TPT && !Type.hasQualifiers() &&
2339 TPT->getDepth() == Depth && TPT->getIndex() == Index;
2342 case TemplateArgument::Expression: {
2343 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
2344 if (!DRE || !DRE->getDecl())
2346 const NonTypeTemplateParmDecl *NTTP =
2347 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
2348 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
2351 case TemplateArgument::Template:
2352 const TemplateTemplateParmDecl *TTP =
2353 dyn_cast_or_null<TemplateTemplateParmDecl>(
2354 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
2355 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
2357 llvm_unreachable("unexpected kind of template argument");
2360 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
2361 ArrayRef<TemplateArgument> Args) {
2362 if (Params->size() != Args.size())
2365 unsigned Depth = Params->getDepth();
2367 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
2368 TemplateArgument Arg = Args[I];
2370 // If the parameter is a pack expansion, the argument must be a pack
2371 // whose only element is a pack expansion.
2372 if (Params->getParam(I)->isParameterPack()) {
2373 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
2374 !Arg.pack_begin()->isPackExpansion())
2376 Arg = Arg.pack_begin()->getPackExpansionPattern();
2379 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
2386 /// Convert the parser's template argument list representation into our form.
2387 static TemplateArgumentListInfo
2388 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
2389 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
2390 TemplateId.RAngleLoc);
2391 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
2392 TemplateId.NumArgs);
2393 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
2394 return TemplateArgs;
2397 DeclResult Sema::ActOnVarTemplateSpecialization(
2398 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
2399 TemplateParameterList *TemplateParams, VarDecl::StorageClass SC,
2400 bool IsPartialSpecialization) {
2401 // D must be variable template id.
2402 assert(D.getName().getKind() == UnqualifiedId::IK_TemplateId &&
2403 "Variable template specialization is declared with a template it.");
2405 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
2406 TemplateArgumentListInfo TemplateArgs =
2407 makeTemplateArgumentListInfo(*this, *TemplateId);
2408 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
2409 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
2410 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
2412 TemplateName Name = TemplateId->Template.get();
2414 // The template-id must name a variable template.
2415 VarTemplateDecl *VarTemplate =
2416 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
2418 NamedDecl *FnTemplate;
2419 if (auto *OTS = Name.getAsOverloadedTemplate())
2420 FnTemplate = *OTS->begin();
2422 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
2424 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
2425 << FnTemplate->getDeclName();
2426 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
2427 << IsPartialSpecialization;
2430 // Check for unexpanded parameter packs in any of the template arguments.
2431 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2432 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
2433 UPPC_PartialSpecialization))
2436 // Check that the template argument list is well-formed for this
2438 SmallVector<TemplateArgument, 4> Converted;
2439 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
2443 // Check that the type of this variable template specialization
2444 // matches the expected type.
2445 TypeSourceInfo *ExpectedDI;
2447 // Do substitution on the type of the declaration
2448 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2449 Converted.data(), Converted.size());
2450 InstantiatingTemplate Inst(*this, TemplateKWLoc, VarTemplate);
2451 if (Inst.isInvalid())
2453 VarDecl *Templated = VarTemplate->getTemplatedDecl();
2455 SubstType(Templated->getTypeSourceInfo(),
2456 MultiLevelTemplateArgumentList(TemplateArgList),
2457 Templated->getTypeSpecStartLoc(), Templated->getDeclName());
2462 // Find the variable template (partial) specialization declaration that
2463 // corresponds to these arguments.
2464 if (IsPartialSpecialization) {
2465 if (CheckTemplatePartialSpecializationArgs(
2466 *this, TemplateNameLoc, VarTemplate->getTemplateParameters(),
2467 TemplateArgs.size(), Converted))
2470 bool InstantiationDependent;
2471 if (!Name.isDependent() &&
2472 !TemplateSpecializationType::anyDependentTemplateArguments(
2473 TemplateArgs.getArgumentArray(), TemplateArgs.size(),
2474 InstantiationDependent)) {
2475 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
2476 << VarTemplate->getDeclName();
2477 IsPartialSpecialization = false;
2480 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
2482 // C++ [temp.class.spec]p9b3:
2484 // -- The argument list of the specialization shall not be identical
2485 // to the implicit argument list of the primary template.
2486 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
2487 << /*variable template*/ 1
2488 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
2489 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
2490 // FIXME: Recover from this by treating the declaration as a redeclaration
2491 // of the primary template.
2496 void *InsertPos = nullptr;
2497 VarTemplateSpecializationDecl *PrevDecl = nullptr;
2499 if (IsPartialSpecialization)
2500 // FIXME: Template parameter list matters too
2501 PrevDecl = VarTemplate->findPartialSpecialization(Converted, InsertPos);
2503 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
2505 VarTemplateSpecializationDecl *Specialization = nullptr;
2507 // Check whether we can declare a variable template specialization in
2508 // the current scope.
2509 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
2511 IsPartialSpecialization))
2514 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
2515 // Since the only prior variable template specialization with these
2516 // arguments was referenced but not declared, reuse that
2517 // declaration node as our own, updating its source location and
2518 // the list of outer template parameters to reflect our new declaration.
2519 Specialization = PrevDecl;
2520 Specialization->setLocation(TemplateNameLoc);
2522 } else if (IsPartialSpecialization) {
2523 // Create a new class template partial specialization declaration node.
2524 VarTemplatePartialSpecializationDecl *PrevPartial =
2525 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
2526 VarTemplatePartialSpecializationDecl *Partial =
2527 VarTemplatePartialSpecializationDecl::Create(
2528 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
2529 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
2530 Converted.data(), Converted.size(), TemplateArgs);
2533 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
2534 Specialization = Partial;
2536 // If we are providing an explicit specialization of a member variable
2537 // template specialization, make a note of that.
2538 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
2539 PrevPartial->setMemberSpecialization();
2541 // Check that all of the template parameters of the variable template
2542 // partial specialization are deducible from the template
2543 // arguments. If not, this variable template partial specialization
2544 // will never be used.
2545 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
2546 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
2547 TemplateParams->getDepth(), DeducibleParams);
2549 if (!DeducibleParams.all()) {
2550 unsigned NumNonDeducible =
2551 DeducibleParams.size() - DeducibleParams.count();
2552 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
2553 << /*variable template*/ 1 << (NumNonDeducible > 1)
2554 << SourceRange(TemplateNameLoc, RAngleLoc);
2555 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
2556 if (!DeducibleParams[I]) {
2557 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
2558 if (Param->getDeclName())
2559 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2560 << Param->getDeclName();
2562 Diag(Param->getLocation(), diag::note_partial_spec_unused_parameter)
2568 // Create a new class template specialization declaration node for
2569 // this explicit specialization or friend declaration.
2570 Specialization = VarTemplateSpecializationDecl::Create(
2571 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
2572 VarTemplate, DI->getType(), DI, SC, Converted.data(), Converted.size());
2573 Specialization->setTemplateArgsInfo(TemplateArgs);
2576 VarTemplate->AddSpecialization(Specialization, InsertPos);
2579 // C++ [temp.expl.spec]p6:
2580 // If a template, a member template or the member of a class template is
2581 // explicitly specialized then that specialization shall be declared
2582 // before the first use of that specialization that would cause an implicit
2583 // instantiation to take place, in every translation unit in which such a
2584 // use occurs; no diagnostic is required.
2585 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
2587 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
2588 // Is there any previous explicit specialization declaration?
2589 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
2596 SourceRange Range(TemplateNameLoc, RAngleLoc);
2597 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
2600 Diag(PrevDecl->getPointOfInstantiation(),
2601 diag::note_instantiation_required_here)
2602 << (PrevDecl->getTemplateSpecializationKind() !=
2603 TSK_ImplicitInstantiation);
2608 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
2609 Specialization->setLexicalDeclContext(CurContext);
2611 // Add the specialization into its lexical context, so that it can
2612 // be seen when iterating through the list of declarations in that
2613 // context. However, specializations are not found by name lookup.
2614 CurContext->addDecl(Specialization);
2616 // Note that this is an explicit specialization.
2617 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
2620 // Check that this isn't a redefinition of this specialization,
2621 // merging with previous declarations.
2622 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
2624 PrevSpec.addDecl(PrevDecl);
2625 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
2626 } else if (Specialization->isStaticDataMember() &&
2627 Specialization->isOutOfLine()) {
2628 Specialization->setAccess(VarTemplate->getAccess());
2631 // Link instantiations of static data members back to the template from
2632 // which they were instantiated.
2633 if (Specialization->isStaticDataMember())
2634 Specialization->setInstantiationOfStaticDataMember(
2635 VarTemplate->getTemplatedDecl(),
2636 Specialization->getSpecializationKind());
2638 return Specialization;
2642 /// \brief A partial specialization whose template arguments have matched
2643 /// a given template-id.
2644 struct PartialSpecMatchResult {
2645 VarTemplatePartialSpecializationDecl *Partial;
2646 TemplateArgumentList *Args;
2651 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
2652 SourceLocation TemplateNameLoc,
2653 const TemplateArgumentListInfo &TemplateArgs) {
2654 assert(Template && "A variable template id without template?");
2656 // Check that the template argument list is well-formed for this template.
2657 SmallVector<TemplateArgument, 4> Converted;
2658 if (CheckTemplateArgumentList(
2659 Template, TemplateNameLoc,
2660 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
2664 // Find the variable template specialization declaration that
2665 // corresponds to these arguments.
2666 void *InsertPos = nullptr;
2667 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
2668 Converted, InsertPos))
2669 // If we already have a variable template specialization, return it.
2672 // This is the first time we have referenced this variable template
2673 // specialization. Create the canonical declaration and add it to
2674 // the set of specializations, based on the closest partial specialization
2675 // that it represents. That is,
2676 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
2677 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
2678 Converted.data(), Converted.size());
2679 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
2680 bool AmbiguousPartialSpec = false;
2681 typedef PartialSpecMatchResult MatchResult;
2682 SmallVector<MatchResult, 4> Matched;
2683 SourceLocation PointOfInstantiation = TemplateNameLoc;
2684 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2686 // 1. Attempt to find the closest partial specialization that this
2687 // specializes, if any.
2688 // If any of the template arguments is dependent, then this is probably
2689 // a placeholder for an incomplete declarative context; which must be
2690 // complete by instantiation time. Thus, do not search through the partial
2691 // specializations yet.
2692 // TODO: Unify with InstantiateClassTemplateSpecialization()?
2693 // Perhaps better after unification of DeduceTemplateArguments() and
2694 // getMoreSpecializedPartialSpecialization().
2695 bool InstantiationDependent = false;
2696 if (!TemplateSpecializationType::anyDependentTemplateArguments(
2697 TemplateArgs, InstantiationDependent)) {
2699 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2700 Template->getPartialSpecializations(PartialSpecs);
2702 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2703 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2704 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2706 if (TemplateDeductionResult Result =
2707 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
2708 // Store the failed-deduction information for use in diagnostics, later.
2709 // TODO: Actually use the failed-deduction info?
2710 FailedCandidates.addCandidate()
2711 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2714 Matched.push_back(PartialSpecMatchResult());
2715 Matched.back().Partial = Partial;
2716 Matched.back().Args = Info.take();
2720 if (Matched.size() >= 1) {
2721 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
2722 if (Matched.size() == 1) {
2723 // -- If exactly one matching specialization is found, the
2724 // instantiation is generated from that specialization.
2725 // We don't need to do anything for this.
2727 // -- If more than one matching specialization is found, the
2728 // partial order rules (14.5.4.2) are used to determine
2729 // whether one of the specializations is more specialized
2730 // than the others. If none of the specializations is more
2731 // specialized than all of the other matching
2732 // specializations, then the use of the variable template is
2733 // ambiguous and the program is ill-formed.
2734 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
2735 PEnd = Matched.end();
2737 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2738 PointOfInstantiation) ==
2743 // Determine if the best partial specialization is more specialized than
2745 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2746 PEnd = Matched.end();
2748 if (P != Best && getMoreSpecializedPartialSpecialization(
2749 P->Partial, Best->Partial,
2750 PointOfInstantiation) != Best->Partial) {
2751 AmbiguousPartialSpec = true;
2757 // Instantiate using the best variable template partial specialization.
2758 InstantiationPattern = Best->Partial;
2759 InstantiationArgs = Best->Args;
2761 // -- If no match is found, the instantiation is generated
2762 // from the primary template.
2763 // InstantiationPattern = Template->getTemplatedDecl();
2767 // 2. Create the canonical declaration.
2768 // Note that we do not instantiate the variable just yet, since
2769 // instantiation is handled in DoMarkVarDeclReferenced().
2770 // FIXME: LateAttrs et al.?
2771 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
2772 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
2773 Converted, TemplateNameLoc, InsertPos /*, LateAttrs, StartingScope*/);
2777 if (AmbiguousPartialSpec) {
2778 // Partial ordering did not produce a clear winner. Complain.
2779 Decl->setInvalidDecl();
2780 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2783 // Print the matching partial specializations.
2784 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2785 PEnd = Matched.end();
2787 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2788 << getTemplateArgumentBindingsText(
2789 P->Partial->getTemplateParameters(), *P->Args);
2793 if (VarTemplatePartialSpecializationDecl *D =
2794 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
2795 Decl->setInstantiationOf(D, InstantiationArgs);
2797 assert(Decl && "No variable template specialization?");
2802 Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
2803 const DeclarationNameInfo &NameInfo,
2804 VarTemplateDecl *Template, SourceLocation TemplateLoc,
2805 const TemplateArgumentListInfo *TemplateArgs) {
2807 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
2809 if (Decl.isInvalid())
2812 VarDecl *Var = cast<VarDecl>(Decl.get());
2813 if (!Var->getTemplateSpecializationKind())
2814 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
2817 // Build an ordinary singleton decl ref.
2818 return BuildDeclarationNameExpr(SS, NameInfo, Var,
2819 /*FoundD=*/nullptr, TemplateArgs);
2822 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
2823 SourceLocation TemplateKWLoc,
2826 const TemplateArgumentListInfo *TemplateArgs) {
2827 // FIXME: Can we do any checking at this point? I guess we could check the
2828 // template arguments that we have against the template name, if the template
2829 // name refers to a single template. That's not a terribly common case,
2831 // foo<int> could identify a single function unambiguously
2832 // This approach does NOT work, since f<int>(1);
2833 // gets resolved prior to resorting to overload resolution
2834 // i.e., template<class T> void f(double);
2835 // vs template<class T, class U> void f(U);
2837 // These should be filtered out by our callers.
2838 assert(!R.empty() && "empty lookup results when building templateid");
2839 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2841 // In C++1y, check variable template ids.
2842 bool InstantiationDependent;
2843 if (R.getAsSingle<VarTemplateDecl>() &&
2844 !TemplateSpecializationType::anyDependentTemplateArguments(
2845 *TemplateArgs, InstantiationDependent)) {
2846 return CheckVarTemplateId(SS, R.getLookupNameInfo(),
2847 R.getAsSingle<VarTemplateDecl>(),
2848 TemplateKWLoc, TemplateArgs);
2851 // We don't want lookup warnings at this point.
2852 R.suppressDiagnostics();
2854 UnresolvedLookupExpr *ULE
2855 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2856 SS.getWithLocInContext(Context),
2858 R.getLookupNameInfo(),
2859 RequiresADL, TemplateArgs,
2860 R.begin(), R.end());
2865 // We actually only call this from template instantiation.
2867 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
2868 SourceLocation TemplateKWLoc,
2869 const DeclarationNameInfo &NameInfo,
2870 const TemplateArgumentListInfo *TemplateArgs) {
2872 assert(TemplateArgs || TemplateKWLoc.isValid());
2874 if (!(DC = computeDeclContext(SS, false)) ||
2875 DC->isDependentContext() ||
2876 RequireCompleteDeclContext(SS, DC))
2877 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
2879 bool MemberOfUnknownSpecialization;
2880 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2881 LookupTemplateName(R, (Scope*)nullptr, SS, QualType(), /*Entering*/ false,
2882 MemberOfUnknownSpecialization);
2884 if (R.isAmbiguous())
2888 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2889 << NameInfo.getName() << SS.getRange();
2893 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
2894 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2896 << NameInfo.getName().getAsString() << SS.getRange();
2897 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2901 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
2904 /// \brief Form a dependent template name.
2906 /// This action forms a dependent template name given the template
2907 /// name and its (presumably dependent) scope specifier. For
2908 /// example, given "MetaFun::template apply", the scope specifier \p
2909 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2910 /// of the "template" keyword, and "apply" is the \p Name.
2911 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
2913 SourceLocation TemplateKWLoc,
2914 UnqualifiedId &Name,
2915 ParsedType ObjectType,
2916 bool EnteringContext,
2917 TemplateTy &Result) {
2918 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
2920 getLangOpts().CPlusPlus11 ?
2921 diag::warn_cxx98_compat_template_outside_of_template :
2922 diag::ext_template_outside_of_template)
2923 << FixItHint::CreateRemoval(TemplateKWLoc);
2925 DeclContext *LookupCtx = nullptr;
2927 LookupCtx = computeDeclContext(SS, EnteringContext);
2928 if (!LookupCtx && ObjectType)
2929 LookupCtx = computeDeclContext(ObjectType.get());
2931 // C++0x [temp.names]p5:
2932 // If a name prefixed by the keyword template is not the name of
2933 // a template, the program is ill-formed. [Note: the keyword
2934 // template may not be applied to non-template members of class
2935 // templates. -end note ] [ Note: as is the case with the
2936 // typename prefix, the template prefix is allowed in cases
2937 // where it is not strictly necessary; i.e., when the
2938 // nested-name-specifier or the expression on the left of the ->
2939 // or . is not dependent on a template-parameter, or the use
2940 // does not appear in the scope of a template. -end note]
2942 // Note: C++03 was more strict here, because it banned the use of
2943 // the "template" keyword prior to a template-name that was not a
2944 // dependent name. C++ DR468 relaxed this requirement (the
2945 // "template" keyword is now permitted). We follow the C++0x
2946 // rules, even in C++03 mode with a warning, retroactively applying the DR.
2947 bool MemberOfUnknownSpecialization;
2948 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
2949 ObjectType, EnteringContext, Result,
2950 MemberOfUnknownSpecialization);
2951 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2952 isa<CXXRecordDecl>(LookupCtx) &&
2953 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2954 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
2955 // This is a dependent template. Handle it below.
2956 } else if (TNK == TNK_Non_template) {
2957 Diag(Name.getLocStart(),
2958 diag::err_template_kw_refers_to_non_template)
2959 << GetNameFromUnqualifiedId(Name).getName()
2960 << Name.getSourceRange()
2962 return TNK_Non_template;
2964 // We found something; return it.
2969 NestedNameSpecifier *Qualifier = SS.getScopeRep();
2971 switch (Name.getKind()) {
2972 case UnqualifiedId::IK_Identifier:
2973 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2975 return TNK_Dependent_template_name;
2977 case UnqualifiedId::IK_OperatorFunctionId:
2978 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2979 Name.OperatorFunctionId.Operator));
2980 return TNK_Function_template;
2982 case UnqualifiedId::IK_LiteralOperatorId:
2983 llvm_unreachable("literal operator id cannot have a dependent scope");
2989 Diag(Name.getLocStart(),
2990 diag::err_template_kw_refers_to_non_template)
2991 << GetNameFromUnqualifiedId(Name).getName()
2992 << Name.getSourceRange()
2994 return TNK_Non_template;
2997 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
2998 TemplateArgumentLoc &AL,
2999 SmallVectorImpl<TemplateArgument> &Converted) {
3000 const TemplateArgument &Arg = AL.getArgument();
3002 TypeSourceInfo *TSI = nullptr;
3004 // Check template type parameter.
3005 switch(Arg.getKind()) {
3006 case TemplateArgument::Type:
3007 // C++ [temp.arg.type]p1:
3008 // A template-argument for a template-parameter which is a
3009 // type shall be a type-id.
3010 ArgType = Arg.getAsType();
3011 TSI = AL.getTypeSourceInfo();
3013 case TemplateArgument::Template: {
3014 // We have a template type parameter but the template argument
3015 // is a template without any arguments.
3016 SourceRange SR = AL.getSourceRange();
3017 TemplateName Name = Arg.getAsTemplate();
3018 Diag(SR.getBegin(), diag::err_template_missing_args)
3020 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
3021 Diag(Decl->getLocation(), diag::note_template_decl_here);
3025 case TemplateArgument::Expression: {
3026 // We have a template type parameter but the template argument is an
3027 // expression; see if maybe it is missing the "typename" keyword.
3029 DeclarationNameInfo NameInfo;
3031 if (DeclRefExpr *ArgExpr = dyn_cast<DeclRefExpr>(Arg.getAsExpr())) {
3032 SS.Adopt(ArgExpr->getQualifierLoc());
3033 NameInfo = ArgExpr->getNameInfo();
3034 } else if (DependentScopeDeclRefExpr *ArgExpr =
3035 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
3036 SS.Adopt(ArgExpr->getQualifierLoc());
3037 NameInfo = ArgExpr->getNameInfo();
3038 } else if (CXXDependentScopeMemberExpr *ArgExpr =
3039 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
3040 if (ArgExpr->isImplicitAccess()) {
3041 SS.Adopt(ArgExpr->getQualifierLoc());
3042 NameInfo = ArgExpr->getMemberNameInfo();
3046 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
3047 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
3048 LookupParsedName(Result, CurScope, &SS);
3050 if (Result.getAsSingle<TypeDecl>() ||
3051 Result.getResultKind() ==
3052 LookupResult::NotFoundInCurrentInstantiation) {
3053 // Suggest that the user add 'typename' before the NNS.
3054 SourceLocation Loc = AL.getSourceRange().getBegin();
3055 Diag(Loc, getLangOpts().MSVCCompat
3056 ? diag::ext_ms_template_type_arg_missing_typename
3057 : diag::err_template_arg_must_be_type_suggest)
3058 << FixItHint::CreateInsertion(Loc, "typename ");
3059 Diag(Param->getLocation(), diag::note_template_param_here);
3061 // Recover by synthesizing a type using the location information that we
3064 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
3066 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
3067 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
3068 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3069 TL.setNameLoc(NameInfo.getLoc());
3070 TSI = TLB.getTypeSourceInfo(Context, ArgType);
3072 // Overwrite our input TemplateArgumentLoc so that we can recover
3074 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
3075 TemplateArgumentLocInfo(TSI));
3083 // We have a template type parameter but the template argument
3085 SourceRange SR = AL.getSourceRange();
3086 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
3087 Diag(Param->getLocation(), diag::note_template_param_here);
3093 if (CheckTemplateArgument(Param, TSI))
3096 // Add the converted template type argument.
3097 ArgType = Context.getCanonicalType(ArgType);
3100 // If an explicitly-specified template argument type is a lifetime type
3101 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
3102 if (getLangOpts().ObjCAutoRefCount &&
3103 ArgType->isObjCLifetimeType() &&
3104 !ArgType.getObjCLifetime()) {
3106 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
3107 ArgType = Context.getQualifiedType(ArgType, Qs);
3110 Converted.push_back(TemplateArgument(ArgType));
3114 /// \brief Substitute template arguments into the default template argument for
3115 /// the given template type parameter.
3117 /// \param SemaRef the semantic analysis object for which we are performing
3118 /// the substitution.
3120 /// \param Template the template that we are synthesizing template arguments
3123 /// \param TemplateLoc the location of the template name that started the
3124 /// template-id we are checking.
3126 /// \param RAngleLoc the location of the right angle bracket ('>') that
3127 /// terminates the template-id.
3129 /// \param Param the template template parameter whose default we are
3130 /// substituting into.
3132 /// \param Converted the list of template arguments provided for template
3133 /// parameters that precede \p Param in the template parameter list.
3134 /// \returns the substituted template argument, or NULL if an error occurred.
3135 static TypeSourceInfo *
3136 SubstDefaultTemplateArgument(Sema &SemaRef,
3137 TemplateDecl *Template,
3138 SourceLocation TemplateLoc,
3139 SourceLocation RAngleLoc,
3140 TemplateTypeParmDecl *Param,
3141 SmallVectorImpl<TemplateArgument> &Converted) {
3142 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
3144 // If the argument type is dependent, instantiate it now based
3145 // on the previously-computed template arguments.
3146 if (ArgType->getType()->isDependentType()) {
3147 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3148 Template, Converted,
3149 SourceRange(TemplateLoc, RAngleLoc));
3150 if (Inst.isInvalid())
3153 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3154 Converted.data(), Converted.size());
3156 // Only substitute for the innermost template argument list.
3157 MultiLevelTemplateArgumentList TemplateArgLists;
3158 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3159 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3160 TemplateArgLists.addOuterTemplateArguments(None);
3162 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3164 SemaRef.SubstType(ArgType, TemplateArgLists,
3165 Param->getDefaultArgumentLoc(), Param->getDeclName());
3171 /// \brief Substitute template arguments into the default template argument for
3172 /// the given non-type template parameter.
3174 /// \param SemaRef the semantic analysis object for which we are performing
3175 /// the substitution.
3177 /// \param Template the template that we are synthesizing template arguments
3180 /// \param TemplateLoc the location of the template name that started the
3181 /// template-id we are checking.
3183 /// \param RAngleLoc the location of the right angle bracket ('>') that
3184 /// terminates the template-id.
3186 /// \param Param the non-type template parameter whose default we are
3187 /// substituting into.
3189 /// \param Converted the list of template arguments provided for template
3190 /// parameters that precede \p Param in the template parameter list.
3192 /// \returns the substituted template argument, or NULL if an error occurred.
3194 SubstDefaultTemplateArgument(Sema &SemaRef,
3195 TemplateDecl *Template,
3196 SourceLocation TemplateLoc,
3197 SourceLocation RAngleLoc,
3198 NonTypeTemplateParmDecl *Param,
3199 SmallVectorImpl<TemplateArgument> &Converted) {
3200 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
3201 Template, Converted,
3202 SourceRange(TemplateLoc, RAngleLoc));
3203 if (Inst.isInvalid())
3206 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3207 Converted.data(), Converted.size());
3209 // Only substitute for the innermost template argument list.
3210 MultiLevelTemplateArgumentList TemplateArgLists;
3211 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3212 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3213 TemplateArgLists.addOuterTemplateArguments(None);
3215 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3216 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
3217 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
3220 /// \brief Substitute template arguments into the default template argument for
3221 /// the given template template parameter.
3223 /// \param SemaRef the semantic analysis object for which we are performing
3224 /// the substitution.
3226 /// \param Template the template that we are synthesizing template arguments
3229 /// \param TemplateLoc the location of the template name that started the
3230 /// template-id we are checking.
3232 /// \param RAngleLoc the location of the right angle bracket ('>') that
3233 /// terminates the template-id.
3235 /// \param Param the template template parameter whose default we are
3236 /// substituting into.
3238 /// \param Converted the list of template arguments provided for template
3239 /// parameters that precede \p Param in the template parameter list.
3241 /// \param QualifierLoc Will be set to the nested-name-specifier (with
3242 /// source-location information) that precedes the template name.
3244 /// \returns the substituted template argument, or NULL if an error occurred.
3246 SubstDefaultTemplateArgument(Sema &SemaRef,
3247 TemplateDecl *Template,
3248 SourceLocation TemplateLoc,
3249 SourceLocation RAngleLoc,
3250 TemplateTemplateParmDecl *Param,
3251 SmallVectorImpl<TemplateArgument> &Converted,
3252 NestedNameSpecifierLoc &QualifierLoc) {
3253 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Template, Converted,
3254 SourceRange(TemplateLoc, RAngleLoc));
3255 if (Inst.isInvalid())
3256 return TemplateName();
3258 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3259 Converted.data(), Converted.size());
3261 // Only substitute for the innermost template argument list.
3262 MultiLevelTemplateArgumentList TemplateArgLists;
3263 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
3264 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
3265 TemplateArgLists.addOuterTemplateArguments(None);
3267 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
3268 // Substitute into the nested-name-specifier first,
3269 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
3272 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
3274 return TemplateName();
3277 return SemaRef.SubstTemplateName(
3279 Param->getDefaultArgument().getArgument().getAsTemplate(),
3280 Param->getDefaultArgument().getTemplateNameLoc(),
3284 /// \brief If the given template parameter has a default template
3285 /// argument, substitute into that default template argument and
3286 /// return the corresponding template argument.
3288 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
3289 SourceLocation TemplateLoc,
3290 SourceLocation RAngleLoc,
3292 SmallVectorImpl<TemplateArgument>
3294 bool &HasDefaultArg) {
3295 HasDefaultArg = false;
3297 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
3298 if (!TypeParm->hasDefaultArgument())
3299 return TemplateArgumentLoc();
3301 HasDefaultArg = true;
3302 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
3308 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
3310 return TemplateArgumentLoc();
3313 if (NonTypeTemplateParmDecl *NonTypeParm
3314 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3315 if (!NonTypeParm->hasDefaultArgument())
3316 return TemplateArgumentLoc();
3318 HasDefaultArg = true;
3319 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
3324 if (Arg.isInvalid())
3325 return TemplateArgumentLoc();
3327 Expr *ArgE = Arg.getAs<Expr>();
3328 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
3331 TemplateTemplateParmDecl *TempTempParm
3332 = cast<TemplateTemplateParmDecl>(Param);
3333 if (!TempTempParm->hasDefaultArgument())
3334 return TemplateArgumentLoc();
3336 HasDefaultArg = true;
3337 NestedNameSpecifierLoc QualifierLoc;
3338 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
3345 return TemplateArgumentLoc();
3347 return TemplateArgumentLoc(TemplateArgument(TName),
3348 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
3349 TempTempParm->getDefaultArgument().getTemplateNameLoc());
3352 /// \brief Check that the given template argument corresponds to the given
3353 /// template parameter.
3355 /// \param Param The template parameter against which the argument will be
3358 /// \param Arg The template argument.
3360 /// \param Template The template in which the template argument resides.
3362 /// \param TemplateLoc The location of the template name for the template
3363 /// whose argument list we're matching.
3365 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
3366 /// the template argument list.
3368 /// \param ArgumentPackIndex The index into the argument pack where this
3369 /// argument will be placed. Only valid if the parameter is a parameter pack.
3371 /// \param Converted The checked, converted argument will be added to the
3372 /// end of this small vector.
3374 /// \param CTAK Describes how we arrived at this particular template argument:
3375 /// explicitly written, deduced, etc.
3377 /// \returns true on error, false otherwise.
3378 bool Sema::CheckTemplateArgument(NamedDecl *Param,
3379 TemplateArgumentLoc &Arg,
3380 NamedDecl *Template,
3381 SourceLocation TemplateLoc,
3382 SourceLocation RAngleLoc,
3383 unsigned ArgumentPackIndex,
3384 SmallVectorImpl<TemplateArgument> &Converted,
3385 CheckTemplateArgumentKind CTAK) {
3386 // Check template type parameters.
3387 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
3388 return CheckTemplateTypeArgument(TTP, Arg, Converted);
3390 // Check non-type template parameters.
3391 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3392 // Do substitution on the type of the non-type template parameter
3393 // with the template arguments we've seen thus far. But if the
3394 // template has a dependent context then we cannot substitute yet.
3395 QualType NTTPType = NTTP->getType();
3396 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
3397 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
3399 if (NTTPType->isDependentType() &&
3400 !isa<TemplateTemplateParmDecl>(Template) &&
3401 !Template->getDeclContext()->isDependentContext()) {
3402 // Do substitution on the type of the non-type template parameter.
3403 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3405 SourceRange(TemplateLoc, RAngleLoc));
3406 if (Inst.isInvalid())
3409 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3410 Converted.data(), Converted.size());
3411 NTTPType = SubstType(NTTPType,
3412 MultiLevelTemplateArgumentList(TemplateArgs),
3413 NTTP->getLocation(),
3414 NTTP->getDeclName());
3415 // If that worked, check the non-type template parameter type
3417 if (!NTTPType.isNull())
3418 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
3419 NTTP->getLocation());
3420 if (NTTPType.isNull())
3424 switch (Arg.getArgument().getKind()) {
3425 case TemplateArgument::Null:
3426 llvm_unreachable("Should never see a NULL template argument here");
3428 case TemplateArgument::Expression: {
3429 TemplateArgument Result;
3431 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
3433 if (Res.isInvalid())
3436 Converted.push_back(Result);
3440 case TemplateArgument::Declaration:
3441 case TemplateArgument::Integral:
3442 case TemplateArgument::NullPtr:
3443 // We've already checked this template argument, so just copy
3444 // it to the list of converted arguments.
3445 Converted.push_back(Arg.getArgument());
3448 case TemplateArgument::Template:
3449 case TemplateArgument::TemplateExpansion:
3450 // We were given a template template argument. It may not be ill-formed;
3452 if (DependentTemplateName *DTN
3453 = Arg.getArgument().getAsTemplateOrTemplatePattern()
3454 .getAsDependentTemplateName()) {
3455 // We have a template argument such as \c T::template X, which we
3456 // parsed as a template template argument. However, since we now
3457 // know that we need a non-type template argument, convert this
3458 // template name into an expression.
3460 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
3461 Arg.getTemplateNameLoc());
3464 SS.Adopt(Arg.getTemplateQualifierLoc());
3465 // FIXME: the template-template arg was a DependentTemplateName,
3466 // so it was provided with a template keyword. However, its source
3467 // location is not stored in the template argument structure.
3468 SourceLocation TemplateKWLoc;
3469 ExprResult E = DependentScopeDeclRefExpr::Create(
3470 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
3473 // If we parsed the template argument as a pack expansion, create a
3474 // pack expansion expression.
3475 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
3476 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
3481 TemplateArgument Result;
3482 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
3486 Converted.push_back(Result);
3490 // We have a template argument that actually does refer to a class
3491 // template, alias template, or template template parameter, and
3492 // therefore cannot be a non-type template argument.
3493 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
3494 << Arg.getSourceRange();
3496 Diag(Param->getLocation(), diag::note_template_param_here);
3499 case TemplateArgument::Type: {
3500 // We have a non-type template parameter but the template
3501 // argument is a type.
3503 // C++ [temp.arg]p2:
3504 // In a template-argument, an ambiguity between a type-id and
3505 // an expression is resolved to a type-id, regardless of the
3506 // form of the corresponding template-parameter.
3508 // We warn specifically about this case, since it can be rather
3509 // confusing for users.
3510 QualType T = Arg.getArgument().getAsType();
3511 SourceRange SR = Arg.getSourceRange();
3512 if (T->isFunctionType())
3513 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
3515 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
3516 Diag(Param->getLocation(), diag::note_template_param_here);
3520 case TemplateArgument::Pack:
3521 llvm_unreachable("Caller must expand template argument packs");
3528 // Check template template parameters.
3529 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
3531 // Substitute into the template parameter list of the template
3532 // template parameter, since previously-supplied template arguments
3533 // may appear within the template template parameter.
3535 // Set up a template instantiation context.
3536 LocalInstantiationScope Scope(*this);
3537 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
3538 TempParm, Converted,
3539 SourceRange(TemplateLoc, RAngleLoc));
3540 if (Inst.isInvalid())
3543 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
3544 Converted.data(), Converted.size());
3545 TempParm = cast_or_null<TemplateTemplateParmDecl>(
3546 SubstDecl(TempParm, CurContext,
3547 MultiLevelTemplateArgumentList(TemplateArgs)));
3552 switch (Arg.getArgument().getKind()) {
3553 case TemplateArgument::Null:
3554 llvm_unreachable("Should never see a NULL template argument here");
3556 case TemplateArgument::Template:
3557 case TemplateArgument::TemplateExpansion:
3558 if (CheckTemplateArgument(TempParm, Arg, ArgumentPackIndex))
3561 Converted.push_back(Arg.getArgument());
3564 case TemplateArgument::Expression:
3565 case TemplateArgument::Type:
3566 // We have a template template parameter but the template
3567 // argument does not refer to a template.
3568 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
3569 << getLangOpts().CPlusPlus11;
3572 case TemplateArgument::Declaration:
3573 llvm_unreachable("Declaration argument with template template parameter");
3574 case TemplateArgument::Integral:
3575 llvm_unreachable("Integral argument with template template parameter");
3576 case TemplateArgument::NullPtr:
3577 llvm_unreachable("Null pointer argument with template template parameter");
3579 case TemplateArgument::Pack:
3580 llvm_unreachable("Caller must expand template argument packs");
3586 /// \brief Diagnose an arity mismatch in the
3587 static bool diagnoseArityMismatch(Sema &S, TemplateDecl *Template,
3588 SourceLocation TemplateLoc,
3589 TemplateArgumentListInfo &TemplateArgs) {
3590 TemplateParameterList *Params = Template->getTemplateParameters();
3591 unsigned NumParams = Params->size();
3592 unsigned NumArgs = TemplateArgs.size();
3595 if (NumArgs > NumParams)
3596 Range = SourceRange(TemplateArgs[NumParams].getLocation(),
3597 TemplateArgs.getRAngleLoc());
3598 S.Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3599 << (NumArgs > NumParams)
3600 << (isa<ClassTemplateDecl>(Template)? 0 :
3601 isa<FunctionTemplateDecl>(Template)? 1 :
3602 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3603 << Template << Range;
3604 S.Diag(Template->getLocation(), diag::note_template_decl_here)
3605 << Params->getSourceRange();
3609 /// \brief Check whether the template parameter is a pack expansion, and if so,
3610 /// determine the number of parameters produced by that expansion. For instance:
3613 /// template<typename ...Ts> struct A {
3614 /// template<Ts ...NTs, template<Ts> class ...TTs, typename ...Us> struct B;
3618 /// In \c A<int,int>::B, \c NTs and \c TTs have expanded pack size 2, and \c Us
3619 /// is not a pack expansion, so returns an empty Optional.
3620 static Optional<unsigned> getExpandedPackSize(NamedDecl *Param) {
3621 if (NonTypeTemplateParmDecl *NTTP
3622 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
3623 if (NTTP->isExpandedParameterPack())
3624 return NTTP->getNumExpansionTypes();
3627 if (TemplateTemplateParmDecl *TTP
3628 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
3629 if (TTP->isExpandedParameterPack())
3630 return TTP->getNumExpansionTemplateParameters();
3636 /// \brief Check that the given template argument list is well-formed
3637 /// for specializing the given template.
3638 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
3639 SourceLocation TemplateLoc,
3640 TemplateArgumentListInfo &TemplateArgs,
3641 bool PartialTemplateArgs,
3642 SmallVectorImpl<TemplateArgument> &Converted) {
3643 TemplateParameterList *Params = Template->getTemplateParameters();
3645 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
3647 // C++ [temp.arg]p1:
3648 // [...] The type and form of each template-argument specified in
3649 // a template-id shall match the type and form specified for the
3650 // corresponding parameter declared by the template in its
3651 // template-parameter-list.
3652 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
3653 SmallVector<TemplateArgument, 2> ArgumentPack;
3654 unsigned ArgIdx = 0, NumArgs = TemplateArgs.size();
3655 LocalInstantiationScope InstScope(*this, true);
3656 for (TemplateParameterList::iterator Param = Params->begin(),
3657 ParamEnd = Params->end();
3658 Param != ParamEnd; /* increment in loop */) {
3659 // If we have an expanded parameter pack, make sure we don't have too
3661 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
3662 if (*Expansions == ArgumentPack.size()) {
3663 // We're done with this parameter pack. Pack up its arguments and add
3664 // them to the list.
3665 Converted.push_back(
3666 TemplateArgument::CreatePackCopy(Context,
3667 ArgumentPack.data(),
3668 ArgumentPack.size()));
3669 ArgumentPack.clear();
3671 // This argument is assigned to the next parameter.
3674 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
3675 // Not enough arguments for this parameter pack.
3676 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
3678 << (isa<ClassTemplateDecl>(Template)? 0 :
3679 isa<FunctionTemplateDecl>(Template)? 1 :
3680 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
3682 Diag(Template->getLocation(), diag::note_template_decl_here)
3683 << Params->getSourceRange();
3688 if (ArgIdx < NumArgs) {
3689 // Check the template argument we were given.
3690 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
3691 TemplateLoc, RAngleLoc,
3692 ArgumentPack.size(), Converted))
3695 bool PackExpansionIntoNonPack =
3696 TemplateArgs[ArgIdx].getArgument().isPackExpansion() &&
3697 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
3698 if (PackExpansionIntoNonPack && isa<TypeAliasTemplateDecl>(Template)) {
3699 // Core issue 1430: we have a pack expansion as an argument to an
3700 // alias template, and it's not part of a parameter pack. This
3701 // can't be canonicalized, so reject it now.
3702 Diag(TemplateArgs[ArgIdx].getLocation(),
3703 diag::err_alias_template_expansion_into_fixed_list)
3704 << TemplateArgs[ArgIdx].getSourceRange();
3705 Diag((*Param)->getLocation(), diag::note_template_param_here);
3709 // We're now done with this argument.
3712 if ((*Param)->isTemplateParameterPack()) {
3713 // The template parameter was a template parameter pack, so take the
3714 // deduced argument and place it on the argument pack. Note that we
3715 // stay on the same template parameter so that we can deduce more
3717 ArgumentPack.push_back(Converted.pop_back_val());
3719 // Move to the next template parameter.
3723 // If we just saw a pack expansion into a non-pack, then directly convert
3724 // the remaining arguments, because we don't know what parameters they'll
3726 if (PackExpansionIntoNonPack) {
3727 if (!ArgumentPack.empty()) {
3728 // If we were part way through filling in an expanded parameter pack,
3729 // fall back to just producing individual arguments.
3730 Converted.insert(Converted.end(),
3731 ArgumentPack.begin(), ArgumentPack.end());
3732 ArgumentPack.clear();
3735 while (ArgIdx < NumArgs) {
3736 Converted.push_back(TemplateArgs[ArgIdx].getArgument());
3746 // If we're checking a partial template argument list, we're done.
3747 if (PartialTemplateArgs) {
3748 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
3749 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3750 ArgumentPack.data(),
3751 ArgumentPack.size()));
3756 // If we have a template parameter pack with no more corresponding
3757 // arguments, just break out now and we'll fill in the argument pack below.
3758 if ((*Param)->isTemplateParameterPack()) {
3759 assert(!getExpandedPackSize(*Param) &&
3760 "Should have dealt with this already");
3762 // A non-expanded parameter pack before the end of the parameter list
3763 // only occurs for an ill-formed template parameter list, unless we've
3764 // got a partial argument list for a function template, so just bail out.
3765 if (Param + 1 != ParamEnd)
3768 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3769 ArgumentPack.data(),
3770 ArgumentPack.size()));
3771 ArgumentPack.clear();
3777 // Check whether we have a default argument.
3778 TemplateArgumentLoc Arg;
3780 // Retrieve the default template argument from the template
3781 // parameter. For each kind of template parameter, we substitute the
3782 // template arguments provided thus far and any "outer" template arguments
3783 // (when the template parameter was part of a nested template) into
3784 // the default argument.
3785 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
3786 if (!TTP->hasDefaultArgument())
3787 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3790 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
3799 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
3801 } else if (NonTypeTemplateParmDecl *NTTP
3802 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
3803 if (!NTTP->hasDefaultArgument())
3804 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3807 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
3815 Expr *Ex = E.getAs<Expr>();
3816 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
3818 TemplateTemplateParmDecl *TempParm
3819 = cast<TemplateTemplateParmDecl>(*Param);
3821 if (!TempParm->hasDefaultArgument())
3822 return diagnoseArityMismatch(*this, Template, TemplateLoc,
3825 NestedNameSpecifierLoc QualifierLoc;
3826 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
3835 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
3836 TempParm->getDefaultArgument().getTemplateNameLoc());
3839 // Introduce an instantiation record that describes where we are using
3840 // the default template argument.
3841 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
3842 SourceRange(TemplateLoc, RAngleLoc));
3843 if (Inst.isInvalid())
3846 // Check the default template argument.
3847 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
3848 RAngleLoc, 0, Converted))
3851 // Core issue 150 (assumed resolution): if this is a template template
3852 // parameter, keep track of the default template arguments from the
3853 // template definition.
3854 if (isTemplateTemplateParameter)
3855 TemplateArgs.addArgument(Arg);
3857 // Move to the next template parameter and argument.
3862 // If we're performing a partial argument substitution, allow any trailing
3863 // pack expansions; they might be empty. This can happen even if
3864 // PartialTemplateArgs is false (the list of arguments is complete but
3865 // still dependent).
3866 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
3867 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
3868 while (ArgIdx < NumArgs &&
3869 TemplateArgs[ArgIdx].getArgument().isPackExpansion())
3870 Converted.push_back(TemplateArgs[ArgIdx++].getArgument());
3873 // If we have any leftover arguments, then there were too many arguments.
3874 // Complain and fail.
3875 if (ArgIdx < NumArgs)
3876 return diagnoseArityMismatch(*this, Template, TemplateLoc, TemplateArgs);
3882 class UnnamedLocalNoLinkageFinder
3883 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
3888 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
3891 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3893 bool Visit(QualType T) {
3894 return inherited::Visit(T.getTypePtr());
3897 #define TYPE(Class, Parent) \
3898 bool Visit##Class##Type(const Class##Type *);
3899 #define ABSTRACT_TYPE(Class, Parent) \
3900 bool Visit##Class##Type(const Class##Type *) { return false; }
3901 #define NON_CANONICAL_TYPE(Class, Parent) \
3902 bool Visit##Class##Type(const Class##Type *) { return false; }
3903 #include "clang/AST/TypeNodes.def"
3905 bool VisitTagDecl(const TagDecl *Tag);
3906 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3910 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
3914 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3915 return Visit(T->getElementType());
3918 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
3919 return Visit(T->getPointeeType());
3922 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
3923 const BlockPointerType* T) {
3924 return Visit(T->getPointeeType());
3927 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
3928 const LValueReferenceType* T) {
3929 return Visit(T->getPointeeType());
3932 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
3933 const RValueReferenceType* T) {
3934 return Visit(T->getPointeeType());
3937 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
3938 const MemberPointerType* T) {
3939 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3942 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
3943 const ConstantArrayType* T) {
3944 return Visit(T->getElementType());
3947 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
3948 const IncompleteArrayType* T) {
3949 return Visit(T->getElementType());
3952 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
3953 const VariableArrayType* T) {
3954 return Visit(T->getElementType());
3957 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
3958 const DependentSizedArrayType* T) {
3959 return Visit(T->getElementType());
3962 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
3963 const DependentSizedExtVectorType* T) {
3964 return Visit(T->getElementType());
3967 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3968 return Visit(T->getElementType());
3971 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
3972 return Visit(T->getElementType());
3975 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
3976 const FunctionProtoType* T) {
3977 for (const auto &A : T->param_types()) {
3982 return Visit(T->getReturnType());
3985 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
3986 const FunctionNoProtoType* T) {
3987 return Visit(T->getReturnType());
3990 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
3991 const UnresolvedUsingType*) {
3995 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
3999 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
4000 return Visit(T->getUnderlyingType());
4003 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
4007 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
4008 const UnaryTransformType*) {
4012 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
4013 return Visit(T->getDeducedType());
4016 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
4017 return VisitTagDecl(T->getDecl());
4020 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
4021 return VisitTagDecl(T->getDecl());
4024 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
4025 const TemplateTypeParmType*) {
4029 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
4030 const SubstTemplateTypeParmPackType *) {
4034 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
4035 const TemplateSpecializationType*) {
4039 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
4040 const InjectedClassNameType* T) {
4041 return VisitTagDecl(T->getDecl());
4044 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
4045 const DependentNameType* T) {
4046 return VisitNestedNameSpecifier(T->getQualifier());
4049 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
4050 const DependentTemplateSpecializationType* T) {
4051 return VisitNestedNameSpecifier(T->getQualifier());
4054 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
4055 const PackExpansionType* T) {
4056 return Visit(T->getPattern());
4059 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
4063 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
4064 const ObjCInterfaceType *) {
4068 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
4069 const ObjCObjectPointerType *) {
4073 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
4074 return Visit(T->getValueType());
4077 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
4078 if (Tag->getDeclContext()->isFunctionOrMethod()) {
4079 S.Diag(SR.getBegin(),
4080 S.getLangOpts().CPlusPlus11 ?
4081 diag::warn_cxx98_compat_template_arg_local_type :
4082 diag::ext_template_arg_local_type)
4083 << S.Context.getTypeDeclType(Tag) << SR;
4087 if (!Tag->hasNameForLinkage()) {
4088 S.Diag(SR.getBegin(),
4089 S.getLangOpts().CPlusPlus11 ?
4090 diag::warn_cxx98_compat_template_arg_unnamed_type :
4091 diag::ext_template_arg_unnamed_type) << SR;
4092 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
4099 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
4100 NestedNameSpecifier *NNS) {
4101 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
4104 switch (NNS->getKind()) {
4105 case NestedNameSpecifier::Identifier:
4106 case NestedNameSpecifier::Namespace:
4107 case NestedNameSpecifier::NamespaceAlias:
4108 case NestedNameSpecifier::Global:
4111 case NestedNameSpecifier::TypeSpec:
4112 case NestedNameSpecifier::TypeSpecWithTemplate:
4113 return Visit(QualType(NNS->getAsType(), 0));
4115 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4119 /// \brief Check a template argument against its corresponding
4120 /// template type parameter.
4122 /// This routine implements the semantics of C++ [temp.arg.type]. It
4123 /// returns true if an error occurred, and false otherwise.
4124 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
4125 TypeSourceInfo *ArgInfo) {
4126 assert(ArgInfo && "invalid TypeSourceInfo");
4127 QualType Arg = ArgInfo->getType();
4128 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
4130 if (Arg->isVariablyModifiedType()) {
4131 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
4132 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
4133 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
4136 // C++03 [temp.arg.type]p2:
4137 // A local type, a type with no linkage, an unnamed type or a type
4138 // compounded from any of these types shall not be used as a
4139 // template-argument for a template type-parameter.
4141 // C++11 allows these, and even in C++03 we allow them as an extension with
4144 if (LangOpts.CPlusPlus11)
4146 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_unnamed_type,
4148 !Diags.isIgnored(diag::warn_cxx98_compat_template_arg_local_type,
4151 NeedsCheck = Arg->hasUnnamedOrLocalType();
4154 UnnamedLocalNoLinkageFinder Finder(*this, SR);
4155 (void)Finder.Visit(Context.getCanonicalType(Arg));
4161 enum NullPointerValueKind {
4167 /// \brief Determine whether the given template argument is a null pointer
4168 /// value of the appropriate type.
4169 static NullPointerValueKind
4170 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
4171 QualType ParamType, Expr *Arg) {
4172 if (Arg->isValueDependent() || Arg->isTypeDependent())
4173 return NPV_NotNullPointer;
4175 if (!S.getLangOpts().CPlusPlus11)
4176 return NPV_NotNullPointer;
4178 // Determine whether we have a constant expression.
4179 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);
4180 if (ArgRV.isInvalid())
4184 Expr::EvalResult EvalResult;
4185 SmallVector<PartialDiagnosticAt, 8> Notes;
4186 EvalResult.Diag = &Notes;
4187 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||
4188 EvalResult.HasSideEffects) {
4189 SourceLocation DiagLoc = Arg->getExprLoc();
4191 // If our only note is the usual "invalid subexpression" note, just point
4192 // the caret at its location rather than producing an essentially
4194 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
4195 diag::note_invalid_subexpr_in_const_expr) {
4196 DiagLoc = Notes[0].first;
4200 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
4201 << Arg->getType() << Arg->getSourceRange();
4202 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
4203 S.Diag(Notes[I].first, Notes[I].second);
4205 S.Diag(Param->getLocation(), diag::note_template_param_here);
4209 // C++11 [temp.arg.nontype]p1:
4210 // - an address constant expression of type std::nullptr_t
4211 if (Arg->getType()->isNullPtrType())
4212 return NPV_NullPointer;
4214 // - a constant expression that evaluates to a null pointer value (4.10); or
4215 // - a constant expression that evaluates to a null member pointer value
4217 if ((EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) ||
4218 (EvalResult.Val.isMemberPointer() &&
4219 !EvalResult.Val.getMemberPointerDecl())) {
4220 // If our expression has an appropriate type, we've succeeded.
4221 bool ObjCLifetimeConversion;
4222 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||
4223 S.IsQualificationConversion(Arg->getType(), ParamType, false,
4224 ObjCLifetimeConversion))
4225 return NPV_NullPointer;
4227 // The types didn't match, but we know we got a null pointer; complain,
4228 // then recover as if the types were correct.
4229 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
4230 << Arg->getType() << ParamType << Arg->getSourceRange();
4231 S.Diag(Param->getLocation(), diag::note_template_param_here);
4232 return NPV_NullPointer;
4235 // If we don't have a null pointer value, but we do have a NULL pointer
4236 // constant, suggest a cast to the appropriate type.
4237 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {
4238 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
4239 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
4240 << ParamType << FixItHint::CreateInsertion(Arg->getLocStart(), Code)
4241 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getLocEnd()),
4243 S.Diag(Param->getLocation(), diag::note_template_param_here);
4244 return NPV_NullPointer;
4247 // FIXME: If we ever want to support general, address-constant expressions
4248 // as non-type template arguments, we should return the ExprResult here to
4249 // be interpreted by the caller.
4250 return NPV_NotNullPointer;
4253 /// \brief Checks whether the given template argument is compatible with its
4254 /// template parameter.
4255 static bool CheckTemplateArgumentIsCompatibleWithParameter(
4256 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
4257 Expr *Arg, QualType ArgType) {
4258 bool ObjCLifetimeConversion;
4259 if (ParamType->isPointerType() &&
4260 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
4261 S.IsQualificationConversion(ArgType, ParamType, false,
4262 ObjCLifetimeConversion)) {
4263 // For pointer-to-object types, qualification conversions are
4266 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
4267 if (!ParamRef->getPointeeType()->isFunctionType()) {
4268 // C++ [temp.arg.nontype]p5b3:
4269 // For a non-type template-parameter of type reference to
4270 // object, no conversions apply. The type referred to by the
4271 // reference may be more cv-qualified than the (otherwise
4272 // identical) type of the template- argument. The
4273 // template-parameter is bound directly to the
4274 // template-argument, which shall be an lvalue.
4276 // FIXME: Other qualifiers?
4277 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
4278 unsigned ArgQuals = ArgType.getCVRQualifiers();
4280 if ((ParamQuals | ArgQuals) != ParamQuals) {
4281 S.Diag(Arg->getLocStart(),
4282 diag::err_template_arg_ref_bind_ignores_quals)
4283 << ParamType << Arg->getType() << Arg->getSourceRange();
4284 S.Diag(Param->getLocation(), diag::note_template_param_here);
4290 // At this point, the template argument refers to an object or
4291 // function with external linkage. We now need to check whether the
4292 // argument and parameter types are compatible.
4293 if (!S.Context.hasSameUnqualifiedType(ArgType,
4294 ParamType.getNonReferenceType())) {
4295 // We can't perform this conversion or binding.
4296 if (ParamType->isReferenceType())
4297 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
4298 << ParamType << ArgIn->getType() << Arg->getSourceRange();
4300 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4301 << ArgIn->getType() << ParamType << Arg->getSourceRange();
4302 S.Diag(Param->getLocation(), diag::note_template_param_here);
4310 /// \brief Checks whether the given template argument is the address
4311 /// of an object or function according to C++ [temp.arg.nontype]p1.
4313 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
4314 NonTypeTemplateParmDecl *Param,
4317 TemplateArgument &Converted) {
4318 bool Invalid = false;
4320 QualType ArgType = Arg->getType();
4322 bool AddressTaken = false;
4323 SourceLocation AddrOpLoc;
4324 if (S.getLangOpts().MicrosoftExt) {
4325 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
4326 // dereference and address-of operators.
4327 Arg = Arg->IgnoreParenCasts();
4329 bool ExtWarnMSTemplateArg = false;
4330 UnaryOperatorKind FirstOpKind;
4331 SourceLocation FirstOpLoc;
4332 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4333 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
4334 if (UnOpKind == UO_Deref)
4335 ExtWarnMSTemplateArg = true;
4336 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
4337 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
4338 if (!AddrOpLoc.isValid()) {
4339 FirstOpKind = UnOpKind;
4340 FirstOpLoc = UnOp->getOperatorLoc();
4345 if (FirstOpLoc.isValid()) {
4346 if (ExtWarnMSTemplateArg)
4347 S.Diag(ArgIn->getLocStart(), diag::ext_ms_deref_template_argument)
4348 << ArgIn->getSourceRange();
4350 if (FirstOpKind == UO_AddrOf)
4351 AddressTaken = true;
4352 else if (Arg->getType()->isPointerType()) {
4353 // We cannot let pointers get dereferenced here, that is obviously not a
4354 // constant expression.
4355 assert(FirstOpKind == UO_Deref);
4356 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4357 << Arg->getSourceRange();
4361 // See through any implicit casts we added to fix the type.
4362 Arg = Arg->IgnoreImpCasts();
4364 // C++ [temp.arg.nontype]p1:
4366 // A template-argument for a non-type, non-template
4367 // template-parameter shall be one of: [...]
4369 // -- the address of an object or function with external
4370 // linkage, including function templates and function
4371 // template-ids but excluding non-static class members,
4372 // expressed as & id-expression where the & is optional if
4373 // the name refers to a function or array, or if the
4374 // corresponding template-parameter is a reference; or
4376 // In C++98/03 mode, give an extension warning on any extra parentheses.
4377 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4378 bool ExtraParens = false;
4379 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4380 if (!Invalid && !ExtraParens) {
4381 S.Diag(Arg->getLocStart(),
4382 S.getLangOpts().CPlusPlus11
4383 ? diag::warn_cxx98_compat_template_arg_extra_parens
4384 : diag::ext_template_arg_extra_parens)
4385 << Arg->getSourceRange();
4389 Arg = Parens->getSubExpr();
4392 while (SubstNonTypeTemplateParmExpr *subst =
4393 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4394 Arg = subst->getReplacement()->IgnoreImpCasts();
4396 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4397 if (UnOp->getOpcode() == UO_AddrOf) {
4398 Arg = UnOp->getSubExpr();
4399 AddressTaken = true;
4400 AddrOpLoc = UnOp->getOperatorLoc();
4404 while (SubstNonTypeTemplateParmExpr *subst =
4405 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4406 Arg = subst->getReplacement()->IgnoreImpCasts();
4409 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg);
4410 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
4412 // If our parameter has pointer type, check for a null template value.
4413 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
4414 NullPointerValueKind NPV;
4415 // dllimport'd entities aren't constant but are available inside of template
4417 if (Entity && Entity->hasAttr<DLLImportAttr>())
4418 NPV = NPV_NotNullPointer;
4420 NPV = isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn);
4422 case NPV_NullPointer:
4423 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4424 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4425 /*isNullPtr=*/true);
4431 case NPV_NotNullPointer:
4436 // Stop checking the precise nature of the argument if it is value dependent,
4437 // it should be checked when instantiated.
4438 if (Arg->isValueDependent()) {
4439 Converted = TemplateArgument(ArgIn);
4443 if (isa<CXXUuidofExpr>(Arg)) {
4444 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType,
4445 ArgIn, Arg, ArgType))
4448 Converted = TemplateArgument(ArgIn);
4453 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
4454 << Arg->getSourceRange();
4455 S.Diag(Param->getLocation(), diag::note_template_param_here);
4459 // Cannot refer to non-static data members
4460 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {
4461 S.Diag(Arg->getLocStart(), diag::err_template_arg_field)
4462 << Entity << Arg->getSourceRange();
4463 S.Diag(Param->getLocation(), diag::note_template_param_here);
4467 // Cannot refer to non-static member functions
4468 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {
4469 if (!Method->isStatic()) {
4470 S.Diag(Arg->getLocStart(), diag::err_template_arg_method)
4471 << Method << Arg->getSourceRange();
4472 S.Diag(Param->getLocation(), diag::note_template_param_here);
4477 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);
4478 VarDecl *Var = dyn_cast<VarDecl>(Entity);
4480 // A non-type template argument must refer to an object or function.
4481 if (!Func && !Var) {
4482 // We found something, but we don't know specifically what it is.
4483 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_object_or_func)
4484 << Arg->getSourceRange();
4485 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4489 // Address / reference template args must have external linkage in C++98.
4490 if (Entity->getFormalLinkage() == InternalLinkage) {
4491 S.Diag(Arg->getLocStart(), S.getLangOpts().CPlusPlus11 ?
4492 diag::warn_cxx98_compat_template_arg_object_internal :
4493 diag::ext_template_arg_object_internal)
4494 << !Func << Entity << Arg->getSourceRange();
4495 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4497 } else if (!Entity->hasLinkage()) {
4498 S.Diag(Arg->getLocStart(), diag::err_template_arg_object_no_linkage)
4499 << !Func << Entity << Arg->getSourceRange();
4500 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
4506 // If the template parameter has pointer type, the function decays.
4507 if (ParamType->isPointerType() && !AddressTaken)
4508 ArgType = S.Context.getPointerType(Func->getType());
4509 else if (AddressTaken && ParamType->isReferenceType()) {
4510 // If we originally had an address-of operator, but the
4511 // parameter has reference type, complain and (if things look
4512 // like they will work) drop the address-of operator.
4513 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
4514 ParamType.getNonReferenceType())) {
4515 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4517 S.Diag(Param->getLocation(), diag::note_template_param_here);
4521 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4523 << FixItHint::CreateRemoval(AddrOpLoc);
4524 S.Diag(Param->getLocation(), diag::note_template_param_here);
4526 ArgType = Func->getType();
4529 // A value of reference type is not an object.
4530 if (Var->getType()->isReferenceType()) {
4531 S.Diag(Arg->getLocStart(),
4532 diag::err_template_arg_reference_var)
4533 << Var->getType() << Arg->getSourceRange();
4534 S.Diag(Param->getLocation(), diag::note_template_param_here);
4538 // A template argument must have static storage duration.
4539 if (Var->getTLSKind()) {
4540 S.Diag(Arg->getLocStart(), diag::err_template_arg_thread_local)
4541 << Arg->getSourceRange();
4542 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
4546 // If the template parameter has pointer type, we must have taken
4547 // the address of this object.
4548 if (ParamType->isReferenceType()) {
4550 // If we originally had an address-of operator, but the
4551 // parameter has reference type, complain and (if things look
4552 // like they will work) drop the address-of operator.
4553 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
4554 ParamType.getNonReferenceType())) {
4555 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4557 S.Diag(Param->getLocation(), diag::note_template_param_here);
4561 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
4563 << FixItHint::CreateRemoval(AddrOpLoc);
4564 S.Diag(Param->getLocation(), diag::note_template_param_here);
4566 ArgType = Var->getType();
4568 } else if (!AddressTaken && ParamType->isPointerType()) {
4569 if (Var->getType()->isArrayType()) {
4570 // Array-to-pointer decay.
4571 ArgType = S.Context.getArrayDecayedType(Var->getType());
4573 // If the template parameter has pointer type but the address of
4574 // this object was not taken, complain and (possibly) recover by
4575 // taking the address of the entity.
4576 ArgType = S.Context.getPointerType(Var->getType());
4577 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
4578 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4580 S.Diag(Param->getLocation(), diag::note_template_param_here);
4584 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
4586 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
4588 S.Diag(Param->getLocation(), diag::note_template_param_here);
4593 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
4597 // Create the template argument.
4598 Converted = TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
4599 ParamType->isReferenceType());
4600 S.MarkAnyDeclReferenced(Arg->getLocStart(), Entity, false);
4604 /// \brief Checks whether the given template argument is a pointer to
4605 /// member constant according to C++ [temp.arg.nontype]p1.
4606 static bool CheckTemplateArgumentPointerToMember(Sema &S,
4607 NonTypeTemplateParmDecl *Param,
4610 TemplateArgument &Converted) {
4611 bool Invalid = false;
4613 // Check for a null pointer value.
4614 Expr *Arg = ResultArg;
4615 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg)) {
4618 case NPV_NullPointer:
4619 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
4620 Converted = TemplateArgument(S.Context.getCanonicalType(ParamType),
4622 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft())
4623 S.RequireCompleteType(Arg->getExprLoc(), ParamType, 0);
4625 case NPV_NotNullPointer:
4629 bool ObjCLifetimeConversion;
4630 if (S.IsQualificationConversion(Arg->getType(),
4631 ParamType.getNonReferenceType(),
4632 false, ObjCLifetimeConversion)) {
4633 Arg = S.ImpCastExprToType(Arg, ParamType, CK_NoOp,
4634 Arg->getValueKind()).get();
4636 } else if (!S.Context.hasSameUnqualifiedType(Arg->getType(),
4637 ParamType.getNonReferenceType())) {
4638 // We can't perform this conversion.
4639 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
4640 << Arg->getType() << ParamType << Arg->getSourceRange();
4641 S.Diag(Param->getLocation(), diag::note_template_param_here);
4645 // See through any implicit casts we added to fix the type.
4646 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
4647 Arg = Cast->getSubExpr();
4649 // C++ [temp.arg.nontype]p1:
4651 // A template-argument for a non-type, non-template
4652 // template-parameter shall be one of: [...]
4654 // -- a pointer to member expressed as described in 5.3.1.
4655 DeclRefExpr *DRE = nullptr;
4657 // In C++98/03 mode, give an extension warning on any extra parentheses.
4658 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
4659 bool ExtraParens = false;
4660 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
4661 if (!Invalid && !ExtraParens) {
4662 S.Diag(Arg->getLocStart(),
4663 S.getLangOpts().CPlusPlus11 ?
4664 diag::warn_cxx98_compat_template_arg_extra_parens :
4665 diag::ext_template_arg_extra_parens)
4666 << Arg->getSourceRange();
4670 Arg = Parens->getSubExpr();
4673 while (SubstNonTypeTemplateParmExpr *subst =
4674 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))
4675 Arg = subst->getReplacement()->IgnoreImpCasts();
4677 // A pointer-to-member constant written &Class::member.
4678 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
4679 if (UnOp->getOpcode() == UO_AddrOf) {
4680 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
4681 if (DRE && !DRE->getQualifier())
4685 // A constant of pointer-to-member type.
4686 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
4687 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
4688 if (VD->getType()->isMemberPointerType()) {
4689 if (isa<NonTypeTemplateParmDecl>(VD)) {
4690 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4691 Converted = TemplateArgument(Arg);
4693 VD = cast<ValueDecl>(VD->getCanonicalDecl());
4694 Converted = TemplateArgument(VD, /*isReferenceParam*/false);
4705 return S.Diag(Arg->getLocStart(),
4706 diag::err_template_arg_not_pointer_to_member_form)
4707 << Arg->getSourceRange();
4709 if (isa<FieldDecl>(DRE->getDecl()) ||
4710 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4711 isa<CXXMethodDecl>(DRE->getDecl())) {
4712 assert((isa<FieldDecl>(DRE->getDecl()) ||
4713 isa<IndirectFieldDecl>(DRE->getDecl()) ||
4714 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
4715 "Only non-static member pointers can make it here");
4717 // Okay: this is the address of a non-static member, and therefore
4718 // a member pointer constant.
4719 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
4720 Converted = TemplateArgument(Arg);
4722 ValueDecl *D = cast<ValueDecl>(DRE->getDecl()->getCanonicalDecl());
4723 Converted = TemplateArgument(D, /*isReferenceParam*/false);
4728 // We found something else, but we don't know specifically what it is.
4729 S.Diag(Arg->getLocStart(),
4730 diag::err_template_arg_not_pointer_to_member_form)
4731 << Arg->getSourceRange();
4732 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
4736 /// \brief Check a template argument against its corresponding
4737 /// non-type template parameter.
4739 /// This routine implements the semantics of C++ [temp.arg.nontype].
4740 /// If an error occurred, it returns ExprError(); otherwise, it
4741 /// returns the converted template argument. \p
4742 /// InstantiatedParamType is the type of the non-type template
4743 /// parameter after it has been instantiated.
4744 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
4745 QualType InstantiatedParamType, Expr *Arg,
4746 TemplateArgument &Converted,
4747 CheckTemplateArgumentKind CTAK) {
4748 SourceLocation StartLoc = Arg->getLocStart();
4750 // If either the parameter has a dependent type or the argument is
4751 // type-dependent, there's nothing we can check now.
4752 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
4753 // FIXME: Produce a cloned, canonical expression?
4754 Converted = TemplateArgument(Arg);
4758 // C++ [temp.arg.nontype]p5:
4759 // The following conversions are performed on each expression used
4760 // as a non-type template-argument. If a non-type
4761 // template-argument cannot be converted to the type of the
4762 // corresponding template-parameter then the program is
4764 QualType ParamType = InstantiatedParamType;
4765 if (ParamType->isIntegralOrEnumerationType()) {
4767 // -- for a non-type template-parameter of integral or
4768 // enumeration type, conversions permitted in a converted
4769 // constant expression are applied.
4772 // -- for a non-type template-parameter of integral or
4773 // enumeration type, integral promotions (4.5) and integral
4774 // conversions (4.7) are applied.
4776 if (CTAK == CTAK_Deduced &&
4777 !Context.hasSameUnqualifiedType(ParamType, Arg->getType())) {
4778 // C++ [temp.deduct.type]p17:
4779 // If, in the declaration of a function template with a non-type
4780 // template-parameter, the non-type template-parameter is used
4781 // in an expression in the function parameter-list and, if the
4782 // corresponding template-argument is deduced, the
4783 // template-argument type shall match the type of the
4784 // template-parameter exactly, except that a template-argument
4785 // deduced from an array bound may be of any integral type.
4786 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
4787 << Arg->getType().getUnqualifiedType()
4788 << ParamType.getUnqualifiedType();
4789 Diag(Param->getLocation(), diag::note_template_param_here);
4793 if (getLangOpts().CPlusPlus11) {
4794 // We can't check arbitrary value-dependent arguments.
4795 // FIXME: If there's no viable conversion to the template parameter type,
4796 // we should be able to diagnose that prior to instantiation.
4797 if (Arg->isValueDependent()) {
4798 Converted = TemplateArgument(Arg);
4802 // C++ [temp.arg.nontype]p1:
4803 // A template-argument for a non-type, non-template template-parameter
4806 // -- for a non-type template-parameter of integral or enumeration
4807 // type, a converted constant expression of the type of the
4808 // template-parameter; or
4810 ExprResult ArgResult =
4811 CheckConvertedConstantExpression(Arg, ParamType, Value,
4813 if (ArgResult.isInvalid())
4816 // Widen the argument value to sizeof(parameter type). This is almost
4817 // always a no-op, except when the parameter type is bool. In
4818 // that case, this may extend the argument from 1 bit to 8 bits.
4819 QualType IntegerType = ParamType;
4820 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4821 IntegerType = Enum->getDecl()->getIntegerType();
4822 Value = Value.extOrTrunc(Context.getTypeSize(IntegerType));
4824 Converted = TemplateArgument(Context, Value,
4825 Context.getCanonicalType(ParamType));
4829 ExprResult ArgResult = DefaultLvalueConversion(Arg);
4830 if (ArgResult.isInvalid())
4832 Arg = ArgResult.get();
4834 QualType ArgType = Arg->getType();
4836 // C++ [temp.arg.nontype]p1:
4837 // A template-argument for a non-type, non-template
4838 // template-parameter shall be one of:
4840 // -- an integral constant-expression of integral or enumeration
4842 // -- the name of a non-type template-parameter; or
4843 SourceLocation NonConstantLoc;
4845 if (!ArgType->isIntegralOrEnumerationType()) {
4846 Diag(Arg->getLocStart(),
4847 diag::err_template_arg_not_integral_or_enumeral)
4848 << ArgType << Arg->getSourceRange();
4849 Diag(Param->getLocation(), diag::note_template_param_here);
4851 } else if (!Arg->isValueDependent()) {
4852 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
4856 TmplArgICEDiagnoser(QualType T) : T(T) { }
4858 void diagnoseNotICE(Sema &S, SourceLocation Loc,
4859 SourceRange SR) override {
4860 S.Diag(Loc, diag::err_template_arg_not_ice) << T << SR;
4862 } Diagnoser(ArgType);
4864 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser,
4870 // From here on out, all we care about are the unqualified forms
4871 // of the parameter and argument types.
4872 ParamType = ParamType.getUnqualifiedType();
4873 ArgType = ArgType.getUnqualifiedType();
4875 // Try to convert the argument to the parameter's type.
4876 if (Context.hasSameType(ParamType, ArgType)) {
4877 // Okay: no conversion necessary
4878 } else if (ParamType->isBooleanType()) {
4879 // This is an integral-to-boolean conversion.
4880 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();
4881 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
4882 !ParamType->isEnumeralType()) {
4883 // This is an integral promotion or conversion.
4884 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();
4886 // We can't perform this conversion.
4887 Diag(Arg->getLocStart(),
4888 diag::err_template_arg_not_convertible)
4889 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
4890 Diag(Param->getLocation(), diag::note_template_param_here);
4894 // Add the value of this argument to the list of converted
4895 // arguments. We use the bitwidth and signedness of the template
4897 if (Arg->isValueDependent()) {
4898 // The argument is value-dependent. Create a new
4899 // TemplateArgument with the converted expression.
4900 Converted = TemplateArgument(Arg);
4904 QualType IntegerType = Context.getCanonicalType(ParamType);
4905 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
4906 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
4908 if (ParamType->isBooleanType()) {
4909 // Value must be zero or one.
4911 unsigned AllowedBits = Context.getTypeSize(IntegerType);
4912 if (Value.getBitWidth() != AllowedBits)
4913 Value = Value.extOrTrunc(AllowedBits);
4914 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
4916 llvm::APSInt OldValue = Value;
4918 // Coerce the template argument's value to the value it will have
4919 // based on the template parameter's type.
4920 unsigned AllowedBits = Context.getTypeSize(IntegerType);
4921 if (Value.getBitWidth() != AllowedBits)
4922 Value = Value.extOrTrunc(AllowedBits);
4923 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
4925 // Complain if an unsigned parameter received a negative value.
4926 if (IntegerType->isUnsignedIntegerOrEnumerationType()
4927 && (OldValue.isSigned() && OldValue.isNegative())) {
4928 Diag(Arg->getLocStart(), diag::warn_template_arg_negative)
4929 << OldValue.toString(10) << Value.toString(10) << Param->getType()
4930 << Arg->getSourceRange();
4931 Diag(Param->getLocation(), diag::note_template_param_here);
4934 // Complain if we overflowed the template parameter's type.
4935 unsigned RequiredBits;
4936 if (IntegerType->isUnsignedIntegerOrEnumerationType())
4937 RequiredBits = OldValue.getActiveBits();
4938 else if (OldValue.isUnsigned())
4939 RequiredBits = OldValue.getActiveBits() + 1;
4941 RequiredBits = OldValue.getMinSignedBits();
4942 if (RequiredBits > AllowedBits) {
4943 Diag(Arg->getLocStart(),
4944 diag::warn_template_arg_too_large)
4945 << OldValue.toString(10) << Value.toString(10) << Param->getType()
4946 << Arg->getSourceRange();
4947 Diag(Param->getLocation(), diag::note_template_param_here);
4951 Converted = TemplateArgument(Context, Value,
4952 ParamType->isEnumeralType()
4953 ? Context.getCanonicalType(ParamType)
4958 QualType ArgType = Arg->getType();
4959 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
4961 // Handle pointer-to-function, reference-to-function, and
4962 // pointer-to-member-function all in (roughly) the same way.
4963 if (// -- For a non-type template-parameter of type pointer to
4964 // function, only the function-to-pointer conversion (4.3) is
4965 // applied. If the template-argument represents a set of
4966 // overloaded functions (or a pointer to such), the matching
4967 // function is selected from the set (13.4).
4968 (ParamType->isPointerType() &&
4969 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
4970 // -- For a non-type template-parameter of type reference to
4971 // function, no conversions apply. If the template-argument
4972 // represents a set of overloaded functions, the matching
4973 // function is selected from the set (13.4).
4974 (ParamType->isReferenceType() &&
4975 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
4976 // -- For a non-type template-parameter of type pointer to
4977 // member function, no conversions apply. If the
4978 // template-argument represents a set of overloaded member
4979 // functions, the matching member function is selected from
4981 (ParamType->isMemberPointerType() &&
4982 ParamType->getAs<MemberPointerType>()->getPointeeType()
4983 ->isFunctionType())) {
4985 if (Arg->getType() == Context.OverloadTy) {
4986 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
4989 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
4992 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
4993 ArgType = Arg->getType();
4998 if (!ParamType->isMemberPointerType()) {
4999 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5006 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5012 if (ParamType->isPointerType()) {
5013 // -- for a non-type template-parameter of type pointer to
5014 // object, qualification conversions (4.4) and the
5015 // array-to-pointer conversion (4.2) are applied.
5016 // C++0x also allows a value of std::nullptr_t.
5017 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
5018 "Only object pointers allowed here");
5020 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5027 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
5028 // -- For a non-type template-parameter of type reference to
5029 // object, no conversions apply. The type referred to by the
5030 // reference may be more cv-qualified than the (otherwise
5031 // identical) type of the template-argument. The
5032 // template-parameter is bound directly to the
5033 // template-argument, which must be an lvalue.
5034 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
5035 "Only object references allowed here");
5037 if (Arg->getType() == Context.OverloadTy) {
5038 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
5039 ParamRefType->getPointeeType(),
5042 if (DiagnoseUseOfDecl(Fn, Arg->getLocStart()))
5045 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
5046 ArgType = Arg->getType();
5051 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
5058 // Deal with parameters of type std::nullptr_t.
5059 if (ParamType->isNullPtrType()) {
5060 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
5061 Converted = TemplateArgument(Arg);
5065 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {
5066 case NPV_NotNullPointer:
5067 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
5068 << Arg->getType() << ParamType;
5069 Diag(Param->getLocation(), diag::note_template_param_here);
5075 case NPV_NullPointer:
5076 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
5077 Converted = TemplateArgument(Context.getCanonicalType(ParamType),
5083 // -- For a non-type template-parameter of type pointer to data
5084 // member, qualification conversions (4.4) are applied.
5085 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
5087 if (CheckTemplateArgumentPointerToMember(*this, Param, ParamType, Arg,
5093 /// \brief Check a template argument against its corresponding
5094 /// template template parameter.
5096 /// This routine implements the semantics of C++ [temp.arg.template].
5097 /// It returns true if an error occurred, and false otherwise.
5098 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
5099 TemplateArgumentLoc &Arg,
5100 unsigned ArgumentPackIndex) {
5101 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
5102 TemplateDecl *Template = Name.getAsTemplateDecl();
5104 // Any dependent template name is fine.
5105 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
5109 // C++0x [temp.arg.template]p1:
5110 // A template-argument for a template template-parameter shall be
5111 // the name of a class template or an alias template, expressed as an
5112 // id-expression. When the template-argument names a class template, only
5113 // primary class templates are considered when matching the
5114 // template template argument with the corresponding parameter;
5115 // partial specializations are not considered even if their
5116 // parameter lists match that of the template template parameter.
5118 // Note that we also allow template template parameters here, which
5119 // will happen when we are dealing with, e.g., class template
5120 // partial specializations.
5121 if (!isa<ClassTemplateDecl>(Template) &&
5122 !isa<TemplateTemplateParmDecl>(Template) &&
5123 !isa<TypeAliasTemplateDecl>(Template)) {
5124 assert(isa<FunctionTemplateDecl>(Template) &&
5125 "Only function templates are possible here");
5126 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
5127 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
5131 TemplateParameterList *Params = Param->getTemplateParameters();
5132 if (Param->isExpandedParameterPack())
5133 Params = Param->getExpansionTemplateParameters(ArgumentPackIndex);
5135 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
5138 TPL_TemplateTemplateArgumentMatch,
5142 /// \brief Given a non-type template argument that refers to a
5143 /// declaration and the type of its corresponding non-type template
5144 /// parameter, produce an expression that properly refers to that
5147 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
5149 SourceLocation Loc) {
5150 // C++ [temp.param]p8:
5152 // A non-type template-parameter of type "array of T" or
5153 // "function returning T" is adjusted to be of type "pointer to
5154 // T" or "pointer to function returning T", respectively.
5155 if (ParamType->isArrayType())
5156 ParamType = Context.getArrayDecayedType(ParamType);
5157 else if (ParamType->isFunctionType())
5158 ParamType = Context.getPointerType(ParamType);
5160 // For a NULL non-type template argument, return nullptr casted to the
5161 // parameter's type.
5162 if (Arg.getKind() == TemplateArgument::NullPtr) {
5163 return ImpCastExprToType(
5164 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
5166 ParamType->getAs<MemberPointerType>()
5167 ? CK_NullToMemberPointer
5168 : CK_NullToPointer);
5170 assert(Arg.getKind() == TemplateArgument::Declaration &&
5171 "Only declaration template arguments permitted here");
5173 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
5175 if (VD->getDeclContext()->isRecord() &&
5176 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
5177 isa<IndirectFieldDecl>(VD))) {
5178 // If the value is a class member, we might have a pointer-to-member.
5179 // Determine whether the non-type template template parameter is of
5180 // pointer-to-member type. If so, we need to build an appropriate
5181 // expression for a pointer-to-member, since a "normal" DeclRefExpr
5182 // would refer to the member itself.
5183 if (ParamType->isMemberPointerType()) {
5185 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
5186 NestedNameSpecifier *Qualifier
5187 = NestedNameSpecifier::Create(Context, nullptr, false,
5188 ClassType.getTypePtr());
5190 SS.MakeTrivial(Context, Qualifier, Loc);
5192 // The actual value-ness of this is unimportant, but for
5193 // internal consistency's sake, references to instance methods
5195 ExprValueKind VK = VK_LValue;
5196 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
5199 ExprResult RefExpr = BuildDeclRefExpr(VD,
5200 VD->getType().getNonReferenceType(),
5204 if (RefExpr.isInvalid())
5207 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5209 // We might need to perform a trailing qualification conversion, since
5210 // the element type on the parameter could be more qualified than the
5211 // element type in the expression we constructed.
5212 bool ObjCLifetimeConversion;
5213 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
5214 ParamType.getUnqualifiedType(), false,
5215 ObjCLifetimeConversion))
5216 RefExpr = ImpCastExprToType(RefExpr.get(), ParamType.getUnqualifiedType(), CK_NoOp);
5218 assert(!RefExpr.isInvalid() &&
5219 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
5220 ParamType.getUnqualifiedType()));
5225 QualType T = VD->getType().getNonReferenceType();
5227 if (ParamType->isPointerType()) {
5228 // When the non-type template parameter is a pointer, take the
5229 // address of the declaration.
5230 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
5231 if (RefExpr.isInvalid())
5234 if (T->isFunctionType() || T->isArrayType()) {
5235 // Decay functions and arrays.
5236 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());
5237 if (RefExpr.isInvalid())
5243 // Take the address of everything else
5244 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
5247 ExprValueKind VK = VK_RValue;
5249 // If the non-type template parameter has reference type, qualify the
5250 // resulting declaration reference with the extra qualifiers on the
5251 // type that the reference refers to.
5252 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
5254 T = Context.getQualifiedType(T,
5255 TargetRef->getPointeeType().getQualifiers());
5256 } else if (isa<FunctionDecl>(VD)) {
5257 // References to functions are always lvalues.
5261 return BuildDeclRefExpr(VD, T, VK, Loc);
5264 /// \brief Construct a new expression that refers to the given
5265 /// integral template argument with the given source-location
5268 /// This routine takes care of the mapping from an integral template
5269 /// argument (which may have any integral type) to the appropriate
5272 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
5273 SourceLocation Loc) {
5274 assert(Arg.getKind() == TemplateArgument::Integral &&
5275 "Operation is only valid for integral template arguments");
5276 QualType OrigT = Arg.getIntegralType();
5278 // If this is an enum type that we're instantiating, we need to use an integer
5279 // type the same size as the enumerator. We don't want to build an
5280 // IntegerLiteral with enum type. The integer type of an enum type can be of
5281 // any integral type with C++11 enum classes, make sure we create the right
5282 // type of literal for it.
5284 if (const EnumType *ET = OrigT->getAs<EnumType>())
5285 T = ET->getDecl()->getIntegerType();
5288 if (T->isAnyCharacterType()) {
5289 CharacterLiteral::CharacterKind Kind;
5290 if (T->isWideCharType())
5291 Kind = CharacterLiteral::Wide;
5292 else if (T->isChar16Type())
5293 Kind = CharacterLiteral::UTF16;
5294 else if (T->isChar32Type())
5295 Kind = CharacterLiteral::UTF32;
5297 Kind = CharacterLiteral::Ascii;
5299 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(),
5301 } else if (T->isBooleanType()) {
5302 E = new (Context) CXXBoolLiteralExpr(Arg.getAsIntegral().getBoolValue(),
5304 } else if (T->isNullPtrType()) {
5305 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
5307 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc);
5310 if (OrigT->isEnumeralType()) {
5311 // FIXME: This is a hack. We need a better way to handle substituted
5312 // non-type template parameters.
5313 E = CStyleCastExpr::Create(Context, OrigT, VK_RValue, CK_IntegralCast, E,
5315 Context.getTrivialTypeSourceInfo(OrigT, Loc),
5322 /// \brief Match two template parameters within template parameter lists.
5323 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
5325 Sema::TemplateParameterListEqualKind Kind,
5326 SourceLocation TemplateArgLoc) {
5327 // Check the actual kind (type, non-type, template).
5328 if (Old->getKind() != New->getKind()) {
5330 unsigned NextDiag = diag::err_template_param_different_kind;
5331 if (TemplateArgLoc.isValid()) {
5332 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5333 NextDiag = diag::note_template_param_different_kind;
5335 S.Diag(New->getLocation(), NextDiag)
5336 << (Kind != Sema::TPL_TemplateMatch);
5337 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
5338 << (Kind != Sema::TPL_TemplateMatch);
5344 // Check that both are parameter packs are neither are parameter packs.
5345 // However, if we are matching a template template argument to a
5346 // template template parameter, the template template parameter can have
5347 // a parameter pack where the template template argument does not.
5348 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
5349 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5350 Old->isTemplateParameterPack())) {
5352 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
5353 if (TemplateArgLoc.isValid()) {
5354 S.Diag(TemplateArgLoc,
5355 diag::err_template_arg_template_params_mismatch);
5356 NextDiag = diag::note_template_parameter_pack_non_pack;
5359 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
5360 : isa<NonTypeTemplateParmDecl>(New)? 1
5362 S.Diag(New->getLocation(), NextDiag)
5363 << ParamKind << New->isParameterPack();
5364 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
5365 << ParamKind << Old->isParameterPack();
5371 // For non-type template parameters, check the type of the parameter.
5372 if (NonTypeTemplateParmDecl *OldNTTP
5373 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
5374 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
5376 // If we are matching a template template argument to a template
5377 // template parameter and one of the non-type template parameter types
5378 // is dependent, then we must wait until template instantiation time
5379 // to actually compare the arguments.
5380 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
5381 (OldNTTP->getType()->isDependentType() ||
5382 NewNTTP->getType()->isDependentType()))
5385 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
5387 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
5388 if (TemplateArgLoc.isValid()) {
5389 S.Diag(TemplateArgLoc,
5390 diag::err_template_arg_template_params_mismatch);
5391 NextDiag = diag::note_template_nontype_parm_different_type;
5393 S.Diag(NewNTTP->getLocation(), NextDiag)
5394 << NewNTTP->getType()
5395 << (Kind != Sema::TPL_TemplateMatch);
5396 S.Diag(OldNTTP->getLocation(),
5397 diag::note_template_nontype_parm_prev_declaration)
5398 << OldNTTP->getType();
5407 // For template template parameters, check the template parameter types.
5408 // The template parameter lists of template template
5409 // parameters must agree.
5410 if (TemplateTemplateParmDecl *OldTTP
5411 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
5412 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
5413 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
5414 OldTTP->getTemplateParameters(),
5416 (Kind == Sema::TPL_TemplateMatch
5417 ? Sema::TPL_TemplateTemplateParmMatch
5425 /// \brief Diagnose a known arity mismatch when comparing template argument
5428 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
5429 TemplateParameterList *New,
5430 TemplateParameterList *Old,
5431 Sema::TemplateParameterListEqualKind Kind,
5432 SourceLocation TemplateArgLoc) {
5433 unsigned NextDiag = diag::err_template_param_list_different_arity;
5434 if (TemplateArgLoc.isValid()) {
5435 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
5436 NextDiag = diag::note_template_param_list_different_arity;
5438 S.Diag(New->getTemplateLoc(), NextDiag)
5439 << (New->size() > Old->size())
5440 << (Kind != Sema::TPL_TemplateMatch)
5441 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
5442 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
5443 << (Kind != Sema::TPL_TemplateMatch)
5444 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
5447 /// \brief Determine whether the given template parameter lists are
5450 /// \param New The new template parameter list, typically written in the
5451 /// source code as part of a new template declaration.
5453 /// \param Old The old template parameter list, typically found via
5454 /// name lookup of the template declared with this template parameter
5457 /// \param Complain If true, this routine will produce a diagnostic if
5458 /// the template parameter lists are not equivalent.
5460 /// \param Kind describes how we are to match the template parameter lists.
5462 /// \param TemplateArgLoc If this source location is valid, then we
5463 /// are actually checking the template parameter list of a template
5464 /// argument (New) against the template parameter list of its
5465 /// corresponding template template parameter (Old). We produce
5466 /// slightly different diagnostics in this scenario.
5468 /// \returns True if the template parameter lists are equal, false
5471 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
5472 TemplateParameterList *Old,
5474 TemplateParameterListEqualKind Kind,
5475 SourceLocation TemplateArgLoc) {
5476 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
5478 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5484 // C++0x [temp.arg.template]p3:
5485 // A template-argument matches a template template-parameter (call it P)
5486 // when each of the template parameters in the template-parameter-list of
5487 // the template-argument's corresponding class template or alias template
5488 // (call it A) matches the corresponding template parameter in the
5489 // template-parameter-list of P. [...]
5490 TemplateParameterList::iterator NewParm = New->begin();
5491 TemplateParameterList::iterator NewParmEnd = New->end();
5492 for (TemplateParameterList::iterator OldParm = Old->begin(),
5493 OldParmEnd = Old->end();
5494 OldParm != OldParmEnd; ++OldParm) {
5495 if (Kind != TPL_TemplateTemplateArgumentMatch ||
5496 !(*OldParm)->isTemplateParameterPack()) {
5497 if (NewParm == NewParmEnd) {
5499 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5505 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5506 Kind, TemplateArgLoc))
5513 // C++0x [temp.arg.template]p3:
5514 // [...] When P's template- parameter-list contains a template parameter
5515 // pack (14.5.3), the template parameter pack will match zero or more
5516 // template parameters or template parameter packs in the
5517 // template-parameter-list of A with the same type and form as the
5518 // template parameter pack in P (ignoring whether those template
5519 // parameters are template parameter packs).
5520 for (; NewParm != NewParmEnd; ++NewParm) {
5521 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
5522 Kind, TemplateArgLoc))
5527 // Make sure we exhausted all of the arguments.
5528 if (NewParm != NewParmEnd) {
5530 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
5539 /// \brief Check whether a template can be declared within this scope.
5541 /// If the template declaration is valid in this scope, returns
5542 /// false. Otherwise, issues a diagnostic and returns true.
5544 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
5548 // Find the nearest enclosing declaration scope.
5549 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5550 (S->getFlags() & Scope::TemplateParamScope) != 0)
5554 // A template [...] shall not have C linkage.
5555 DeclContext *Ctx = S->getEntity();
5556 if (Ctx && Ctx->isExternCContext())
5557 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
5558 << TemplateParams->getSourceRange();
5560 while (Ctx && isa<LinkageSpecDecl>(Ctx))
5561 Ctx = Ctx->getParent();
5564 // A template-declaration can appear only as a namespace scope or
5565 // class scope declaration.
5567 if (Ctx->isFileContext())
5569 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {
5570 // C++ [temp.mem]p2:
5571 // A local class shall not have member templates.
5572 if (RD->isLocalClass())
5573 return Diag(TemplateParams->getTemplateLoc(),
5574 diag::err_template_inside_local_class)
5575 << TemplateParams->getSourceRange();
5581 return Diag(TemplateParams->getTemplateLoc(),
5582 diag::err_template_outside_namespace_or_class_scope)
5583 << TemplateParams->getSourceRange();
5586 /// \brief Determine what kind of template specialization the given declaration
5588 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
5590 return TSK_Undeclared;
5592 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
5593 return Record->getTemplateSpecializationKind();
5594 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
5595 return Function->getTemplateSpecializationKind();
5596 if (VarDecl *Var = dyn_cast<VarDecl>(D))
5597 return Var->getTemplateSpecializationKind();
5599 return TSK_Undeclared;
5602 /// \brief Check whether a specialization is well-formed in the current
5605 /// This routine determines whether a template specialization can be declared
5606 /// in the current context (C++ [temp.expl.spec]p2).
5608 /// \param S the semantic analysis object for which this check is being
5611 /// \param Specialized the entity being specialized or instantiated, which
5612 /// may be a kind of template (class template, function template, etc.) or
5613 /// a member of a class template (member function, static data member,
5616 /// \param PrevDecl the previous declaration of this entity, if any.
5618 /// \param Loc the location of the explicit specialization or instantiation of
5621 /// \param IsPartialSpecialization whether this is a partial specialization of
5622 /// a class template.
5624 /// \returns true if there was an error that we cannot recover from, false
5626 static bool CheckTemplateSpecializationScope(Sema &S,
5627 NamedDecl *Specialized,
5628 NamedDecl *PrevDecl,
5630 bool IsPartialSpecialization) {
5631 // Keep these "kind" numbers in sync with the %select statements in the
5632 // various diagnostics emitted by this routine.
5634 if (isa<ClassTemplateDecl>(Specialized))
5635 EntityKind = IsPartialSpecialization? 1 : 0;
5636 else if (isa<VarTemplateDecl>(Specialized))
5637 EntityKind = IsPartialSpecialization ? 3 : 2;
5638 else if (isa<FunctionTemplateDecl>(Specialized))
5640 else if (isa<CXXMethodDecl>(Specialized))
5642 else if (isa<VarDecl>(Specialized))
5644 else if (isa<RecordDecl>(Specialized))
5646 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)
5649 S.Diag(Loc, diag::err_template_spec_unknown_kind)
5650 << S.getLangOpts().CPlusPlus11;
5651 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5655 // C++ [temp.expl.spec]p2:
5656 // An explicit specialization shall be declared in the namespace
5657 // of which the template is a member, or, for member templates, in
5658 // the namespace of which the enclosing class or enclosing class
5659 // template is a member. An explicit specialization of a member
5660 // function, member class or static data member of a class
5661 // template shall be declared in the namespace of which the class
5662 // template is a member. Such a declaration may also be a
5663 // definition. If the declaration is not a definition, the
5664 // specialization may be defined later in the name- space in which
5665 // the explicit specialization was declared, or in a namespace
5666 // that encloses the one in which the explicit specialization was
5668 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
5669 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
5674 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
5675 if (S.getLangOpts().MicrosoftExt) {
5676 // Do not warn for class scope explicit specialization during
5677 // instantiation, warning was already emitted during pattern
5678 // semantic analysis.
5679 if (!S.ActiveTemplateInstantiations.size())
5680 S.Diag(Loc, diag::ext_function_specialization_in_class)
5683 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5689 if (S.CurContext->isRecord() &&
5690 !S.CurContext->Equals(Specialized->getDeclContext())) {
5691 // Make sure that we're specializing in the right record context.
5692 // Otherwise, things can go horribly wrong.
5693 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
5698 // C++ [temp.class.spec]p6:
5699 // A class template partial specialization may be declared or redeclared
5700 // in any namespace scope in which its definition may be defined (14.5.1
5702 DeclContext *SpecializedContext
5703 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
5704 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
5706 // Make sure that this redeclaration (or definition) occurs in an enclosing
5708 // Note that HandleDeclarator() performs this check for explicit
5709 // specializations of function templates, static data members, and member
5710 // functions, so we skip the check here for those kinds of entities.
5711 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
5712 // Should we refactor that check, so that it occurs later?
5713 if (!DC->Encloses(SpecializedContext) &&
5714 !(isa<FunctionTemplateDecl>(Specialized) ||
5715 isa<FunctionDecl>(Specialized) ||
5716 isa<VarTemplateDecl>(Specialized) ||
5717 isa<VarDecl>(Specialized))) {
5718 if (isa<TranslationUnitDecl>(SpecializedContext))
5719 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
5720 << EntityKind << Specialized;
5721 else if (isa<NamespaceDecl>(SpecializedContext))
5722 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
5723 << EntityKind << Specialized
5724 << cast<NamedDecl>(SpecializedContext);
5726 llvm_unreachable("unexpected namespace context for specialization");
5728 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5729 } else if ((!PrevDecl ||
5730 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
5731 getTemplateSpecializationKind(PrevDecl) ==
5732 TSK_ImplicitInstantiation)) {
5733 // C++ [temp.exp.spec]p2:
5734 // An explicit specialization shall be declared in the namespace of which
5735 // the template is a member, or, for member templates, in the namespace
5736 // of which the enclosing class or enclosing class template is a member.
5737 // An explicit specialization of a member function, member class or
5738 // static data member of a class template shall be declared in the
5739 // namespace of which the class template is a member.
5741 // C++11 [temp.expl.spec]p2:
5742 // An explicit specialization shall be declared in a namespace enclosing
5743 // the specialized template.
5744 // C++11 [temp.explicit]p3:
5745 // An explicit instantiation shall appear in an enclosing namespace of its
5747 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext)) {
5748 bool IsCPlusPlus11Extension = DC->Encloses(SpecializedContext);
5749 if (isa<TranslationUnitDecl>(SpecializedContext)) {
5750 assert(!IsCPlusPlus11Extension &&
5751 "DC encloses TU but isn't in enclosing namespace set");
5752 S.Diag(Loc, diag::err_template_spec_decl_out_of_scope_global)
5753 << EntityKind << Specialized;
5754 } else if (isa<NamespaceDecl>(SpecializedContext)) {
5756 if (!IsCPlusPlus11Extension)
5757 Diag = diag::err_template_spec_decl_out_of_scope;
5758 else if (!S.getLangOpts().CPlusPlus11)
5759 Diag = diag::ext_template_spec_decl_out_of_scope;
5761 Diag = diag::warn_cxx98_compat_template_spec_decl_out_of_scope;
5763 << EntityKind << Specialized << cast<NamedDecl>(SpecializedContext);
5766 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
5773 static SourceRange findTemplateParameter(unsigned Depth, Expr *E) {
5774 if (!E->isInstantiationDependent())
5775 return SourceLocation();
5776 DependencyChecker Checker(Depth);
5777 Checker.TraverseStmt(E);
5778 if (Checker.Match && Checker.MatchLoc.isInvalid())
5779 return E->getSourceRange();
5780 return Checker.MatchLoc;
5783 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
5784 if (!TL.getType()->isDependentType())
5785 return SourceLocation();
5786 DependencyChecker Checker(Depth);
5787 Checker.TraverseTypeLoc(TL);
5788 if (Checker.Match && Checker.MatchLoc.isInvalid())
5789 return TL.getSourceRange();
5790 return Checker.MatchLoc;
5793 /// \brief Subroutine of Sema::CheckTemplatePartialSpecializationArgs
5794 /// that checks non-type template partial specialization arguments.
5795 static bool CheckNonTypeTemplatePartialSpecializationArgs(
5796 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
5797 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
5798 for (unsigned I = 0; I != NumArgs; ++I) {
5799 if (Args[I].getKind() == TemplateArgument::Pack) {
5800 if (CheckNonTypeTemplatePartialSpecializationArgs(
5801 S, TemplateNameLoc, Param, Args[I].pack_begin(),
5802 Args[I].pack_size(), IsDefaultArgument))
5808 if (Args[I].getKind() != TemplateArgument::Expression)
5811 Expr *ArgExpr = Args[I].getAsExpr();
5813 // We can have a pack expansion of any of the bullets below.
5814 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
5815 ArgExpr = Expansion->getPattern();
5817 // Strip off any implicit casts we added as part of type checking.
5818 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
5819 ArgExpr = ICE->getSubExpr();
5821 // C++ [temp.class.spec]p8:
5822 // A non-type argument is non-specialized if it is the name of a
5823 // non-type parameter. All other non-type arguments are
5826 // Below, we check the two conditions that only apply to
5827 // specialized non-type arguments, so skip any non-specialized
5829 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
5830 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
5833 // C++ [temp.class.spec]p9:
5834 // Within the argument list of a class template partial
5835 // specialization, the following restrictions apply:
5836 // -- A partially specialized non-type argument expression
5837 // shall not involve a template parameter of the partial
5838 // specialization except when the argument expression is a
5839 // simple identifier.
5840 SourceRange ParamUseRange =
5841 findTemplateParameter(Param->getDepth(), ArgExpr);
5842 if (ParamUseRange.isValid()) {
5843 if (IsDefaultArgument) {
5844 S.Diag(TemplateNameLoc,
5845 diag::err_dependent_non_type_arg_in_partial_spec);
5846 S.Diag(ParamUseRange.getBegin(),
5847 diag::note_dependent_non_type_default_arg_in_partial_spec)
5850 S.Diag(ParamUseRange.getBegin(),
5851 diag::err_dependent_non_type_arg_in_partial_spec)
5857 // -- The type of a template parameter corresponding to a
5858 // specialized non-type argument shall not be dependent on a
5859 // parameter of the specialization.
5861 // FIXME: We need to delay this check until instantiation in some cases:
5863 // template<template<typename> class X> struct A {
5864 // template<typename T, X<T> N> struct B;
5865 // template<typename T> struct B<T, 0>;
5867 // template<typename> using X = int;
5868 // A<X>::B<int, 0> b;
5869 ParamUseRange = findTemplateParameter(
5870 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
5871 if (ParamUseRange.isValid()) {
5872 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getLocStart(),
5873 diag::err_dependent_typed_non_type_arg_in_partial_spec)
5874 << Param->getType() << ParamUseRange;
5875 S.Diag(Param->getLocation(), diag::note_template_param_here)
5876 << (IsDefaultArgument ? ParamUseRange : SourceRange());
5884 /// \brief Check the non-type template arguments of a class template
5885 /// partial specialization according to C++ [temp.class.spec]p9.
5887 /// \param TemplateNameLoc the location of the template name.
5888 /// \param TemplateParams the template parameters of the primary class
5890 /// \param NumExplicit the number of explicitly-specified template arguments.
5891 /// \param TemplateArgs the template arguments of the class template
5892 /// partial specialization.
5894 /// \returns \c true if there was an error, \c false otherwise.
5895 static bool CheckTemplatePartialSpecializationArgs(
5896 Sema &S, SourceLocation TemplateNameLoc,
5897 TemplateParameterList *TemplateParams, unsigned NumExplicit,
5898 SmallVectorImpl<TemplateArgument> &TemplateArgs) {
5899 const TemplateArgument *ArgList = TemplateArgs.data();
5901 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5902 NonTypeTemplateParmDecl *Param
5903 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
5907 if (CheckNonTypeTemplatePartialSpecializationArgs(
5908 S, TemplateNameLoc, Param, &ArgList[I], 1, I >= NumExplicit))
5916 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
5918 SourceLocation KWLoc,
5919 SourceLocation ModulePrivateLoc,
5920 TemplateIdAnnotation &TemplateId,
5921 AttributeList *Attr,
5922 MultiTemplateParamsArg TemplateParameterLists) {
5923 assert(TUK != TUK_Reference && "References are not specializations");
5925 CXXScopeSpec &SS = TemplateId.SS;
5927 // NOTE: KWLoc is the location of the tag keyword. This will instead
5928 // store the location of the outermost template keyword in the declaration.
5929 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
5930 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
5931 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
5932 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
5933 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
5935 // Find the class template we're specializing
5936 TemplateName Name = TemplateId.Template.get();
5937 ClassTemplateDecl *ClassTemplate
5938 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
5940 if (!ClassTemplate) {
5941 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
5942 << (Name.getAsTemplateDecl() &&
5943 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
5947 bool isExplicitSpecialization = false;
5948 bool isPartialSpecialization = false;
5950 // Check the validity of the template headers that introduce this
5952 // FIXME: We probably shouldn't complain about these headers for
5953 // friend declarations.
5954 bool Invalid = false;
5955 TemplateParameterList *TemplateParams =
5956 MatchTemplateParametersToScopeSpecifier(
5957 KWLoc, TemplateNameLoc, SS, &TemplateId,
5958 TemplateParameterLists, TUK == TUK_Friend, isExplicitSpecialization,
5963 if (TemplateParams && TemplateParams->size() > 0) {
5964 isPartialSpecialization = true;
5966 if (TUK == TUK_Friend) {
5967 Diag(KWLoc, diag::err_partial_specialization_friend)
5968 << SourceRange(LAngleLoc, RAngleLoc);
5972 // C++ [temp.class.spec]p10:
5973 // The template parameter list of a specialization shall not
5974 // contain default template argument values.
5975 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
5976 Decl *Param = TemplateParams->getParam(I);
5977 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
5978 if (TTP->hasDefaultArgument()) {
5979 Diag(TTP->getDefaultArgumentLoc(),
5980 diag::err_default_arg_in_partial_spec);
5981 TTP->removeDefaultArgument();
5983 } else if (NonTypeTemplateParmDecl *NTTP
5984 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5985 if (Expr *DefArg = NTTP->getDefaultArgument()) {
5986 Diag(NTTP->getDefaultArgumentLoc(),
5987 diag::err_default_arg_in_partial_spec)
5988 << DefArg->getSourceRange();
5989 NTTP->removeDefaultArgument();
5992 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
5993 if (TTP->hasDefaultArgument()) {
5994 Diag(TTP->getDefaultArgument().getLocation(),
5995 diag::err_default_arg_in_partial_spec)
5996 << TTP->getDefaultArgument().getSourceRange();
5997 TTP->removeDefaultArgument();
6001 } else if (TemplateParams) {
6002 if (TUK == TUK_Friend)
6003 Diag(KWLoc, diag::err_template_spec_friend)
6004 << FixItHint::CreateRemoval(
6005 SourceRange(TemplateParams->getTemplateLoc(),
6006 TemplateParams->getRAngleLoc()))
6007 << SourceRange(LAngleLoc, RAngleLoc);
6009 isExplicitSpecialization = true;
6011 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
6014 // Check that the specialization uses the same tag kind as the
6015 // original template.
6016 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6017 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
6018 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
6019 Kind, TUK == TUK_Definition, KWLoc,
6020 *ClassTemplate->getIdentifier())) {
6021 Diag(KWLoc, diag::err_use_with_wrong_tag)
6023 << FixItHint::CreateReplacement(KWLoc,
6024 ClassTemplate->getTemplatedDecl()->getKindName());
6025 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
6026 diag::note_previous_use);
6027 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
6030 // Translate the parser's template argument list in our AST format.
6031 TemplateArgumentListInfo TemplateArgs =
6032 makeTemplateArgumentListInfo(*this, TemplateId);
6034 // Check for unexpanded parameter packs in any of the template arguments.
6035 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6036 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
6037 UPPC_PartialSpecialization))
6040 // Check that the template argument list is well-formed for this
6042 SmallVector<TemplateArgument, 4> Converted;
6043 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
6044 TemplateArgs, false, Converted))
6047 // Find the class template (partial) specialization declaration that
6048 // corresponds to these arguments.
6049 if (isPartialSpecialization) {
6050 if (CheckTemplatePartialSpecializationArgs(
6051 *this, TemplateNameLoc, ClassTemplate->getTemplateParameters(),
6052 TemplateArgs.size(), Converted))
6055 bool InstantiationDependent;
6056 if (!Name.isDependent() &&
6057 !TemplateSpecializationType::anyDependentTemplateArguments(
6058 TemplateArgs.getArgumentArray(),
6059 TemplateArgs.size(),
6060 InstantiationDependent)) {
6061 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
6062 << ClassTemplate->getDeclName();
6063 isPartialSpecialization = false;
6067 void *InsertPos = nullptr;
6068 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
6070 if (isPartialSpecialization)
6071 // FIXME: Template parameter list matters, too
6072 PrevDecl = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
6074 PrevDecl = ClassTemplate->findSpecialization(Converted, InsertPos);
6076 ClassTemplateSpecializationDecl *Specialization = nullptr;
6078 // Check whether we can declare a class template specialization in
6079 // the current scope.
6080 if (TUK != TUK_Friend &&
6081 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
6083 isPartialSpecialization))
6086 // The canonical type
6088 if (isPartialSpecialization) {
6089 // Build the canonical type that describes the converted template
6090 // arguments of the class template partial specialization.
6091 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
6092 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
6096 if (Context.hasSameType(CanonType,
6097 ClassTemplate->getInjectedClassNameSpecialization())) {
6098 // C++ [temp.class.spec]p9b3:
6100 // -- The argument list of the specialization shall not be identical
6101 // to the implicit argument list of the primary template.
6102 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
6103 << /*class template*/0 << (TUK == TUK_Definition)
6104 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
6105 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
6106 ClassTemplate->getIdentifier(),
6110 AS_none, /*ModulePrivateLoc=*/SourceLocation(),
6111 /*FriendLoc*/SourceLocation(),
6112 TemplateParameterLists.size() - 1,
6113 TemplateParameterLists.data());
6116 // Create a new class template partial specialization declaration node.
6117 ClassTemplatePartialSpecializationDecl *PrevPartial
6118 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
6119 ClassTemplatePartialSpecializationDecl *Partial
6120 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
6121 ClassTemplate->getDeclContext(),
6122 KWLoc, TemplateNameLoc,
6130 SetNestedNameSpecifier(Partial, SS);
6131 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
6132 Partial->setTemplateParameterListsInfo(Context,
6133 TemplateParameterLists.size() - 1,
6134 TemplateParameterLists.data());
6138 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
6139 Specialization = Partial;
6141 // If we are providing an explicit specialization of a member class
6142 // template specialization, make a note of that.
6143 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
6144 PrevPartial->setMemberSpecialization();
6146 // Check that all of the template parameters of the class template
6147 // partial specialization are deducible from the template
6148 // arguments. If not, this class template partial specialization
6149 // will never be used.
6150 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
6151 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
6152 TemplateParams->getDepth(),
6155 if (!DeducibleParams.all()) {
6156 unsigned NumNonDeducible = DeducibleParams.size()-DeducibleParams.count();
6157 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
6158 << /*class template*/0 << (NumNonDeducible > 1)
6159 << SourceRange(TemplateNameLoc, RAngleLoc);
6160 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
6161 if (!DeducibleParams[I]) {
6162 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
6163 if (Param->getDeclName())
6164 Diag(Param->getLocation(),
6165 diag::note_partial_spec_unused_parameter)
6166 << Param->getDeclName();
6168 Diag(Param->getLocation(),
6169 diag::note_partial_spec_unused_parameter)
6175 // Create a new class template specialization declaration node for
6176 // this explicit specialization or friend declaration.
6178 = ClassTemplateSpecializationDecl::Create(Context, Kind,
6179 ClassTemplate->getDeclContext(),
6180 KWLoc, TemplateNameLoc,
6185 SetNestedNameSpecifier(Specialization, SS);
6186 if (TemplateParameterLists.size() > 0) {
6187 Specialization->setTemplateParameterListsInfo(Context,
6188 TemplateParameterLists.size(),
6189 TemplateParameterLists.data());
6193 ClassTemplate->AddSpecialization(Specialization, InsertPos);
6195 CanonType = Context.getTypeDeclType(Specialization);
6198 // C++ [temp.expl.spec]p6:
6199 // If a template, a member template or the member of a class template is
6200 // explicitly specialized then that specialization shall be declared
6201 // before the first use of that specialization that would cause an implicit
6202 // instantiation to take place, in every translation unit in which such a
6203 // use occurs; no diagnostic is required.
6204 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
6206 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6207 // Is there any previous explicit specialization declaration?
6208 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6215 SourceRange Range(TemplateNameLoc, RAngleLoc);
6216 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
6217 << Context.getTypeDeclType(Specialization) << Range;
6219 Diag(PrevDecl->getPointOfInstantiation(),
6220 diag::note_instantiation_required_here)
6221 << (PrevDecl->getTemplateSpecializationKind()
6222 != TSK_ImplicitInstantiation);
6227 // If this is not a friend, note that this is an explicit specialization.
6228 if (TUK != TUK_Friend)
6229 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
6231 // Check that this isn't a redefinition of this specialization.
6232 if (TUK == TUK_Definition) {
6233 if (RecordDecl *Def = Specialization->getDefinition()) {
6234 SourceRange Range(TemplateNameLoc, RAngleLoc);
6235 Diag(TemplateNameLoc, diag::err_redefinition)
6236 << Context.getTypeDeclType(Specialization) << Range;
6237 Diag(Def->getLocation(), diag::note_previous_definition);
6238 Specialization->setInvalidDecl();
6244 ProcessDeclAttributeList(S, Specialization, Attr);
6246 // Add alignment attributes if necessary; these attributes are checked when
6247 // the ASTContext lays out the structure.
6248 if (TUK == TUK_Definition) {
6249 AddAlignmentAttributesForRecord(Specialization);
6250 AddMsStructLayoutForRecord(Specialization);
6253 if (ModulePrivateLoc.isValid())
6254 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
6255 << (isPartialSpecialization? 1 : 0)
6256 << FixItHint::CreateRemoval(ModulePrivateLoc);
6258 // Build the fully-sugared type for this class template
6259 // specialization as the user wrote in the specialization
6260 // itself. This means that we'll pretty-print the type retrieved
6261 // from the specialization's declaration the way that the user
6262 // actually wrote the specialization, rather than formatting the
6263 // name based on the "canonical" representation used to store the
6264 // template arguments in the specialization.
6265 TypeSourceInfo *WrittenTy
6266 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
6267 TemplateArgs, CanonType);
6268 if (TUK != TUK_Friend) {
6269 Specialization->setTypeAsWritten(WrittenTy);
6270 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
6273 // C++ [temp.expl.spec]p9:
6274 // A template explicit specialization is in the scope of the
6275 // namespace in which the template was defined.
6277 // We actually implement this paragraph where we set the semantic
6278 // context (in the creation of the ClassTemplateSpecializationDecl),
6279 // but we also maintain the lexical context where the actual
6280 // definition occurs.
6281 Specialization->setLexicalDeclContext(CurContext);
6283 // We may be starting the definition of this specialization.
6284 if (TUK == TUK_Definition)
6285 Specialization->startDefinition();
6287 if (TUK == TUK_Friend) {
6288 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
6292 Friend->setAccess(AS_public);
6293 CurContext->addDecl(Friend);
6295 // Add the specialization into its lexical context, so that it can
6296 // be seen when iterating through the list of declarations in that
6297 // context. However, specializations are not found by name lookup.
6298 CurContext->addDecl(Specialization);
6300 return Specialization;
6303 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
6304 MultiTemplateParamsArg TemplateParameterLists,
6306 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
6307 ActOnDocumentableDecl(NewDecl);
6311 Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
6312 MultiTemplateParamsArg TemplateParameterLists,
6314 assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
6315 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
6317 if (FTI.hasPrototype) {
6318 // FIXME: Diagnose arguments without names in C.
6321 Scope *ParentScope = FnBodyScope->getParent();
6323 D.setFunctionDefinitionKind(FDK_Definition);
6324 Decl *DP = HandleDeclarator(ParentScope, D,
6325 TemplateParameterLists);
6326 return ActOnStartOfFunctionDef(FnBodyScope, DP);
6329 /// \brief Strips various properties off an implicit instantiation
6330 /// that has just been explicitly specialized.
6331 static void StripImplicitInstantiation(NamedDecl *D) {
6334 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6335 FD->setInlineSpecified(false);
6337 for (auto I : FD->params())
6342 /// \brief Compute the diagnostic location for an explicit instantiation
6343 // declaration or definition.
6344 static SourceLocation DiagLocForExplicitInstantiation(
6345 NamedDecl* D, SourceLocation PointOfInstantiation) {
6346 // Explicit instantiations following a specialization have no effect and
6347 // hence no PointOfInstantiation. In that case, walk decl backwards
6348 // until a valid name loc is found.
6349 SourceLocation PrevDiagLoc = PointOfInstantiation;
6350 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
6351 Prev = Prev->getPreviousDecl()) {
6352 PrevDiagLoc = Prev->getLocation();
6354 assert(PrevDiagLoc.isValid() &&
6355 "Explicit instantiation without point of instantiation?");
6359 /// \brief Diagnose cases where we have an explicit template specialization
6360 /// before/after an explicit template instantiation, producing diagnostics
6361 /// for those cases where they are required and determining whether the
6362 /// new specialization/instantiation will have any effect.
6364 /// \param NewLoc the location of the new explicit specialization or
6367 /// \param NewTSK the kind of the new explicit specialization or instantiation.
6369 /// \param PrevDecl the previous declaration of the entity.
6371 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
6373 /// \param PrevPointOfInstantiation if valid, indicates where the previus
6374 /// declaration was instantiated (either implicitly or explicitly).
6376 /// \param HasNoEffect will be set to true to indicate that the new
6377 /// specialization or instantiation has no effect and should be ignored.
6379 /// \returns true if there was an error that should prevent the introduction of
6380 /// the new declaration into the AST, false otherwise.
6382 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
6383 TemplateSpecializationKind NewTSK,
6384 NamedDecl *PrevDecl,
6385 TemplateSpecializationKind PrevTSK,
6386 SourceLocation PrevPointOfInstantiation,
6387 bool &HasNoEffect) {
6388 HasNoEffect = false;
6391 case TSK_Undeclared:
6392 case TSK_ImplicitInstantiation:
6394 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
6395 "previous declaration must be implicit!");
6398 case TSK_ExplicitSpecialization:
6400 case TSK_Undeclared:
6401 case TSK_ExplicitSpecialization:
6402 // Okay, we're just specializing something that is either already
6403 // explicitly specialized or has merely been mentioned without any
6407 case TSK_ImplicitInstantiation:
6408 if (PrevPointOfInstantiation.isInvalid()) {
6409 // The declaration itself has not actually been instantiated, so it is
6410 // still okay to specialize it.
6411 StripImplicitInstantiation(PrevDecl);
6416 case TSK_ExplicitInstantiationDeclaration:
6417 case TSK_ExplicitInstantiationDefinition:
6418 assert((PrevTSK == TSK_ImplicitInstantiation ||
6419 PrevPointOfInstantiation.isValid()) &&
6420 "Explicit instantiation without point of instantiation?");
6422 // C++ [temp.expl.spec]p6:
6423 // If a template, a member template or the member of a class template
6424 // is explicitly specialized then that specialization shall be declared
6425 // before the first use of that specialization that would cause an
6426 // implicit instantiation to take place, in every translation unit in
6427 // which such a use occurs; no diagnostic is required.
6428 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6429 // Is there any previous explicit specialization declaration?
6430 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
6434 Diag(NewLoc, diag::err_specialization_after_instantiation)
6436 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
6437 << (PrevTSK != TSK_ImplicitInstantiation);
6442 case TSK_ExplicitInstantiationDeclaration:
6444 case TSK_ExplicitInstantiationDeclaration:
6445 // This explicit instantiation declaration is redundant (that's okay).
6449 case TSK_Undeclared:
6450 case TSK_ImplicitInstantiation:
6451 // We're explicitly instantiating something that may have already been
6452 // implicitly instantiated; that's fine.
6455 case TSK_ExplicitSpecialization:
6456 // C++0x [temp.explicit]p4:
6457 // For a given set of template parameters, if an explicit instantiation
6458 // of a template appears after a declaration of an explicit
6459 // specialization for that template, the explicit instantiation has no
6464 case TSK_ExplicitInstantiationDefinition:
6465 // C++0x [temp.explicit]p10:
6466 // If an entity is the subject of both an explicit instantiation
6467 // declaration and an explicit instantiation definition in the same
6468 // translation unit, the definition shall follow the declaration.
6470 diag::err_explicit_instantiation_declaration_after_definition);
6472 // Explicit instantiations following a specialization have no effect and
6473 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
6474 // until a valid name loc is found.
6475 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6476 diag::note_explicit_instantiation_definition_here);
6481 case TSK_ExplicitInstantiationDefinition:
6483 case TSK_Undeclared:
6484 case TSK_ImplicitInstantiation:
6485 // We're explicitly instantiating something that may have already been
6486 // implicitly instantiated; that's fine.
6489 case TSK_ExplicitSpecialization:
6490 // C++ DR 259, C++0x [temp.explicit]p4:
6491 // For a given set of template parameters, if an explicit
6492 // instantiation of a template appears after a declaration of
6493 // an explicit specialization for that template, the explicit
6494 // instantiation has no effect.
6496 // In C++98/03 mode, we only give an extension warning here, because it
6497 // is not harmful to try to explicitly instantiate something that
6498 // has been explicitly specialized.
6499 Diag(NewLoc, getLangOpts().CPlusPlus11 ?
6500 diag::warn_cxx98_compat_explicit_instantiation_after_specialization :
6501 diag::ext_explicit_instantiation_after_specialization)
6503 Diag(PrevDecl->getLocation(),
6504 diag::note_previous_template_specialization);
6508 case TSK_ExplicitInstantiationDeclaration:
6509 // We're explicity instantiating a definition for something for which we
6510 // were previously asked to suppress instantiations. That's fine.
6512 // C++0x [temp.explicit]p4:
6513 // For a given set of template parameters, if an explicit instantiation
6514 // of a template appears after a declaration of an explicit
6515 // specialization for that template, the explicit instantiation has no
6517 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
6518 // Is there any previous explicit specialization declaration?
6519 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
6527 case TSK_ExplicitInstantiationDefinition:
6528 // C++0x [temp.spec]p5:
6529 // For a given template and a given set of template-arguments,
6530 // - an explicit instantiation definition shall appear at most once
6533 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
6534 Diag(NewLoc, (getLangOpts().MSVCCompat)
6535 ? diag::ext_explicit_instantiation_duplicate
6536 : diag::err_explicit_instantiation_duplicate)
6538 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
6539 diag::note_previous_explicit_instantiation);
6545 llvm_unreachable("Missing specialization/instantiation case?");
6548 /// \brief Perform semantic analysis for the given dependent function
6549 /// template specialization.
6551 /// The only possible way to get a dependent function template specialization
6552 /// is with a friend declaration, like so:
6555 /// template \<class T> void foo(T);
6556 /// template \<class T> class A {
6557 /// friend void foo<>(T);
6561 /// There really isn't any useful analysis we can do here, so we
6562 /// just store the information.
6564 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
6565 const TemplateArgumentListInfo &ExplicitTemplateArgs,
6566 LookupResult &Previous) {
6567 // Remove anything from Previous that isn't a function template in
6568 // the correct context.
6569 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6570 LookupResult::Filter F = Previous.makeFilter();
6571 while (F.hasNext()) {
6572 NamedDecl *D = F.next()->getUnderlyingDecl();
6573 if (!isa<FunctionTemplateDecl>(D) ||
6574 !FDLookupContext->InEnclosingNamespaceSetOf(
6575 D->getDeclContext()->getRedeclContext()))
6580 // Should this be diagnosed here?
6581 if (Previous.empty()) return true;
6583 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
6584 ExplicitTemplateArgs);
6588 /// \brief Perform semantic analysis for the given function template
6591 /// This routine performs all of the semantic analysis required for an
6592 /// explicit function template specialization. On successful completion,
6593 /// the function declaration \p FD will become a function template
6596 /// \param FD the function declaration, which will be updated to become a
6597 /// function template specialization.
6599 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
6600 /// if any. Note that this may be valid info even when 0 arguments are
6601 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
6602 /// as it anyway contains info on the angle brackets locations.
6604 /// \param Previous the set of declarations that may be specialized by
6605 /// this function specialization.
6606 bool Sema::CheckFunctionTemplateSpecialization(
6607 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
6608 LookupResult &Previous) {
6609 // The set of function template specializations that could match this
6610 // explicit function template specialization.
6611 UnresolvedSet<8> Candidates;
6612 TemplateSpecCandidateSet FailedCandidates(FD->getLocation());
6614 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
6615 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6617 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
6618 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
6619 // Only consider templates found within the same semantic lookup scope as
6621 if (!FDLookupContext->InEnclosingNamespaceSetOf(
6622 Ovl->getDeclContext()->getRedeclContext()))
6625 // When matching a constexpr member function template specialization
6626 // against the primary template, we don't yet know whether the
6627 // specialization has an implicit 'const' (because we don't know whether
6628 // it will be a static member function until we know which template it
6629 // specializes), so adjust it now assuming it specializes this template.
6630 QualType FT = FD->getType();
6631 if (FD->isConstexpr()) {
6632 CXXMethodDecl *OldMD =
6633 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
6634 if (OldMD && OldMD->isConst()) {
6635 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
6636 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6637 EPI.TypeQuals |= Qualifiers::Const;
6638 FT = Context.getFunctionType(FPT->getReturnType(),
6639 FPT->getParamTypes(), EPI);
6643 // C++ [temp.expl.spec]p11:
6644 // A trailing template-argument can be left unspecified in the
6645 // template-id naming an explicit function template specialization
6646 // provided it can be deduced from the function argument type.
6647 // Perform template argument deduction to determine whether we may be
6648 // specializing this template.
6649 // FIXME: It is somewhat wasteful to build
6650 TemplateDeductionInfo Info(FailedCandidates.getLocation());
6651 FunctionDecl *Specialization = nullptr;
6652 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
6653 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
6654 ExplicitTemplateArgs, FT, Specialization, Info)) {
6655 // Template argument deduction failed; record why it failed, so
6656 // that we can provide nifty diagnostics.
6657 FailedCandidates.addCandidate()
6658 .set(FunTmpl->getTemplatedDecl(),
6659 MakeDeductionFailureInfo(Context, TDK, Info));
6664 // Record this candidate.
6665 Candidates.addDecl(Specialization, I.getAccess());
6669 // Find the most specialized function template.
6670 UnresolvedSetIterator Result = getMostSpecialized(
6671 Candidates.begin(), Candidates.end(), FailedCandidates,
6673 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
6674 PDiag(diag::err_function_template_spec_ambiguous)
6675 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
6676 PDiag(diag::note_function_template_spec_matched));
6678 if (Result == Candidates.end())
6681 // Ignore access information; it doesn't figure into redeclaration checking.
6682 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
6684 FunctionTemplateSpecializationInfo *SpecInfo
6685 = Specialization->getTemplateSpecializationInfo();
6686 assert(SpecInfo && "Function template specialization info missing?");
6688 // Note: do not overwrite location info if previous template
6689 // specialization kind was explicit.
6690 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
6691 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
6692 Specialization->setLocation(FD->getLocation());
6693 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
6694 // function can differ from the template declaration with respect to
6695 // the constexpr specifier.
6696 Specialization->setConstexpr(FD->isConstexpr());
6699 // FIXME: Check if the prior specialization has a point of instantiation.
6700 // If so, we have run afoul of .
6702 // If this is a friend declaration, then we're not really declaring
6703 // an explicit specialization.
6704 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
6706 // Check the scope of this explicit specialization.
6708 CheckTemplateSpecializationScope(*this,
6709 Specialization->getPrimaryTemplate(),
6710 Specialization, FD->getLocation(),
6714 // C++ [temp.expl.spec]p6:
6715 // If a template, a member template or the member of a class template is
6716 // explicitly specialized then that specialization shall be declared
6717 // before the first use of that specialization that would cause an implicit
6718 // instantiation to take place, in every translation unit in which such a
6719 // use occurs; no diagnostic is required.
6720 bool HasNoEffect = false;
6722 CheckSpecializationInstantiationRedecl(FD->getLocation(),
6723 TSK_ExplicitSpecialization,
6725 SpecInfo->getTemplateSpecializationKind(),
6726 SpecInfo->getPointOfInstantiation(),
6730 // Mark the prior declaration as an explicit specialization, so that later
6731 // clients know that this is an explicit specialization.
6733 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
6734 MarkUnusedFileScopedDecl(Specialization);
6737 // Turn the given function declaration into a function template
6738 // specialization, with the template arguments from the previous
6740 // Take copies of (semantic and syntactic) template argument lists.
6741 const TemplateArgumentList* TemplArgs = new (Context)
6742 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
6743 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
6744 TemplArgs, /*InsertPos=*/nullptr,
6745 SpecInfo->getTemplateSpecializationKind(),
6746 ExplicitTemplateArgs);
6748 // The "previous declaration" for this function template specialization is
6749 // the prior function template specialization.
6751 Previous.addDecl(Specialization);
6755 /// \brief Perform semantic analysis for the given non-template member
6758 /// This routine performs all of the semantic analysis required for an
6759 /// explicit member function specialization. On successful completion,
6760 /// the function declaration \p FD will become a member function
6763 /// \param Member the member declaration, which will be updated to become a
6766 /// \param Previous the set of declarations, one of which may be specialized
6767 /// by this function specialization; the set will be modified to contain the
6768 /// redeclared member.
6770 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
6771 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
6773 // Try to find the member we are instantiating.
6774 NamedDecl *Instantiation = nullptr;
6775 NamedDecl *InstantiatedFrom = nullptr;
6776 MemberSpecializationInfo *MSInfo = nullptr;
6778 if (Previous.empty()) {
6779 // Nowhere to look anyway.
6780 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
6781 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6783 NamedDecl *D = (*I)->getUnderlyingDecl();
6784 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
6785 QualType Adjusted = Function->getType();
6786 if (!hasExplicitCallingConv(Adjusted))
6787 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());
6788 if (Context.hasSameType(Adjusted, Method->getType())) {
6789 Instantiation = Method;
6790 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
6791 MSInfo = Method->getMemberSpecializationInfo();
6796 } else if (isa<VarDecl>(Member)) {
6798 if (Previous.isSingleResult() &&
6799 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
6800 if (PrevVar->isStaticDataMember()) {
6801 Instantiation = PrevVar;
6802 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
6803 MSInfo = PrevVar->getMemberSpecializationInfo();
6805 } else if (isa<RecordDecl>(Member)) {
6806 CXXRecordDecl *PrevRecord;
6807 if (Previous.isSingleResult() &&
6808 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
6809 Instantiation = PrevRecord;
6810 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
6811 MSInfo = PrevRecord->getMemberSpecializationInfo();
6813 } else if (isa<EnumDecl>(Member)) {
6815 if (Previous.isSingleResult() &&
6816 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {
6817 Instantiation = PrevEnum;
6818 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
6819 MSInfo = PrevEnum->getMemberSpecializationInfo();
6823 if (!Instantiation) {
6824 // There is no previous declaration that matches. Since member
6825 // specializations are always out-of-line, the caller will complain about
6826 // this mismatch later.
6830 // If this is a friend, just bail out here before we start turning
6831 // things into explicit specializations.
6832 if (Member->getFriendObjectKind() != Decl::FOK_None) {
6833 // Preserve instantiation information.
6834 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
6835 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
6836 cast<CXXMethodDecl>(InstantiatedFrom),
6837 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
6838 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
6839 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6840 cast<CXXRecordDecl>(InstantiatedFrom),
6841 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
6845 Previous.addDecl(Instantiation);
6849 // Make sure that this is a specialization of a member.
6850 if (!InstantiatedFrom) {
6851 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
6853 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
6857 // C++ [temp.expl.spec]p6:
6858 // If a template, a member template or the member of a class template is
6859 // explicitly specialized then that specialization shall be declared
6860 // before the first use of that specialization that would cause an implicit
6861 // instantiation to take place, in every translation unit in which such a
6862 // use occurs; no diagnostic is required.
6863 assert(MSInfo && "Member specialization info missing?");
6865 bool HasNoEffect = false;
6866 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
6867 TSK_ExplicitSpecialization,
6869 MSInfo->getTemplateSpecializationKind(),
6870 MSInfo->getPointOfInstantiation(),
6874 // Check the scope of this explicit specialization.
6875 if (CheckTemplateSpecializationScope(*this,
6877 Instantiation, Member->getLocation(),
6881 // Note that this is an explicit instantiation of a member.
6882 // the original declaration to note that it is an explicit specialization
6883 // (if it was previously an implicit instantiation). This latter step
6884 // makes bookkeeping easier.
6885 if (isa<FunctionDecl>(Member)) {
6886 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
6887 if (InstantiationFunction->getTemplateSpecializationKind() ==
6888 TSK_ImplicitInstantiation) {
6889 InstantiationFunction->setTemplateSpecializationKind(
6890 TSK_ExplicitSpecialization);
6891 InstantiationFunction->setLocation(Member->getLocation());
6894 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
6895 cast<CXXMethodDecl>(InstantiatedFrom),
6896 TSK_ExplicitSpecialization);
6897 MarkUnusedFileScopedDecl(InstantiationFunction);
6898 } else if (isa<VarDecl>(Member)) {
6899 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
6900 if (InstantiationVar->getTemplateSpecializationKind() ==
6901 TSK_ImplicitInstantiation) {
6902 InstantiationVar->setTemplateSpecializationKind(
6903 TSK_ExplicitSpecialization);
6904 InstantiationVar->setLocation(Member->getLocation());
6907 cast<VarDecl>(Member)->setInstantiationOfStaticDataMember(
6908 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
6909 MarkUnusedFileScopedDecl(InstantiationVar);
6910 } else if (isa<CXXRecordDecl>(Member)) {
6911 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
6912 if (InstantiationClass->getTemplateSpecializationKind() ==
6913 TSK_ImplicitInstantiation) {
6914 InstantiationClass->setTemplateSpecializationKind(
6915 TSK_ExplicitSpecialization);
6916 InstantiationClass->setLocation(Member->getLocation());
6919 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
6920 cast<CXXRecordDecl>(InstantiatedFrom),
6921 TSK_ExplicitSpecialization);
6923 assert(isa<EnumDecl>(Member) && "Only member enums remain");
6924 EnumDecl *InstantiationEnum = cast<EnumDecl>(Instantiation);
6925 if (InstantiationEnum->getTemplateSpecializationKind() ==
6926 TSK_ImplicitInstantiation) {
6927 InstantiationEnum->setTemplateSpecializationKind(
6928 TSK_ExplicitSpecialization);
6929 InstantiationEnum->setLocation(Member->getLocation());
6932 cast<EnumDecl>(Member)->setInstantiationOfMemberEnum(
6933 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);
6936 // Save the caller the trouble of having to figure out which declaration
6937 // this specialization matches.
6939 Previous.addDecl(Instantiation);
6943 /// \brief Check the scope of an explicit instantiation.
6945 /// \returns true if a serious error occurs, false otherwise.
6946 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
6947 SourceLocation InstLoc,
6948 bool WasQualifiedName) {
6949 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
6950 DeclContext *CurContext = S.CurContext->getRedeclContext();
6952 if (CurContext->isRecord()) {
6953 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
6958 // C++11 [temp.explicit]p3:
6959 // An explicit instantiation shall appear in an enclosing namespace of its
6960 // template. If the name declared in the explicit instantiation is an
6961 // unqualified name, the explicit instantiation shall appear in the
6962 // namespace where its template is declared or, if that namespace is inline
6963 // (7.3.1), any namespace from its enclosing namespace set.
6965 // This is DR275, which we do not retroactively apply to C++98/03.
6966 if (WasQualifiedName) {
6967 if (CurContext->Encloses(OrigContext))
6970 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
6974 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {
6975 if (WasQualifiedName)
6977 S.getLangOpts().CPlusPlus11?
6978 diag::err_explicit_instantiation_out_of_scope :
6979 diag::warn_explicit_instantiation_out_of_scope_0x)
6983 S.getLangOpts().CPlusPlus11?
6984 diag::err_explicit_instantiation_unqualified_wrong_namespace :
6985 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
6989 S.getLangOpts().CPlusPlus11?
6990 diag::err_explicit_instantiation_must_be_global :
6991 diag::warn_explicit_instantiation_must_be_global_0x)
6993 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
6997 /// \brief Determine whether the given scope specifier has a template-id in it.
6998 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
7002 // C++11 [temp.explicit]p3:
7003 // If the explicit instantiation is for a member function, a member class
7004 // or a static data member of a class template specialization, the name of
7005 // the class template specialization in the qualified-id for the member
7006 // name shall be a simple-template-id.
7008 // C++98 has the same restriction, just worded differently.
7009 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
7010 NNS = NNS->getPrefix())
7011 if (const Type *T = NNS->getAsType())
7012 if (isa<TemplateSpecializationType>(T))
7018 // Explicit instantiation of a class template specialization
7020 Sema::ActOnExplicitInstantiation(Scope *S,
7021 SourceLocation ExternLoc,
7022 SourceLocation TemplateLoc,
7024 SourceLocation KWLoc,
7025 const CXXScopeSpec &SS,
7026 TemplateTy TemplateD,
7027 SourceLocation TemplateNameLoc,
7028 SourceLocation LAngleLoc,
7029 ASTTemplateArgsPtr TemplateArgsIn,
7030 SourceLocation RAngleLoc,
7031 AttributeList *Attr) {
7032 // Find the class template we're specializing
7033 TemplateName Name = TemplateD.get();
7034 TemplateDecl *TD = Name.getAsTemplateDecl();
7035 // Check that the specialization uses the same tag kind as the
7036 // original template.
7037 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7038 assert(Kind != TTK_Enum &&
7039 "Invalid enum tag in class template explicit instantiation!");
7041 if (isa<TypeAliasTemplateDecl>(TD)) {
7042 Diag(KWLoc, diag::err_tag_reference_non_tag) << Kind;
7043 Diag(TD->getTemplatedDecl()->getLocation(),
7044 diag::note_previous_use);
7048 ClassTemplateDecl *ClassTemplate = cast<ClassTemplateDecl>(TD);
7050 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
7051 Kind, /*isDefinition*/false, KWLoc,
7052 *ClassTemplate->getIdentifier())) {
7053 Diag(KWLoc, diag::err_use_with_wrong_tag)
7055 << FixItHint::CreateReplacement(KWLoc,
7056 ClassTemplate->getTemplatedDecl()->getKindName());
7057 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
7058 diag::note_previous_use);
7059 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
7062 // C++0x [temp.explicit]p2:
7063 // There are two forms of explicit instantiation: an explicit instantiation
7064 // definition and an explicit instantiation declaration. An explicit
7065 // instantiation declaration begins with the extern keyword. [...]
7066 TemplateSpecializationKind TSK
7067 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7068 : TSK_ExplicitInstantiationDeclaration;
7070 // Translate the parser's template argument list in our AST format.
7071 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7072 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7074 // Check that the template argument list is well-formed for this
7076 SmallVector<TemplateArgument, 4> Converted;
7077 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
7078 TemplateArgs, false, Converted))
7081 // Find the class template specialization declaration that
7082 // corresponds to these arguments.
7083 void *InsertPos = nullptr;
7084 ClassTemplateSpecializationDecl *PrevDecl
7085 = ClassTemplate->findSpecialization(Converted, InsertPos);
7087 TemplateSpecializationKind PrevDecl_TSK
7088 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
7090 // C++0x [temp.explicit]p2:
7091 // [...] An explicit instantiation shall appear in an enclosing
7092 // namespace of its template. [...]
7094 // This is C++ DR 275.
7095 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
7099 ClassTemplateSpecializationDecl *Specialization = nullptr;
7101 bool HasNoEffect = false;
7103 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
7104 PrevDecl, PrevDecl_TSK,
7105 PrevDecl->getPointOfInstantiation(),
7109 // Even though HasNoEffect == true means that this explicit instantiation
7110 // has no effect on semantics, we go on to put its syntax in the AST.
7112 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
7113 PrevDecl_TSK == TSK_Undeclared) {
7114 // Since the only prior class template specialization with these
7115 // arguments was referenced but not declared, reuse that
7116 // declaration node as our own, updating the source location
7117 // for the template name to reflect our new declaration.
7118 // (Other source locations will be updated later.)
7119 Specialization = PrevDecl;
7120 Specialization->setLocation(TemplateNameLoc);
7125 if (!Specialization) {
7126 // Create a new class template specialization declaration node for
7127 // this explicit specialization.
7129 = ClassTemplateSpecializationDecl::Create(Context, Kind,
7130 ClassTemplate->getDeclContext(),
7131 KWLoc, TemplateNameLoc,
7136 SetNestedNameSpecifier(Specialization, SS);
7138 if (!HasNoEffect && !PrevDecl) {
7139 // Insert the new specialization.
7140 ClassTemplate->AddSpecialization(Specialization, InsertPos);
7144 // Build the fully-sugared type for this explicit instantiation as
7145 // the user wrote in the explicit instantiation itself. This means
7146 // that we'll pretty-print the type retrieved from the
7147 // specialization's declaration the way that the user actually wrote
7148 // the explicit instantiation, rather than formatting the name based
7149 // on the "canonical" representation used to store the template
7150 // arguments in the specialization.
7151 TypeSourceInfo *WrittenTy
7152 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
7154 Context.getTypeDeclType(Specialization));
7155 Specialization->setTypeAsWritten(WrittenTy);
7157 // Set source locations for keywords.
7158 Specialization->setExternLoc(ExternLoc);
7159 Specialization->setTemplateKeywordLoc(TemplateLoc);
7160 Specialization->setRBraceLoc(SourceLocation());
7163 ProcessDeclAttributeList(S, Specialization, Attr);
7165 // Add the explicit instantiation into its lexical context. However,
7166 // since explicit instantiations are never found by name lookup, we
7167 // just put it into the declaration context directly.
7168 Specialization->setLexicalDeclContext(CurContext);
7169 CurContext->addDecl(Specialization);
7171 // Syntax is now OK, so return if it has no other effect on semantics.
7173 // Set the template specialization kind.
7174 Specialization->setTemplateSpecializationKind(TSK);
7175 return Specialization;
7178 // C++ [temp.explicit]p3:
7179 // A definition of a class template or class member template
7180 // shall be in scope at the point of the explicit instantiation of
7181 // the class template or class member template.
7183 // This check comes when we actually try to perform the
7185 ClassTemplateSpecializationDecl *Def
7186 = cast_or_null<ClassTemplateSpecializationDecl>(
7187 Specialization->getDefinition());
7189 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
7190 else if (TSK == TSK_ExplicitInstantiationDefinition) {
7191 MarkVTableUsed(TemplateNameLoc, Specialization, true);
7192 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
7195 // Instantiate the members of this class template specialization.
7196 Def = cast_or_null<ClassTemplateSpecializationDecl>(
7197 Specialization->getDefinition());
7199 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
7201 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
7202 // TSK_ExplicitInstantiationDefinition
7203 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
7204 TSK == TSK_ExplicitInstantiationDefinition)
7205 // FIXME: Need to notify the ASTMutationListener that we did this.
7206 Def->setTemplateSpecializationKind(TSK);
7208 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
7211 // Set the template specialization kind.
7212 Specialization->setTemplateSpecializationKind(TSK);
7213 return Specialization;
7216 // Explicit instantiation of a member class of a class template.
7218 Sema::ActOnExplicitInstantiation(Scope *S,
7219 SourceLocation ExternLoc,
7220 SourceLocation TemplateLoc,
7222 SourceLocation KWLoc,
7224 IdentifierInfo *Name,
7225 SourceLocation NameLoc,
7226 AttributeList *Attr) {
7229 bool IsDependent = false;
7230 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
7231 KWLoc, SS, Name, NameLoc, Attr, AS_none,
7232 /*ModulePrivateLoc=*/SourceLocation(),
7233 MultiTemplateParamsArg(), Owned, IsDependent,
7234 SourceLocation(), false, TypeResult(),
7235 /*IsTypeSpecifier*/false);
7236 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
7241 TagDecl *Tag = cast<TagDecl>(TagD);
7242 assert(!Tag->isEnum() && "shouldn't see enumerations here");
7244 if (Tag->isInvalidDecl())
7247 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
7248 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
7250 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
7251 << Context.getTypeDeclType(Record);
7252 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
7256 // C++0x [temp.explicit]p2:
7257 // If the explicit instantiation is for a class or member class, the
7258 // elaborated-type-specifier in the declaration shall include a
7259 // simple-template-id.
7261 // C++98 has the same restriction, just worded differently.
7262 if (!ScopeSpecifierHasTemplateId(SS))
7263 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
7264 << Record << SS.getRange();
7266 // C++0x [temp.explicit]p2:
7267 // There are two forms of explicit instantiation: an explicit instantiation
7268 // definition and an explicit instantiation declaration. An explicit
7269 // instantiation declaration begins with the extern keyword. [...]
7270 TemplateSpecializationKind TSK
7271 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7272 : TSK_ExplicitInstantiationDeclaration;
7274 // C++0x [temp.explicit]p2:
7275 // [...] An explicit instantiation shall appear in an enclosing
7276 // namespace of its template. [...]
7278 // This is C++ DR 275.
7279 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
7281 // Verify that it is okay to explicitly instantiate here.
7282 CXXRecordDecl *PrevDecl
7283 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());
7284 if (!PrevDecl && Record->getDefinition())
7287 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
7288 bool HasNoEffect = false;
7289 assert(MSInfo && "No member specialization information?");
7290 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
7292 MSInfo->getTemplateSpecializationKind(),
7293 MSInfo->getPointOfInstantiation(),
7300 CXXRecordDecl *RecordDef
7301 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7303 // C++ [temp.explicit]p3:
7304 // A definition of a member class of a class template shall be in scope
7305 // at the point of an explicit instantiation of the member class.
7307 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
7309 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
7310 << 0 << Record->getDeclName() << Record->getDeclContext();
7311 Diag(Pattern->getLocation(), diag::note_forward_declaration)
7315 if (InstantiateClass(NameLoc, Record, Def,
7316 getTemplateInstantiationArgs(Record),
7320 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
7326 // Instantiate all of the members of the class.
7327 InstantiateClassMembers(NameLoc, RecordDef,
7328 getTemplateInstantiationArgs(Record), TSK);
7330 if (TSK == TSK_ExplicitInstantiationDefinition)
7331 MarkVTableUsed(NameLoc, RecordDef, true);
7333 // FIXME: We don't have any representation for explicit instantiations of
7334 // member classes. Such a representation is not needed for compilation, but it
7335 // should be available for clients that want to see all of the declarations in
7340 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
7341 SourceLocation ExternLoc,
7342 SourceLocation TemplateLoc,
7344 // Explicit instantiations always require a name.
7345 // TODO: check if/when DNInfo should replace Name.
7346 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7347 DeclarationName Name = NameInfo.getName();
7349 if (!D.isInvalidType())
7350 Diag(D.getDeclSpec().getLocStart(),
7351 diag::err_explicit_instantiation_requires_name)
7352 << D.getDeclSpec().getSourceRange()
7353 << D.getSourceRange();
7358 // The scope passed in may not be a decl scope. Zip up the scope tree until
7359 // we find one that is.
7360 while ((S->getFlags() & Scope::DeclScope) == 0 ||
7361 (S->getFlags() & Scope::TemplateParamScope) != 0)
7364 // Determine the type of the declaration.
7365 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
7366 QualType R = T->getType();
7371 // A storage-class-specifier shall not be specified in [...] an explicit
7372 // instantiation (14.7.2) directive.
7373 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
7374 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
7377 } else if (D.getDeclSpec().getStorageClassSpec()
7378 != DeclSpec::SCS_unspecified) {
7379 // Complain about then remove the storage class specifier.
7380 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
7381 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7383 D.getMutableDeclSpec().ClearStorageClassSpecs();
7386 // C++0x [temp.explicit]p1:
7387 // [...] An explicit instantiation of a function template shall not use the
7388 // inline or constexpr specifiers.
7389 // Presumably, this also applies to member functions of class templates as
7391 if (D.getDeclSpec().isInlineSpecified())
7392 Diag(D.getDeclSpec().getInlineSpecLoc(),
7393 getLangOpts().CPlusPlus11 ?
7394 diag::err_explicit_instantiation_inline :
7395 diag::warn_explicit_instantiation_inline_0x)
7396 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7397 if (D.getDeclSpec().isConstexprSpecified() && R->isFunctionType())
7398 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
7399 // not already specified.
7400 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7401 diag::err_explicit_instantiation_constexpr);
7403 // C++0x [temp.explicit]p2:
7404 // There are two forms of explicit instantiation: an explicit instantiation
7405 // definition and an explicit instantiation declaration. An explicit
7406 // instantiation declaration begins with the extern keyword. [...]
7407 TemplateSpecializationKind TSK
7408 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
7409 : TSK_ExplicitInstantiationDeclaration;
7411 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
7412 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
7414 if (!R->isFunctionType()) {
7415 // C++ [temp.explicit]p1:
7416 // A [...] static data member of a class template can be explicitly
7417 // instantiated from the member definition associated with its class
7419 // C++1y [temp.explicit]p1:
7420 // A [...] variable [...] template specialization can be explicitly
7421 // instantiated from its template.
7422 if (Previous.isAmbiguous())
7425 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
7426 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
7428 if (!PrevTemplate) {
7429 if (!Prev || !Prev->isStaticDataMember()) {
7430 // We expect to see a data data member here.
7431 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
7433 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7435 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
7439 if (!Prev->getInstantiatedFromStaticDataMember()) {
7440 // FIXME: Check for explicit specialization?
7441 Diag(D.getIdentifierLoc(),
7442 diag::err_explicit_instantiation_data_member_not_instantiated)
7444 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
7445 // FIXME: Can we provide a note showing where this was declared?
7449 // Explicitly instantiate a variable template.
7451 // C++1y [dcl.spec.auto]p6:
7452 // ... A program that uses auto or decltype(auto) in a context not
7453 // explicitly allowed in this section is ill-formed.
7455 // This includes auto-typed variable template instantiations.
7456 if (R->isUndeducedType()) {
7457 Diag(T->getTypeLoc().getLocStart(),
7458 diag::err_auto_not_allowed_var_inst);
7462 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7463 // C++1y [temp.explicit]p3:
7464 // If the explicit instantiation is for a variable, the unqualified-id
7465 // in the declaration shall be a template-id.
7466 Diag(D.getIdentifierLoc(),
7467 diag::err_explicit_instantiation_without_template_id)
7469 Diag(PrevTemplate->getLocation(),
7470 diag::note_explicit_instantiation_here);
7474 // Translate the parser's template argument list into our AST format.
7475 TemplateArgumentListInfo TemplateArgs =
7476 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7478 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc,
7479 D.getIdentifierLoc(), TemplateArgs);
7480 if (Res.isInvalid())
7483 // Ignore access control bits, we don't need them for redeclaration
7485 Prev = cast<VarDecl>(Res.get());
7488 // C++0x [temp.explicit]p2:
7489 // If the explicit instantiation is for a member function, a member class
7490 // or a static data member of a class template specialization, the name of
7491 // the class template specialization in the qualified-id for the member
7492 // name shall be a simple-template-id.
7494 // C++98 has the same restriction, just worded differently.
7496 // This does not apply to variable template specializations, where the
7497 // template-id is in the unqualified-id instead.
7498 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
7499 Diag(D.getIdentifierLoc(),
7500 diag::ext_explicit_instantiation_without_qualified_id)
7501 << Prev << D.getCXXScopeSpec().getRange();
7503 // Check the scope of this explicit instantiation.
7504 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
7506 // Verify that it is okay to explicitly instantiate here.
7507 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
7508 SourceLocation POI = Prev->getPointOfInstantiation();
7509 bool HasNoEffect = false;
7510 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
7511 PrevTSK, POI, HasNoEffect))
7515 // Instantiate static data member or variable template.
7517 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7519 // Merge attributes.
7520 if (AttributeList *Attr = D.getDeclSpec().getAttributes().getList())
7521 ProcessDeclAttributeList(S, Prev, Attr);
7523 if (TSK == TSK_ExplicitInstantiationDefinition)
7524 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);
7527 // Check the new variable specialization against the parsed input.
7528 if (PrevTemplate && Prev && !Context.hasSameType(Prev->getType(), R)) {
7529 Diag(T->getTypeLoc().getLocStart(),
7530 diag::err_invalid_var_template_spec_type)
7531 << 0 << PrevTemplate << R << Prev->getType();
7532 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
7533 << 2 << PrevTemplate->getDeclName();
7537 // FIXME: Create an ExplicitInstantiation node?
7538 return (Decl*) nullptr;
7541 // If the declarator is a template-id, translate the parser's template
7542 // argument list into our AST format.
7543 bool HasExplicitTemplateArgs = false;
7544 TemplateArgumentListInfo TemplateArgs;
7545 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7546 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);
7547 HasExplicitTemplateArgs = true;
7550 // C++ [temp.explicit]p1:
7551 // A [...] function [...] can be explicitly instantiated from its template.
7552 // A member function [...] of a class template can be explicitly
7553 // instantiated from the member definition associated with its class
7555 UnresolvedSet<8> Matches;
7556 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
7557 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
7559 NamedDecl *Prev = *P;
7560 if (!HasExplicitTemplateArgs) {
7561 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
7562 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType());
7563 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {
7566 Matches.addDecl(Method, P.getAccess());
7567 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
7573 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
7577 TemplateDeductionInfo Info(FailedCandidates.getLocation());
7578 FunctionDecl *Specialization = nullptr;
7579 if (TemplateDeductionResult TDK
7580 = DeduceTemplateArguments(FunTmpl,
7581 (HasExplicitTemplateArgs ? &TemplateArgs
7583 R, Specialization, Info)) {
7584 // Keep track of almost-matches.
7585 FailedCandidates.addCandidate()
7586 .set(FunTmpl->getTemplatedDecl(),
7587 MakeDeductionFailureInfo(Context, TDK, Info));
7592 Matches.addDecl(Specialization, P.getAccess());
7595 // Find the most specialized function template specialization.
7596 UnresolvedSetIterator Result = getMostSpecialized(
7597 Matches.begin(), Matches.end(), FailedCandidates,
7598 D.getIdentifierLoc(),
7599 PDiag(diag::err_explicit_instantiation_not_known) << Name,
7600 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
7601 PDiag(diag::note_explicit_instantiation_candidate));
7603 if (Result == Matches.end())
7606 // Ignore access control bits, we don't need them for redeclaration checking.
7607 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
7609 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
7610 Diag(D.getIdentifierLoc(),
7611 diag::err_explicit_instantiation_member_function_not_instantiated)
7613 << (Specialization->getTemplateSpecializationKind() ==
7614 TSK_ExplicitSpecialization);
7615 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
7619 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
7620 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
7621 PrevDecl = Specialization;
7624 bool HasNoEffect = false;
7625 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
7627 PrevDecl->getTemplateSpecializationKind(),
7628 PrevDecl->getPointOfInstantiation(),
7632 // FIXME: We may still want to build some representation of this
7633 // explicit specialization.
7635 return (Decl*) nullptr;
7638 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
7639 AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
7641 ProcessDeclAttributeList(S, Specialization, Attr);
7643 if (Specialization->isDefined()) {
7644 // Let the ASTConsumer know that this function has been explicitly
7645 // instantiated now, and its linkage might have changed.
7646 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));
7647 } else if (TSK == TSK_ExplicitInstantiationDefinition)
7648 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
7650 // C++0x [temp.explicit]p2:
7651 // If the explicit instantiation is for a member function, a member class
7652 // or a static data member of a class template specialization, the name of
7653 // the class template specialization in the qualified-id for the member
7654 // name shall be a simple-template-id.
7656 // C++98 has the same restriction, just worded differently.
7657 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
7658 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
7659 D.getCXXScopeSpec().isSet() &&
7660 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
7661 Diag(D.getIdentifierLoc(),
7662 diag::ext_explicit_instantiation_without_qualified_id)
7663 << Specialization << D.getCXXScopeSpec().getRange();
7665 CheckExplicitInstantiationScope(*this,
7666 FunTmpl? (NamedDecl *)FunTmpl
7667 : Specialization->getInstantiatedFromMemberFunction(),
7668 D.getIdentifierLoc(),
7669 D.getCXXScopeSpec().isSet());
7671 // FIXME: Create some kind of ExplicitInstantiationDecl here.
7672 return (Decl*) nullptr;
7676 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
7677 const CXXScopeSpec &SS, IdentifierInfo *Name,
7678 SourceLocation TagLoc, SourceLocation NameLoc) {
7679 // This has to hold, because SS is expected to be defined.
7680 assert(Name && "Expected a name in a dependent tag");
7682 NestedNameSpecifier *NNS = SS.getScopeRep();
7686 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
7688 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
7689 Diag(NameLoc, diag::err_dependent_tag_decl)
7690 << (TUK == TUK_Definition) << Kind << SS.getRange();
7694 // Create the resulting type.
7695 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
7696 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
7698 // Create type-source location information for this type.
7700 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
7701 TL.setElaboratedKeywordLoc(TagLoc);
7702 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7703 TL.setNameLoc(NameLoc);
7704 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
7708 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
7709 const CXXScopeSpec &SS, const IdentifierInfo &II,
7710 SourceLocation IdLoc) {
7714 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7716 getLangOpts().CPlusPlus11 ?
7717 diag::warn_cxx98_compat_typename_outside_of_template :
7718 diag::ext_typename_outside_of_template)
7719 << FixItHint::CreateRemoval(TypenameLoc);
7721 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
7722 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
7723 TypenameLoc, QualifierLoc, II, IdLoc);
7727 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
7728 if (isa<DependentNameType>(T)) {
7729 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
7730 TL.setElaboratedKeywordLoc(TypenameLoc);
7731 TL.setQualifierLoc(QualifierLoc);
7732 TL.setNameLoc(IdLoc);
7734 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
7735 TL.setElaboratedKeywordLoc(TypenameLoc);
7736 TL.setQualifierLoc(QualifierLoc);
7737 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
7740 return CreateParsedType(T, TSI);
7744 Sema::ActOnTypenameType(Scope *S,
7745 SourceLocation TypenameLoc,
7746 const CXXScopeSpec &SS,
7747 SourceLocation TemplateKWLoc,
7748 TemplateTy TemplateIn,
7749 SourceLocation TemplateNameLoc,
7750 SourceLocation LAngleLoc,
7751 ASTTemplateArgsPtr TemplateArgsIn,
7752 SourceLocation RAngleLoc) {
7753 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
7755 getLangOpts().CPlusPlus11 ?
7756 diag::warn_cxx98_compat_typename_outside_of_template :
7757 diag::ext_typename_outside_of_template)
7758 << FixItHint::CreateRemoval(TypenameLoc);
7760 // Translate the parser's template argument list in our AST format.
7761 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
7762 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
7764 TemplateName Template = TemplateIn.get();
7765 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
7766 // Construct a dependent template specialization type.
7767 assert(DTN && "dependent template has non-dependent name?");
7768 assert(DTN->getQualifier() == SS.getScopeRep());
7769 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
7770 DTN->getQualifier(),
7771 DTN->getIdentifier(),
7774 // Create source-location information for this type.
7775 TypeLocBuilder Builder;
7776 DependentTemplateSpecializationTypeLoc SpecTL
7777 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
7778 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
7779 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
7780 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7781 SpecTL.setTemplateNameLoc(TemplateNameLoc);
7782 SpecTL.setLAngleLoc(LAngleLoc);
7783 SpecTL.setRAngleLoc(RAngleLoc);
7784 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7785 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7786 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
7789 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
7793 // Provide source-location information for the template specialization type.
7794 TypeLocBuilder Builder;
7795 TemplateSpecializationTypeLoc SpecTL
7796 = Builder.push<TemplateSpecializationTypeLoc>(T);
7797 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
7798 SpecTL.setTemplateNameLoc(TemplateNameLoc);
7799 SpecTL.setLAngleLoc(LAngleLoc);
7800 SpecTL.setRAngleLoc(RAngleLoc);
7801 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
7802 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
7804 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
7805 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
7806 TL.setElaboratedKeywordLoc(TypenameLoc);
7807 TL.setQualifierLoc(SS.getWithLocInContext(Context));
7809 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
7810 return CreateParsedType(T, TSI);
7814 /// Determine whether this failed name lookup should be treated as being
7815 /// disabled by a usage of std::enable_if.
7816 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
7817 SourceRange &CondRange) {
7818 // We must be looking for a ::type...
7819 if (!II.isStr("type"))
7822 // ... within an explicitly-written template specialization...
7823 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
7825 TypeLoc EnableIfTy = NNS.getTypeLoc();
7826 TemplateSpecializationTypeLoc EnableIfTSTLoc =
7827 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
7828 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
7830 const TemplateSpecializationType *EnableIfTST =
7831 cast<TemplateSpecializationType>(EnableIfTSTLoc.getTypePtr());
7833 // ... which names a complete class template declaration...
7834 const TemplateDecl *EnableIfDecl =
7835 EnableIfTST->getTemplateName().getAsTemplateDecl();
7836 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
7839 // ... called "enable_if".
7840 const IdentifierInfo *EnableIfII =
7841 EnableIfDecl->getDeclName().getAsIdentifierInfo();
7842 if (!EnableIfII || !EnableIfII->isStr("enable_if"))
7845 // Assume the first template argument is the condition.
7846 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();
7850 /// \brief Build the type that describes a C++ typename specifier,
7851 /// e.g., "typename T::type".
7853 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
7854 SourceLocation KeywordLoc,
7855 NestedNameSpecifierLoc QualifierLoc,
7856 const IdentifierInfo &II,
7857 SourceLocation IILoc) {
7859 SS.Adopt(QualifierLoc);
7861 DeclContext *Ctx = computeDeclContext(SS);
7863 // If the nested-name-specifier is dependent and couldn't be
7864 // resolved to a type, build a typename type.
7865 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
7866 return Context.getDependentNameType(Keyword,
7867 QualifierLoc.getNestedNameSpecifier(),
7871 // If the nested-name-specifier refers to the current instantiation,
7872 // the "typename" keyword itself is superfluous. In C++03, the
7873 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
7874 // allows such extraneous "typename" keywords, and we retroactively
7875 // apply this DR to C++03 code with only a warning. In any case we continue.
7877 if (RequireCompleteDeclContext(SS, Ctx))
7880 DeclarationName Name(&II);
7881 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
7882 LookupQualifiedName(Result, Ctx);
7883 unsigned DiagID = 0;
7884 Decl *Referenced = nullptr;
7885 switch (Result.getResultKind()) {
7886 case LookupResult::NotFound: {
7887 // If we're looking up 'type' within a template named 'enable_if', produce
7888 // a more specific diagnostic.
7889 SourceRange CondRange;
7890 if (isEnableIf(QualifierLoc, II, CondRange)) {
7891 Diag(CondRange.getBegin(), diag::err_typename_nested_not_found_enable_if)
7892 << Ctx << CondRange;
7896 DiagID = diag::err_typename_nested_not_found;
7900 case LookupResult::FoundUnresolvedValue: {
7901 // We found a using declaration that is a value. Most likely, the using
7902 // declaration itself is meant to have the 'typename' keyword.
7903 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
7905 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
7906 << Name << Ctx << FullRange;
7907 if (UnresolvedUsingValueDecl *Using
7908 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
7909 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
7910 Diag(Loc, diag::note_using_value_decl_missing_typename)
7911 << FixItHint::CreateInsertion(Loc, "typename ");
7914 // Fall through to create a dependent typename type, from which we can recover
7917 case LookupResult::NotFoundInCurrentInstantiation:
7918 // Okay, it's a member of an unknown instantiation.
7919 return Context.getDependentNameType(Keyword,
7920 QualifierLoc.getNestedNameSpecifier(),
7923 case LookupResult::Found:
7924 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
7925 // We found a type. Build an ElaboratedType, since the
7926 // typename-specifier was just sugar.
7927 return Context.getElaboratedType(ETK_Typename,
7928 QualifierLoc.getNestedNameSpecifier(),
7929 Context.getTypeDeclType(Type));
7932 DiagID = diag::err_typename_nested_not_type;
7933 Referenced = Result.getFoundDecl();
7936 case LookupResult::FoundOverloaded:
7937 DiagID = diag::err_typename_nested_not_type;
7938 Referenced = *Result.begin();
7941 case LookupResult::Ambiguous:
7945 // If we get here, it's because name lookup did not find a
7946 // type. Emit an appropriate diagnostic and return an error.
7947 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
7949 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
7951 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
7957 // See Sema::RebuildTypeInCurrentInstantiation
7958 class CurrentInstantiationRebuilder
7959 : public TreeTransform<CurrentInstantiationRebuilder> {
7961 DeclarationName Entity;
7964 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
7966 CurrentInstantiationRebuilder(Sema &SemaRef,
7968 DeclarationName Entity)
7969 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
7970 Loc(Loc), Entity(Entity) { }
7972 /// \brief Determine whether the given type \p T has already been
7975 /// For the purposes of type reconstruction, a type has already been
7976 /// transformed if it is NULL or if it is not dependent.
7977 bool AlreadyTransformed(QualType T) {
7978 return T.isNull() || !T->isDependentType();
7981 /// \brief Returns the location of the entity whose type is being
7983 SourceLocation getBaseLocation() { return Loc; }
7985 /// \brief Returns the name of the entity whose type is being rebuilt.
7986 DeclarationName getBaseEntity() { return Entity; }
7988 /// \brief Sets the "base" location and entity when that
7989 /// information is known based on another transformation.
7990 void setBase(SourceLocation Loc, DeclarationName Entity) {
7992 this->Entity = Entity;
7995 ExprResult TransformLambdaExpr(LambdaExpr *E) {
7996 // Lambdas never need to be transformed.
8002 /// \brief Rebuilds a type within the context of the current instantiation.
8004 /// The type \p T is part of the type of an out-of-line member definition of
8005 /// a class template (or class template partial specialization) that was parsed
8006 /// and constructed before we entered the scope of the class template (or
8007 /// partial specialization thereof). This routine will rebuild that type now
8008 /// that we have entered the declarator's scope, which may produce different
8009 /// canonical types, e.g.,
8012 /// template<typename T>
8014 /// typedef T* pointer;
8018 /// template<typename T>
8019 /// typename X<T>::pointer X<T>::data() { ... }
8022 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
8023 /// since we do not know that we can look into X<T> when we parsed the type.
8024 /// This function will rebuild the type, performing the lookup of "pointer"
8025 /// in X<T> and returning an ElaboratedType whose canonical type is the same
8026 /// as the canonical type of T*, allowing the return types of the out-of-line
8027 /// definition and the declaration to match.
8028 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8030 DeclarationName Name) {
8031 if (!T || !T->getType()->isDependentType())
8034 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
8035 return Rebuilder.TransformType(T);
8038 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
8039 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
8041 return Rebuilder.TransformExpr(E);
8044 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
8048 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
8049 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
8051 NestedNameSpecifierLoc Rebuilt
8052 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
8060 /// \brief Rebuild the template parameters now that we know we're in a current
8062 bool Sema::RebuildTemplateParamsInCurrentInstantiation(
8063 TemplateParameterList *Params) {
8064 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8065 Decl *Param = Params->getParam(I);
8067 // There is nothing to rebuild in a type parameter.
8068 if (isa<TemplateTypeParmDecl>(Param))
8071 // Rebuild the template parameter list of a template template parameter.
8072 if (TemplateTemplateParmDecl *TTP
8073 = dyn_cast<TemplateTemplateParmDecl>(Param)) {
8074 if (RebuildTemplateParamsInCurrentInstantiation(
8075 TTP->getTemplateParameters()))
8081 // Rebuild the type of a non-type template parameter.
8082 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);
8083 TypeSourceInfo *NewTSI
8084 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),
8085 NTTP->getLocation(),
8086 NTTP->getDeclName());
8090 if (NewTSI != NTTP->getTypeSourceInfo()) {
8091 NTTP->setTypeSourceInfo(NewTSI);
8092 NTTP->setType(NewTSI->getType());
8099 /// \brief Produces a formatted string that describes the binding of
8100 /// template parameters to template arguments.
8102 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8103 const TemplateArgumentList &Args) {
8104 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
8108 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8109 const TemplateArgument *Args,
8111 SmallString<128> Str;
8112 llvm::raw_svector_ostream Out(Str);
8114 if (!Params || Params->size() == 0 || NumArgs == 0)
8115 return std::string();
8117 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
8126 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
8127 Out << Id->getName();
8133 Args[I].print(getPrintingPolicy(), Out);
8140 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
8141 CachedTokens &Toks) {
8145 LateParsedTemplate *LPT = new LateParsedTemplate;
8147 // Take tokens to avoid allocations
8148 LPT->Toks.swap(Toks);
8150 LateParsedTemplateMap[FD] = LPT;
8152 FD->setLateTemplateParsed(true);
8155 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
8158 FD->setLateTemplateParsed(false);
8161 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
8162 DeclContext *DC = CurContext;
8165 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
8166 const FunctionDecl *FD = RD->isLocalClass();
8167 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
8168 } else if (DC->isTranslationUnit() || DC->isNamespace())
8171 DC = DC->getParent();