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 "clang/Sema/SemaInternal.h"
13 #include "clang/Sema/Lookup.h"
14 #include "clang/Sema/Scope.h"
15 #include "clang/Sema/Template.h"
16 #include "clang/Sema/TemplateDeduction.h"
17 #include "TreeTransform.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/DeclFriend.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/TypeVisitor.h"
25 #include "clang/Sema/DeclSpec.h"
26 #include "clang/Sema/ParsedTemplate.h"
27 #include "clang/Basic/LangOptions.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "llvm/ADT/StringExtras.h"
30 using namespace clang;
33 // Exported for use by Parser.
35 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
37 if (!N) return SourceRange();
38 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
41 /// \brief Determine whether the declaration found is acceptable as the name
42 /// of a template and, if so, return that template declaration. Otherwise,
44 static NamedDecl *isAcceptableTemplateName(ASTContext &Context,
46 NamedDecl *D = Orig->getUnderlyingDecl();
48 if (isa<TemplateDecl>(D))
51 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
52 // C++ [temp.local]p1:
53 // Like normal (non-template) classes, class templates have an
54 // injected-class-name (Clause 9). The injected-class-name
55 // can be used with or without a template-argument-list. When
56 // it is used without a template-argument-list, it is
57 // equivalent to the injected-class-name followed by the
58 // template-parameters of the class template enclosed in
59 // <>. When it is used with a template-argument-list, it
60 // refers to the specified class template specialization,
61 // which could be the current specialization or another
63 if (Record->isInjectedClassName()) {
64 Record = cast<CXXRecordDecl>(Record->getDeclContext());
65 if (Record->getDescribedClassTemplate())
66 return Record->getDescribedClassTemplate();
68 if (ClassTemplateSpecializationDecl *Spec
69 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
70 return Spec->getSpecializedTemplate();
79 void Sema::FilterAcceptableTemplateNames(LookupResult &R) {
80 // The set of class templates we've already seen.
81 llvm::SmallPtrSet<ClassTemplateDecl *, 8> ClassTemplates;
82 LookupResult::Filter filter = R.makeFilter();
83 while (filter.hasNext()) {
84 NamedDecl *Orig = filter.next();
85 NamedDecl *Repl = isAcceptableTemplateName(Context, Orig);
88 else if (Repl != Orig) {
90 // C++ [temp.local]p3:
91 // A lookup that finds an injected-class-name (10.2) can result in an
92 // ambiguity in certain cases (for example, if it is found in more than
93 // one base class). If all of the injected-class-names that are found
94 // refer to specializations of the same class template, and if the name
95 // is used as a template-name, the reference refers to the class
96 // template itself and not a specialization thereof, and is not
98 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl))
99 if (!ClassTemplates.insert(ClassTmpl)) {
104 // FIXME: we promote access to public here as a workaround to
105 // the fact that LookupResult doesn't let us remember that we
106 // found this template through a particular injected class name,
107 // which means we end up doing nasty things to the invariants.
108 // Pretending that access is public is *much* safer.
109 filter.replace(Repl, AS_public);
115 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R) {
116 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I)
117 if (isAcceptableTemplateName(Context, *I))
123 TemplateNameKind Sema::isTemplateName(Scope *S,
125 bool hasTemplateKeyword,
127 ParsedType ObjectTypePtr,
128 bool EnteringContext,
129 TemplateTy &TemplateResult,
130 bool &MemberOfUnknownSpecialization) {
131 assert(getLangOptions().CPlusPlus && "No template names in C!");
133 DeclarationName TName;
134 MemberOfUnknownSpecialization = false;
136 switch (Name.getKind()) {
137 case UnqualifiedId::IK_Identifier:
138 TName = DeclarationName(Name.Identifier);
141 case UnqualifiedId::IK_OperatorFunctionId:
142 TName = Context.DeclarationNames.getCXXOperatorName(
143 Name.OperatorFunctionId.Operator);
146 case UnqualifiedId::IK_LiteralOperatorId:
147 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
151 return TNK_Non_template;
154 QualType ObjectType = ObjectTypePtr.get();
156 LookupResult R(*this, TName, Name.getSourceRange().getBegin(),
158 LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
159 MemberOfUnknownSpecialization);
160 if (R.empty()) return TNK_Non_template;
161 if (R.isAmbiguous()) {
162 // Suppress diagnostics; we'll redo this lookup later.
163 R.suppressDiagnostics();
165 // FIXME: we might have ambiguous templates, in which case we
166 // should at least parse them properly!
167 return TNK_Non_template;
170 TemplateName Template;
171 TemplateNameKind TemplateKind;
173 unsigned ResultCount = R.end() - R.begin();
174 if (ResultCount > 1) {
175 // We assume that we'll preserve the qualifier from a function
176 // template name in other ways.
177 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
178 TemplateKind = TNK_Function_template;
180 // We'll do this lookup again later.
181 R.suppressDiagnostics();
183 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl());
185 if (SS.isSet() && !SS.isInvalid()) {
186 NestedNameSpecifier *Qualifier
187 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
188 Template = Context.getQualifiedTemplateName(Qualifier,
189 hasTemplateKeyword, TD);
191 Template = TemplateName(TD);
194 if (isa<FunctionTemplateDecl>(TD)) {
195 TemplateKind = TNK_Function_template;
197 // We'll do this lookup again later.
198 R.suppressDiagnostics();
200 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
201 isa<TypeAliasTemplateDecl>(TD));
202 TemplateKind = TNK_Type_template;
206 TemplateResult = TemplateTy::make(Template);
210 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
211 SourceLocation IILoc,
213 const CXXScopeSpec *SS,
214 TemplateTy &SuggestedTemplate,
215 TemplateNameKind &SuggestedKind) {
216 // We can't recover unless there's a dependent scope specifier preceding the
218 // FIXME: Typo correction?
219 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
220 computeDeclContext(*SS))
223 // The code is missing a 'template' keyword prior to the dependent template
225 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
226 Diag(IILoc, diag::err_template_kw_missing)
227 << Qualifier << II.getName()
228 << FixItHint::CreateInsertion(IILoc, "template ");
230 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
231 SuggestedKind = TNK_Dependent_template_name;
235 void Sema::LookupTemplateName(LookupResult &Found,
236 Scope *S, CXXScopeSpec &SS,
238 bool EnteringContext,
239 bool &MemberOfUnknownSpecialization) {
240 // Determine where to perform name lookup
241 MemberOfUnknownSpecialization = false;
242 DeclContext *LookupCtx = 0;
243 bool isDependent = false;
244 if (!ObjectType.isNull()) {
245 // This nested-name-specifier occurs in a member access expression, e.g.,
246 // x->B::f, and we are looking into the type of the object.
247 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist");
248 LookupCtx = computeDeclContext(ObjectType);
249 isDependent = ObjectType->isDependentType();
250 assert((isDependent || !ObjectType->isIncompleteType()) &&
251 "Caller should have completed object type");
252 } else if (SS.isSet()) {
253 // This nested-name-specifier occurs after another nested-name-specifier,
254 // so long into the context associated with the prior nested-name-specifier.
255 LookupCtx = computeDeclContext(SS, EnteringContext);
256 isDependent = isDependentScopeSpecifier(SS);
258 // The declaration context must be complete.
259 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
263 bool ObjectTypeSearchedInScope = false;
265 // Perform "qualified" name lookup into the declaration context we
266 // computed, which is either the type of the base of a member access
267 // expression or the declaration context associated with a prior
268 // nested-name-specifier.
269 LookupQualifiedName(Found, LookupCtx);
271 if (!ObjectType.isNull() && Found.empty()) {
272 // C++ [basic.lookup.classref]p1:
273 // In a class member access expression (5.2.5), if the . or -> token is
274 // immediately followed by an identifier followed by a <, the
275 // identifier must be looked up to determine whether the < is the
276 // beginning of a template argument list (14.2) or a less-than operator.
277 // The identifier is first looked up in the class of the object
278 // expression. If the identifier is not found, it is then looked up in
279 // the context of the entire postfix-expression and shall name a class
280 // or function template.
281 if (S) LookupName(Found, S);
282 ObjectTypeSearchedInScope = true;
284 } else if (isDependent && (!S || ObjectType.isNull())) {
285 // We cannot look into a dependent object type or nested nme
287 MemberOfUnknownSpecialization = true;
290 // Perform unqualified name lookup in the current scope.
291 LookupName(Found, S);
294 if (Found.empty() && !isDependent) {
295 // If we did not find any names, attempt to correct any typos.
296 DeclarationName Name = Found.getLookupName();
297 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx,
298 false, CTC_CXXCasts)) {
299 FilterAcceptableTemplateNames(Found);
300 if (!Found.empty()) {
302 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest)
303 << Name << LookupCtx << Found.getLookupName() << SS.getRange()
304 << FixItHint::CreateReplacement(Found.getNameLoc(),
305 Found.getLookupName().getAsString());
307 Diag(Found.getNameLoc(), diag::err_no_template_suggest)
308 << Name << Found.getLookupName()
309 << FixItHint::CreateReplacement(Found.getNameLoc(),
310 Found.getLookupName().getAsString());
311 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>())
312 Diag(Template->getLocation(), diag::note_previous_decl)
313 << Template->getDeclName();
317 Found.setLookupName(Name);
321 FilterAcceptableTemplateNames(Found);
324 MemberOfUnknownSpecialization = true;
328 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) {
329 // C++ [basic.lookup.classref]p1:
330 // [...] If the lookup in the class of the object expression finds a
331 // template, the name is also looked up in the context of the entire
332 // postfix-expression and [...]
334 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
336 LookupName(FoundOuter, S);
337 FilterAcceptableTemplateNames(FoundOuter);
339 if (FoundOuter.empty()) {
340 // - if the name is not found, the name found in the class of the
341 // object expression is used, otherwise
342 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) {
343 // - if the name is found in the context of the entire
344 // postfix-expression and does not name a class template, the name
345 // found in the class of the object expression is used, otherwise
346 } else if (!Found.isSuppressingDiagnostics()) {
347 // - if the name found is a class template, it must refer to the same
348 // entity as the one found in the class of the object expression,
349 // otherwise the program is ill-formed.
350 if (!Found.isSingleResult() ||
351 Found.getFoundDecl()->getCanonicalDecl()
352 != FoundOuter.getFoundDecl()->getCanonicalDecl()) {
353 Diag(Found.getNameLoc(),
354 diag::ext_nested_name_member_ref_lookup_ambiguous)
355 << Found.getLookupName()
357 Diag(Found.getRepresentativeDecl()->getLocation(),
358 diag::note_ambig_member_ref_object_type)
360 Diag(FoundOuter.getFoundDecl()->getLocation(),
361 diag::note_ambig_member_ref_scope);
363 // Recover by taking the template that we found in the object
364 // expression's type.
370 /// ActOnDependentIdExpression - Handle a dependent id-expression that
371 /// was just parsed. This is only possible with an explicit scope
372 /// specifier naming a dependent type.
374 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
375 const DeclarationNameInfo &NameInfo,
376 bool isAddressOfOperand,
377 const TemplateArgumentListInfo *TemplateArgs) {
378 DeclContext *DC = getFunctionLevelDeclContext();
380 if (!isAddressOfOperand &&
381 isa<CXXMethodDecl>(DC) &&
382 cast<CXXMethodDecl>(DC)->isInstance()) {
383 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
385 // Since the 'this' expression is synthesized, we don't need to
386 // perform the double-lookup check.
387 NamedDecl *FirstQualifierInScope = 0;
389 return Owned(CXXDependentScopeMemberExpr::Create(Context,
390 /*This*/ 0, ThisType,
392 /*Op*/ SourceLocation(),
393 SS.getWithLocInContext(Context),
394 FirstQualifierInScope,
399 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs);
403 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
404 const DeclarationNameInfo &NameInfo,
405 const TemplateArgumentListInfo *TemplateArgs) {
406 return Owned(DependentScopeDeclRefExpr::Create(Context,
407 SS.getWithLocInContext(Context),
412 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
413 /// that the template parameter 'PrevDecl' is being shadowed by a new
414 /// declaration at location Loc. Returns true to indicate that this is
415 /// an error, and false otherwise.
416 bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
417 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
419 // Microsoft Visual C++ permits template parameters to be shadowed.
420 if (getLangOptions().Microsoft)
423 // C++ [temp.local]p4:
424 // A template-parameter shall not be redeclared within its
425 // scope (including nested scopes).
426 Diag(Loc, diag::err_template_param_shadow)
427 << cast<NamedDecl>(PrevDecl)->getDeclName();
428 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
432 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
433 /// the parameter D to reference the templated declaration and return a pointer
434 /// to the template declaration. Otherwise, do nothing to D and return null.
435 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
436 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
437 D = Temp->getTemplatedDecl();
443 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
444 SourceLocation EllipsisLoc) const {
445 assert(Kind == Template &&
446 "Only template template arguments can be pack expansions here");
447 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
448 "Template template argument pack expansion without packs");
449 ParsedTemplateArgument Result(*this);
450 Result.EllipsisLoc = EllipsisLoc;
454 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
455 const ParsedTemplateArgument &Arg) {
457 switch (Arg.getKind()) {
458 case ParsedTemplateArgument::Type: {
460 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
462 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
463 return TemplateArgumentLoc(TemplateArgument(T), DI);
466 case ParsedTemplateArgument::NonType: {
467 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
468 return TemplateArgumentLoc(TemplateArgument(E), E);
471 case ParsedTemplateArgument::Template: {
472 TemplateName Template = Arg.getAsTemplate().get();
473 TemplateArgument TArg;
474 if (Arg.getEllipsisLoc().isValid())
475 TArg = TemplateArgument(Template, llvm::Optional<unsigned int>());
478 return TemplateArgumentLoc(TArg,
479 Arg.getScopeSpec().getWithLocInContext(
482 Arg.getEllipsisLoc());
486 llvm_unreachable("Unhandled parsed template argument");
487 return TemplateArgumentLoc();
490 /// \brief Translates template arguments as provided by the parser
491 /// into template arguments used by semantic analysis.
492 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
493 TemplateArgumentListInfo &TemplateArgs) {
494 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
495 TemplateArgs.addArgument(translateTemplateArgument(*this,
499 /// ActOnTypeParameter - Called when a C++ template type parameter
500 /// (e.g., "typename T") has been parsed. Typename specifies whether
501 /// the keyword "typename" was used to declare the type parameter
502 /// (otherwise, "class" was used), and KeyLoc is the location of the
503 /// "class" or "typename" keyword. ParamName is the name of the
504 /// parameter (NULL indicates an unnamed template parameter) and
505 /// ParamNameLoc is the location of the parameter name (if any).
506 /// If the type parameter has a default argument, it will be added
507 /// later via ActOnTypeParameterDefault.
508 Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis,
509 SourceLocation EllipsisLoc,
510 SourceLocation KeyLoc,
511 IdentifierInfo *ParamName,
512 SourceLocation ParamNameLoc,
513 unsigned Depth, unsigned Position,
514 SourceLocation EqualLoc,
515 ParsedType DefaultArg) {
516 assert(S->isTemplateParamScope() &&
517 "Template type parameter not in template parameter scope!");
518 bool Invalid = false;
521 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc,
524 if (PrevDecl && PrevDecl->isTemplateParameter())
525 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc,
529 SourceLocation Loc = ParamNameLoc;
533 TemplateTypeParmDecl *Param
534 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
535 KeyLoc, Loc, Depth, Position, ParamName,
537 Param->setAccess(AS_public);
539 Param->setInvalidDecl();
542 // Add the template parameter into the current scope.
544 IdResolver.AddDecl(Param);
547 // C++0x [temp.param]p9:
548 // A default template-argument may be specified for any kind of
549 // template-parameter that is not a template parameter pack.
550 if (DefaultArg && Ellipsis) {
551 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
552 DefaultArg = ParsedType();
555 // Handle the default argument, if provided.
557 TypeSourceInfo *DefaultTInfo;
558 GetTypeFromParser(DefaultArg, &DefaultTInfo);
560 assert(DefaultTInfo && "expected source information for type");
562 // Check for unexpanded parameter packs.
563 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo,
564 UPPC_DefaultArgument))
567 // Check the template argument itself.
568 if (CheckTemplateArgument(Param, DefaultTInfo)) {
569 Param->setInvalidDecl();
573 Param->setDefaultArgument(DefaultTInfo, false);
579 /// \brief Check that the type of a non-type template parameter is
582 /// \returns the (possibly-promoted) parameter type if valid;
583 /// otherwise, produces a diagnostic and returns a NULL type.
585 Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) {
586 // We don't allow variably-modified types as the type of non-type template
588 if (T->isVariablyModifiedType()) {
589 Diag(Loc, diag::err_variably_modified_nontype_template_param)
594 // C++ [temp.param]p4:
596 // A non-type template-parameter shall have one of the following
597 // (optionally cv-qualified) types:
599 // -- integral or enumeration type,
600 if (T->isIntegralOrEnumerationType() ||
601 // -- pointer to object or pointer to function,
602 T->isPointerType() ||
603 // -- reference to object or reference to function,
604 T->isReferenceType() ||
605 // -- pointer to member,
606 T->isMemberPointerType() ||
607 // -- std::nullptr_t.
608 T->isNullPtrType() ||
609 // If T is a dependent type, we can't do the check now, so we
610 // assume that it is well-formed.
611 T->isDependentType())
613 // C++ [temp.param]p8:
615 // A non-type template-parameter of type "array of T" or
616 // "function returning T" is adjusted to be of type "pointer to
617 // T" or "pointer to function returning T", respectively.
618 else if (T->isArrayType())
619 // FIXME: Keep the type prior to promotion?
620 return Context.getArrayDecayedType(T);
621 else if (T->isFunctionType())
622 // FIXME: Keep the type prior to promotion?
623 return Context.getPointerType(T);
625 Diag(Loc, diag::err_template_nontype_parm_bad_type)
631 Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
634 SourceLocation EqualLoc,
636 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
637 QualType T = TInfo->getType();
639 assert(S->isTemplateParamScope() &&
640 "Non-type template parameter not in template parameter scope!");
641 bool Invalid = false;
643 IdentifierInfo *ParamName = D.getIdentifier();
645 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(),
648 if (PrevDecl && PrevDecl->isTemplateParameter())
649 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
653 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc());
655 T = Context.IntTy; // Recover with an 'int' type.
659 bool IsParameterPack = D.hasEllipsis();
660 NonTypeTemplateParmDecl *Param
661 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
662 D.getSourceRange().getBegin(),
663 D.getIdentifierLoc(),
664 Depth, Position, ParamName, T,
665 IsParameterPack, TInfo);
666 Param->setAccess(AS_public);
669 Param->setInvalidDecl();
671 if (D.getIdentifier()) {
672 // Add the template parameter into the current scope.
674 IdResolver.AddDecl(Param);
677 // C++0x [temp.param]p9:
678 // A default template-argument may be specified for any kind of
679 // template-parameter that is not a template parameter pack.
680 if (Default && IsParameterPack) {
681 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
685 // Check the well-formedness of the default template argument, if provided.
687 // Check for unexpanded parameter packs.
688 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
691 TemplateArgument Converted;
692 ExprResult DefaultRes = CheckTemplateArgument(Param, Param->getType(), Default, Converted);
693 if (DefaultRes.isInvalid()) {
694 Param->setInvalidDecl();
697 Default = DefaultRes.take();
699 Param->setDefaultArgument(Default, false);
705 /// ActOnTemplateTemplateParameter - Called when a C++ template template
706 /// parameter (e.g. T in template <template <typename> class T> class array)
707 /// has been parsed. S is the current scope.
708 Decl *Sema::ActOnTemplateTemplateParameter(Scope* S,
709 SourceLocation TmpLoc,
710 TemplateParamsTy *Params,
711 SourceLocation EllipsisLoc,
712 IdentifierInfo *Name,
713 SourceLocation NameLoc,
716 SourceLocation EqualLoc,
717 ParsedTemplateArgument Default) {
718 assert(S->isTemplateParamScope() &&
719 "Template template parameter not in template parameter scope!");
721 // Construct the parameter object.
722 bool IsParameterPack = EllipsisLoc.isValid();
723 TemplateTemplateParmDecl *Param =
724 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
725 NameLoc.isInvalid()? TmpLoc : NameLoc,
726 Depth, Position, IsParameterPack,
728 Param->setAccess(AS_public);
730 // If the template template parameter has a name, then link the identifier
731 // into the scope and lookup mechanisms.
734 IdResolver.AddDecl(Param);
737 if (Params->size() == 0) {
738 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
739 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
740 Param->setInvalidDecl();
743 // C++0x [temp.param]p9:
744 // A default template-argument may be specified for any kind of
745 // template-parameter that is not a template parameter pack.
746 if (IsParameterPack && !Default.isInvalid()) {
747 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
748 Default = ParsedTemplateArgument();
751 if (!Default.isInvalid()) {
752 // Check only that we have a template template argument. We don't want to
753 // try to check well-formedness now, because our template template parameter
754 // might have dependent types in its template parameters, which we wouldn't
755 // be able to match now.
757 // If none of the template template parameter's template arguments mention
758 // other template parameters, we could actually perform more checking here.
759 // However, it isn't worth doing.
760 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
761 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
762 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template)
763 << DefaultArg.getSourceRange();
767 // Check for unexpanded parameter packs.
768 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
769 DefaultArg.getArgument().getAsTemplate(),
770 UPPC_DefaultArgument))
773 Param->setDefaultArgument(DefaultArg, false);
779 /// ActOnTemplateParameterList - Builds a TemplateParameterList that
780 /// contains the template parameters in Params/NumParams.
781 Sema::TemplateParamsTy *
782 Sema::ActOnTemplateParameterList(unsigned Depth,
783 SourceLocation ExportLoc,
784 SourceLocation TemplateLoc,
785 SourceLocation LAngleLoc,
786 Decl **Params, unsigned NumParams,
787 SourceLocation RAngleLoc) {
788 if (ExportLoc.isValid())
789 Diag(ExportLoc, diag::warn_template_export_unsupported);
791 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
792 (NamedDecl**)Params, NumParams,
796 static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) {
798 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext()));
802 Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK,
803 SourceLocation KWLoc, CXXScopeSpec &SS,
804 IdentifierInfo *Name, SourceLocation NameLoc,
806 TemplateParameterList *TemplateParams,
808 unsigned NumOuterTemplateParamLists,
809 TemplateParameterList** OuterTemplateParamLists) {
810 assert(TemplateParams && TemplateParams->size() > 0 &&
811 "No template parameters");
812 assert(TUK != TUK_Reference && "Can only declare or define class templates");
813 bool Invalid = false;
815 // Check that we can declare a template here.
816 if (CheckTemplateDeclScope(S, TemplateParams))
819 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
820 assert(Kind != TTK_Enum && "can't build template of enumerated type");
822 // There is no such thing as an unnamed class template.
824 Diag(KWLoc, diag::err_template_unnamed_class);
828 // Find any previous declaration with this name.
829 DeclContext *SemanticContext;
830 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName,
832 if (SS.isNotEmpty() && !SS.isInvalid()) {
833 SemanticContext = computeDeclContext(SS, true);
834 if (!SemanticContext) {
835 // FIXME: Produce a reasonable diagnostic here
839 if (RequireCompleteDeclContext(SS, SemanticContext))
842 LookupQualifiedName(Previous, SemanticContext);
844 SemanticContext = CurContext;
845 LookupName(Previous, S);
848 if (Previous.isAmbiguous())
851 NamedDecl *PrevDecl = 0;
852 if (Previous.begin() != Previous.end())
853 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
855 // If there is a previous declaration with the same name, check
856 // whether this is a valid redeclaration.
857 ClassTemplateDecl *PrevClassTemplate
858 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
860 // We may have found the injected-class-name of a class template,
861 // class template partial specialization, or class template specialization.
862 // In these cases, grab the template that is being defined or specialized.
863 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
864 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
865 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
867 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
868 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
870 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
871 ->getSpecializedTemplate();
875 if (TUK == TUK_Friend) {
876 // C++ [namespace.memdef]p3:
877 // [...] When looking for a prior declaration of a class or a function
878 // declared as a friend, and when the name of the friend class or
879 // function is neither a qualified name nor a template-id, scopes outside
880 // the innermost enclosing namespace scope are not considered.
882 DeclContext *OutermostContext = CurContext;
883 while (!OutermostContext->isFileContext())
884 OutermostContext = OutermostContext->getLookupParent();
887 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
888 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
889 SemanticContext = PrevDecl->getDeclContext();
891 // Declarations in outer scopes don't matter. However, the outermost
892 // context we computed is the semantic context for our new
894 PrevDecl = PrevClassTemplate = 0;
895 SemanticContext = OutermostContext;
899 if (CurContext->isDependentContext()) {
900 // If this is a dependent context, we don't want to link the friend
901 // class template to the template in scope, because that would perform
902 // checking of the template parameter lists that can't be performed
903 // until the outer context is instantiated.
904 PrevDecl = PrevClassTemplate = 0;
906 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S))
907 PrevDecl = PrevClassTemplate = 0;
909 if (PrevClassTemplate) {
910 // Ensure that the template parameter lists are compatible.
911 if (!TemplateParameterListsAreEqual(TemplateParams,
912 PrevClassTemplate->getTemplateParameters(),
917 // C++ [temp.class]p4:
918 // In a redeclaration, partial specialization, explicit
919 // specialization or explicit instantiation of a class template,
920 // the class-key shall agree in kind with the original class
921 // template declaration (7.1.5.3).
922 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
923 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
924 TUK == TUK_Definition, KWLoc, *Name)) {
925 Diag(KWLoc, diag::err_use_with_wrong_tag)
927 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
928 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
929 Kind = PrevRecordDecl->getTagKind();
932 // Check for redefinition of this class template.
933 if (TUK == TUK_Definition) {
934 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
935 Diag(NameLoc, diag::err_redefinition) << Name;
936 Diag(Def->getLocation(), diag::note_previous_definition);
937 // FIXME: Would it make sense to try to "forget" the previous
938 // definition, as part of error recovery?
942 } else if (PrevDecl && PrevDecl->isTemplateParameter()) {
943 // Maybe we will complain about the shadowed template parameter.
944 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
945 // Just pretend that we didn't see the previous declaration.
947 } else if (PrevDecl) {
949 // A class template shall not have the same name as any other
950 // template, class, function, object, enumeration, enumerator,
951 // namespace, or type in the same scope (3.3), except as specified
953 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
954 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
958 // Check the template parameter list of this declaration, possibly
959 // merging in the template parameter list from the previous class
960 // template declaration.
961 if (CheckTemplateParameterList(TemplateParams,
962 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0,
963 (SS.isSet() && SemanticContext &&
964 SemanticContext->isRecord() &&
965 SemanticContext->isDependentContext())
966 ? TPC_ClassTemplateMember
967 : TPC_ClassTemplate))
971 // If the name of the template was qualified, we must be defining the
972 // template out-of-line.
973 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate &&
974 !(TUK == TUK_Friend && CurContext->isDependentContext()))
975 Diag(NameLoc, diag::err_member_def_does_not_match)
976 << Name << SemanticContext << SS.getRange();
979 CXXRecordDecl *NewClass =
980 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
982 PrevClassTemplate->getTemplatedDecl() : 0,
983 /*DelayTypeCreation=*/true);
984 SetNestedNameSpecifier(NewClass, SS);
985 if (NumOuterTemplateParamLists > 0)
986 NewClass->setTemplateParameterListsInfo(Context,
987 NumOuterTemplateParamLists,
988 OuterTemplateParamLists);
990 ClassTemplateDecl *NewTemplate
991 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
992 DeclarationName(Name), TemplateParams,
993 NewClass, PrevClassTemplate);
994 NewClass->setDescribedClassTemplate(NewTemplate);
996 // Build the type for the class template declaration now.
997 QualType T = NewTemplate->getInjectedClassNameSpecialization();
998 T = Context.getInjectedClassNameType(NewClass, T);
999 assert(T->isDependentType() && "Class template type is not dependent?");
1002 // If we are providing an explicit specialization of a member that is a
1003 // class template, make a note of that.
1004 if (PrevClassTemplate &&
1005 PrevClassTemplate->getInstantiatedFromMemberTemplate())
1006 PrevClassTemplate->setMemberSpecialization();
1008 // Set the access specifier.
1009 if (!Invalid && TUK != TUK_Friend)
1010 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
1012 // Set the lexical context of these templates
1013 NewClass->setLexicalDeclContext(CurContext);
1014 NewTemplate->setLexicalDeclContext(CurContext);
1016 if (TUK == TUK_Definition)
1017 NewClass->startDefinition();
1020 ProcessDeclAttributeList(S, NewClass, Attr);
1022 if (TUK != TUK_Friend)
1023 PushOnScopeChains(NewTemplate, S);
1025 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
1026 NewTemplate->setAccess(PrevClassTemplate->getAccess());
1027 NewClass->setAccess(PrevClassTemplate->getAccess());
1030 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */
1031 PrevClassTemplate != NULL);
1033 // Friend templates are visible in fairly strange ways.
1034 if (!CurContext->isDependentContext()) {
1035 DeclContext *DC = SemanticContext->getRedeclContext();
1036 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false);
1037 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
1038 PushOnScopeChains(NewTemplate, EnclosingScope,
1039 /* AddToContext = */ false);
1042 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
1043 NewClass->getLocation(),
1045 /*FIXME:*/NewClass->getLocation());
1046 Friend->setAccess(AS_public);
1047 CurContext->addDecl(Friend);
1051 NewTemplate->setInvalidDecl();
1052 NewClass->setInvalidDecl();
1057 /// \brief Diagnose the presence of a default template argument on a
1058 /// template parameter, which is ill-formed in certain contexts.
1060 /// \returns true if the default template argument should be dropped.
1061 static bool DiagnoseDefaultTemplateArgument(Sema &S,
1062 Sema::TemplateParamListContext TPC,
1063 SourceLocation ParamLoc,
1064 SourceRange DefArgRange) {
1066 case Sema::TPC_ClassTemplate:
1067 case Sema::TPC_TypeAliasTemplate:
1070 case Sema::TPC_FunctionTemplate:
1071 case Sema::TPC_FriendFunctionTemplateDefinition:
1072 // C++ [temp.param]p9:
1073 // A default template-argument shall not be specified in a
1074 // function template declaration or a function template
1076 // If a friend function template declaration specifies a default
1077 // template-argument, that declaration shall be a definition and shall be
1078 // the only declaration of the function template in the translation unit.
1079 // (C++98/03 doesn't have this wording; see DR226).
1080 if (!S.getLangOptions().CPlusPlus0x)
1082 diag::ext_template_parameter_default_in_function_template)
1086 case Sema::TPC_ClassTemplateMember:
1087 // C++0x [temp.param]p9:
1088 // A default template-argument shall not be specified in the
1089 // template-parameter-lists of the definition of a member of a
1090 // class template that appears outside of the member's class.
1091 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
1095 case Sema::TPC_FriendFunctionTemplate:
1096 // C++ [temp.param]p9:
1097 // A default template-argument shall not be specified in a
1098 // friend template declaration.
1099 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
1103 // FIXME: C++0x [temp.param]p9 allows default template-arguments
1104 // for friend function templates if there is only a single
1105 // declaration (and it is a definition). Strange!
1111 /// \brief Check for unexpanded parameter packs within the template parameters
1112 /// of a template template parameter, recursively.
1113 static bool DiagnoseUnexpandedParameterPacks(Sema &S,
1114 TemplateTemplateParmDecl *TTP) {
1115 TemplateParameterList *Params = TTP->getTemplateParameters();
1116 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
1117 NamedDecl *P = Params->getParam(I);
1118 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
1119 if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
1120 NTTP->getTypeSourceInfo(),
1121 Sema::UPPC_NonTypeTemplateParameterType))
1127 if (TemplateTemplateParmDecl *InnerTTP
1128 = dyn_cast<TemplateTemplateParmDecl>(P))
1129 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
1136 /// \brief Checks the validity of a template parameter list, possibly
1137 /// considering the template parameter list from a previous
1140 /// If an "old" template parameter list is provided, it must be
1141 /// equivalent (per TemplateParameterListsAreEqual) to the "new"
1142 /// template parameter list.
1144 /// \param NewParams Template parameter list for a new template
1145 /// declaration. This template parameter list will be updated with any
1146 /// default arguments that are carried through from the previous
1147 /// template parameter list.
1149 /// \param OldParams If provided, template parameter list from a
1150 /// previous declaration of the same template. Default template
1151 /// arguments will be merged from the old template parameter list to
1152 /// the new template parameter list.
1154 /// \param TPC Describes the context in which we are checking the given
1155 /// template parameter list.
1157 /// \returns true if an error occurred, false otherwise.
1158 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
1159 TemplateParameterList *OldParams,
1160 TemplateParamListContext TPC) {
1161 bool Invalid = false;
1163 // C++ [temp.param]p10:
1164 // The set of default template-arguments available for use with a
1165 // template declaration or definition is obtained by merging the
1166 // default arguments from the definition (if in scope) and all
1167 // declarations in scope in the same way default function
1168 // arguments are (8.3.6).
1169 bool SawDefaultArgument = false;
1170 SourceLocation PreviousDefaultArgLoc;
1172 bool SawParameterPack = false;
1173 SourceLocation ParameterPackLoc;
1175 // Dummy initialization to avoid warnings.
1176 TemplateParameterList::iterator OldParam = NewParams->end();
1178 OldParam = OldParams->begin();
1180 bool RemoveDefaultArguments = false;
1181 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1182 NewParamEnd = NewParams->end();
1183 NewParam != NewParamEnd; ++NewParam) {
1184 // Variables used to diagnose redundant default arguments
1185 bool RedundantDefaultArg = false;
1186 SourceLocation OldDefaultLoc;
1187 SourceLocation NewDefaultLoc;
1189 // Variables used to diagnose missing default arguments
1190 bool MissingDefaultArg = false;
1192 // C++0x [temp.param]p11:
1193 // If a template parameter of a primary class template or alias template
1194 // is a template parameter pack, it shall be the last template parameter.
1195 if (SawParameterPack &&
1196 (TPC == TPC_ClassTemplate || TPC == TPC_TypeAliasTemplate)) {
1197 Diag(ParameterPackLoc,
1198 diag::err_template_param_pack_must_be_last_template_parameter);
1202 if (TemplateTypeParmDecl *NewTypeParm
1203 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
1204 // Check the presence of a default argument here.
1205 if (NewTypeParm->hasDefaultArgument() &&
1206 DiagnoseDefaultTemplateArgument(*this, TPC,
1207 NewTypeParm->getLocation(),
1208 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
1210 NewTypeParm->removeDefaultArgument();
1212 // Merge default arguments for template type parameters.
1213 TemplateTypeParmDecl *OldTypeParm
1214 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0;
1216 if (NewTypeParm->isParameterPack()) {
1217 assert(!NewTypeParm->hasDefaultArgument() &&
1218 "Parameter packs can't have a default argument!");
1219 SawParameterPack = true;
1220 ParameterPackLoc = NewTypeParm->getLocation();
1221 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() &&
1222 NewTypeParm->hasDefaultArgument()) {
1223 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
1224 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
1225 SawDefaultArgument = true;
1226 RedundantDefaultArg = true;
1227 PreviousDefaultArgLoc = NewDefaultLoc;
1228 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
1229 // Merge the default argument from the old declaration to the
1231 SawDefaultArgument = true;
1232 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(),
1234 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
1235 } else if (NewTypeParm->hasDefaultArgument()) {
1236 SawDefaultArgument = true;
1237 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
1238 } else if (SawDefaultArgument)
1239 MissingDefaultArg = true;
1240 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
1241 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
1242 // Check for unexpanded parameter packs.
1243 if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
1244 NewNonTypeParm->getTypeSourceInfo(),
1245 UPPC_NonTypeTemplateParameterType)) {
1250 // Check the presence of a default argument here.
1251 if (NewNonTypeParm->hasDefaultArgument() &&
1252 DiagnoseDefaultTemplateArgument(*this, TPC,
1253 NewNonTypeParm->getLocation(),
1254 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
1255 NewNonTypeParm->removeDefaultArgument();
1258 // Merge default arguments for non-type template parameters
1259 NonTypeTemplateParmDecl *OldNonTypeParm
1260 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0;
1261 if (NewNonTypeParm->isParameterPack()) {
1262 assert(!NewNonTypeParm->hasDefaultArgument() &&
1263 "Parameter packs can't have a default argument!");
1264 SawParameterPack = true;
1265 ParameterPackLoc = NewNonTypeParm->getLocation();
1266 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() &&
1267 NewNonTypeParm->hasDefaultArgument()) {
1268 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
1269 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
1270 SawDefaultArgument = true;
1271 RedundantDefaultArg = true;
1272 PreviousDefaultArgLoc = NewDefaultLoc;
1273 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
1274 // Merge the default argument from the old declaration to the
1276 SawDefaultArgument = true;
1277 // FIXME: We need to create a new kind of "default argument"
1278 // expression that points to a previous non-type template
1280 NewNonTypeParm->setDefaultArgument(
1281 OldNonTypeParm->getDefaultArgument(),
1282 /*Inherited=*/ true);
1283 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
1284 } else if (NewNonTypeParm->hasDefaultArgument()) {
1285 SawDefaultArgument = true;
1286 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
1287 } else if (SawDefaultArgument)
1288 MissingDefaultArg = true;
1290 // Check the presence of a default argument here.
1291 TemplateTemplateParmDecl *NewTemplateParm
1292 = cast<TemplateTemplateParmDecl>(*NewParam);
1294 // Check for unexpanded parameter packs, recursively.
1295 if (DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
1300 if (NewTemplateParm->hasDefaultArgument() &&
1301 DiagnoseDefaultTemplateArgument(*this, TPC,
1302 NewTemplateParm->getLocation(),
1303 NewTemplateParm->getDefaultArgument().getSourceRange()))
1304 NewTemplateParm->removeDefaultArgument();
1306 // Merge default arguments for template template parameters
1307 TemplateTemplateParmDecl *OldTemplateParm
1308 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0;
1309 if (NewTemplateParm->isParameterPack()) {
1310 assert(!NewTemplateParm->hasDefaultArgument() &&
1311 "Parameter packs can't have a default argument!");
1312 SawParameterPack = true;
1313 ParameterPackLoc = NewTemplateParm->getLocation();
1314 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() &&
1315 NewTemplateParm->hasDefaultArgument()) {
1316 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
1317 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
1318 SawDefaultArgument = true;
1319 RedundantDefaultArg = true;
1320 PreviousDefaultArgLoc = NewDefaultLoc;
1321 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
1322 // Merge the default argument from the old declaration to the
1324 SawDefaultArgument = true;
1325 // FIXME: We need to create a new kind of "default argument" expression
1326 // that points to a previous template template parameter.
1327 NewTemplateParm->setDefaultArgument(
1328 OldTemplateParm->getDefaultArgument(),
1329 /*Inherited=*/ true);
1330 PreviousDefaultArgLoc
1331 = OldTemplateParm->getDefaultArgument().getLocation();
1332 } else if (NewTemplateParm->hasDefaultArgument()) {
1333 SawDefaultArgument = true;
1334 PreviousDefaultArgLoc
1335 = NewTemplateParm->getDefaultArgument().getLocation();
1336 } else if (SawDefaultArgument)
1337 MissingDefaultArg = true;
1340 if (RedundantDefaultArg) {
1341 // C++ [temp.param]p12:
1342 // A template-parameter shall not be given default arguments
1343 // by two different declarations in the same scope.
1344 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
1345 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
1347 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
1348 // C++ [temp.param]p11:
1349 // If a template-parameter of a class template has a default
1350 // template-argument, each subsequent template-parameter shall either
1351 // have a default template-argument supplied or be a template parameter
1353 Diag((*NewParam)->getLocation(),
1354 diag::err_template_param_default_arg_missing);
1355 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
1357 RemoveDefaultArguments = true;
1360 // If we have an old template parameter list that we're merging
1361 // in, move on to the next parameter.
1366 // We were missing some default arguments at the end of the list, so remove
1367 // all of the default arguments.
1368 if (RemoveDefaultArguments) {
1369 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
1370 NewParamEnd = NewParams->end();
1371 NewParam != NewParamEnd; ++NewParam) {
1372 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
1373 TTP->removeDefaultArgument();
1374 else if (NonTypeTemplateParmDecl *NTTP
1375 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
1376 NTTP->removeDefaultArgument();
1378 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
1387 /// A class which looks for a use of a certain level of template
1389 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
1390 typedef RecursiveASTVisitor<DependencyChecker> super;
1395 DependencyChecker(TemplateParameterList *Params) : Match(false) {
1396 NamedDecl *ND = Params->getParam(0);
1397 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
1398 Depth = PD->getDepth();
1399 } else if (NonTypeTemplateParmDecl *PD =
1400 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
1401 Depth = PD->getDepth();
1403 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
1407 bool Matches(unsigned ParmDepth) {
1408 if (ParmDepth >= Depth) {
1415 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
1416 return !Matches(T->getDepth());
1419 bool TraverseTemplateName(TemplateName N) {
1420 if (TemplateTemplateParmDecl *PD =
1421 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
1422 if (Matches(PD->getDepth())) return false;
1423 return super::TraverseTemplateName(N);
1426 bool VisitDeclRefExpr(DeclRefExpr *E) {
1427 if (NonTypeTemplateParmDecl *PD =
1428 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) {
1429 if (PD->getDepth() == Depth) {
1434 return super::VisitDeclRefExpr(E);
1437 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
1438 return TraverseType(T->getInjectedSpecializationType());
1443 /// Determines whether a given type depends on the given parameter
1446 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
1447 DependencyChecker Checker(Params);
1448 Checker.TraverseType(T);
1449 return Checker.Match;
1452 // Find the source range corresponding to the named type in the given
1453 // nested-name-specifier, if any.
1454 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
1456 const CXXScopeSpec &SS) {
1457 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
1458 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
1459 if (const Type *CurType = NNS->getAsType()) {
1460 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
1461 return NNSLoc.getTypeLoc().getSourceRange();
1465 NNSLoc = NNSLoc.getPrefix();
1468 return SourceRange();
1471 /// \brief Match the given template parameter lists to the given scope
1472 /// specifier, returning the template parameter list that applies to the
1475 /// \param DeclStartLoc the start of the declaration that has a scope
1476 /// specifier or a template parameter list.
1478 /// \param DeclLoc The location of the declaration itself.
1480 /// \param SS the scope specifier that will be matched to the given template
1481 /// parameter lists. This scope specifier precedes a qualified name that is
1484 /// \param ParamLists the template parameter lists, from the outermost to the
1485 /// innermost template parameter lists.
1487 /// \param NumParamLists the number of template parameter lists in ParamLists.
1489 /// \param IsFriend Whether to apply the slightly different rules for
1490 /// matching template parameters to scope specifiers in friend
1493 /// \param IsExplicitSpecialization will be set true if the entity being
1494 /// declared is an explicit specialization, false otherwise.
1496 /// \returns the template parameter list, if any, that corresponds to the
1497 /// name that is preceded by the scope specifier @p SS. This template
1498 /// parameter list may have template parameters (if we're declaring a
1499 /// template) or may have no template parameters (if we're declaring a
1500 /// template specialization), or may be NULL (if what we're declaring isn't
1501 /// itself a template).
1502 TemplateParameterList *
1503 Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc,
1504 SourceLocation DeclLoc,
1505 const CXXScopeSpec &SS,
1506 TemplateParameterList **ParamLists,
1507 unsigned NumParamLists,
1509 bool &IsExplicitSpecialization,
1511 IsExplicitSpecialization = false;
1514 // The sequence of nested types to which we will match up the template
1515 // parameter lists. We first build this list by starting with the type named
1516 // by the nested-name-specifier and walking out until we run out of types.
1517 llvm::SmallVector<QualType, 4> NestedTypes;
1519 if (SS.getScopeRep()) {
1520 if (CXXRecordDecl *Record
1521 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
1522 T = Context.getTypeDeclType(Record);
1524 T = QualType(SS.getScopeRep()->getAsType(), 0);
1527 // If we found an explicit specialization that prevents us from needing
1528 // 'template<>' headers, this will be set to the location of that
1529 // explicit specialization.
1530 SourceLocation ExplicitSpecLoc;
1532 while (!T.isNull()) {
1533 NestedTypes.push_back(T);
1535 // Retrieve the parent of a record type.
1536 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1537 // If this type is an explicit specialization, we're done.
1538 if (ClassTemplateSpecializationDecl *Spec
1539 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1540 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
1541 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
1542 ExplicitSpecLoc = Spec->getLocation();
1545 } else if (Record->getTemplateSpecializationKind()
1546 == TSK_ExplicitSpecialization) {
1547 ExplicitSpecLoc = Record->getLocation();
1551 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
1552 T = Context.getTypeDeclType(Parent);
1558 if (const TemplateSpecializationType *TST
1559 = T->getAs<TemplateSpecializationType>()) {
1560 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1561 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
1562 T = Context.getTypeDeclType(Parent);
1569 // Look one step prior in a dependent template specialization type.
1570 if (const DependentTemplateSpecializationType *DependentTST
1571 = T->getAs<DependentTemplateSpecializationType>()) {
1572 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
1573 T = QualType(NNS->getAsType(), 0);
1579 // Look one step prior in a dependent name type.
1580 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
1581 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
1582 T = QualType(NNS->getAsType(), 0);
1588 // Retrieve the parent of an enumeration type.
1589 if (const EnumType *EnumT = T->getAs<EnumType>()) {
1590 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
1592 EnumDecl *Enum = EnumT->getDecl();
1594 // Get to the parent type.
1595 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
1596 T = Context.getTypeDeclType(Parent);
1604 // Reverse the nested types list, since we want to traverse from the outermost
1605 // to the innermost while checking template-parameter-lists.
1606 std::reverse(NestedTypes.begin(), NestedTypes.end());
1608 // C++0x [temp.expl.spec]p17:
1609 // A member or a member template may be nested within many
1610 // enclosing class templates. In an explicit specialization for
1611 // such a member, the member declaration shall be preceded by a
1612 // template<> for each enclosing class template that is
1613 // explicitly specialized.
1614 bool SawNonEmptyTemplateParameterList = false;
1615 unsigned ParamIdx = 0;
1616 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
1618 T = NestedTypes[TypeIdx];
1620 // Whether we expect a 'template<>' header.
1621 bool NeedEmptyTemplateHeader = false;
1623 // Whether we expect a template header with parameters.
1624 bool NeedNonemptyTemplateHeader = false;
1626 // For a dependent type, the set of template parameters that we
1628 TemplateParameterList *ExpectedTemplateParams = 0;
1630 // C++0x [temp.expl.spec]p15:
1631 // A member or a member template may be nested within many enclosing
1632 // class templates. In an explicit specialization for such a member, the
1633 // member declaration shall be preceded by a template<> for each
1634 // enclosing class template that is explicitly specialized.
1635 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
1636 if (ClassTemplatePartialSpecializationDecl *Partial
1637 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
1638 ExpectedTemplateParams = Partial->getTemplateParameters();
1639 NeedNonemptyTemplateHeader = true;
1640 } else if (Record->isDependentType()) {
1641 if (Record->getDescribedClassTemplate()) {
1642 ExpectedTemplateParams = Record->getDescribedClassTemplate()
1643 ->getTemplateParameters();
1644 NeedNonemptyTemplateHeader = true;
1646 } else if (ClassTemplateSpecializationDecl *Spec
1647 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
1648 // C++0x [temp.expl.spec]p4:
1649 // Members of an explicitly specialized class template are defined
1650 // in the same manner as members of normal classes, and not using
1651 // the template<> syntax.
1652 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
1653 NeedEmptyTemplateHeader = true;
1656 } else if (Record->getTemplateSpecializationKind()) {
1657 if (Record->getTemplateSpecializationKind()
1658 != TSK_ExplicitSpecialization &&
1659 TypeIdx == NumTypes - 1)
1660 IsExplicitSpecialization = true;
1664 } else if (const TemplateSpecializationType *TST
1665 = T->getAs<TemplateSpecializationType>()) {
1666 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
1667 ExpectedTemplateParams = Template->getTemplateParameters();
1668 NeedNonemptyTemplateHeader = true;
1670 } else if (T->getAs<DependentTemplateSpecializationType>()) {
1671 // FIXME: We actually could/should check the template arguments here
1672 // against the corresponding template parameter list.
1673 NeedNonemptyTemplateHeader = false;
1676 // C++ [temp.expl.spec]p16:
1677 // In an explicit specialization declaration for a member of a class
1678 // template or a member template that ap- pears in namespace scope, the
1679 // member template and some of its enclosing class templates may remain
1680 // unspecialized, except that the declaration shall not explicitly
1681 // specialize a class member template if its en- closing class templates
1682 // are not explicitly specialized as well.
1683 if (ParamIdx < NumParamLists) {
1684 if (ParamLists[ParamIdx]->size() == 0) {
1685 if (SawNonEmptyTemplateParameterList) {
1686 Diag(DeclLoc, diag::err_specialize_member_of_template)
1687 << ParamLists[ParamIdx]->getSourceRange();
1689 IsExplicitSpecialization = false;
1693 SawNonEmptyTemplateParameterList = true;
1696 if (NeedEmptyTemplateHeader) {
1697 // If we're on the last of the types, and we need a 'template<>' header
1698 // here, then it's an explicit specialization.
1699 if (TypeIdx == NumTypes - 1)
1700 IsExplicitSpecialization = true;
1702 if (ParamIdx < NumParamLists) {
1703 if (ParamLists[ParamIdx]->size() > 0) {
1704 // The header has template parameters when it shouldn't. Complain.
1705 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1706 diag::err_template_param_list_matches_nontemplate)
1708 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
1709 ParamLists[ParamIdx]->getRAngleLoc())
1710 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1715 // Consume this template header.
1721 // We don't have a template header, but we should.
1722 SourceLocation ExpectedTemplateLoc;
1723 if (NumParamLists > 0)
1724 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
1726 ExpectedTemplateLoc = DeclStartLoc;
1728 Diag(DeclLoc, diag::err_template_spec_needs_header)
1729 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS)
1730 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
1736 if (NeedNonemptyTemplateHeader) {
1737 // In friend declarations we can have template-ids which don't
1738 // depend on the corresponding template parameter lists. But
1739 // assume that empty parameter lists are supposed to match this
1741 if (IsFriend && T->isDependentType()) {
1742 if (ParamIdx < NumParamLists &&
1743 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
1744 ExpectedTemplateParams = 0;
1749 if (ParamIdx < NumParamLists) {
1750 // Check the template parameter list, if we can.
1751 if (ExpectedTemplateParams &&
1752 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
1753 ExpectedTemplateParams,
1754 true, TPL_TemplateMatch))
1758 CheckTemplateParameterList(ParamLists[ParamIdx], 0,
1759 TPC_ClassTemplateMember))
1766 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
1768 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
1774 // If there were at least as many template-ids as there were template
1775 // parameter lists, then there are no template parameter lists remaining for
1776 // the declaration itself.
1777 if (ParamIdx >= NumParamLists)
1780 // If there were too many template parameter lists, complain about that now.
1781 if (ParamIdx < NumParamLists - 1) {
1782 bool HasAnyExplicitSpecHeader = false;
1783 bool AllExplicitSpecHeaders = true;
1784 for (unsigned I = ParamIdx; I != NumParamLists - 1; ++I) {
1785 if (ParamLists[I]->size() == 0)
1786 HasAnyExplicitSpecHeader = true;
1788 AllExplicitSpecHeaders = false;
1791 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
1792 AllExplicitSpecHeaders? diag::warn_template_spec_extra_headers
1793 : diag::err_template_spec_extra_headers)
1794 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
1795 ParamLists[NumParamLists - 2]->getRAngleLoc());
1797 // If there was a specialization somewhere, such that 'template<>' is
1798 // not required, and there were any 'template<>' headers, note where the
1799 // specialization occurred.
1800 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader)
1801 Diag(ExplicitSpecLoc,
1802 diag::note_explicit_template_spec_does_not_need_header)
1803 << NestedTypes.back();
1805 // We have a template parameter list with no corresponding scope, which
1806 // means that the resulting template declaration can't be instantiated
1807 // properly (we'll end up with dependent nodes when we shouldn't).
1808 if (!AllExplicitSpecHeaders)
1812 // C++ [temp.expl.spec]p16:
1813 // In an explicit specialization declaration for a member of a class
1814 // template or a member template that ap- pears in namespace scope, the
1815 // member template and some of its enclosing class templates may remain
1816 // unspecialized, except that the declaration shall not explicitly
1817 // specialize a class member template if its en- closing class templates
1818 // are not explicitly specialized as well.
1819 if (ParamLists[NumParamLists - 1]->size() == 0 &&
1820 SawNonEmptyTemplateParameterList) {
1821 Diag(DeclLoc, diag::err_specialize_member_of_template)
1822 << ParamLists[ParamIdx]->getSourceRange();
1824 IsExplicitSpecialization = false;
1828 // Return the last template parameter list, which corresponds to the
1829 // entity being declared.
1830 return ParamLists[NumParamLists - 1];
1833 void Sema::NoteAllFoundTemplates(TemplateName Name) {
1834 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1835 Diag(Template->getLocation(), diag::note_template_declared_here)
1836 << (isa<FunctionTemplateDecl>(Template)? 0
1837 : isa<ClassTemplateDecl>(Template)? 1
1838 : isa<TypeAliasTemplateDecl>(Template)? 2
1840 << Template->getDeclName();
1844 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
1845 for (OverloadedTemplateStorage::iterator I = OST->begin(),
1848 Diag((*I)->getLocation(), diag::note_template_declared_here)
1849 << 0 << (*I)->getDeclName();
1856 QualType Sema::CheckTemplateIdType(TemplateName Name,
1857 SourceLocation TemplateLoc,
1858 TemplateArgumentListInfo &TemplateArgs) {
1859 DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1860 if (DTN && DTN->isIdentifier())
1861 // When building a template-id where the template-name is dependent,
1862 // assume the template is a type template. Either our assumption is
1863 // correct, or the code is ill-formed and will be diagnosed when the
1864 // dependent name is substituted.
1865 return Context.getDependentTemplateSpecializationType(ETK_None,
1866 DTN->getQualifier(),
1867 DTN->getIdentifier(),
1870 TemplateDecl *Template = Name.getAsTemplateDecl();
1871 if (!Template || isa<FunctionTemplateDecl>(Template)) {
1872 // We might have a substituted template template parameter pack. If so,
1873 // build a template specialization type for it.
1874 if (Name.getAsSubstTemplateTemplateParmPack())
1875 return Context.getTemplateSpecializationType(Name, TemplateArgs);
1877 Diag(TemplateLoc, diag::err_template_id_not_a_type)
1879 NoteAllFoundTemplates(Name);
1883 // Check that the template argument list is well-formed for this
1885 llvm::SmallVector<TemplateArgument, 4> Converted;
1886 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
1890 assert((Converted.size() == Template->getTemplateParameters()->size()) &&
1891 "Converted template argument list is too short!");
1895 if (TypeAliasTemplateDecl *AliasTemplate
1896 = dyn_cast<TypeAliasTemplateDecl>(Template)) {
1897 // Find the canonical type for this type alias template specialization.
1898 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
1899 if (Pattern->isInvalidDecl())
1902 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
1903 Converted.data(), Converted.size());
1905 // Only substitute for the innermost template argument list.
1906 MultiLevelTemplateArgumentList TemplateArgLists;
1907 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
1908 unsigned Depth = AliasTemplate->getTemplateParameters()->getDepth();
1909 for (unsigned I = 0; I < Depth; ++I)
1910 TemplateArgLists.addOuterTemplateArguments(0, 0);
1912 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
1913 CanonType = SubstType(Pattern->getUnderlyingType(),
1914 TemplateArgLists, AliasTemplate->getLocation(),
1915 AliasTemplate->getDeclName());
1916 if (CanonType.isNull())
1918 } else if (Name.isDependent() ||
1919 TemplateSpecializationType::anyDependentTemplateArguments(
1921 // This class template specialization is a dependent
1922 // type. Therefore, its canonical type is another class template
1923 // specialization type that contains all of the converted
1924 // arguments in canonical form. This ensures that, e.g., A<T> and
1925 // A<T, T> have identical types when A is declared as:
1927 // template<typename T, typename U = T> struct A;
1928 TemplateName CanonName = Context.getCanonicalTemplateName(Name);
1929 CanonType = Context.getTemplateSpecializationType(CanonName,
1933 // FIXME: CanonType is not actually the canonical type, and unfortunately
1934 // it is a TemplateSpecializationType that we will never use again.
1935 // In the future, we need to teach getTemplateSpecializationType to only
1936 // build the canonical type and return that to us.
1937 CanonType = Context.getCanonicalType(CanonType);
1939 // This might work out to be a current instantiation, in which
1940 // case the canonical type needs to be the InjectedClassNameType.
1942 // TODO: in theory this could be a simple hashtable lookup; most
1943 // changes to CurContext don't change the set of current
1945 if (isa<ClassTemplateDecl>(Template)) {
1946 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
1947 // If we get out to a namespace, we're done.
1948 if (Ctx->isFileContext()) break;
1950 // If this isn't a record, keep looking.
1951 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
1952 if (!Record) continue;
1954 // Look for one of the two cases with InjectedClassNameTypes
1955 // and check whether it's the same template.
1956 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
1957 !Record->getDescribedClassTemplate())
1960 // Fetch the injected class name type and check whether its
1961 // injected type is equal to the type we just built.
1962 QualType ICNT = Context.getTypeDeclType(Record);
1963 QualType Injected = cast<InjectedClassNameType>(ICNT)
1964 ->getInjectedSpecializationType();
1966 if (CanonType != Injected->getCanonicalTypeInternal())
1969 // If so, the canonical type of this TST is the injected
1970 // class name type of the record we just found.
1971 assert(ICNT.isCanonical());
1976 } else if (ClassTemplateDecl *ClassTemplate
1977 = dyn_cast<ClassTemplateDecl>(Template)) {
1978 // Find the class template specialization declaration that
1979 // corresponds to these arguments.
1980 void *InsertPos = 0;
1981 ClassTemplateSpecializationDecl *Decl
1982 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(),
1985 // This is the first time we have referenced this class template
1986 // specialization. Create the canonical declaration and add it to
1987 // the set of specializations.
1988 Decl = ClassTemplateSpecializationDecl::Create(Context,
1989 ClassTemplate->getTemplatedDecl()->getTagKind(),
1990 ClassTemplate->getDeclContext(),
1991 ClassTemplate->getLocation(),
1992 ClassTemplate->getLocation(),
1995 Converted.size(), 0);
1996 ClassTemplate->AddSpecialization(Decl, InsertPos);
1997 Decl->setLexicalDeclContext(CurContext);
2000 CanonType = Context.getTypeDeclType(Decl);
2001 assert(isa<RecordType>(CanonType) &&
2002 "type of non-dependent specialization is not a RecordType");
2005 // Build the fully-sugared type for this class template
2006 // specialization, which refers back to the class template
2007 // specialization we created or found.
2008 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
2012 Sema::ActOnTemplateIdType(CXXScopeSpec &SS,
2013 TemplateTy TemplateD, SourceLocation TemplateLoc,
2014 SourceLocation LAngleLoc,
2015 ASTTemplateArgsPtr TemplateArgsIn,
2016 SourceLocation RAngleLoc) {
2020 TemplateName Template = TemplateD.getAsVal<TemplateName>();
2022 // Translate the parser's template argument list in our AST format.
2023 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2024 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2026 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2027 QualType T = Context.getDependentTemplateSpecializationType(ETK_None,
2028 DTN->getQualifier(),
2029 DTN->getIdentifier(),
2032 // Build type-source information.
2034 DependentTemplateSpecializationTypeLoc SpecTL
2035 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2036 SpecTL.setKeywordLoc(SourceLocation());
2037 SpecTL.setNameLoc(TemplateLoc);
2038 SpecTL.setLAngleLoc(LAngleLoc);
2039 SpecTL.setRAngleLoc(RAngleLoc);
2040 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2041 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2042 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2043 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2046 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2047 TemplateArgsIn.release();
2049 if (Result.isNull())
2052 // Build type-source information.
2054 TemplateSpecializationTypeLoc SpecTL
2055 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2056 SpecTL.setTemplateNameLoc(TemplateLoc);
2057 SpecTL.setLAngleLoc(LAngleLoc);
2058 SpecTL.setRAngleLoc(RAngleLoc);
2059 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2060 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2062 if (SS.isNotEmpty()) {
2063 // Create an elaborated-type-specifier containing the nested-name-specifier.
2064 Result = Context.getElaboratedType(ETK_None, SS.getScopeRep(), Result);
2065 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2066 ElabTL.setKeywordLoc(SourceLocation());
2067 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2070 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2073 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
2074 TypeSpecifierType TagSpec,
2075 SourceLocation TagLoc,
2077 TemplateTy TemplateD,
2078 SourceLocation TemplateLoc,
2079 SourceLocation LAngleLoc,
2080 ASTTemplateArgsPtr TemplateArgsIn,
2081 SourceLocation RAngleLoc) {
2082 TemplateName Template = TemplateD.getAsVal<TemplateName>();
2084 // Translate the parser's template argument list in our AST format.
2085 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
2086 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
2088 // Determine the tag kind
2089 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
2090 ElaboratedTypeKeyword Keyword
2091 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
2093 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
2094 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
2095 DTN->getQualifier(),
2096 DTN->getIdentifier(),
2099 // Build type-source information.
2101 DependentTemplateSpecializationTypeLoc SpecTL
2102 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
2103 SpecTL.setKeywordLoc(TagLoc);
2104 SpecTL.setNameLoc(TemplateLoc);
2105 SpecTL.setLAngleLoc(LAngleLoc);
2106 SpecTL.setRAngleLoc(RAngleLoc);
2107 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
2108 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
2109 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
2110 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
2113 if (TypeAliasTemplateDecl *TAT =
2114 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
2115 // C++0x [dcl.type.elab]p2:
2116 // If the identifier resolves to a typedef-name or the simple-template-id
2117 // resolves to an alias template specialization, the
2118 // elaborated-type-specifier is ill-formed.
2119 Diag(TemplateLoc, diag::err_tag_reference_non_tag) << 4;
2120 Diag(TAT->getLocation(), diag::note_declared_at);
2123 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
2124 if (Result.isNull())
2125 return TypeResult();
2127 // Check the tag kind
2128 if (const RecordType *RT = Result->getAs<RecordType>()) {
2129 RecordDecl *D = RT->getDecl();
2131 IdentifierInfo *Id = D->getIdentifier();
2132 assert(Id && "templated class must have an identifier");
2134 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
2136 Diag(TagLoc, diag::err_use_with_wrong_tag)
2138 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
2139 Diag(D->getLocation(), diag::note_previous_use);
2143 // Provide source-location information for the template specialization.
2145 TemplateSpecializationTypeLoc SpecTL
2146 = TLB.push<TemplateSpecializationTypeLoc>(Result);
2147 SpecTL.setTemplateNameLoc(TemplateLoc);
2148 SpecTL.setLAngleLoc(LAngleLoc);
2149 SpecTL.setRAngleLoc(RAngleLoc);
2150 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
2151 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
2153 // Construct an elaborated type containing the nested-name-specifier (if any)
2155 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
2156 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
2157 ElabTL.setKeywordLoc(TagLoc);
2158 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
2159 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
2162 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
2165 const TemplateArgumentListInfo &TemplateArgs) {
2166 // FIXME: Can we do any checking at this point? I guess we could check the
2167 // template arguments that we have against the template name, if the template
2168 // name refers to a single template. That's not a terribly common case,
2170 // foo<int> could identify a single function unambiguously
2171 // This approach does NOT work, since f<int>(1);
2172 // gets resolved prior to resorting to overload resolution
2173 // i.e., template<class T> void f(double);
2174 // vs template<class T, class U> void f(U);
2176 // These should be filtered out by our callers.
2177 assert(!R.empty() && "empty lookup results when building templateid");
2178 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
2180 // We don't want lookup warnings at this point.
2181 R.suppressDiagnostics();
2183 UnresolvedLookupExpr *ULE
2184 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2185 SS.getWithLocInContext(Context),
2186 R.getLookupNameInfo(),
2187 RequiresADL, TemplateArgs,
2188 R.begin(), R.end());
2193 // We actually only call this from template instantiation.
2195 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
2196 const DeclarationNameInfo &NameInfo,
2197 const TemplateArgumentListInfo &TemplateArgs) {
2199 if (!(DC = computeDeclContext(SS, false)) ||
2200 DC->isDependentContext() ||
2201 RequireCompleteDeclContext(SS, DC))
2202 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs);
2204 bool MemberOfUnknownSpecialization;
2205 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2206 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false,
2207 MemberOfUnknownSpecialization);
2209 if (R.isAmbiguous())
2213 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template)
2214 << NameInfo.getName() << SS.getRange();
2218 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
2219 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
2220 << (NestedNameSpecifier*) SS.getScopeRep()
2221 << NameInfo.getName() << SS.getRange();
2222 Diag(Temp->getLocation(), diag::note_referenced_class_template);
2226 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs);
2229 /// \brief Form a dependent template name.
2231 /// This action forms a dependent template name given the template
2232 /// name and its (presumably dependent) scope specifier. For
2233 /// example, given "MetaFun::template apply", the scope specifier \p
2234 /// SS will be "MetaFun::", \p TemplateKWLoc contains the location
2235 /// of the "template" keyword, and "apply" is the \p Name.
2236 TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S,
2237 SourceLocation TemplateKWLoc,
2239 UnqualifiedId &Name,
2240 ParsedType ObjectType,
2241 bool EnteringContext,
2242 TemplateTy &Result) {
2243 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() &&
2244 !getLangOptions().CPlusPlus0x)
2245 Diag(TemplateKWLoc, diag::ext_template_outside_of_template)
2246 << FixItHint::CreateRemoval(TemplateKWLoc);
2248 DeclContext *LookupCtx = 0;
2250 LookupCtx = computeDeclContext(SS, EnteringContext);
2251 if (!LookupCtx && ObjectType)
2252 LookupCtx = computeDeclContext(ObjectType.get());
2254 // C++0x [temp.names]p5:
2255 // If a name prefixed by the keyword template is not the name of
2256 // a template, the program is ill-formed. [Note: the keyword
2257 // template may not be applied to non-template members of class
2258 // templates. -end note ] [ Note: as is the case with the
2259 // typename prefix, the template prefix is allowed in cases
2260 // where it is not strictly necessary; i.e., when the
2261 // nested-name-specifier or the expression on the left of the ->
2262 // or . is not dependent on a template-parameter, or the use
2263 // does not appear in the scope of a template. -end note]
2265 // Note: C++03 was more strict here, because it banned the use of
2266 // the "template" keyword prior to a template-name that was not a
2267 // dependent name. C++ DR468 relaxed this requirement (the
2268 // "template" keyword is now permitted). We follow the C++0x
2269 // rules, even in C++03 mode with a warning, retroactively applying the DR.
2270 bool MemberOfUnknownSpecialization;
2271 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name,
2272 ObjectType, EnteringContext, Result,
2273 MemberOfUnknownSpecialization);
2274 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() &&
2275 isa<CXXRecordDecl>(LookupCtx) &&
2276 (!cast<CXXRecordDecl>(LookupCtx)->hasDefinition() ||
2277 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases())) {
2278 // This is a dependent template. Handle it below.
2279 } else if (TNK == TNK_Non_template) {
2280 Diag(Name.getSourceRange().getBegin(),
2281 diag::err_template_kw_refers_to_non_template)
2282 << GetNameFromUnqualifiedId(Name).getName()
2283 << Name.getSourceRange()
2285 return TNK_Non_template;
2287 // We found something; return it.
2292 NestedNameSpecifier *Qualifier
2293 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
2295 switch (Name.getKind()) {
2296 case UnqualifiedId::IK_Identifier:
2297 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2299 return TNK_Dependent_template_name;
2301 case UnqualifiedId::IK_OperatorFunctionId:
2302 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier,
2303 Name.OperatorFunctionId.Operator));
2304 return TNK_Dependent_template_name;
2306 case UnqualifiedId::IK_LiteralOperatorId:
2307 assert(false && "We don't support these; Parse shouldn't have allowed propagation");
2313 Diag(Name.getSourceRange().getBegin(),
2314 diag::err_template_kw_refers_to_non_template)
2315 << GetNameFromUnqualifiedId(Name).getName()
2316 << Name.getSourceRange()
2318 return TNK_Non_template;
2321 bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
2322 const TemplateArgumentLoc &AL,
2323 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2324 const TemplateArgument &Arg = AL.getArgument();
2326 // Check template type parameter.
2327 switch(Arg.getKind()) {
2328 case TemplateArgument::Type:
2329 // C++ [temp.arg.type]p1:
2330 // A template-argument for a template-parameter which is a
2331 // type shall be a type-id.
2333 case TemplateArgument::Template: {
2334 // We have a template type parameter but the template argument
2335 // is a template without any arguments.
2336 SourceRange SR = AL.getSourceRange();
2337 TemplateName Name = Arg.getAsTemplate();
2338 Diag(SR.getBegin(), diag::err_template_missing_args)
2340 if (TemplateDecl *Decl = Name.getAsTemplateDecl())
2341 Diag(Decl->getLocation(), diag::note_template_decl_here);
2346 // We have a template type parameter but the template argument
2348 SourceRange SR = AL.getSourceRange();
2349 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
2350 Diag(Param->getLocation(), diag::note_template_param_here);
2356 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo()))
2359 // Add the converted template type argument.
2360 Converted.push_back(
2361 TemplateArgument(Context.getCanonicalType(Arg.getAsType())));
2365 /// \brief Substitute template arguments into the default template argument for
2366 /// the given template type parameter.
2368 /// \param SemaRef the semantic analysis object for which we are performing
2369 /// the substitution.
2371 /// \param Template the template that we are synthesizing template arguments
2374 /// \param TemplateLoc the location of the template name that started the
2375 /// template-id we are checking.
2377 /// \param RAngleLoc the location of the right angle bracket ('>') that
2378 /// terminates the template-id.
2380 /// \param Param the template template parameter whose default we are
2381 /// substituting into.
2383 /// \param Converted the list of template arguments provided for template
2384 /// parameters that precede \p Param in the template parameter list.
2385 /// \returns the substituted template argument, or NULL if an error occurred.
2386 static TypeSourceInfo *
2387 SubstDefaultTemplateArgument(Sema &SemaRef,
2388 TemplateDecl *Template,
2389 SourceLocation TemplateLoc,
2390 SourceLocation RAngleLoc,
2391 TemplateTypeParmDecl *Param,
2392 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2393 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
2395 // If the argument type is dependent, instantiate it now based
2396 // on the previously-computed template arguments.
2397 if (ArgType->getType()->isDependentType()) {
2398 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2399 Converted.data(), Converted.size());
2401 MultiLevelTemplateArgumentList AllTemplateArgs
2402 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2404 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2405 Template, Converted.data(),
2407 SourceRange(TemplateLoc, RAngleLoc));
2409 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs,
2410 Param->getDefaultArgumentLoc(),
2411 Param->getDeclName());
2417 /// \brief Substitute template arguments into the default template argument for
2418 /// the given non-type template parameter.
2420 /// \param SemaRef the semantic analysis object for which we are performing
2421 /// the substitution.
2423 /// \param Template the template that we are synthesizing template arguments
2426 /// \param TemplateLoc the location of the template name that started the
2427 /// template-id we are checking.
2429 /// \param RAngleLoc the location of the right angle bracket ('>') that
2430 /// terminates the template-id.
2432 /// \param Param the non-type template parameter whose default we are
2433 /// substituting into.
2435 /// \param Converted the list of template arguments provided for template
2436 /// parameters that precede \p Param in the template parameter list.
2438 /// \returns the substituted template argument, or NULL if an error occurred.
2440 SubstDefaultTemplateArgument(Sema &SemaRef,
2441 TemplateDecl *Template,
2442 SourceLocation TemplateLoc,
2443 SourceLocation RAngleLoc,
2444 NonTypeTemplateParmDecl *Param,
2445 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2446 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2447 Converted.data(), Converted.size());
2449 MultiLevelTemplateArgumentList AllTemplateArgs
2450 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2452 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2453 Template, Converted.data(),
2455 SourceRange(TemplateLoc, RAngleLoc));
2457 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs);
2460 /// \brief Substitute template arguments into the default template argument for
2461 /// the given template template parameter.
2463 /// \param SemaRef the semantic analysis object for which we are performing
2464 /// the substitution.
2466 /// \param Template the template that we are synthesizing template arguments
2469 /// \param TemplateLoc the location of the template name that started the
2470 /// template-id we are checking.
2472 /// \param RAngleLoc the location of the right angle bracket ('>') that
2473 /// terminates the template-id.
2475 /// \param Param the template template parameter whose default we are
2476 /// substituting into.
2478 /// \param Converted the list of template arguments provided for template
2479 /// parameters that precede \p Param in the template parameter list.
2481 /// \param QualifierLoc Will be set to the nested-name-specifier (with
2482 /// source-location information) that precedes the template name.
2484 /// \returns the substituted template argument, or NULL if an error occurred.
2486 SubstDefaultTemplateArgument(Sema &SemaRef,
2487 TemplateDecl *Template,
2488 SourceLocation TemplateLoc,
2489 SourceLocation RAngleLoc,
2490 TemplateTemplateParmDecl *Param,
2491 llvm::SmallVectorImpl<TemplateArgument> &Converted,
2492 NestedNameSpecifierLoc &QualifierLoc) {
2493 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2494 Converted.data(), Converted.size());
2496 MultiLevelTemplateArgumentList AllTemplateArgs
2497 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs);
2499 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
2500 Template, Converted.data(),
2502 SourceRange(TemplateLoc, RAngleLoc));
2504 // Substitute into the nested-name-specifier first,
2505 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
2507 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2510 return TemplateName();
2513 return SemaRef.SubstTemplateName(QualifierLoc,
2514 Param->getDefaultArgument().getArgument().getAsTemplate(),
2515 Param->getDefaultArgument().getTemplateNameLoc(),
2519 /// \brief If the given template parameter has a default template
2520 /// argument, substitute into that default template argument and
2521 /// return the corresponding template argument.
2523 Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
2524 SourceLocation TemplateLoc,
2525 SourceLocation RAngleLoc,
2527 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2528 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
2529 if (!TypeParm->hasDefaultArgument())
2530 return TemplateArgumentLoc();
2532 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
2538 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
2540 return TemplateArgumentLoc();
2543 if (NonTypeTemplateParmDecl *NonTypeParm
2544 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2545 if (!NonTypeParm->hasDefaultArgument())
2546 return TemplateArgumentLoc();
2548 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
2553 if (Arg.isInvalid())
2554 return TemplateArgumentLoc();
2556 Expr *ArgE = Arg.takeAs<Expr>();
2557 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
2560 TemplateTemplateParmDecl *TempTempParm
2561 = cast<TemplateTemplateParmDecl>(Param);
2562 if (!TempTempParm->hasDefaultArgument())
2563 return TemplateArgumentLoc();
2566 NestedNameSpecifierLoc QualifierLoc;
2567 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
2574 return TemplateArgumentLoc();
2576 return TemplateArgumentLoc(TemplateArgument(TName),
2577 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
2578 TempTempParm->getDefaultArgument().getTemplateNameLoc());
2581 /// \brief Check that the given template argument corresponds to the given
2582 /// template parameter.
2584 /// \param Param The template parameter against which the argument will be
2587 /// \param Arg The template argument.
2589 /// \param Template The template in which the template argument resides.
2591 /// \param TemplateLoc The location of the template name for the template
2592 /// whose argument list we're matching.
2594 /// \param RAngleLoc The location of the right angle bracket ('>') that closes
2595 /// the template argument list.
2597 /// \param ArgumentPackIndex The index into the argument pack where this
2598 /// argument will be placed. Only valid if the parameter is a parameter pack.
2600 /// \param Converted The checked, converted argument will be added to the
2601 /// end of this small vector.
2603 /// \param CTAK Describes how we arrived at this particular template argument:
2604 /// explicitly written, deduced, etc.
2606 /// \returns true on error, false otherwise.
2607 bool Sema::CheckTemplateArgument(NamedDecl *Param,
2608 const TemplateArgumentLoc &Arg,
2609 NamedDecl *Template,
2610 SourceLocation TemplateLoc,
2611 SourceLocation RAngleLoc,
2612 unsigned ArgumentPackIndex,
2613 llvm::SmallVectorImpl<TemplateArgument> &Converted,
2614 CheckTemplateArgumentKind CTAK) {
2615 // Check template type parameters.
2616 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2617 return CheckTemplateTypeArgument(TTP, Arg, Converted);
2619 // Check non-type template parameters.
2620 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
2621 // Do substitution on the type of the non-type template parameter
2622 // with the template arguments we've seen thus far. But if the
2623 // template has a dependent context then we cannot substitute yet.
2624 QualType NTTPType = NTTP->getType();
2625 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
2626 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
2628 if (NTTPType->isDependentType() &&
2629 !isa<TemplateTemplateParmDecl>(Template) &&
2630 !Template->getDeclContext()->isDependentContext()) {
2631 // Do substitution on the type of the non-type template parameter.
2632 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2633 NTTP, Converted.data(), Converted.size(),
2634 SourceRange(TemplateLoc, RAngleLoc));
2636 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2637 Converted.data(), Converted.size());
2638 NTTPType = SubstType(NTTPType,
2639 MultiLevelTemplateArgumentList(TemplateArgs),
2640 NTTP->getLocation(),
2641 NTTP->getDeclName());
2642 // If that worked, check the non-type template parameter type
2644 if (!NTTPType.isNull())
2645 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
2646 NTTP->getLocation());
2647 if (NTTPType.isNull())
2651 switch (Arg.getArgument().getKind()) {
2652 case TemplateArgument::Null:
2653 assert(false && "Should never see a NULL template argument here");
2656 case TemplateArgument::Expression: {
2657 TemplateArgument Result;
2659 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
2661 if (Res.isInvalid())
2664 Converted.push_back(Result);
2668 case TemplateArgument::Declaration:
2669 case TemplateArgument::Integral:
2670 // We've already checked this template argument, so just copy
2671 // it to the list of converted arguments.
2672 Converted.push_back(Arg.getArgument());
2675 case TemplateArgument::Template:
2676 case TemplateArgument::TemplateExpansion:
2677 // We were given a template template argument. It may not be ill-formed;
2679 if (DependentTemplateName *DTN
2680 = Arg.getArgument().getAsTemplateOrTemplatePattern()
2681 .getAsDependentTemplateName()) {
2682 // We have a template argument such as \c T::template X, which we
2683 // parsed as a template template argument. However, since we now
2684 // know that we need a non-type template argument, convert this
2685 // template name into an expression.
2687 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
2688 Arg.getTemplateNameLoc());
2691 SS.Adopt(Arg.getTemplateQualifierLoc());
2692 ExprResult E = Owned(DependentScopeDeclRefExpr::Create(Context,
2693 SS.getWithLocInContext(Context),
2696 // If we parsed the template argument as a pack expansion, create a
2697 // pack expansion expression.
2698 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
2699 E = ActOnPackExpansion(E.take(), Arg.getTemplateEllipsisLoc());
2704 TemplateArgument Result;
2705 E = CheckTemplateArgument(NTTP, NTTPType, E.take(), Result);
2709 Converted.push_back(Result);
2713 // We have a template argument that actually does refer to a class
2714 // template, alias template, or template template parameter, and
2715 // therefore cannot be a non-type template argument.
2716 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
2717 << Arg.getSourceRange();
2719 Diag(Param->getLocation(), diag::note_template_param_here);
2722 case TemplateArgument::Type: {
2723 // We have a non-type template parameter but the template
2724 // argument is a type.
2726 // C++ [temp.arg]p2:
2727 // In a template-argument, an ambiguity between a type-id and
2728 // an expression is resolved to a type-id, regardless of the
2729 // form of the corresponding template-parameter.
2731 // We warn specifically about this case, since it can be rather
2732 // confusing for users.
2733 QualType T = Arg.getArgument().getAsType();
2734 SourceRange SR = Arg.getSourceRange();
2735 if (T->isFunctionType())
2736 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
2738 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
2739 Diag(Param->getLocation(), diag::note_template_param_here);
2743 case TemplateArgument::Pack:
2744 llvm_unreachable("Caller must expand template argument packs");
2752 // Check template template parameters.
2753 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
2755 // Substitute into the template parameter list of the template
2756 // template parameter, since previously-supplied template arguments
2757 // may appear within the template template parameter.
2759 // Set up a template instantiation context.
2760 LocalInstantiationScope Scope(*this);
2761 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
2762 TempParm, Converted.data(), Converted.size(),
2763 SourceRange(TemplateLoc, RAngleLoc));
2765 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
2766 Converted.data(), Converted.size());
2767 TempParm = cast_or_null<TemplateTemplateParmDecl>(
2768 SubstDecl(TempParm, CurContext,
2769 MultiLevelTemplateArgumentList(TemplateArgs)));
2774 switch (Arg.getArgument().getKind()) {
2775 case TemplateArgument::Null:
2776 assert(false && "Should never see a NULL template argument here");
2779 case TemplateArgument::Template:
2780 case TemplateArgument::TemplateExpansion:
2781 if (CheckTemplateArgument(TempParm, Arg))
2784 Converted.push_back(Arg.getArgument());
2787 case TemplateArgument::Expression:
2788 case TemplateArgument::Type:
2789 // We have a template template parameter but the template
2790 // argument does not refer to a template.
2791 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
2792 << getLangOptions().CPlusPlus0x;
2795 case TemplateArgument::Declaration:
2797 "Declaration argument with template template parameter");
2799 case TemplateArgument::Integral:
2801 "Integral argument with template template parameter");
2804 case TemplateArgument::Pack:
2805 llvm_unreachable("Caller must expand template argument packs");
2812 /// \brief Check that the given template argument list is well-formed
2813 /// for specializing the given template.
2814 bool Sema::CheckTemplateArgumentList(TemplateDecl *Template,
2815 SourceLocation TemplateLoc,
2816 TemplateArgumentListInfo &TemplateArgs,
2817 bool PartialTemplateArgs,
2818 llvm::SmallVectorImpl<TemplateArgument> &Converted) {
2819 TemplateParameterList *Params = Template->getTemplateParameters();
2820 unsigned NumParams = Params->size();
2821 unsigned NumArgs = TemplateArgs.size();
2822 bool Invalid = false;
2824 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc();
2826 bool HasParameterPack =
2827 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack();
2829 if ((NumArgs > NumParams && !HasParameterPack) ||
2830 (NumArgs < Params->getMinRequiredArguments() &&
2831 !PartialTemplateArgs)) {
2832 // FIXME: point at either the first arg beyond what we can handle,
2833 // or the '>', depending on whether we have too many or too few
2836 if (NumArgs > NumParams)
2837 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc);
2838 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2839 << (NumArgs > NumParams)
2840 << (isa<ClassTemplateDecl>(Template)? 0 :
2841 isa<FunctionTemplateDecl>(Template)? 1 :
2842 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2843 << Template << Range;
2844 Diag(Template->getLocation(), diag::note_template_decl_here)
2845 << Params->getSourceRange();
2849 // C++ [temp.arg]p1:
2850 // [...] The type and form of each template-argument specified in
2851 // a template-id shall match the type and form specified for the
2852 // corresponding parameter declared by the template in its
2853 // template-parameter-list.
2854 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
2855 llvm::SmallVector<TemplateArgument, 2> ArgumentPack;
2856 TemplateParameterList::iterator Param = Params->begin(),
2857 ParamEnd = Params->end();
2858 unsigned ArgIdx = 0;
2859 LocalInstantiationScope InstScope(*this, true);
2860 while (Param != ParamEnd) {
2861 if (ArgIdx < NumArgs) {
2862 // If we have an expanded parameter pack, make sure we don't have too
2864 if (NonTypeTemplateParmDecl *NTTP
2865 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2866 if (NTTP->isExpandedParameterPack() &&
2867 ArgumentPack.size() >= NTTP->getNumExpansionTypes()) {
2868 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
2870 << (isa<ClassTemplateDecl>(Template)? 0 :
2871 isa<FunctionTemplateDecl>(Template)? 1 :
2872 isa<TemplateTemplateParmDecl>(Template)? 2 : 3)
2874 Diag(Template->getLocation(), diag::note_template_decl_here)
2875 << Params->getSourceRange();
2880 // Check the template argument we were given.
2881 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template,
2882 TemplateLoc, RAngleLoc,
2883 ArgumentPack.size(), Converted))
2886 if ((*Param)->isTemplateParameterPack()) {
2887 // The template parameter was a template parameter pack, so take the
2888 // deduced argument and place it on the argument pack. Note that we
2889 // stay on the same template parameter so that we can deduce more
2891 ArgumentPack.push_back(Converted.back());
2892 Converted.pop_back();
2894 // Move to the next template parameter.
2901 // If we're checking a partial template argument list, we're done.
2902 if (PartialTemplateArgs) {
2903 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
2904 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
2905 ArgumentPack.data(),
2906 ArgumentPack.size()));
2911 // If we have a template parameter pack with no more corresponding
2912 // arguments, just break out now and we'll fill in the argument pack below.
2913 if ((*Param)->isTemplateParameterPack())
2916 // If our template is a template template parameter that hasn't acquired
2917 // its proper context yet (e.g., because we're using the template template
2918 // parameter in the signature of a function template, before we've built
2919 // the function template itself), don't attempt substitution of default
2920 // template arguments at this point: we don't have enough context to
2922 if (isTemplateTemplateParameter &&
2923 Template->getDeclContext()->isTranslationUnit())
2926 // We have a default template argument that we will use.
2927 TemplateArgumentLoc Arg;
2929 // Retrieve the default template argument from the template
2930 // parameter. For each kind of template parameter, we substitute the
2931 // template arguments provided thus far and any "outer" template arguments
2932 // (when the template parameter was part of a nested template) into
2933 // the default argument.
2934 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
2935 if (!TTP->hasDefaultArgument()) {
2936 assert(Invalid && "Missing default argument");
2940 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
2949 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
2951 } else if (NonTypeTemplateParmDecl *NTTP
2952 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
2953 if (!NTTP->hasDefaultArgument()) {
2954 assert(Invalid && "Missing default argument");
2958 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
2966 Expr *Ex = E.takeAs<Expr>();
2967 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
2969 TemplateTemplateParmDecl *TempParm
2970 = cast<TemplateTemplateParmDecl>(*Param);
2972 if (!TempParm->hasDefaultArgument()) {
2973 assert(Invalid && "Missing default argument");
2977 NestedNameSpecifierLoc QualifierLoc;
2978 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
2987 Arg = TemplateArgumentLoc(TemplateArgument(Name), QualifierLoc,
2988 TempParm->getDefaultArgument().getTemplateNameLoc());
2991 // Introduce an instantiation record that describes where we are using
2992 // the default template argument.
2993 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param,
2994 Converted.data(), Converted.size(),
2995 SourceRange(TemplateLoc, RAngleLoc));
2997 // Check the default template argument.
2998 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
2999 RAngleLoc, 0, Converted))
3002 // Core issue 150 (assumed resolution): if this is a template template
3003 // parameter, keep track of the default template arguments from the
3004 // template definition.
3005 if (isTemplateTemplateParameter)
3006 TemplateArgs.addArgument(Arg);
3008 // Move to the next template parameter and argument.
3013 // Form argument packs for each of the parameter packs remaining.
3014 while (Param != ParamEnd) {
3015 // If we're checking a partial list of template arguments, don't fill
3016 // in arguments for non-template parameter packs.
3018 if ((*Param)->isTemplateParameterPack()) {
3019 if (ArgumentPack.empty())
3020 Converted.push_back(TemplateArgument(0, 0));
3022 Converted.push_back(TemplateArgument::CreatePackCopy(Context,
3023 ArgumentPack.data(),
3024 ArgumentPack.size()));
3025 ArgumentPack.clear();
3036 class UnnamedLocalNoLinkageFinder
3037 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
3042 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
3045 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
3047 bool Visit(QualType T) {
3048 return inherited::Visit(T.getTypePtr());
3051 #define TYPE(Class, Parent) \
3052 bool Visit##Class##Type(const Class##Type *);
3053 #define ABSTRACT_TYPE(Class, Parent) \
3054 bool Visit##Class##Type(const Class##Type *) { return false; }
3055 #define NON_CANONICAL_TYPE(Class, Parent) \
3056 bool Visit##Class##Type(const Class##Type *) { return false; }
3057 #include "clang/AST/TypeNodes.def"
3059 bool VisitTagDecl(const TagDecl *Tag);
3060 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
3064 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
3068 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
3069 return Visit(T->getElementType());
3072 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
3073 return Visit(T->getPointeeType());
3076 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
3077 const BlockPointerType* T) {
3078 return Visit(T->getPointeeType());
3081 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
3082 const LValueReferenceType* T) {
3083 return Visit(T->getPointeeType());
3086 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
3087 const RValueReferenceType* T) {
3088 return Visit(T->getPointeeType());
3091 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
3092 const MemberPointerType* T) {
3093 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0));
3096 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
3097 const ConstantArrayType* T) {
3098 return Visit(T->getElementType());
3101 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
3102 const IncompleteArrayType* T) {
3103 return Visit(T->getElementType());
3106 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
3107 const VariableArrayType* T) {
3108 return Visit(T->getElementType());
3111 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
3112 const DependentSizedArrayType* T) {
3113 return Visit(T->getElementType());
3116 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
3117 const DependentSizedExtVectorType* T) {
3118 return Visit(T->getElementType());
3121 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
3122 return Visit(T->getElementType());
3125 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
3126 return Visit(T->getElementType());
3129 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
3130 const FunctionProtoType* T) {
3131 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
3132 AEnd = T->arg_type_end();
3138 return Visit(T->getResultType());
3141 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
3142 const FunctionNoProtoType* T) {
3143 return Visit(T->getResultType());
3146 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
3147 const UnresolvedUsingType*) {
3151 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
3155 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
3156 return Visit(T->getUnderlyingType());
3159 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
3163 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
3164 const UnaryTransformType*) {
3168 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
3169 return Visit(T->getDeducedType());
3172 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
3173 return VisitTagDecl(T->getDecl());
3176 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
3177 return VisitTagDecl(T->getDecl());
3180 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
3181 const TemplateTypeParmType*) {
3185 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
3186 const SubstTemplateTypeParmPackType *) {
3190 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
3191 const TemplateSpecializationType*) {
3195 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
3196 const InjectedClassNameType* T) {
3197 return VisitTagDecl(T->getDecl());
3200 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
3201 const DependentNameType* T) {
3202 return VisitNestedNameSpecifier(T->getQualifier());
3205 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
3206 const DependentTemplateSpecializationType* T) {
3207 return VisitNestedNameSpecifier(T->getQualifier());
3210 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
3211 const PackExpansionType* T) {
3212 return Visit(T->getPattern());
3215 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
3219 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
3220 const ObjCInterfaceType *) {
3224 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
3225 const ObjCObjectPointerType *) {
3229 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
3230 if (Tag->getDeclContext()->isFunctionOrMethod()) {
3231 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type)
3232 << S.Context.getTypeDeclType(Tag) << SR;
3236 if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl()) {
3237 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR;
3238 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
3245 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
3246 NestedNameSpecifier *NNS) {
3247 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix()))
3250 switch (NNS->getKind()) {
3251 case NestedNameSpecifier::Identifier:
3252 case NestedNameSpecifier::Namespace:
3253 case NestedNameSpecifier::NamespaceAlias:
3254 case NestedNameSpecifier::Global:
3257 case NestedNameSpecifier::TypeSpec:
3258 case NestedNameSpecifier::TypeSpecWithTemplate:
3259 return Visit(QualType(NNS->getAsType(), 0));
3265 /// \brief Check a template argument against its corresponding
3266 /// template type parameter.
3268 /// This routine implements the semantics of C++ [temp.arg.type]. It
3269 /// returns true if an error occurred, and false otherwise.
3270 bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param,
3271 TypeSourceInfo *ArgInfo) {
3272 assert(ArgInfo && "invalid TypeSourceInfo");
3273 QualType Arg = ArgInfo->getType();
3274 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
3276 if (Arg->isVariablyModifiedType()) {
3277 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
3278 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {
3279 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
3282 // C++03 [temp.arg.type]p2:
3283 // A local type, a type with no linkage, an unnamed type or a type
3284 // compounded from any of these types shall not be used as a
3285 // template-argument for a template type-parameter.
3287 // C++0x allows these, and even in C++03 we allow them as an extension with
3289 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) {
3290 UnnamedLocalNoLinkageFinder Finder(*this, SR);
3291 (void)Finder.Visit(Context.getCanonicalType(Arg));
3297 /// \brief Checks whether the given template argument is the address
3298 /// of an object or function according to C++ [temp.arg.nontype]p1.
3300 CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S,
3301 NonTypeTemplateParmDecl *Param,
3304 TemplateArgument &Converted) {
3305 bool Invalid = false;
3307 QualType ArgType = Arg->getType();
3309 // See through any implicit casts we added to fix the type.
3310 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
3311 Arg = Cast->getSubExpr();
3313 // C++ [temp.arg.nontype]p1:
3315 // A template-argument for a non-type, non-template
3316 // template-parameter shall be one of: [...]
3318 // -- the address of an object or function with external
3319 // linkage, including function templates and function
3320 // template-ids but excluding non-static class members,
3321 // expressed as & id-expression where the & is optional if
3322 // the name refers to a function or array, or if the
3323 // corresponding template-parameter is a reference; or
3324 DeclRefExpr *DRE = 0;
3326 // In C++98/03 mode, give an extension warning on any extra parentheses.
3327 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3328 bool ExtraParens = false;
3329 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
3330 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) {
3331 S.Diag(Arg->getSourceRange().getBegin(),
3332 diag::ext_template_arg_extra_parens)
3333 << Arg->getSourceRange();
3337 Arg = Parens->getSubExpr();
3340 bool AddressTaken = false;
3341 SourceLocation AddrOpLoc;
3342 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
3343 if (UnOp->getOpcode() == UO_AddrOf) {
3344 // Support &__uuidof(class_with_uuid) as a non-type template argument.
3345 // Very common in Microsoft COM headers.
3346 if (S.getLangOptions().Microsoft &&
3347 isa<CXXUuidofExpr>(UnOp->getSubExpr())) {
3348 Converted = TemplateArgument(ArgIn);
3352 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
3353 AddressTaken = true;
3354 AddrOpLoc = UnOp->getOperatorLoc();
3357 if (S.getLangOptions().Microsoft && isa<CXXUuidofExpr>(Arg)) {
3358 Converted = TemplateArgument(ArgIn);
3361 DRE = dyn_cast<DeclRefExpr>(Arg);
3364 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref)
3365 << Arg->getSourceRange();
3366 S.Diag(Param->getLocation(), diag::note_template_param_here);
3370 // Stop checking the precise nature of the argument if it is value dependent,
3371 // it should be checked when instantiated.
3372 if (Arg->isValueDependent()) {
3373 Converted = TemplateArgument(ArgIn);
3377 if (!isa<ValueDecl>(DRE->getDecl())) {
3378 S.Diag(Arg->getSourceRange().getBegin(),
3379 diag::err_template_arg_not_object_or_func_form)
3380 << Arg->getSourceRange();
3381 S.Diag(Param->getLocation(), diag::note_template_param_here);
3385 NamedDecl *Entity = 0;
3387 // Cannot refer to non-static data members
3388 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) {
3389 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field)
3390 << Field << Arg->getSourceRange();
3391 S.Diag(Param->getLocation(), diag::note_template_param_here);
3395 // Cannot refer to non-static member functions
3396 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl()))
3397 if (!Method->isStatic()) {
3398 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method)
3399 << Method << Arg->getSourceRange();
3400 S.Diag(Param->getLocation(), diag::note_template_param_here);
3404 // Functions must have external linkage.
3405 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) {
3406 if (!isExternalLinkage(Func->getLinkage())) {
3407 S.Diag(Arg->getSourceRange().getBegin(),
3408 diag::err_template_arg_function_not_extern)
3409 << Func << Arg->getSourceRange();
3410 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object)
3415 // Okay: we've named a function with external linkage.
3418 // If the template parameter has pointer type, the function decays.
3419 if (ParamType->isPointerType() && !AddressTaken)
3420 ArgType = S.Context.getPointerType(Func->getType());
3421 else if (AddressTaken && ParamType->isReferenceType()) {
3422 // If we originally had an address-of operator, but the
3423 // parameter has reference type, complain and (if things look
3424 // like they will work) drop the address-of operator.
3425 if (!S.Context.hasSameUnqualifiedType(Func->getType(),
3426 ParamType.getNonReferenceType())) {
3427 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3429 S.Diag(Param->getLocation(), diag::note_template_param_here);
3433 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3435 << FixItHint::CreateRemoval(AddrOpLoc);
3436 S.Diag(Param->getLocation(), diag::note_template_param_here);
3438 ArgType = Func->getType();
3440 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
3441 if (!isExternalLinkage(Var->getLinkage())) {
3442 S.Diag(Arg->getSourceRange().getBegin(),
3443 diag::err_template_arg_object_not_extern)
3444 << Var << Arg->getSourceRange();
3445 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object)
3450 // A value of reference type is not an object.
3451 if (Var->getType()->isReferenceType()) {
3452 S.Diag(Arg->getSourceRange().getBegin(),
3453 diag::err_template_arg_reference_var)
3454 << Var->getType() << Arg->getSourceRange();
3455 S.Diag(Param->getLocation(), diag::note_template_param_here);
3459 // Okay: we've named an object with external linkage
3462 // If the template parameter has pointer type, we must have taken
3463 // the address of this object.
3464 if (ParamType->isReferenceType()) {
3466 // If we originally had an address-of operator, but the
3467 // parameter has reference type, complain and (if things look
3468 // like they will work) drop the address-of operator.
3469 if (!S.Context.hasSameUnqualifiedType(Var->getType(),
3470 ParamType.getNonReferenceType())) {
3471 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3473 S.Diag(Param->getLocation(), diag::note_template_param_here);
3477 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
3479 << FixItHint::CreateRemoval(AddrOpLoc);
3480 S.Diag(Param->getLocation(), diag::note_template_param_here);
3482 ArgType = Var->getType();
3484 } else if (!AddressTaken && ParamType->isPointerType()) {
3485 if (Var->getType()->isArrayType()) {
3486 // Array-to-pointer decay.
3487 ArgType = S.Context.getArrayDecayedType(Var->getType());
3489 // If the template parameter has pointer type but the address of
3490 // this object was not taken, complain and (possibly) recover by
3491 // taking the address of the entity.
3492 ArgType = S.Context.getPointerType(Var->getType());
3493 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {
3494 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3496 S.Diag(Param->getLocation(), diag::note_template_param_here);
3500 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of)
3502 << FixItHint::CreateInsertion(Arg->getLocStart(), "&");
3504 S.Diag(Param->getLocation(), diag::note_template_param_here);
3508 // We found something else, but we don't know specifically what it is.
3509 S.Diag(Arg->getSourceRange().getBegin(),
3510 diag::err_template_arg_not_object_or_func)
3511 << Arg->getSourceRange();
3512 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
3516 if (ParamType->isPointerType() &&
3517 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() &&
3518 S.IsQualificationConversion(ArgType, ParamType, false)) {
3519 // For pointer-to-object types, qualification conversions are
3522 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
3523 if (!ParamRef->getPointeeType()->isFunctionType()) {
3524 // C++ [temp.arg.nontype]p5b3:
3525 // For a non-type template-parameter of type reference to
3526 // object, no conversions apply. The type referred to by the
3527 // reference may be more cv-qualified than the (otherwise
3528 // identical) type of the template- argument. The
3529 // template-parameter is bound directly to the
3530 // template-argument, which shall be an lvalue.
3532 // FIXME: Other qualifiers?
3533 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
3534 unsigned ArgQuals = ArgType.getCVRQualifiers();
3536 if ((ParamQuals | ArgQuals) != ParamQuals) {
3537 S.Diag(Arg->getSourceRange().getBegin(),
3538 diag::err_template_arg_ref_bind_ignores_quals)
3539 << ParamType << Arg->getType()
3540 << Arg->getSourceRange();
3541 S.Diag(Param->getLocation(), diag::note_template_param_here);
3547 // At this point, the template argument refers to an object or
3548 // function with external linkage. We now need to check whether the
3549 // argument and parameter types are compatible.
3550 if (!S.Context.hasSameUnqualifiedType(ArgType,
3551 ParamType.getNonReferenceType())) {
3552 // We can't perform this conversion or binding.
3553 if (ParamType->isReferenceType())
3554 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind)
3555 << ParamType << Arg->getType() << Arg->getSourceRange();
3557 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible)
3558 << Arg->getType() << ParamType << Arg->getSourceRange();
3559 S.Diag(Param->getLocation(), diag::note_template_param_here);
3564 // Create the template argument.
3565 Converted = TemplateArgument(Entity->getCanonicalDecl());
3566 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity);
3570 /// \brief Checks whether the given template argument is a pointer to
3571 /// member constant according to C++ [temp.arg.nontype]p1.
3572 bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg,
3573 TemplateArgument &Converted) {
3574 bool Invalid = false;
3576 // See through any implicit casts we added to fix the type.
3577 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg))
3578 Arg = Cast->getSubExpr();
3580 // C++ [temp.arg.nontype]p1:
3582 // A template-argument for a non-type, non-template
3583 // template-parameter shall be one of: [...]
3585 // -- a pointer to member expressed as described in 5.3.1.
3586 DeclRefExpr *DRE = 0;
3588 // In C++98/03 mode, give an extension warning on any extra parentheses.
3589 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
3590 bool ExtraParens = false;
3591 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {
3592 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) {
3593 Diag(Arg->getSourceRange().getBegin(),
3594 diag::ext_template_arg_extra_parens)
3595 << Arg->getSourceRange();
3599 Arg = Parens->getSubExpr();
3602 // A pointer-to-member constant written &Class::member.
3603 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {
3604 if (UnOp->getOpcode() == UO_AddrOf) {
3605 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());
3606 if (DRE && !DRE->getQualifier())
3610 // A constant of pointer-to-member type.
3611 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {
3612 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) {
3613 if (VD->getType()->isMemberPointerType()) {
3614 if (isa<NonTypeTemplateParmDecl>(VD) ||
3615 (isa<VarDecl>(VD) &&
3616 Context.getCanonicalType(VD->getType()).isConstQualified())) {
3617 if (Arg->isTypeDependent() || Arg->isValueDependent())
3618 Converted = TemplateArgument(Arg);
3620 Converted = TemplateArgument(VD->getCanonicalDecl());
3630 return Diag(Arg->getSourceRange().getBegin(),
3631 diag::err_template_arg_not_pointer_to_member_form)
3632 << Arg->getSourceRange();
3634 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) {
3635 assert((isa<FieldDecl>(DRE->getDecl()) ||
3636 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) &&
3637 "Only non-static member pointers can make it here");
3639 // Okay: this is the address of a non-static member, and therefore
3640 // a member pointer constant.
3641 if (Arg->isTypeDependent() || Arg->isValueDependent())
3642 Converted = TemplateArgument(Arg);
3644 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl());
3648 // We found something else, but we don't know specifically what it is.
3649 Diag(Arg->getSourceRange().getBegin(),
3650 diag::err_template_arg_not_pointer_to_member_form)
3651 << Arg->getSourceRange();
3652 Diag(DRE->getDecl()->getLocation(),
3653 diag::note_template_arg_refers_here);
3657 /// \brief Check a template argument against its corresponding
3658 /// non-type template parameter.
3660 /// This routine implements the semantics of C++ [temp.arg.nontype].
3661 /// If an error occurred, it returns ExprError(); otherwise, it
3662 /// returns the converted template argument. \p
3663 /// InstantiatedParamType is the type of the non-type template
3664 /// parameter after it has been instantiated.
3665 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
3666 QualType InstantiatedParamType, Expr *Arg,
3667 TemplateArgument &Converted,
3668 CheckTemplateArgumentKind CTAK) {
3669 SourceLocation StartLoc = Arg->getSourceRange().getBegin();
3671 // If either the parameter has a dependent type or the argument is
3672 // type-dependent, there's nothing we can check now.
3673 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) {
3674 // FIXME: Produce a cloned, canonical expression?
3675 Converted = TemplateArgument(Arg);
3679 // C++ [temp.arg.nontype]p5:
3680 // The following conversions are performed on each expression used
3681 // as a non-type template-argument. If a non-type
3682 // template-argument cannot be converted to the type of the
3683 // corresponding template-parameter then the program is
3686 // -- for a non-type template-parameter of integral or
3687 // enumeration type, integral promotions (4.5) and integral
3688 // conversions (4.7) are applied.
3689 QualType ParamType = InstantiatedParamType;
3690 QualType ArgType = Arg->getType();
3691 if (ParamType->isIntegralOrEnumerationType()) {
3692 // C++ [temp.arg.nontype]p1:
3693 // A template-argument for a non-type, non-template
3694 // template-parameter shall be one of:
3696 // -- an integral constant-expression of integral or enumeration
3698 // -- the name of a non-type template-parameter; or
3699 SourceLocation NonConstantLoc;
3701 if (!ArgType->isIntegralOrEnumerationType()) {
3702 Diag(Arg->getSourceRange().getBegin(),
3703 diag::err_template_arg_not_integral_or_enumeral)
3704 << ArgType << Arg->getSourceRange();
3705 Diag(Param->getLocation(), diag::note_template_param_here);
3707 } else if (!Arg->isValueDependent() &&
3708 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) {
3709 Diag(NonConstantLoc, diag::err_template_arg_not_ice)
3710 << ArgType << Arg->getSourceRange();
3714 // From here on out, all we care about are the unqualified forms
3715 // of the parameter and argument types.
3716 ParamType = ParamType.getUnqualifiedType();
3717 ArgType = ArgType.getUnqualifiedType();
3719 // Try to convert the argument to the parameter's type.
3720 if (Context.hasSameType(ParamType, ArgType)) {
3721 // Okay: no conversion necessary
3722 } else if (CTAK == CTAK_Deduced) {
3723 // C++ [temp.deduct.type]p17:
3724 // If, in the declaration of a function template with a non-type
3725 // template-parameter, the non-type template- parameter is used
3726 // in an expression in the function parameter-list and, if the
3727 // corresponding template-argument is deduced, the
3728 // template-argument type shall match the type of the
3729 // template-parameter exactly, except that a template-argument
3730 // deduced from an array bound may be of any integral type.
3731 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
3732 << ArgType << ParamType;
3733 Diag(Param->getLocation(), diag::note_template_param_here);
3735 } else if (ParamType->isBooleanType()) {
3736 // This is an integral-to-boolean conversion.
3737 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).take();
3738 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||
3739 !ParamType->isEnumeralType()) {
3740 // This is an integral promotion or conversion.
3741 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).take();
3743 // We can't perform this conversion.
3744 Diag(Arg->getSourceRange().getBegin(),
3745 diag::err_template_arg_not_convertible)
3746 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
3747 Diag(Param->getLocation(), diag::note_template_param_here);
3751 // Add the value of this argument to the list of converted
3752 // arguments. We use the bitwidth and signedness of the template
3754 if (Arg->isValueDependent()) {
3755 // The argument is value-dependent. Create a new
3756 // TemplateArgument with the converted expression.
3757 Converted = TemplateArgument(Arg);
3761 QualType IntegerType = Context.getCanonicalType(ParamType);
3762 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
3763 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType());
3765 if (ParamType->isBooleanType()) {
3766 // Value must be zero or one.
3768 unsigned AllowedBits = Context.getTypeSize(IntegerType);
3769 if (Value.getBitWidth() != AllowedBits)
3770 Value = Value.extOrTrunc(AllowedBits);
3771 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
3773 llvm::APSInt OldValue = Value;
3775 // Coerce the template argument's value to the value it will have
3776 // based on the template parameter's type.
3777 unsigned AllowedBits = Context.getTypeSize(IntegerType);
3778 if (Value.getBitWidth() != AllowedBits)
3779 Value = Value.extOrTrunc(AllowedBits);
3780 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
3782 // Complain if an unsigned parameter received a negative value.
3783 if (IntegerType->isUnsignedIntegerOrEnumerationType()
3784 && (OldValue.isSigned() && OldValue.isNegative())) {
3785 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative)
3786 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3787 << Arg->getSourceRange();
3788 Diag(Param->getLocation(), diag::note_template_param_here);
3791 // Complain if we overflowed the template parameter's type.
3792 unsigned RequiredBits;
3793 if (IntegerType->isUnsignedIntegerOrEnumerationType())
3794 RequiredBits = OldValue.getActiveBits();
3795 else if (OldValue.isUnsigned())
3796 RequiredBits = OldValue.getActiveBits() + 1;
3798 RequiredBits = OldValue.getMinSignedBits();
3799 if (RequiredBits > AllowedBits) {
3800 Diag(Arg->getSourceRange().getBegin(),
3801 diag::warn_template_arg_too_large)
3802 << OldValue.toString(10) << Value.toString(10) << Param->getType()
3803 << Arg->getSourceRange();
3804 Diag(Param->getLocation(), diag::note_template_param_here);
3808 Converted = TemplateArgument(Value,
3809 ParamType->isEnumeralType() ? ParamType
3814 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
3816 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion
3817 // from a template argument of type std::nullptr_t to a non-type
3818 // template parameter of type pointer to object, pointer to
3819 // function, or pointer-to-member, respectively.
3820 if (ArgType->isNullPtrType()) {
3821 if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
3822 Converted = TemplateArgument((NamedDecl *)0);
3826 if (ParamType->isNullPtrType()) {
3827 llvm::APSInt Zero(Context.getTypeSize(Context.NullPtrTy), true);
3828 Converted = TemplateArgument(Zero, Context.NullPtrTy);
3833 // Handle pointer-to-function, reference-to-function, and
3834 // pointer-to-member-function all in (roughly) the same way.
3835 if (// -- For a non-type template-parameter of type pointer to
3836 // function, only the function-to-pointer conversion (4.3) is
3837 // applied. If the template-argument represents a set of
3838 // overloaded functions (or a pointer to such), the matching
3839 // function is selected from the set (13.4).
3840 (ParamType->isPointerType() &&
3841 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) ||
3842 // -- For a non-type template-parameter of type reference to
3843 // function, no conversions apply. If the template-argument
3844 // represents a set of overloaded functions, the matching
3845 // function is selected from the set (13.4).
3846 (ParamType->isReferenceType() &&
3847 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
3848 // -- For a non-type template-parameter of type pointer to
3849 // member function, no conversions apply. If the
3850 // template-argument represents a set of overloaded member
3851 // functions, the matching member function is selected from
3853 (ParamType->isMemberPointerType() &&
3854 ParamType->getAs<MemberPointerType>()->getPointeeType()
3855 ->isFunctionType())) {
3857 if (Arg->getType() == Context.OverloadTy) {
3858 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,
3861 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3864 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3865 ArgType = Arg->getType();
3870 if (!ParamType->isMemberPointerType()) {
3871 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3878 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType(),
3880 Arg = ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg)).take();
3881 } else if (!Context.hasSameUnqualifiedType(ArgType,
3882 ParamType.getNonReferenceType())) {
3883 // We can't perform this conversion.
3884 Diag(Arg->getSourceRange().getBegin(),
3885 diag::err_template_arg_not_convertible)
3886 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
3887 Diag(Param->getLocation(), diag::note_template_param_here);
3891 if (CheckTemplateArgumentPointerToMember(Arg, Converted))
3896 if (ParamType->isPointerType()) {
3897 // -- for a non-type template-parameter of type pointer to
3898 // object, qualification conversions (4.4) and the
3899 // array-to-pointer conversion (4.2) are applied.
3900 // C++0x also allows a value of std::nullptr_t.
3901 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
3902 "Only object pointers allowed here");
3904 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3911 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
3912 // -- For a non-type template-parameter of type reference to
3913 // object, no conversions apply. The type referred to by the
3914 // reference may be more cv-qualified than the (otherwise
3915 // identical) type of the template-argument. The
3916 // template-parameter is bound directly to the
3917 // template-argument, which must be an lvalue.
3918 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
3919 "Only object references allowed here");
3921 if (Arg->getType() == Context.OverloadTy) {
3922 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,
3923 ParamRefType->getPointeeType(),
3926 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin()))
3929 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn);
3930 ArgType = Arg->getType();
3935 if (CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param,
3942 // -- For a non-type template-parameter of type pointer to data
3943 // member, qualification conversions (4.4) are applied.
3944 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
3946 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) {
3947 // Types match exactly: nothing more to do here.
3948 } else if (IsQualificationConversion(ArgType, ParamType, false)) {
3949 Arg = ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg)).take();
3951 // We can't perform this conversion.
3952 Diag(Arg->getSourceRange().getBegin(),
3953 diag::err_template_arg_not_convertible)
3954 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange();
3955 Diag(Param->getLocation(), diag::note_template_param_here);
3959 if (CheckTemplateArgumentPointerToMember(Arg, Converted))
3964 /// \brief Check a template argument against its corresponding
3965 /// template template parameter.
3967 /// This routine implements the semantics of C++ [temp.arg.template].
3968 /// It returns true if an error occurred, and false otherwise.
3969 bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param,
3970 const TemplateArgumentLoc &Arg) {
3971 TemplateName Name = Arg.getArgument().getAsTemplate();
3972 TemplateDecl *Template = Name.getAsTemplateDecl();
3974 // Any dependent template name is fine.
3975 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
3979 // C++0x [temp.arg.template]p1:
3980 // A template-argument for a template template-parameter shall be
3981 // the name of a class template or an alias template, expressed as an
3982 // id-expression. When the template-argument names a class template, only
3983 // primary class templates are considered when matching the
3984 // template template argument with the corresponding parameter;
3985 // partial specializations are not considered even if their
3986 // parameter lists match that of the template template parameter.
3988 // Note that we also allow template template parameters here, which
3989 // will happen when we are dealing with, e.g., class template
3990 // partial specializations.
3991 if (!isa<ClassTemplateDecl>(Template) &&
3992 !isa<TemplateTemplateParmDecl>(Template) &&
3993 !isa<TypeAliasTemplateDecl>(Template)) {
3994 assert(isa<FunctionTemplateDecl>(Template) &&
3995 "Only function templates are possible here");
3996 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template);
3997 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
4001 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(),
4002 Param->getTemplateParameters(),
4004 TPL_TemplateTemplateArgumentMatch,
4008 /// \brief Given a non-type template argument that refers to a
4009 /// declaration and the type of its corresponding non-type template
4010 /// parameter, produce an expression that properly refers to that
4013 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
4015 SourceLocation Loc) {
4016 assert(Arg.getKind() == TemplateArgument::Declaration &&
4017 "Only declaration template arguments permitted here");
4018 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
4020 if (VD->getDeclContext()->isRecord() &&
4021 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) {
4022 // If the value is a class member, we might have a pointer-to-member.
4023 // Determine whether the non-type template template parameter is of
4024 // pointer-to-member type. If so, we need to build an appropriate
4025 // expression for a pointer-to-member, since a "normal" DeclRefExpr
4026 // would refer to the member itself.
4027 if (ParamType->isMemberPointerType()) {
4029 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext()));
4030 NestedNameSpecifier *Qualifier
4031 = NestedNameSpecifier::Create(Context, 0, false,
4032 ClassType.getTypePtr());
4034 SS.MakeTrivial(Context, Qualifier, Loc);
4036 // The actual value-ness of this is unimportant, but for
4037 // internal consistency's sake, references to instance methods
4039 ExprValueKind VK = VK_LValue;
4040 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance())
4043 ExprResult RefExpr = BuildDeclRefExpr(VD,
4044 VD->getType().getNonReferenceType(),
4048 if (RefExpr.isInvalid())
4051 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
4053 // We might need to perform a trailing qualification conversion, since
4054 // the element type on the parameter could be more qualified than the
4055 // element type in the expression we constructed.
4056 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(),
4057 ParamType.getUnqualifiedType(), false))
4058 RefExpr = ImpCastExprToType(RefExpr.take(), ParamType.getUnqualifiedType(), CK_NoOp);
4060 assert(!RefExpr.isInvalid() &&
4061 Context.hasSameType(((Expr*) RefExpr.get())->getType(),
4062 ParamType.getUnqualifiedType()));
4063 return move(RefExpr);
4067 QualType T = VD->getType().getNonReferenceType();
4068 if (ParamType->isPointerType()) {
4069 // When the non-type template parameter is a pointer, take the
4070 // address of the declaration.
4071 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc);
4072 if (RefExpr.isInvalid())
4075 if (T->isFunctionType() || T->isArrayType()) {
4076 // Decay functions and arrays.
4077 RefExpr = DefaultFunctionArrayConversion(RefExpr.take());
4078 if (RefExpr.isInvalid())
4081 return move(RefExpr);
4084 // Take the address of everything else
4085 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());
4088 ExprValueKind VK = VK_RValue;
4090 // If the non-type template parameter has reference type, qualify the
4091 // resulting declaration reference with the extra qualifiers on the
4092 // type that the reference refers to.
4093 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) {
4095 T = Context.getQualifiedType(T,
4096 TargetRef->getPointeeType().getQualifiers());
4099 return BuildDeclRefExpr(VD, T, VK, Loc);
4102 /// \brief Construct a new expression that refers to the given
4103 /// integral template argument with the given source-location
4106 /// This routine takes care of the mapping from an integral template
4107 /// argument (which may have any integral type) to the appropriate
4110 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
4111 SourceLocation Loc) {
4112 assert(Arg.getKind() == TemplateArgument::Integral &&
4113 "Operation is only valid for integral template arguments");
4114 QualType T = Arg.getIntegralType();
4115 if (T->isCharType() || T->isWideCharType())
4116 return Owned(new (Context) CharacterLiteral(
4117 Arg.getAsIntegral()->getZExtValue(),
4118 T->isWideCharType(), T, Loc));
4119 if (T->isBooleanType())
4120 return Owned(new (Context) CXXBoolLiteralExpr(
4121 Arg.getAsIntegral()->getBoolValue(),
4124 if (T->isNullPtrType())
4125 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
4127 // If this is an enum type that we're instantiating, we need to use an integer
4128 // type the same size as the enumerator. We don't want to build an
4129 // IntegerLiteral with enum type.
4131 if (const EnumType *ET = T->getAs<EnumType>())
4132 BT = ET->getDecl()->getIntegerType();
4136 Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc);
4137 if (T->isEnumeralType()) {
4138 // FIXME: This is a hack. We need a better way to handle substituted
4139 // non-type template parameters.
4140 E = CStyleCastExpr::Create(Context, T, VK_RValue, CK_IntegralCast, E, 0,
4141 Context.getTrivialTypeSourceInfo(T, Loc),
4148 /// \brief Match two template parameters within template parameter lists.
4149 static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old,
4151 Sema::TemplateParameterListEqualKind Kind,
4152 SourceLocation TemplateArgLoc) {
4153 // Check the actual kind (type, non-type, template).
4154 if (Old->getKind() != New->getKind()) {
4156 unsigned NextDiag = diag::err_template_param_different_kind;
4157 if (TemplateArgLoc.isValid()) {
4158 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
4159 NextDiag = diag::note_template_param_different_kind;
4161 S.Diag(New->getLocation(), NextDiag)
4162 << (Kind != Sema::TPL_TemplateMatch);
4163 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
4164 << (Kind != Sema::TPL_TemplateMatch);
4170 // Check that both are parameter packs are neither are parameter packs.
4171 // However, if we are matching a template template argument to a
4172 // template template parameter, the template template parameter can have
4173 // a parameter pack where the template template argument does not.
4174 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
4175 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
4176 Old->isTemplateParameterPack())) {
4178 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
4179 if (TemplateArgLoc.isValid()) {
4180 S.Diag(TemplateArgLoc,
4181 diag::err_template_arg_template_params_mismatch);
4182 NextDiag = diag::note_template_parameter_pack_non_pack;
4185 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0
4186 : isa<NonTypeTemplateParmDecl>(New)? 1
4188 S.Diag(New->getLocation(), NextDiag)
4189 << ParamKind << New->isParameterPack();
4190 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
4191 << ParamKind << Old->isParameterPack();
4197 // For non-type template parameters, check the type of the parameter.
4198 if (NonTypeTemplateParmDecl *OldNTTP
4199 = dyn_cast<NonTypeTemplateParmDecl>(Old)) {
4200 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);
4202 // If we are matching a template template argument to a template
4203 // template parameter and one of the non-type template parameter types
4204 // is dependent, then we must wait until template instantiation time
4205 // to actually compare the arguments.
4206 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
4207 (OldNTTP->getType()->isDependentType() ||
4208 NewNTTP->getType()->isDependentType()))
4211 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) {
4213 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
4214 if (TemplateArgLoc.isValid()) {
4215 S.Diag(TemplateArgLoc,
4216 diag::err_template_arg_template_params_mismatch);
4217 NextDiag = diag::note_template_nontype_parm_different_type;
4219 S.Diag(NewNTTP->getLocation(), NextDiag)
4220 << NewNTTP->getType()
4221 << (Kind != Sema::TPL_TemplateMatch);
4222 S.Diag(OldNTTP->getLocation(),
4223 diag::note_template_nontype_parm_prev_declaration)
4224 << OldNTTP->getType();
4233 // For template template parameters, check the template parameter types.
4234 // The template parameter lists of template template
4235 // parameters must agree.
4236 if (TemplateTemplateParmDecl *OldTTP
4237 = dyn_cast<TemplateTemplateParmDecl>(Old)) {
4238 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);
4239 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(),
4240 OldTTP->getTemplateParameters(),
4242 (Kind == Sema::TPL_TemplateMatch
4243 ? Sema::TPL_TemplateTemplateParmMatch
4251 /// \brief Diagnose a known arity mismatch when comparing template argument
4254 void DiagnoseTemplateParameterListArityMismatch(Sema &S,
4255 TemplateParameterList *New,
4256 TemplateParameterList *Old,
4257 Sema::TemplateParameterListEqualKind Kind,
4258 SourceLocation TemplateArgLoc) {
4259 unsigned NextDiag = diag::err_template_param_list_different_arity;
4260 if (TemplateArgLoc.isValid()) {
4261 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
4262 NextDiag = diag::note_template_param_list_different_arity;
4264 S.Diag(New->getTemplateLoc(), NextDiag)
4265 << (New->size() > Old->size())
4266 << (Kind != Sema::TPL_TemplateMatch)
4267 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
4268 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
4269 << (Kind != Sema::TPL_TemplateMatch)
4270 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
4273 /// \brief Determine whether the given template parameter lists are
4276 /// \param New The new template parameter list, typically written in the
4277 /// source code as part of a new template declaration.
4279 /// \param Old The old template parameter list, typically found via
4280 /// name lookup of the template declared with this template parameter
4283 /// \param Complain If true, this routine will produce a diagnostic if
4284 /// the template parameter lists are not equivalent.
4286 /// \param Kind describes how we are to match the template parameter lists.
4288 /// \param TemplateArgLoc If this source location is valid, then we
4289 /// are actually checking the template parameter list of a template
4290 /// argument (New) against the template parameter list of its
4291 /// corresponding template template parameter (Old). We produce
4292 /// slightly different diagnostics in this scenario.
4294 /// \returns True if the template parameter lists are equal, false
4297 Sema::TemplateParameterListsAreEqual(TemplateParameterList *New,
4298 TemplateParameterList *Old,
4300 TemplateParameterListEqualKind Kind,
4301 SourceLocation TemplateArgLoc) {
4302 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
4304 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4310 // C++0x [temp.arg.template]p3:
4311 // A template-argument matches a template template-parameter (call it P)
4312 // when each of the template parameters in the template-parameter-list of
4313 // the template-argument's corresponding class template or alias template
4314 // (call it A) matches the corresponding template parameter in the
4315 // template-parameter-list of P. [...]
4316 TemplateParameterList::iterator NewParm = New->begin();
4317 TemplateParameterList::iterator NewParmEnd = New->end();
4318 for (TemplateParameterList::iterator OldParm = Old->begin(),
4319 OldParmEnd = Old->end();
4320 OldParm != OldParmEnd; ++OldParm) {
4321 if (Kind != TPL_TemplateTemplateArgumentMatch ||
4322 !(*OldParm)->isTemplateParameterPack()) {
4323 if (NewParm == NewParmEnd) {
4325 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4331 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
4332 Kind, TemplateArgLoc))
4339 // C++0x [temp.arg.template]p3:
4340 // [...] When P's template- parameter-list contains a template parameter
4341 // pack (14.5.3), the template parameter pack will match zero or more
4342 // template parameters or template parameter packs in the
4343 // template-parameter-list of A with the same type and form as the
4344 // template parameter pack in P (ignoring whether those template
4345 // parameters are template parameter packs).
4346 for (; NewParm != NewParmEnd; ++NewParm) {
4347 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain,
4348 Kind, TemplateArgLoc))
4353 // Make sure we exhausted all of the arguments.
4354 if (NewParm != NewParmEnd) {
4356 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,
4365 /// \brief Check whether a template can be declared within this scope.
4367 /// If the template declaration is valid in this scope, returns
4368 /// false. Otherwise, issues a diagnostic and returns true.
4370 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
4371 // Find the nearest enclosing declaration scope.
4372 while ((S->getFlags() & Scope::DeclScope) == 0 ||
4373 (S->getFlags() & Scope::TemplateParamScope) != 0)
4377 // A template-declaration can appear only as a namespace scope or
4378 // class scope declaration.
4379 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
4380 if (Ctx && isa<LinkageSpecDecl>(Ctx) &&
4381 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx)
4382 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
4383 << TemplateParams->getSourceRange();
4385 while (Ctx && isa<LinkageSpecDecl>(Ctx))
4386 Ctx = Ctx->getParent();
4388 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord()))
4391 return Diag(TemplateParams->getTemplateLoc(),
4392 diag::err_template_outside_namespace_or_class_scope)
4393 << TemplateParams->getSourceRange();
4396 /// \brief Determine what kind of template specialization the given declaration
4398 static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) {
4400 return TSK_Undeclared;
4402 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))
4403 return Record->getTemplateSpecializationKind();
4404 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
4405 return Function->getTemplateSpecializationKind();
4406 if (VarDecl *Var = dyn_cast<VarDecl>(D))
4407 return Var->getTemplateSpecializationKind();
4409 return TSK_Undeclared;
4412 /// \brief Check whether a specialization is well-formed in the current
4415 /// This routine determines whether a template specialization can be declared
4416 /// in the current context (C++ [temp.expl.spec]p2).
4418 /// \param S the semantic analysis object for which this check is being
4421 /// \param Specialized the entity being specialized or instantiated, which
4422 /// may be a kind of template (class template, function template, etc.) or
4423 /// a member of a class template (member function, static data member,
4426 /// \param PrevDecl the previous declaration of this entity, if any.
4428 /// \param Loc the location of the explicit specialization or instantiation of
4431 /// \param IsPartialSpecialization whether this is a partial specialization of
4432 /// a class template.
4434 /// \returns true if there was an error that we cannot recover from, false
4436 static bool CheckTemplateSpecializationScope(Sema &S,
4437 NamedDecl *Specialized,
4438 NamedDecl *PrevDecl,
4440 bool IsPartialSpecialization) {
4441 // Keep these "kind" numbers in sync with the %select statements in the
4442 // various diagnostics emitted by this routine.
4444 if (isa<ClassTemplateDecl>(Specialized))
4445 EntityKind = IsPartialSpecialization? 1 : 0;
4446 else if (isa<FunctionTemplateDecl>(Specialized))
4448 else if (isa<CXXMethodDecl>(Specialized))
4450 else if (isa<VarDecl>(Specialized))
4452 else if (isa<RecordDecl>(Specialized))
4455 S.Diag(Loc, diag::err_template_spec_unknown_kind);
4456 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
4460 // C++ [temp.expl.spec]p2:
4461 // An explicit specialization shall be declared in the namespace
4462 // of which the template is a member, or, for member templates, in
4463 // the namespace of which the enclosing class or enclosing class
4464 // template is a member. An explicit specialization of a member
4465 // function, member class or static data member of a class
4466 // template shall be declared in the namespace of which the class
4467 // template is a member. Such a declaration may also be a
4468 // definition. If the declaration is not a definition, the
4469 // specialization may be defined later in the name- space in which
4470 // the explicit specialization was declared, or in a namespace
4471 // that encloses the one in which the explicit specialization was
4473 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
4474 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
4479 if (S.CurContext->isRecord() && !IsPartialSpecialization) {
4480 S.Diag(Loc, diag::err_template_spec_decl_class_scope)
4485 // C++ [temp.class.spec]p6:
4486 // A class template partial specialization may be declared or redeclared
4487 // in any namespace scope in which its definition may be defined (14.5.1
4489 bool ComplainedAboutScope = false;
4490 DeclContext *SpecializedContext
4491 = Specialized->getDeclContext()->getEnclosingNamespaceContext();
4492 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext();
4494 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared ||
4495 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){
4496 // C++ [temp.exp.spec]p2:
4497 // An explicit specialization shall be declared in the namespace of which
4498 // the template is a member, or, for member templates, in the namespace
4499 // of which the enclosing class or enclosing class template is a member.
4500 // An explicit specialization of a member function, member class or
4501 // static data member of a class template shall be declared in the
4502 // namespace of which the class template is a member.
4504 // C++0x [temp.expl.spec]p2:
4505 // An explicit specialization shall be declared in a namespace enclosing
4506 // the specialized template.
4507 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) &&
4508 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) {
4509 bool IsCPlusPlus0xExtension
4510 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext);
4511 if (isa<TranslationUnitDecl>(SpecializedContext))
4512 S.Diag(Loc, IsCPlusPlus0xExtension
4513 ? diag::ext_template_spec_decl_out_of_scope_global
4514 : diag::err_template_spec_decl_out_of_scope_global)
4515 << EntityKind << Specialized;
4516 else if (isa<NamespaceDecl>(SpecializedContext))
4517 S.Diag(Loc, IsCPlusPlus0xExtension
4518 ? diag::ext_template_spec_decl_out_of_scope
4519 : diag::err_template_spec_decl_out_of_scope)
4520 << EntityKind << Specialized
4521 << cast<NamedDecl>(SpecializedContext);
4523 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
4524 ComplainedAboutScope = true;
4528 // Make sure that this redeclaration (or definition) occurs in an enclosing
4530 // Note that HandleDeclarator() performs this check for explicit
4531 // specializations of function templates, static data members, and member
4532 // functions, so we skip the check here for those kinds of entities.
4533 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though.
4534 // Should we refactor that check, so that it occurs later?
4535 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) &&
4536 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) ||
4537 isa<FunctionDecl>(Specialized))) {
4538 if (isa<TranslationUnitDecl>(SpecializedContext))
4539 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
4540 << EntityKind << Specialized;
4541 else if (isa<NamespaceDecl>(SpecializedContext))
4542 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope)
4543 << EntityKind << Specialized
4544 << cast<NamedDecl>(SpecializedContext);
4546 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
4549 // FIXME: check for specialization-after-instantiation errors and such.
4554 /// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs
4555 /// that checks non-type template partial specialization arguments.
4556 static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S,
4557 NonTypeTemplateParmDecl *Param,
4558 const TemplateArgument *Args,
4560 for (unsigned I = 0; I != NumArgs; ++I) {
4561 if (Args[I].getKind() == TemplateArgument::Pack) {
4562 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
4563 Args[I].pack_begin(),
4564 Args[I].pack_size()))
4570 Expr *ArgExpr = Args[I].getAsExpr();
4575 // We can have a pack expansion of any of the bullets below.
4576 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))
4577 ArgExpr = Expansion->getPattern();
4579 // Strip off any implicit casts we added as part of type checking.
4580 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4581 ArgExpr = ICE->getSubExpr();
4583 // C++ [temp.class.spec]p8:
4584 // A non-type argument is non-specialized if it is the name of a
4585 // non-type parameter. All other non-type arguments are
4588 // Below, we check the two conditions that only apply to
4589 // specialized non-type arguments, so skip any non-specialized
4591 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))
4592 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))
4595 // C++ [temp.class.spec]p9:
4596 // Within the argument list of a class template partial
4597 // specialization, the following restrictions apply:
4598 // -- A partially specialized non-type argument expression
4599 // shall not involve a template parameter of the partial
4600 // specialization except when the argument expression is a
4601 // simple identifier.
4602 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) {
4603 S.Diag(ArgExpr->getLocStart(),
4604 diag::err_dependent_non_type_arg_in_partial_spec)
4605 << ArgExpr->getSourceRange();
4609 // -- The type of a template parameter corresponding to a
4610 // specialized non-type argument shall not be dependent on a
4611 // parameter of the specialization.
4612 if (Param->getType()->isDependentType()) {
4613 S.Diag(ArgExpr->getLocStart(),
4614 diag::err_dependent_typed_non_type_arg_in_partial_spec)
4616 << ArgExpr->getSourceRange();
4617 S.Diag(Param->getLocation(), diag::note_template_param_here);
4625 /// \brief Check the non-type template arguments of a class template
4626 /// partial specialization according to C++ [temp.class.spec]p9.
4628 /// \param TemplateParams the template parameters of the primary class
4631 /// \param TemplateArg the template arguments of the class template
4632 /// partial specialization.
4634 /// \returns true if there was an error, false otherwise.
4635 static bool CheckClassTemplatePartialSpecializationArgs(Sema &S,
4636 TemplateParameterList *TemplateParams,
4637 llvm::SmallVectorImpl<TemplateArgument> &TemplateArgs) {
4638 const TemplateArgument *ArgList = TemplateArgs.data();
4640 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4641 NonTypeTemplateParmDecl *Param
4642 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));
4646 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param,
4654 /// \brief Retrieve the previous declaration of the given declaration.
4655 static NamedDecl *getPreviousDecl(NamedDecl *ND) {
4656 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4657 return VD->getPreviousDeclaration();
4658 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND))
4659 return FD->getPreviousDeclaration();
4660 if (TagDecl *TD = dyn_cast<TagDecl>(ND))
4661 return TD->getPreviousDeclaration();
4662 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4663 return TD->getPreviousDeclaration();
4664 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4665 return FTD->getPreviousDeclaration();
4666 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND))
4667 return CTD->getPreviousDeclaration();
4672 Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec,
4674 SourceLocation KWLoc,
4676 TemplateTy TemplateD,
4677 SourceLocation TemplateNameLoc,
4678 SourceLocation LAngleLoc,
4679 ASTTemplateArgsPtr TemplateArgsIn,
4680 SourceLocation RAngleLoc,
4681 AttributeList *Attr,
4682 MultiTemplateParamsArg TemplateParameterLists) {
4683 assert(TUK != TUK_Reference && "References are not specializations");
4685 // NOTE: KWLoc is the location of the tag keyword. This will instead
4686 // store the location of the outermost template keyword in the declaration.
4687 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
4688 ? TemplateParameterLists.get()[0]->getTemplateLoc() : SourceLocation();
4690 // Find the class template we're specializing
4691 TemplateName Name = TemplateD.getAsVal<TemplateName>();
4692 ClassTemplateDecl *ClassTemplate
4693 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());
4695 if (!ClassTemplate) {
4696 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
4697 << (Name.getAsTemplateDecl() &&
4698 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
4702 bool isExplicitSpecialization = false;
4703 bool isPartialSpecialization = false;
4705 // Check the validity of the template headers that introduce this
4707 // FIXME: We probably shouldn't complain about these headers for
4708 // friend declarations.
4709 bool Invalid = false;
4710 TemplateParameterList *TemplateParams
4711 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc,
4714 (TemplateParameterList**)TemplateParameterLists.get(),
4715 TemplateParameterLists.size(),
4717 isExplicitSpecialization,
4722 if (TemplateParams && TemplateParams->size() > 0) {
4723 isPartialSpecialization = true;
4725 if (TUK == TUK_Friend) {
4726 Diag(KWLoc, diag::err_partial_specialization_friend)
4727 << SourceRange(LAngleLoc, RAngleLoc);
4731 // C++ [temp.class.spec]p10:
4732 // The template parameter list of a specialization shall not
4733 // contain default template argument values.
4734 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
4735 Decl *Param = TemplateParams->getParam(I);
4736 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {
4737 if (TTP->hasDefaultArgument()) {
4738 Diag(TTP->getDefaultArgumentLoc(),
4739 diag::err_default_arg_in_partial_spec);
4740 TTP->removeDefaultArgument();
4742 } else if (NonTypeTemplateParmDecl *NTTP
4743 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
4744 if (Expr *DefArg = NTTP->getDefaultArgument()) {
4745 Diag(NTTP->getDefaultArgumentLoc(),
4746 diag::err_default_arg_in_partial_spec)
4747 << DefArg->getSourceRange();
4748 NTTP->removeDefaultArgument();
4751 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);
4752 if (TTP->hasDefaultArgument()) {
4753 Diag(TTP->getDefaultArgument().getLocation(),
4754 diag::err_default_arg_in_partial_spec)
4755 << TTP->getDefaultArgument().getSourceRange();
4756 TTP->removeDefaultArgument();
4760 } else if (TemplateParams) {
4761 if (TUK == TUK_Friend)
4762 Diag(KWLoc, diag::err_template_spec_friend)
4763 << FixItHint::CreateRemoval(
4764 SourceRange(TemplateParams->getTemplateLoc(),
4765 TemplateParams->getRAngleLoc()))
4766 << SourceRange(LAngleLoc, RAngleLoc);
4768 isExplicitSpecialization = true;
4769 } else if (TUK != TUK_Friend) {
4770 Diag(KWLoc, diag::err_template_spec_needs_header)
4771 << FixItHint::CreateInsertion(KWLoc, "template<> ");
4772 isExplicitSpecialization = true;
4775 // Check that the specialization uses the same tag kind as the
4776 // original template.
4777 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4778 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!");
4779 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
4780 Kind, TUK == TUK_Definition, KWLoc,
4781 *ClassTemplate->getIdentifier())) {
4782 Diag(KWLoc, diag::err_use_with_wrong_tag)
4784 << FixItHint::CreateReplacement(KWLoc,
4785 ClassTemplate->getTemplatedDecl()->getKindName());
4786 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
4787 diag::note_previous_use);
4788 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
4791 // Translate the parser's template argument list in our AST format.
4792 TemplateArgumentListInfo TemplateArgs;
4793 TemplateArgs.setLAngleLoc(LAngleLoc);
4794 TemplateArgs.setRAngleLoc(RAngleLoc);
4795 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4797 // Check for unexpanded parameter packs in any of the template arguments.
4798 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4799 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4800 UPPC_PartialSpecialization))
4803 // Check that the template argument list is well-formed for this
4805 llvm::SmallVector<TemplateArgument, 4> Converted;
4806 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
4807 TemplateArgs, false, Converted))
4810 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
4811 "Converted template argument list is too short!");
4813 // Find the class template (partial) specialization declaration that
4814 // corresponds to these arguments.
4815 if (isPartialSpecialization) {
4816 if (CheckClassTemplatePartialSpecializationArgs(*this,
4817 ClassTemplate->getTemplateParameters(),
4821 if (!Name.isDependent() &&
4822 !TemplateSpecializationType::anyDependentTemplateArguments(
4823 TemplateArgs.getArgumentArray(),
4824 TemplateArgs.size())) {
4825 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4826 << ClassTemplate->getDeclName();
4827 isPartialSpecialization = false;
4831 void *InsertPos = 0;
4832 ClassTemplateSpecializationDecl *PrevDecl = 0;
4834 if (isPartialSpecialization)
4835 // FIXME: Template parameter list matters, too
4837 = ClassTemplate->findPartialSpecialization(Converted.data(),
4842 = ClassTemplate->findSpecialization(Converted.data(),
4843 Converted.size(), InsertPos);
4845 ClassTemplateSpecializationDecl *Specialization = 0;
4847 // Check whether we can declare a class template specialization in
4848 // the current scope.
4849 if (TUK != TUK_Friend &&
4850 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
4852 isPartialSpecialization))
4855 // The canonical type
4858 (PrevDecl->getSpecializationKind() == TSK_Undeclared ||
4859 TUK == TUK_Friend)) {
4860 // Since the only prior class template specialization with these
4861 // arguments was referenced but not declared, or we're only
4862 // referencing this specialization as a friend, reuse that
4863 // declaration node as our own, updating its source location and
4864 // the list of outer template parameters to reflect our new declaration.
4865 Specialization = PrevDecl;
4866 Specialization->setLocation(TemplateNameLoc);
4867 if (TemplateParameterLists.size() > 0) {
4868 Specialization->setTemplateParameterListsInfo(Context,
4869 TemplateParameterLists.size(),
4870 (TemplateParameterList**) TemplateParameterLists.release());
4873 CanonType = Context.getTypeDeclType(Specialization);
4874 } else if (isPartialSpecialization) {
4875 // Build the canonical type that describes the converted template
4876 // arguments of the class template partial specialization.
4877 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
4878 CanonType = Context.getTemplateSpecializationType(CanonTemplate,
4882 if (Context.hasSameType(CanonType,
4883 ClassTemplate->getInjectedClassNameSpecialization())) {
4884 // C++ [temp.class.spec]p9b3:
4886 // -- The argument list of the specialization shall not be identical
4887 // to the implicit argument list of the primary template.
4888 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4889 << (TUK == TUK_Definition)
4890 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4891 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
4892 ClassTemplate->getIdentifier(),
4897 TemplateParameterLists.size() - 1,
4898 (TemplateParameterList**) TemplateParameterLists.release());
4901 // Create a new class template partial specialization declaration node.
4902 ClassTemplatePartialSpecializationDecl *PrevPartial
4903 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);
4904 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber()
4905 : ClassTemplate->getNextPartialSpecSequenceNumber();
4906 ClassTemplatePartialSpecializationDecl *Partial
4907 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind,
4908 ClassTemplate->getDeclContext(),
4909 KWLoc, TemplateNameLoc,
4918 SetNestedNameSpecifier(Partial, SS);
4919 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
4920 Partial->setTemplateParameterListsInfo(Context,
4921 TemplateParameterLists.size() - 1,
4922 (TemplateParameterList**) TemplateParameterLists.release());
4926 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);
4927 Specialization = Partial;
4929 // If we are providing an explicit specialization of a member class
4930 // template specialization, make a note of that.
4931 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4932 PrevPartial->setMemberSpecialization();
4934 // Check that all of the template parameters of the class template
4935 // partial specialization are deducible from the template
4936 // arguments. If not, this class template partial specialization
4937 // will never be used.
4938 llvm::SmallVector<bool, 8> DeducibleParams;
4939 DeducibleParams.resize(TemplateParams->size());
4940 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4941 TemplateParams->getDepth(),
4943 unsigned NumNonDeducible = 0;
4944 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I)
4945 if (!DeducibleParams[I])
4948 if (NumNonDeducible) {
4949 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible)
4950 << (NumNonDeducible > 1)
4951 << SourceRange(TemplateNameLoc, RAngleLoc);
4952 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4953 if (!DeducibleParams[I]) {
4954 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I));
4955 if (Param->getDeclName())
4956 Diag(Param->getLocation(),
4957 diag::note_partial_spec_unused_parameter)
4958 << Param->getDeclName();
4960 Diag(Param->getLocation(),
4961 diag::note_partial_spec_unused_parameter)
4967 // Create a new class template specialization declaration node for
4968 // this explicit specialization or friend declaration.
4970 = ClassTemplateSpecializationDecl::Create(Context, Kind,
4971 ClassTemplate->getDeclContext(),
4972 KWLoc, TemplateNameLoc,
4977 SetNestedNameSpecifier(Specialization, SS);
4978 if (TemplateParameterLists.size() > 0) {
4979 Specialization->setTemplateParameterListsInfo(Context,
4980 TemplateParameterLists.size(),
4981 (TemplateParameterList**) TemplateParameterLists.release());
4985 ClassTemplate->AddSpecialization(Specialization, InsertPos);
4987 CanonType = Context.getTypeDeclType(Specialization);
4990 // C++ [temp.expl.spec]p6:
4991 // If a template, a member template or the member of a class template is
4992 // explicitly specialized then that specialization shall be declared
4993 // before the first use of that specialization that would cause an implicit
4994 // instantiation to take place, in every translation unit in which such a
4995 // use occurs; no diagnostic is required.
4996 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4998 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
4999 // Is there any previous explicit specialization declaration?
5000 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
5007 SourceRange Range(TemplateNameLoc, RAngleLoc);
5008 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
5009 << Context.getTypeDeclType(Specialization) << Range;
5011 Diag(PrevDecl->getPointOfInstantiation(),
5012 diag::note_instantiation_required_here)
5013 << (PrevDecl->getTemplateSpecializationKind()
5014 != TSK_ImplicitInstantiation);
5019 // If this is not a friend, note that this is an explicit specialization.
5020 if (TUK != TUK_Friend)
5021 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
5023 // Check that this isn't a redefinition of this specialization.
5024 if (TUK == TUK_Definition) {
5025 if (RecordDecl *Def = Specialization->getDefinition()) {
5026 SourceRange Range(TemplateNameLoc, RAngleLoc);
5027 Diag(TemplateNameLoc, diag::err_redefinition)
5028 << Context.getTypeDeclType(Specialization) << Range;
5029 Diag(Def->getLocation(), diag::note_previous_definition);
5030 Specialization->setInvalidDecl();
5036 ProcessDeclAttributeList(S, Specialization, Attr);
5038 // Build the fully-sugared type for this class template
5039 // specialization as the user wrote in the specialization
5040 // itself. This means that we'll pretty-print the type retrieved
5041 // from the specialization's declaration the way that the user
5042 // actually wrote the specialization, rather than formatting the
5043 // name based on the "canonical" representation used to store the
5044 // template arguments in the specialization.
5045 TypeSourceInfo *WrittenTy
5046 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5047 TemplateArgs, CanonType);
5048 if (TUK != TUK_Friend) {
5049 Specialization->setTypeAsWritten(WrittenTy);
5050 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
5052 TemplateArgsIn.release();
5054 // C++ [temp.expl.spec]p9:
5055 // A template explicit specialization is in the scope of the
5056 // namespace in which the template was defined.
5058 // We actually implement this paragraph where we set the semantic
5059 // context (in the creation of the ClassTemplateSpecializationDecl),
5060 // but we also maintain the lexical context where the actual
5061 // definition occurs.
5062 Specialization->setLexicalDeclContext(CurContext);
5064 // We may be starting the definition of this specialization.
5065 if (TUK == TUK_Definition)
5066 Specialization->startDefinition();
5068 if (TUK == TUK_Friend) {
5069 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,
5073 Friend->setAccess(AS_public);
5074 CurContext->addDecl(Friend);
5076 // Add the specialization into its lexical context, so that it can
5077 // be seen when iterating through the list of declarations in that
5078 // context. However, specializations are not found by name lookup.
5079 CurContext->addDecl(Specialization);
5081 return Specialization;
5084 Decl *Sema::ActOnTemplateDeclarator(Scope *S,
5085 MultiTemplateParamsArg TemplateParameterLists,
5087 return HandleDeclarator(S, D, move(TemplateParameterLists), false);
5090 Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope,
5091 MultiTemplateParamsArg TemplateParameterLists,
5093 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
5094 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
5096 if (FTI.hasPrototype) {
5097 // FIXME: Diagnose arguments without names in C.
5100 Scope *ParentScope = FnBodyScope->getParent();
5102 Decl *DP = HandleDeclarator(ParentScope, D,
5103 move(TemplateParameterLists),
5104 /*IsFunctionDefinition=*/true);
5105 if (FunctionTemplateDecl *FunctionTemplate
5106 = dyn_cast_or_null<FunctionTemplateDecl>(DP))
5107 return ActOnStartOfFunctionDef(FnBodyScope,
5108 FunctionTemplate->getTemplatedDecl());
5109 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP))
5110 return ActOnStartOfFunctionDef(FnBodyScope, Function);
5114 /// \brief Strips various properties off an implicit instantiation
5115 /// that has just been explicitly specialized.
5116 static void StripImplicitInstantiation(NamedDecl *D) {
5119 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5120 FD->setInlineSpecified(false);
5124 /// \brief Diagnose cases where we have an explicit template specialization
5125 /// before/after an explicit template instantiation, producing diagnostics
5126 /// for those cases where they are required and determining whether the
5127 /// new specialization/instantiation will have any effect.
5129 /// \param NewLoc the location of the new explicit specialization or
5132 /// \param NewTSK the kind of the new explicit specialization or instantiation.
5134 /// \param PrevDecl the previous declaration of the entity.
5136 /// \param PrevTSK the kind of the old explicit specialization or instantiatin.
5138 /// \param PrevPointOfInstantiation if valid, indicates where the previus
5139 /// declaration was instantiated (either implicitly or explicitly).
5141 /// \param HasNoEffect will be set to true to indicate that the new
5142 /// specialization or instantiation has no effect and should be ignored.
5144 /// \returns true if there was an error that should prevent the introduction of
5145 /// the new declaration into the AST, false otherwise.
5147 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
5148 TemplateSpecializationKind NewTSK,
5149 NamedDecl *PrevDecl,
5150 TemplateSpecializationKind PrevTSK,
5151 SourceLocation PrevPointOfInstantiation,
5152 bool &HasNoEffect) {
5153 HasNoEffect = false;
5156 case TSK_Undeclared:
5157 case TSK_ImplicitInstantiation:
5158 assert(false && "Don't check implicit instantiations here");
5161 case TSK_ExplicitSpecialization:
5163 case TSK_Undeclared:
5164 case TSK_ExplicitSpecialization:
5165 // Okay, we're just specializing something that is either already
5166 // explicitly specialized or has merely been mentioned without any
5170 case TSK_ImplicitInstantiation:
5171 if (PrevPointOfInstantiation.isInvalid()) {
5172 // The declaration itself has not actually been instantiated, so it is
5173 // still okay to specialize it.
5174 StripImplicitInstantiation(PrevDecl);
5179 case TSK_ExplicitInstantiationDeclaration:
5180 case TSK_ExplicitInstantiationDefinition:
5181 assert((PrevTSK == TSK_ImplicitInstantiation ||
5182 PrevPointOfInstantiation.isValid()) &&
5183 "Explicit instantiation without point of instantiation?");
5185 // C++ [temp.expl.spec]p6:
5186 // If a template, a member template or the member of a class template
5187 // is explicitly specialized then that specialization shall be declared
5188 // before the first use of that specialization that would cause an
5189 // implicit instantiation to take place, in every translation unit in
5190 // which such a use occurs; no diagnostic is required.
5191 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) {
5192 // Is there any previous explicit specialization declaration?
5193 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)
5197 Diag(NewLoc, diag::err_specialization_after_instantiation)
5199 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
5200 << (PrevTSK != TSK_ImplicitInstantiation);
5206 case TSK_ExplicitInstantiationDeclaration:
5208 case TSK_ExplicitInstantiationDeclaration:
5209 // This explicit instantiation declaration is redundant (that's okay).
5213 case TSK_Undeclared:
5214 case TSK_ImplicitInstantiation:
5215 // We're explicitly instantiating something that may have already been
5216 // implicitly instantiated; that's fine.
5219 case TSK_ExplicitSpecialization:
5220 // C++0x [temp.explicit]p4:
5221 // For a given set of template parameters, if an explicit instantiation
5222 // of a template appears after a declaration of an explicit
5223 // specialization for that template, the explicit instantiation has no
5228 case TSK_ExplicitInstantiationDefinition:
5229 // C++0x [temp.explicit]p10:
5230 // If an entity is the subject of both an explicit instantiation
5231 // declaration and an explicit instantiation definition in the same
5232 // translation unit, the definition shall follow the declaration.
5234 diag::err_explicit_instantiation_declaration_after_definition);
5235 Diag(PrevPointOfInstantiation,
5236 diag::note_explicit_instantiation_definition_here);
5237 assert(PrevPointOfInstantiation.isValid() &&
5238 "Explicit instantiation without point of instantiation?");
5244 case TSK_ExplicitInstantiationDefinition:
5246 case TSK_Undeclared:
5247 case TSK_ImplicitInstantiation:
5248 // We're explicitly instantiating something that may have already been
5249 // implicitly instantiated; that's fine.
5252 case TSK_ExplicitSpecialization:
5253 // C++ DR 259, C++0x [temp.explicit]p4:
5254 // For a given set of template parameters, if an explicit
5255 // instantiation of a template appears after a declaration of
5256 // an explicit specialization for that template, the explicit
5257 // instantiation has no effect.
5259 // In C++98/03 mode, we only give an extension warning here, because it
5260 // is not harmful to try to explicitly instantiate something that
5261 // has been explicitly specialized.
5262 if (!getLangOptions().CPlusPlus0x) {
5263 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization)
5265 Diag(PrevDecl->getLocation(),
5266 diag::note_previous_template_specialization);
5271 case TSK_ExplicitInstantiationDeclaration:
5272 // We're explicity instantiating a definition for something for which we
5273 // were previously asked to suppress instantiations. That's fine.
5276 case TSK_ExplicitInstantiationDefinition:
5277 // C++0x [temp.spec]p5:
5278 // For a given template and a given set of template-arguments,
5279 // - an explicit instantiation definition shall appear at most once
5281 Diag(NewLoc, diag::err_explicit_instantiation_duplicate)
5283 Diag(PrevPointOfInstantiation,
5284 diag::note_previous_explicit_instantiation);
5291 assert(false && "Missing specialization/instantiation case?");
5296 /// \brief Perform semantic analysis for the given dependent function
5297 /// template specialization. The only possible way to get a dependent
5298 /// function template specialization is with a friend declaration,
5301 /// template <class T> void foo(T);
5302 /// template <class T> class A {
5303 /// friend void foo<>(T);
5306 /// There really isn't any useful analysis we can do here, so we
5307 /// just store the information.
5309 Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
5310 const TemplateArgumentListInfo &ExplicitTemplateArgs,
5311 LookupResult &Previous) {
5312 // Remove anything from Previous that isn't a function template in
5313 // the correct context.
5314 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
5315 LookupResult::Filter F = Previous.makeFilter();
5316 while (F.hasNext()) {
5317 NamedDecl *D = F.next()->getUnderlyingDecl();
5318 if (!isa<FunctionTemplateDecl>(D) ||
5319 !FDLookupContext->InEnclosingNamespaceSetOf(
5320 D->getDeclContext()->getRedeclContext()))
5325 // Should this be diagnosed here?
5326 if (Previous.empty()) return true;
5328 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),
5329 ExplicitTemplateArgs);
5333 /// \brief Perform semantic analysis for the given function template
5336 /// This routine performs all of the semantic analysis required for an
5337 /// explicit function template specialization. On successful completion,
5338 /// the function declaration \p FD will become a function template
5341 /// \param FD the function declaration, which will be updated to become a
5342 /// function template specialization.
5344 /// \param ExplicitTemplateArgs the explicitly-provided template arguments,
5345 /// if any. Note that this may be valid info even when 0 arguments are
5346 /// explicitly provided as in, e.g., \c void sort<>(char*, char*);
5347 /// as it anyway contains info on the angle brackets locations.
5349 /// \param PrevDecl the set of declarations that may be specialized by
5350 /// this function specialization.
5352 Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD,
5353 TemplateArgumentListInfo *ExplicitTemplateArgs,
5354 LookupResult &Previous) {
5355 // The set of function template specializations that could match this
5356 // explicit function template specialization.
5357 UnresolvedSet<8> Candidates;
5359 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
5360 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5362 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
5363 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {
5364 // Only consider templates found within the same semantic lookup scope as
5366 if (!FDLookupContext->InEnclosingNamespaceSetOf(
5367 Ovl->getDeclContext()->getRedeclContext()))
5370 // C++ [temp.expl.spec]p11:
5371 // A trailing template-argument can be left unspecified in the
5372 // template-id naming an explicit function template specialization
5373 // provided it can be deduced from the function argument type.
5374 // Perform template argument deduction to determine whether we may be
5375 // specializing this template.
5376 // FIXME: It is somewhat wasteful to build
5377 TemplateDeductionInfo Info(Context, FD->getLocation());
5378 FunctionDecl *Specialization = 0;
5379 if (TemplateDeductionResult TDK
5380 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs,
5384 // FIXME: Template argument deduction failed; record why it failed, so
5385 // that we can provide nifty diagnostics.
5390 // Record this candidate.
5391 Candidates.addDecl(Specialization, I.getAccess());
5395 // Find the most specialized function template.
5396 UnresolvedSetIterator Result
5397 = getMostSpecialized(Candidates.begin(), Candidates.end(),
5398 TPOC_Other, 0, FD->getLocation(),
5399 PDiag(diag::err_function_template_spec_no_match)
5400 << FD->getDeclName(),
5401 PDiag(diag::err_function_template_spec_ambiguous)
5402 << FD->getDeclName() << (ExplicitTemplateArgs != 0),
5403 PDiag(diag::note_function_template_spec_matched));
5404 if (Result == Candidates.end())
5407 // Ignore access information; it doesn't figure into redeclaration checking.
5408 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
5410 FunctionTemplateSpecializationInfo *SpecInfo
5411 = Specialization->getTemplateSpecializationInfo();
5412 assert(SpecInfo && "Function template specialization info missing?");
5414 // Note: do not overwrite location info if previous template
5415 // specialization kind was explicit.
5416 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
5417 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation)
5418 Specialization->setLocation(FD->getLocation());
5421 // FIXME: Check if the prior specialization has a point of instantiation.
5422 // If so, we have run afoul of .
5424 // If this is a friend declaration, then we're not really declaring
5425 // an explicit specialization.
5426 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
5428 // Check the scope of this explicit specialization.
5430 CheckTemplateSpecializationScope(*this,
5431 Specialization->getPrimaryTemplate(),
5432 Specialization, FD->getLocation(),
5436 // C++ [temp.expl.spec]p6:
5437 // If a template, a member template or the member of a class template is
5438 // explicitly specialized then that specialization shall be declared
5439 // before the first use of that specialization that would cause an implicit
5440 // instantiation to take place, in every translation unit in which such a
5441 // use occurs; no diagnostic is required.
5442 bool HasNoEffect = false;
5444 CheckSpecializationInstantiationRedecl(FD->getLocation(),
5445 TSK_ExplicitSpecialization,
5447 SpecInfo->getTemplateSpecializationKind(),
5448 SpecInfo->getPointOfInstantiation(),
5452 // Mark the prior declaration as an explicit specialization, so that later
5453 // clients know that this is an explicit specialization.
5455 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
5456 MarkUnusedFileScopedDecl(Specialization);
5459 // Turn the given function declaration into a function template
5460 // specialization, with the template arguments from the previous
5462 // Take copies of (semantic and syntactic) template argument lists.
5463 const TemplateArgumentList* TemplArgs = new (Context)
5464 TemplateArgumentList(Specialization->getTemplateSpecializationArgs());
5465 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs
5466 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0;
5467 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(),
5468 TemplArgs, /*InsertPos=*/0,
5469 SpecInfo->getTemplateSpecializationKind(),
5470 TemplArgsAsWritten);
5471 FD->setStorageClass(Specialization->getStorageClass());
5473 // The "previous declaration" for this function template specialization is
5474 // the prior function template specialization.
5476 Previous.addDecl(Specialization);
5480 /// \brief Perform semantic analysis for the given non-template member
5483 /// This routine performs all of the semantic analysis required for an
5484 /// explicit member function specialization. On successful completion,
5485 /// the function declaration \p FD will become a member function
5488 /// \param Member the member declaration, which will be updated to become a
5491 /// \param Previous the set of declarations, one of which may be specialized
5492 /// by this function specialization; the set will be modified to contain the
5493 /// redeclared member.
5495 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
5496 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
5498 // Try to find the member we are instantiating.
5499 NamedDecl *Instantiation = 0;
5500 NamedDecl *InstantiatedFrom = 0;
5501 MemberSpecializationInfo *MSInfo = 0;
5503 if (Previous.empty()) {
5504 // Nowhere to look anyway.
5505 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {
5506 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
5508 NamedDecl *D = (*I)->getUnderlyingDecl();
5509 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5510 if (Context.hasSameType(Function->getType(), Method->getType())) {
5511 Instantiation = Method;
5512 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
5513 MSInfo = Method->getMemberSpecializationInfo();
5518 } else if (isa<VarDecl>(Member)) {
5520 if (Previous.isSingleResult() &&
5521 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))
5522 if (PrevVar->isStaticDataMember()) {
5523 Instantiation = PrevVar;
5524 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
5525 MSInfo = PrevVar->getMemberSpecializationInfo();
5527 } else if (isa<RecordDecl>(Member)) {
5528 CXXRecordDecl *PrevRecord;
5529 if (Previous.isSingleResult() &&
5530 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {
5531 Instantiation = PrevRecord;
5532 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
5533 MSInfo = PrevRecord->getMemberSpecializationInfo();
5537 if (!Instantiation) {
5538 // There is no previous declaration that matches. Since member
5539 // specializations are always out-of-line, the caller will complain about
5540 // this mismatch later.
5544 // If this is a friend, just bail out here before we start turning
5545 // things into explicit specializations.
5546 if (Member->getFriendObjectKind() != Decl::FOK_None) {
5547 // Preserve instantiation information.
5548 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {
5549 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(
5550 cast<CXXMethodDecl>(InstantiatedFrom),
5551 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());
5552 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {
5553 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
5554 cast<CXXRecordDecl>(InstantiatedFrom),
5555 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());
5559 Previous.addDecl(Instantiation);
5563 // Make sure that this is a specialization of a member.
5564 if (!InstantiatedFrom) {
5565 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
5567 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
5571 // C++ [temp.expl.spec]p6:
5572 // If a template, a member template or the member of a class template is
5573 // explicitly specialized then that spe- cialization shall be declared
5574 // before the first use of that specialization that would cause an implicit
5575 // instantiation to take place, in every translation unit in which such a
5576 // use occurs; no diagnostic is required.
5577 assert(MSInfo && "Member specialization info missing?");
5579 bool HasNoEffect = false;
5580 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),
5581 TSK_ExplicitSpecialization,
5583 MSInfo->getTemplateSpecializationKind(),
5584 MSInfo->getPointOfInstantiation(),
5588 // Check the scope of this explicit specialization.
5589 if (CheckTemplateSpecializationScope(*this,
5591 Instantiation, Member->getLocation(),
5595 // Note that this is an explicit instantiation of a member.
5596 // the original declaration to note that it is an explicit specialization
5597 // (if it was previously an implicit instantiation). This latter step
5598 // makes bookkeeping easier.
5599 if (isa<FunctionDecl>(Member)) {
5600 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);
5601 if (InstantiationFunction->getTemplateSpecializationKind() ==
5602 TSK_ImplicitInstantiation) {
5603 InstantiationFunction->setTemplateSpecializationKind(
5604 TSK_ExplicitSpecialization);
5605 InstantiationFunction->setLocation(Member->getLocation());
5608 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction(
5609 cast<CXXMethodDecl>(InstantiatedFrom),
5610 TSK_ExplicitSpecialization);
5611 MarkUnusedFileScopedDecl(InstantiationFunction);
5612 } else if (isa<VarDecl>(Member)) {
5613 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation);
5614 if (InstantiationVar->getTemplateSpecializationKind() ==
5615 TSK_ImplicitInstantiation) {
5616 InstantiationVar->setTemplateSpecializationKind(
5617 TSK_ExplicitSpecialization);
5618 InstantiationVar->setLocation(Member->getLocation());
5621 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member),
5622 cast<VarDecl>(InstantiatedFrom),
5623 TSK_ExplicitSpecialization);
5624 MarkUnusedFileScopedDecl(InstantiationVar);
5626 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain");
5627 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation);
5628 if (InstantiationClass->getTemplateSpecializationKind() ==
5629 TSK_ImplicitInstantiation) {
5630 InstantiationClass->setTemplateSpecializationKind(
5631 TSK_ExplicitSpecialization);
5632 InstantiationClass->setLocation(Member->getLocation());
5635 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(
5636 cast<CXXRecordDecl>(InstantiatedFrom),
5637 TSK_ExplicitSpecialization);
5640 // Save the caller the trouble of having to figure out which declaration
5641 // this specialization matches.
5643 Previous.addDecl(Instantiation);
5647 /// \brief Check the scope of an explicit instantiation.
5649 /// \returns true if a serious error occurs, false otherwise.
5650 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
5651 SourceLocation InstLoc,
5652 bool WasQualifiedName) {
5653 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
5654 DeclContext *CurContext = S.CurContext->getRedeclContext();
5656 if (CurContext->isRecord()) {
5657 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
5662 // C++0x [temp.explicit]p2:
5663 // An explicit instantiation shall appear in an enclosing namespace of its
5666 // This is DR275, which we do not retroactively apply to C++98/03.
5667 if (S.getLangOptions().CPlusPlus0x &&
5668 !CurContext->Encloses(OrigContext)) {
5669 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext))
5671 S.getLangOptions().CPlusPlus0x?
5672 diag::err_explicit_instantiation_out_of_scope
5673 : diag::warn_explicit_instantiation_out_of_scope_0x)
5677 S.getLangOptions().CPlusPlus0x?
5678 diag::err_explicit_instantiation_must_be_global
5679 : diag::warn_explicit_instantiation_out_of_scope_0x)
5681 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
5685 // C++0x [temp.explicit]p2:
5686 // If the name declared in the explicit instantiation is an unqualified
5687 // name, the explicit instantiation shall appear in the namespace where
5688 // its template is declared or, if that namespace is inline (7.3.1), any
5689 // namespace from its enclosing namespace set.
5690 if (WasQualifiedName)
5693 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))
5697 S.getLangOptions().CPlusPlus0x?
5698 diag::err_explicit_instantiation_unqualified_wrong_namespace
5699 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
5700 << D << OrigContext;
5701 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
5705 /// \brief Determine whether the given scope specifier has a template-id in it.
5706 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
5710 // C++0x [temp.explicit]p2:
5711 // If the explicit instantiation is for a member function, a member class
5712 // or a static data member of a class template specialization, the name of
5713 // the class template specialization in the qualified-id for the member
5714 // name shall be a simple-template-id.
5716 // C++98 has the same restriction, just worded differently.
5717 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
5718 NNS; NNS = NNS->getPrefix())
5719 if (const Type *T = NNS->getAsType())
5720 if (isa<TemplateSpecializationType>(T))
5726 // Explicit instantiation of a class template specialization
5728 Sema::ActOnExplicitInstantiation(Scope *S,
5729 SourceLocation ExternLoc,
5730 SourceLocation TemplateLoc,
5732 SourceLocation KWLoc,
5733 const CXXScopeSpec &SS,
5734 TemplateTy TemplateD,
5735 SourceLocation TemplateNameLoc,
5736 SourceLocation LAngleLoc,
5737 ASTTemplateArgsPtr TemplateArgsIn,
5738 SourceLocation RAngleLoc,
5739 AttributeList *Attr) {
5740 // Find the class template we're specializing
5741 TemplateName Name = TemplateD.getAsVal<TemplateName>();
5742 ClassTemplateDecl *ClassTemplate
5743 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl());
5745 // Check that the specialization uses the same tag kind as the
5746 // original template.
5747 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
5748 assert(Kind != TTK_Enum &&
5749 "Invalid enum tag in class template explicit instantiation!");
5750 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),
5751 Kind, /*isDefinition*/false, KWLoc,
5752 *ClassTemplate->getIdentifier())) {
5753 Diag(KWLoc, diag::err_use_with_wrong_tag)
5755 << FixItHint::CreateReplacement(KWLoc,
5756 ClassTemplate->getTemplatedDecl()->getKindName());
5757 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
5758 diag::note_previous_use);
5759 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
5762 // C++0x [temp.explicit]p2:
5763 // There are two forms of explicit instantiation: an explicit instantiation
5764 // definition and an explicit instantiation declaration. An explicit
5765 // instantiation declaration begins with the extern keyword. [...]
5766 TemplateSpecializationKind TSK
5767 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5768 : TSK_ExplicitInstantiationDeclaration;
5770 // Translate the parser's template argument list in our AST format.
5771 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
5772 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
5774 // Check that the template argument list is well-formed for this
5776 llvm::SmallVector<TemplateArgument, 4> Converted;
5777 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc,
5778 TemplateArgs, false, Converted))
5781 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) &&
5782 "Converted template argument list is too short!");
5784 // Find the class template specialization declaration that
5785 // corresponds to these arguments.
5786 void *InsertPos = 0;
5787 ClassTemplateSpecializationDecl *PrevDecl
5788 = ClassTemplate->findSpecialization(Converted.data(),
5789 Converted.size(), InsertPos);
5791 TemplateSpecializationKind PrevDecl_TSK
5792 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
5794 // C++0x [temp.explicit]p2:
5795 // [...] An explicit instantiation shall appear in an enclosing
5796 // namespace of its template. [...]
5798 // This is C++ DR 275.
5799 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc,
5803 ClassTemplateSpecializationDecl *Specialization = 0;
5805 bool HasNoEffect = false;
5807 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
5808 PrevDecl, PrevDecl_TSK,
5809 PrevDecl->getPointOfInstantiation(),
5813 // Even though HasNoEffect == true means that this explicit instantiation
5814 // has no effect on semantics, we go on to put its syntax in the AST.
5816 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
5817 PrevDecl_TSK == TSK_Undeclared) {
5818 // Since the only prior class template specialization with these
5819 // arguments was referenced but not declared, reuse that
5820 // declaration node as our own, updating the source location
5821 // for the template name to reflect our new declaration.
5822 // (Other source locations will be updated later.)
5823 Specialization = PrevDecl;
5824 Specialization->setLocation(TemplateNameLoc);
5829 if (!Specialization) {
5830 // Create a new class template specialization declaration node for
5831 // this explicit specialization.
5833 = ClassTemplateSpecializationDecl::Create(Context, Kind,
5834 ClassTemplate->getDeclContext(),
5835 KWLoc, TemplateNameLoc,
5840 SetNestedNameSpecifier(Specialization, SS);
5842 if (!HasNoEffect && !PrevDecl) {
5843 // Insert the new specialization.
5844 ClassTemplate->AddSpecialization(Specialization, InsertPos);
5848 // Build the fully-sugared type for this explicit instantiation as
5849 // the user wrote in the explicit instantiation itself. This means
5850 // that we'll pretty-print the type retrieved from the
5851 // specialization's declaration the way that the user actually wrote
5852 // the explicit instantiation, rather than formatting the name based
5853 // on the "canonical" representation used to store the template
5854 // arguments in the specialization.
5855 TypeSourceInfo *WrittenTy
5856 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc,
5858 Context.getTypeDeclType(Specialization));
5859 Specialization->setTypeAsWritten(WrittenTy);
5860 TemplateArgsIn.release();
5862 // Set source locations for keywords.
5863 Specialization->setExternLoc(ExternLoc);
5864 Specialization->setTemplateKeywordLoc(TemplateLoc);
5866 // Add the explicit instantiation into its lexical context. However,
5867 // since explicit instantiations are never found by name lookup, we
5868 // just put it into the declaration context directly.
5869 Specialization->setLexicalDeclContext(CurContext);
5870 CurContext->addDecl(Specialization);
5872 // Syntax is now OK, so return if it has no other effect on semantics.
5874 // Set the template specialization kind.
5875 Specialization->setTemplateSpecializationKind(TSK);
5876 return Specialization;
5879 // C++ [temp.explicit]p3:
5880 // A definition of a class template or class member template
5881 // shall be in scope at the point of the explicit instantiation of
5882 // the class template or class member template.
5884 // This check comes when we actually try to perform the
5886 ClassTemplateSpecializationDecl *Def
5887 = cast_or_null<ClassTemplateSpecializationDecl>(
5888 Specialization->getDefinition());
5890 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK);
5891 else if (TSK == TSK_ExplicitInstantiationDefinition) {
5892 MarkVTableUsed(TemplateNameLoc, Specialization, true);
5893 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
5896 // Instantiate the members of this class template specialization.
5897 Def = cast_or_null<ClassTemplateSpecializationDecl>(
5898 Specialization->getDefinition());
5900 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
5902 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
5903 // TSK_ExplicitInstantiationDefinition
5904 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
5905 TSK == TSK_ExplicitInstantiationDefinition)
5906 Def->setTemplateSpecializationKind(TSK);
5908 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);
5911 // Set the template specialization kind.
5912 Specialization->setTemplateSpecializationKind(TSK);
5913 return Specialization;
5916 // Explicit instantiation of a member class of a class template.
5918 Sema::ActOnExplicitInstantiation(Scope *S,
5919 SourceLocation ExternLoc,
5920 SourceLocation TemplateLoc,
5922 SourceLocation KWLoc,
5924 IdentifierInfo *Name,
5925 SourceLocation NameLoc,
5926 AttributeList *Attr) {
5929 bool IsDependent = false;
5930 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference,
5931 KWLoc, SS, Name, NameLoc, Attr, AS_none,
5932 MultiTemplateParamsArg(*this, 0, 0),
5933 Owned, IsDependent, false, false,
5935 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
5940 TagDecl *Tag = cast<TagDecl>(TagD);
5941 if (Tag->isEnum()) {
5942 Diag(TemplateLoc, diag::err_explicit_instantiation_enum)
5943 << Context.getTypeDeclType(Tag);
5947 if (Tag->isInvalidDecl())
5950 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);
5951 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
5953 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
5954 << Context.getTypeDeclType(Record);
5955 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
5959 // C++0x [temp.explicit]p2:
5960 // If the explicit instantiation is for a class or member class, the
5961 // elaborated-type-specifier in the declaration shall include a
5962 // simple-template-id.
5964 // C++98 has the same restriction, just worded differently.
5965 if (!ScopeSpecifierHasTemplateId(SS))
5966 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
5967 << Record << SS.getRange();
5969 // C++0x [temp.explicit]p2:
5970 // There are two forms of explicit instantiation: an explicit instantiation
5971 // definition and an explicit instantiation declaration. An explicit
5972 // instantiation declaration begins with the extern keyword. [...]
5973 TemplateSpecializationKind TSK
5974 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
5975 : TSK_ExplicitInstantiationDeclaration;
5977 // C++0x [temp.explicit]p2:
5978 // [...] An explicit instantiation shall appear in an enclosing
5979 // namespace of its template. [...]
5981 // This is C++ DR 275.
5982 CheckExplicitInstantiationScope(*this, Record, NameLoc, true);
5984 // Verify that it is okay to explicitly instantiate here.
5985 CXXRecordDecl *PrevDecl
5986 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration());
5987 if (!PrevDecl && Record->getDefinition())
5990 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
5991 bool HasNoEffect = false;
5992 assert(MSInfo && "No member specialization information?");
5993 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
5995 MSInfo->getTemplateSpecializationKind(),
5996 MSInfo->getPointOfInstantiation(),
6003 CXXRecordDecl *RecordDef
6004 = cast_or_null<CXXRecordDecl>(Record->getDefinition());
6006 // C++ [temp.explicit]p3:
6007 // A definition of a member class of a class template shall be in scope
6008 // at the point of an explicit instantiation of the member class.
6010 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
6012 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
6013 << 0 << Record->getDeclName() << Record->getDeclContext();
6014 Diag(Pattern->getLocation(), diag::note_forward_declaration)
6018 if (InstantiateClass(NameLoc, Record, Def,
6019 getTemplateInstantiationArgs(Record),
6023 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());
6029 // Instantiate all of the members of the class.
6030 InstantiateClassMembers(NameLoc, RecordDef,
6031 getTemplateInstantiationArgs(Record), TSK);
6033 if (TSK == TSK_ExplicitInstantiationDefinition)
6034 MarkVTableUsed(NameLoc, RecordDef, true);
6036 // FIXME: We don't have any representation for explicit instantiations of
6037 // member classes. Such a representation is not needed for compilation, but it
6038 // should be available for clients that want to see all of the declarations in
6043 DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
6044 SourceLocation ExternLoc,
6045 SourceLocation TemplateLoc,
6047 // Explicit instantiations always require a name.
6048 // TODO: check if/when DNInfo should replace Name.
6049 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
6050 DeclarationName Name = NameInfo.getName();
6052 if (!D.isInvalidType())
6053 Diag(D.getDeclSpec().getSourceRange().getBegin(),
6054 diag::err_explicit_instantiation_requires_name)
6055 << D.getDeclSpec().getSourceRange()
6056 << D.getSourceRange();
6061 // The scope passed in may not be a decl scope. Zip up the scope tree until
6062 // we find one that is.
6063 while ((S->getFlags() & Scope::DeclScope) == 0 ||
6064 (S->getFlags() & Scope::TemplateParamScope) != 0)
6067 // Determine the type of the declaration.
6068 TypeSourceInfo *T = GetTypeForDeclarator(D, S);
6069 QualType R = T->getType();
6074 // A storage-class-specifier shall not be specified in [...] an explicit
6075 // instantiation (14.7.2) directive.
6076 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
6077 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
6080 } else if (D.getDeclSpec().getStorageClassSpec()
6081 != DeclSpec::SCS_unspecified) {
6082 // Complain about then remove the storage class specifier.
6083 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
6084 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6086 D.getMutableDeclSpec().ClearStorageClassSpecs();
6089 // C++0x [temp.explicit]p1:
6090 // [...] An explicit instantiation of a function template shall not use the
6091 // inline or constexpr specifiers.
6092 // Presumably, this also applies to member functions of class templates as
6094 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x)
6095 Diag(D.getDeclSpec().getInlineSpecLoc(),
6096 diag::err_explicit_instantiation_inline)
6097 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6099 // FIXME: check for constexpr specifier.
6101 // C++0x [temp.explicit]p2:
6102 // There are two forms of explicit instantiation: an explicit instantiation
6103 // definition and an explicit instantiation declaration. An explicit
6104 // instantiation declaration begins with the extern keyword. [...]
6105 TemplateSpecializationKind TSK
6106 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
6107 : TSK_ExplicitInstantiationDeclaration;
6109 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
6110 LookupParsedName(Previous, S, &D.getCXXScopeSpec());
6112 if (!R->isFunctionType()) {
6113 // C++ [temp.explicit]p1:
6114 // A [...] static data member of a class template can be explicitly
6115 // instantiated from the member definition associated with its class
6117 if (Previous.isAmbiguous())
6120 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
6121 if (!Prev || !Prev->isStaticDataMember()) {
6122 // We expect to see a data data member here.
6123 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
6125 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
6127 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
6131 if (!Prev->getInstantiatedFromStaticDataMember()) {
6132 // FIXME: Check for explicit specialization?
6133 Diag(D.getIdentifierLoc(),
6134 diag::err_explicit_instantiation_data_member_not_instantiated)
6136 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
6137 // FIXME: Can we provide a note showing where this was declared?
6141 // C++0x [temp.explicit]p2:
6142 // If the explicit instantiation is for a member function, a member class
6143 // or a static data member of a class template specialization, the name of
6144 // the class template specialization in the qualified-id for the member
6145 // name shall be a simple-template-id.
6147 // C++98 has the same restriction, just worded differently.
6148 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
6149 Diag(D.getIdentifierLoc(),
6150 diag::ext_explicit_instantiation_without_qualified_id)
6151 << Prev << D.getCXXScopeSpec().getRange();
6153 // Check the scope of this explicit instantiation.
6154 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true);
6156 // Verify that it is okay to explicitly instantiate here.
6157 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo();
6158 assert(MSInfo && "Missing static data member specialization info?");
6159 bool HasNoEffect = false;
6160 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
6161 MSInfo->getTemplateSpecializationKind(),
6162 MSInfo->getPointOfInstantiation(),
6168 // Instantiate static data member.
6169 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
6170 if (TSK == TSK_ExplicitInstantiationDefinition)
6171 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev);
6173 // FIXME: Create an ExplicitInstantiation node?
6177 // If the declarator is a template-id, translate the parser's template
6178 // argument list into our AST format.
6179 bool HasExplicitTemplateArgs = false;
6180 TemplateArgumentListInfo TemplateArgs;
6181 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6182 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
6183 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
6184 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
6185 ASTTemplateArgsPtr TemplateArgsPtr(*this,
6186 TemplateId->getTemplateArgs(),
6187 TemplateId->NumArgs);
6188 translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
6189 HasExplicitTemplateArgs = true;
6190 TemplateArgsPtr.release();
6193 // C++ [temp.explicit]p1:
6194 // A [...] function [...] can be explicitly instantiated from its template.
6195 // A member function [...] of a class template can be explicitly
6196 // instantiated from the member definition associated with its class
6198 UnresolvedSet<8> Matches;
6199 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
6201 NamedDecl *Prev = *P;
6202 if (!HasExplicitTemplateArgs) {
6203 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {
6204 if (Context.hasSameUnqualifiedType(Method->getType(), R)) {
6207 Matches.addDecl(Method, P.getAccess());
6208 if (Method->getTemplateSpecializationKind() == TSK_Undeclared)
6214 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);
6218 TemplateDeductionInfo Info(Context, D.getIdentifierLoc());
6219 FunctionDecl *Specialization = 0;
6220 if (TemplateDeductionResult TDK
6221 = DeduceTemplateArguments(FunTmpl,
6222 (HasExplicitTemplateArgs ? &TemplateArgs : 0),
6223 R, Specialization, Info)) {
6224 // FIXME: Keep track of almost-matches?
6229 Matches.addDecl(Specialization, P.getAccess());
6232 // Find the most specialized function template specialization.
6233 UnresolvedSetIterator Result
6234 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 0,
6235 D.getIdentifierLoc(),
6236 PDiag(diag::err_explicit_instantiation_not_known) << Name,
6237 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
6238 PDiag(diag::note_explicit_instantiation_candidate));
6240 if (Result == Matches.end())
6243 // Ignore access control bits, we don't need them for redeclaration checking.
6244 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);
6246 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
6247 Diag(D.getIdentifierLoc(),
6248 diag::err_explicit_instantiation_member_function_not_instantiated)
6250 << (Specialization->getTemplateSpecializationKind() ==
6251 TSK_ExplicitSpecialization);
6252 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
6256 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration();
6257 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
6258 PrevDecl = Specialization;
6261 bool HasNoEffect = false;
6262 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
6264 PrevDecl->getTemplateSpecializationKind(),
6265 PrevDecl->getPointOfInstantiation(),
6269 // FIXME: We may still want to build some representation of this
6270 // explicit specialization.
6275 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());
6277 if (TSK == TSK_ExplicitInstantiationDefinition)
6278 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);
6280 // C++0x [temp.explicit]p2:
6281 // If the explicit instantiation is for a member function, a member class
6282 // or a static data member of a class template specialization, the name of
6283 // the class template specialization in the qualified-id for the member
6284 // name shall be a simple-template-id.
6286 // C++98 has the same restriction, just worded differently.
6287 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
6288 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl &&
6289 D.getCXXScopeSpec().isSet() &&
6290 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
6291 Diag(D.getIdentifierLoc(),
6292 diag::ext_explicit_instantiation_without_qualified_id)
6293 << Specialization << D.getCXXScopeSpec().getRange();
6295 CheckExplicitInstantiationScope(*this,
6296 FunTmpl? (NamedDecl *)FunTmpl
6297 : Specialization->getInstantiatedFromMemberFunction(),
6298 D.getIdentifierLoc(),
6299 D.getCXXScopeSpec().isSet());
6301 // FIXME: Create some kind of ExplicitInstantiationDecl here.
6306 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
6307 const CXXScopeSpec &SS, IdentifierInfo *Name,
6308 SourceLocation TagLoc, SourceLocation NameLoc) {
6309 // This has to hold, because SS is expected to be defined.
6310 assert(Name && "Expected a name in a dependent tag");
6312 NestedNameSpecifier *NNS
6313 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
6317 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
6319 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
6320 Diag(NameLoc, diag::err_dependent_tag_decl)
6321 << (TUK == TUK_Definition) << Kind << SS.getRange();
6325 // Create the resulting type.
6326 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
6327 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);
6329 // Create type-source location information for this type.
6331 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);
6332 TL.setKeywordLoc(TagLoc);
6333 TL.setQualifierLoc(SS.getWithLocInContext(Context));
6334 TL.setNameLoc(NameLoc);
6335 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
6339 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6340 const CXXScopeSpec &SS, const IdentifierInfo &II,
6341 SourceLocation IdLoc) {
6345 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
6346 !getLangOptions().CPlusPlus0x)
6347 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
6348 << FixItHint::CreateRemoval(TypenameLoc);
6350 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6351 QualType T = CheckTypenameType(TypenameLoc.isValid()? ETK_Typename : ETK_None,
6352 TypenameLoc, QualifierLoc, II, IdLoc);
6356 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
6357 if (isa<DependentNameType>(T)) {
6358 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc());
6359 TL.setKeywordLoc(TypenameLoc);
6360 TL.setQualifierLoc(QualifierLoc);
6361 TL.setNameLoc(IdLoc);
6363 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc());
6364 TL.setKeywordLoc(TypenameLoc);
6365 TL.setQualifierLoc(QualifierLoc);
6366 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc);
6369 return CreateParsedType(T, TSI);
6373 Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
6374 const CXXScopeSpec &SS,
6375 SourceLocation TemplateLoc,
6376 TemplateTy TemplateIn,
6377 SourceLocation TemplateNameLoc,
6378 SourceLocation LAngleLoc,
6379 ASTTemplateArgsPtr TemplateArgsIn,
6380 SourceLocation RAngleLoc) {
6381 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() &&
6382 !getLangOptions().CPlusPlus0x)
6383 Diag(TypenameLoc, diag::ext_typename_outside_of_template)
6384 << FixItHint::CreateRemoval(TypenameLoc);
6386 // Translate the parser's template argument list in our AST format.
6387 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
6388 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
6390 TemplateName Template = TemplateIn.get();
6391 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6392 // Construct a dependent template specialization type.
6393 assert(DTN && "dependent template has non-dependent name?");
6394 assert(DTN->getQualifier()
6395 == static_cast<NestedNameSpecifier*>(SS.getScopeRep()));
6396 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename,
6397 DTN->getQualifier(),
6398 DTN->getIdentifier(),
6401 // Create source-location information for this type.
6402 TypeLocBuilder Builder;
6403 DependentTemplateSpecializationTypeLoc SpecTL
6404 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
6405 SpecTL.setLAngleLoc(LAngleLoc);
6406 SpecTL.setRAngleLoc(RAngleLoc);
6407 SpecTL.setKeywordLoc(TypenameLoc);
6408 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
6409 SpecTL.setNameLoc(TemplateNameLoc);
6410 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6411 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
6412 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
6415 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
6419 // Provide source-location information for the template specialization
6421 TypeLocBuilder Builder;
6422 TemplateSpecializationTypeLoc SpecTL
6423 = Builder.push<TemplateSpecializationTypeLoc>(T);
6425 // FIXME: No place to set the location of the 'template' keyword!
6426 SpecTL.setLAngleLoc(LAngleLoc);
6427 SpecTL.setRAngleLoc(RAngleLoc);
6428 SpecTL.setTemplateNameLoc(TemplateNameLoc);
6429 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
6430 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
6432 T = Context.getElaboratedType(ETK_Typename, SS.getScopeRep(), T);
6433 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
6434 TL.setKeywordLoc(TypenameLoc);
6435 TL.setQualifierLoc(SS.getWithLocInContext(Context));
6437 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
6438 return CreateParsedType(T, TSI);
6442 /// \brief Build the type that describes a C++ typename specifier,
6443 /// e.g., "typename T::type".
6445 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
6446 SourceLocation KeywordLoc,
6447 NestedNameSpecifierLoc QualifierLoc,
6448 const IdentifierInfo &II,
6449 SourceLocation IILoc) {
6451 SS.Adopt(QualifierLoc);
6453 DeclContext *Ctx = computeDeclContext(SS);
6455 // If the nested-name-specifier is dependent and couldn't be
6456 // resolved to a type, build a typename type.
6457 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
6458 return Context.getDependentNameType(Keyword,
6459 QualifierLoc.getNestedNameSpecifier(),
6463 // If the nested-name-specifier refers to the current instantiation,
6464 // the "typename" keyword itself is superfluous. In C++03, the
6465 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
6466 // allows such extraneous "typename" keywords, and we retroactively
6467 // apply this DR to C++03 code with only a warning. In any case we continue.
6469 if (RequireCompleteDeclContext(SS, Ctx))
6472 DeclarationName Name(&II);
6473 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
6474 LookupQualifiedName(Result, Ctx);
6475 unsigned DiagID = 0;
6476 Decl *Referenced = 0;
6477 switch (Result.getResultKind()) {
6478 case LookupResult::NotFound:
6479 DiagID = diag::err_typename_nested_not_found;
6482 case LookupResult::FoundUnresolvedValue: {
6483 // We found a using declaration that is a value. Most likely, the using
6484 // declaration itself is meant to have the 'typename' keyword.
6485 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
6487 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
6488 << Name << Ctx << FullRange;
6489 if (UnresolvedUsingValueDecl *Using
6490 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){
6491 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
6492 Diag(Loc, diag::note_using_value_decl_missing_typename)
6493 << FixItHint::CreateInsertion(Loc, "typename ");
6496 // Fall through to create a dependent typename type, from which we can recover
6499 case LookupResult::NotFoundInCurrentInstantiation:
6500 // Okay, it's a member of an unknown instantiation.
6501 return Context.getDependentNameType(Keyword,
6502 QualifierLoc.getNestedNameSpecifier(),
6505 case LookupResult::Found:
6506 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {
6507 // We found a type. Build an ElaboratedType, since the
6508 // typename-specifier was just sugar.
6509 return Context.getElaboratedType(ETK_Typename,
6510 QualifierLoc.getNestedNameSpecifier(),
6511 Context.getTypeDeclType(Type));
6514 DiagID = diag::err_typename_nested_not_type;
6515 Referenced = Result.getFoundDecl();
6519 llvm_unreachable("unresolved using decl in non-dependent context");
6522 case LookupResult::FoundOverloaded:
6523 DiagID = diag::err_typename_nested_not_type;
6524 Referenced = *Result.begin();
6527 case LookupResult::Ambiguous:
6531 // If we get here, it's because name lookup did not find a
6532 // type. Emit an appropriate diagnostic and return an error.
6533 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
6535 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
6537 Diag(Referenced->getLocation(), diag::note_typename_refers_here)
6543 // See Sema::RebuildTypeInCurrentInstantiation
6544 class CurrentInstantiationRebuilder
6545 : public TreeTransform<CurrentInstantiationRebuilder> {
6547 DeclarationName Entity;
6550 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
6552 CurrentInstantiationRebuilder(Sema &SemaRef,
6554 DeclarationName Entity)
6555 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
6556 Loc(Loc), Entity(Entity) { }
6558 /// \brief Determine whether the given type \p T has already been
6561 /// For the purposes of type reconstruction, a type has already been
6562 /// transformed if it is NULL or if it is not dependent.
6563 bool AlreadyTransformed(QualType T) {
6564 return T.isNull() || !T->isDependentType();
6567 /// \brief Returns the location of the entity whose type is being
6569 SourceLocation getBaseLocation() { return Loc; }
6571 /// \brief Returns the name of the entity whose type is being rebuilt.
6572 DeclarationName getBaseEntity() { return Entity; }
6574 /// \brief Sets the "base" location and entity when that
6575 /// information is known based on another transformation.
6576 void setBase(SourceLocation Loc, DeclarationName Entity) {
6578 this->Entity = Entity;
6583 /// \brief Rebuilds a type within the context of the current instantiation.
6585 /// The type \p T is part of the type of an out-of-line member definition of
6586 /// a class template (or class template partial specialization) that was parsed
6587 /// and constructed before we entered the scope of the class template (or
6588 /// partial specialization thereof). This routine will rebuild that type now
6589 /// that we have entered the declarator's scope, which may produce different
6590 /// canonical types, e.g.,
6593 /// template<typename T>
6595 /// typedef T* pointer;
6599 /// template<typename T>
6600 /// typename X<T>::pointer X<T>::data() { ... }
6603 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
6604 /// since we do not know that we can look into X<T> when we parsed the type.
6605 /// This function will rebuild the type, performing the lookup of "pointer"
6606 /// in X<T> and returning an ElaboratedType whose canonical type is the same
6607 /// as the canonical type of T*, allowing the return types of the out-of-line
6608 /// definition and the declaration to match.
6609 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
6611 DeclarationName Name) {
6612 if (!T || !T->getType()->isDependentType())
6615 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
6616 return Rebuilder.TransformType(T);
6619 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
6620 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
6622 return Rebuilder.TransformExpr(E);
6625 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
6629 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
6630 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
6632 NestedNameSpecifierLoc Rebuilt
6633 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
6641 /// \brief Produces a formatted string that describes the binding of
6642 /// template parameters to template arguments.
6644 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6645 const TemplateArgumentList &Args) {
6646 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());
6650 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
6651 const TemplateArgument *Args,
6653 llvm::SmallString<128> Str;
6654 llvm::raw_svector_ostream Out(Str);
6656 if (!Params || Params->size() == 0 || NumArgs == 0)
6657 return std::string();
6659 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
6668 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {
6669 Out << Id->getName();
6675 Args[I].print(Context.PrintingPolicy, Out);
6682 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag) {
6685 FD->setLateTemplateParsed(Flag);
6688 bool Sema::IsInsideALocalClassWithinATemplateFunction() {
6689 DeclContext *DC = CurContext;
6692 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {
6693 const FunctionDecl *FD = RD->isLocalClass();
6694 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
6695 } else if (DC->isTranslationUnit() || DC->isNamespace())
6698 DC = DC->getParent();