SemaTemplate.cpp revision 4c9be89bb615ec07eb3ed507c8fa9d0baa8a5ad7
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===/ 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7//===----------------------------------------------------------------------===/ 8// 9// This file implements semantic analysis for C++ templates. 10//===----------------------------------------------------------------------===/ 11 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" 30using namespace clang; 31using namespace sema; 32 33// Exported for use by Parser. 34SourceRange 35clang::getTemplateParamsRange(TemplateParameterList const * const *Ps, 36 unsigned N) { 37 if (!N) return SourceRange(); 38 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc()); 39} 40 41/// \brief Determine whether the declaration found is acceptable as the name 42/// of a template and, if so, return that template declaration. Otherwise, 43/// returns NULL. 44static NamedDecl *isAcceptableTemplateName(ASTContext &Context, 45 NamedDecl *Orig) { 46 NamedDecl *D = Orig->getUnderlyingDecl(); 47 48 if (isa<TemplateDecl>(D)) 49 return Orig; 50 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 62 // specialization. 63 if (Record->isInjectedClassName()) { 64 Record = cast<CXXRecordDecl>(Record->getDeclContext()); 65 if (Record->getDescribedClassTemplate()) 66 return Record->getDescribedClassTemplate(); 67 68 if (ClassTemplateSpecializationDecl *Spec 69 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) 70 return Spec->getSpecializedTemplate(); 71 } 72 73 return 0; 74 } 75 76 return 0; 77} 78 79static void FilterAcceptableTemplateNames(ASTContext &C, 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(C, Orig); 86 if (!Repl) 87 filter.erase(); 88 else if (Repl != Orig) { 89 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 followed by a template-argument-list, the reference refers to the 96 // class template itself and not a specialization thereof, and is not 97 // ambiguous. 98 // 99 // FIXME: Will we eventually have to do the same for alias templates? 100 if (ClassTemplateDecl *ClassTmpl = dyn_cast<ClassTemplateDecl>(Repl)) 101 if (!ClassTemplates.insert(ClassTmpl)) { 102 filter.erase(); 103 continue; 104 } 105 106 // FIXME: we promote access to public here as a workaround to 107 // the fact that LookupResult doesn't let us remember that we 108 // found this template through a particular injected class name, 109 // which means we end up doing nasty things to the invariants. 110 // Pretending that access is public is *much* safer. 111 filter.replace(Repl, AS_public); 112 } 113 } 114 filter.done(); 115} 116 117TemplateNameKind Sema::isTemplateName(Scope *S, 118 CXXScopeSpec &SS, 119 bool hasTemplateKeyword, 120 UnqualifiedId &Name, 121 ParsedType ObjectTypePtr, 122 bool EnteringContext, 123 TemplateTy &TemplateResult, 124 bool &MemberOfUnknownSpecialization) { 125 assert(getLangOptions().CPlusPlus && "No template names in C!"); 126 127 DeclarationName TName; 128 MemberOfUnknownSpecialization = false; 129 130 switch (Name.getKind()) { 131 case UnqualifiedId::IK_Identifier: 132 TName = DeclarationName(Name.Identifier); 133 break; 134 135 case UnqualifiedId::IK_OperatorFunctionId: 136 TName = Context.DeclarationNames.getCXXOperatorName( 137 Name.OperatorFunctionId.Operator); 138 break; 139 140 case UnqualifiedId::IK_LiteralOperatorId: 141 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier); 142 break; 143 144 default: 145 return TNK_Non_template; 146 } 147 148 QualType ObjectType = ObjectTypePtr.get(); 149 150 LookupResult R(*this, TName, Name.getSourceRange().getBegin(), 151 LookupOrdinaryName); 152 LookupTemplateName(R, S, SS, ObjectType, EnteringContext, 153 MemberOfUnknownSpecialization); 154 if (R.empty()) return TNK_Non_template; 155 if (R.isAmbiguous()) { 156 // Suppress diagnostics; we'll redo this lookup later. 157 R.suppressDiagnostics(); 158 159 // FIXME: we might have ambiguous templates, in which case we 160 // should at least parse them properly! 161 return TNK_Non_template; 162 } 163 164 TemplateName Template; 165 TemplateNameKind TemplateKind; 166 167 unsigned ResultCount = R.end() - R.begin(); 168 if (ResultCount > 1) { 169 // We assume that we'll preserve the qualifier from a function 170 // template name in other ways. 171 Template = Context.getOverloadedTemplateName(R.begin(), R.end()); 172 TemplateKind = TNK_Function_template; 173 174 // We'll do this lookup again later. 175 R.suppressDiagnostics(); 176 } else { 177 TemplateDecl *TD = cast<TemplateDecl>((*R.begin())->getUnderlyingDecl()); 178 179 if (SS.isSet() && !SS.isInvalid()) { 180 NestedNameSpecifier *Qualifier 181 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 182 Template = Context.getQualifiedTemplateName(Qualifier, 183 hasTemplateKeyword, TD); 184 } else { 185 Template = TemplateName(TD); 186 } 187 188 if (isa<FunctionTemplateDecl>(TD)) { 189 TemplateKind = TNK_Function_template; 190 191 // We'll do this lookup again later. 192 R.suppressDiagnostics(); 193 } else { 194 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD)); 195 TemplateKind = TNK_Type_template; 196 } 197 } 198 199 TemplateResult = TemplateTy::make(Template); 200 return TemplateKind; 201} 202 203bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II, 204 SourceLocation IILoc, 205 Scope *S, 206 const CXXScopeSpec *SS, 207 TemplateTy &SuggestedTemplate, 208 TemplateNameKind &SuggestedKind) { 209 // We can't recover unless there's a dependent scope specifier preceding the 210 // template name. 211 // FIXME: Typo correction? 212 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) || 213 computeDeclContext(*SS)) 214 return false; 215 216 // The code is missing a 'template' keyword prior to the dependent template 217 // name. 218 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep(); 219 Diag(IILoc, diag::err_template_kw_missing) 220 << Qualifier << II.getName() 221 << FixItHint::CreateInsertion(IILoc, "template "); 222 SuggestedTemplate 223 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II)); 224 SuggestedKind = TNK_Dependent_template_name; 225 return true; 226} 227 228void Sema::LookupTemplateName(LookupResult &Found, 229 Scope *S, CXXScopeSpec &SS, 230 QualType ObjectType, 231 bool EnteringContext, 232 bool &MemberOfUnknownSpecialization) { 233 // Determine where to perform name lookup 234 MemberOfUnknownSpecialization = false; 235 DeclContext *LookupCtx = 0; 236 bool isDependent = false; 237 if (!ObjectType.isNull()) { 238 // This nested-name-specifier occurs in a member access expression, e.g., 239 // x->B::f, and we are looking into the type of the object. 240 assert(!SS.isSet() && "ObjectType and scope specifier cannot coexist"); 241 LookupCtx = computeDeclContext(ObjectType); 242 isDependent = ObjectType->isDependentType(); 243 assert((isDependent || !ObjectType->isIncompleteType()) && 244 "Caller should have completed object type"); 245 } else if (SS.isSet()) { 246 // This nested-name-specifier occurs after another nested-name-specifier, 247 // so long into the context associated with the prior nested-name-specifier. 248 LookupCtx = computeDeclContext(SS, EnteringContext); 249 isDependent = isDependentScopeSpecifier(SS); 250 251 // The declaration context must be complete. 252 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx)) 253 return; 254 } 255 256 bool ObjectTypeSearchedInScope = false; 257 if (LookupCtx) { 258 // Perform "qualified" name lookup into the declaration context we 259 // computed, which is either the type of the base of a member access 260 // expression or the declaration context associated with a prior 261 // nested-name-specifier. 262 LookupQualifiedName(Found, LookupCtx); 263 264 if (!ObjectType.isNull() && Found.empty()) { 265 // C++ [basic.lookup.classref]p1: 266 // In a class member access expression (5.2.5), if the . or -> token is 267 // immediately followed by an identifier followed by a <, the 268 // identifier must be looked up to determine whether the < is the 269 // beginning of a template argument list (14.2) or a less-than operator. 270 // The identifier is first looked up in the class of the object 271 // expression. If the identifier is not found, it is then looked up in 272 // the context of the entire postfix-expression and shall name a class 273 // or function template. 274 if (S) LookupName(Found, S); 275 ObjectTypeSearchedInScope = true; 276 } 277 } else if (isDependent && (!S || ObjectType.isNull())) { 278 // We cannot look into a dependent object type or nested nme 279 // specifier. 280 MemberOfUnknownSpecialization = true; 281 return; 282 } else { 283 // Perform unqualified name lookup in the current scope. 284 LookupName(Found, S); 285 } 286 287 if (Found.empty() && !isDependent) { 288 // If we did not find any names, attempt to correct any typos. 289 DeclarationName Name = Found.getLookupName(); 290 if (DeclarationName Corrected = CorrectTypo(Found, S, &SS, LookupCtx, 291 false, CTC_CXXCasts)) { 292 FilterAcceptableTemplateNames(Context, Found); 293 if (!Found.empty()) { 294 if (LookupCtx) 295 Diag(Found.getNameLoc(), diag::err_no_member_template_suggest) 296 << Name << LookupCtx << Found.getLookupName() << SS.getRange() 297 << FixItHint::CreateReplacement(Found.getNameLoc(), 298 Found.getLookupName().getAsString()); 299 else 300 Diag(Found.getNameLoc(), diag::err_no_template_suggest) 301 << Name << Found.getLookupName() 302 << FixItHint::CreateReplacement(Found.getNameLoc(), 303 Found.getLookupName().getAsString()); 304 if (TemplateDecl *Template = Found.getAsSingle<TemplateDecl>()) 305 Diag(Template->getLocation(), diag::note_previous_decl) 306 << Template->getDeclName(); 307 } 308 } else { 309 Found.clear(); 310 Found.setLookupName(Name); 311 } 312 } 313 314 FilterAcceptableTemplateNames(Context, Found); 315 if (Found.empty()) { 316 if (isDependent) 317 MemberOfUnknownSpecialization = true; 318 return; 319 } 320 321 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope) { 322 // C++ [basic.lookup.classref]p1: 323 // [...] If the lookup in the class of the object expression finds a 324 // template, the name is also looked up in the context of the entire 325 // postfix-expression and [...] 326 // 327 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(), 328 LookupOrdinaryName); 329 LookupName(FoundOuter, S); 330 FilterAcceptableTemplateNames(Context, FoundOuter); 331 332 if (FoundOuter.empty()) { 333 // - if the name is not found, the name found in the class of the 334 // object expression is used, otherwise 335 } else if (!FoundOuter.getAsSingle<ClassTemplateDecl>()) { 336 // - if the name is found in the context of the entire 337 // postfix-expression and does not name a class template, the name 338 // found in the class of the object expression is used, otherwise 339 } else if (!Found.isSuppressingDiagnostics()) { 340 // - if the name found is a class template, it must refer to the same 341 // entity as the one found in the class of the object expression, 342 // otherwise the program is ill-formed. 343 if (!Found.isSingleResult() || 344 Found.getFoundDecl()->getCanonicalDecl() 345 != FoundOuter.getFoundDecl()->getCanonicalDecl()) { 346 Diag(Found.getNameLoc(), 347 diag::ext_nested_name_member_ref_lookup_ambiguous) 348 << Found.getLookupName() 349 << ObjectType; 350 Diag(Found.getRepresentativeDecl()->getLocation(), 351 diag::note_ambig_member_ref_object_type) 352 << ObjectType; 353 Diag(FoundOuter.getFoundDecl()->getLocation(), 354 diag::note_ambig_member_ref_scope); 355 356 // Recover by taking the template that we found in the object 357 // expression's type. 358 } 359 } 360 } 361} 362 363/// ActOnDependentIdExpression - Handle a dependent id-expression that 364/// was just parsed. This is only possible with an explicit scope 365/// specifier naming a dependent type. 366ExprResult 367Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS, 368 const DeclarationNameInfo &NameInfo, 369 bool isAddressOfOperand, 370 const TemplateArgumentListInfo *TemplateArgs) { 371 DeclContext *DC = getFunctionLevelDeclContext(); 372 373 if (!isAddressOfOperand && 374 isa<CXXMethodDecl>(DC) && 375 cast<CXXMethodDecl>(DC)->isInstance()) { 376 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context); 377 378 // Since the 'this' expression is synthesized, we don't need to 379 // perform the double-lookup check. 380 NamedDecl *FirstQualifierInScope = 0; 381 382 return Owned(CXXDependentScopeMemberExpr::Create(Context, 383 /*This*/ 0, ThisType, 384 /*IsArrow*/ true, 385 /*Op*/ SourceLocation(), 386 SS.getWithLocInContext(Context), 387 FirstQualifierInScope, 388 NameInfo, 389 TemplateArgs)); 390 } 391 392 return BuildDependentDeclRefExpr(SS, NameInfo, TemplateArgs); 393} 394 395ExprResult 396Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 397 const DeclarationNameInfo &NameInfo, 398 const TemplateArgumentListInfo *TemplateArgs) { 399 return Owned(DependentScopeDeclRefExpr::Create(Context, 400 SS.getWithLocInContext(Context), 401 NameInfo, 402 TemplateArgs)); 403} 404 405/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining 406/// that the template parameter 'PrevDecl' is being shadowed by a new 407/// declaration at location Loc. Returns true to indicate that this is 408/// an error, and false otherwise. 409bool Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) { 410 assert(PrevDecl->isTemplateParameter() && "Not a template parameter"); 411 412 // Microsoft Visual C++ permits template parameters to be shadowed. 413 if (getLangOptions().Microsoft) 414 return false; 415 416 // C++ [temp.local]p4: 417 // A template-parameter shall not be redeclared within its 418 // scope (including nested scopes). 419 Diag(Loc, diag::err_template_param_shadow) 420 << cast<NamedDecl>(PrevDecl)->getDeclName(); 421 Diag(PrevDecl->getLocation(), diag::note_template_param_here); 422 return true; 423} 424 425/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset 426/// the parameter D to reference the templated declaration and return a pointer 427/// to the template declaration. Otherwise, do nothing to D and return null. 428TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) { 429 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) { 430 D = Temp->getTemplatedDecl(); 431 return Temp; 432 } 433 return 0; 434} 435 436ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion( 437 SourceLocation EllipsisLoc) const { 438 assert(Kind == Template && 439 "Only template template arguments can be pack expansions here"); 440 assert(getAsTemplate().get().containsUnexpandedParameterPack() && 441 "Template template argument pack expansion without packs"); 442 ParsedTemplateArgument Result(*this); 443 Result.EllipsisLoc = EllipsisLoc; 444 return Result; 445} 446 447static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, 448 const ParsedTemplateArgument &Arg) { 449 450 switch (Arg.getKind()) { 451 case ParsedTemplateArgument::Type: { 452 TypeSourceInfo *DI; 453 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI); 454 if (!DI) 455 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation()); 456 return TemplateArgumentLoc(TemplateArgument(T), DI); 457 } 458 459 case ParsedTemplateArgument::NonType: { 460 Expr *E = static_cast<Expr *>(Arg.getAsExpr()); 461 return TemplateArgumentLoc(TemplateArgument(E), E); 462 } 463 464 case ParsedTemplateArgument::Template: { 465 TemplateName Template = Arg.getAsTemplate().get(); 466 TemplateArgument TArg; 467 if (Arg.getEllipsisLoc().isValid()) 468 TArg = TemplateArgument(Template, llvm::Optional<unsigned int>()); 469 else 470 TArg = Template; 471 return TemplateArgumentLoc(TArg, 472 Arg.getScopeSpec().getRange(), 473 Arg.getLocation(), 474 Arg.getEllipsisLoc()); 475 } 476 } 477 478 llvm_unreachable("Unhandled parsed template argument"); 479 return TemplateArgumentLoc(); 480} 481 482/// \brief Translates template arguments as provided by the parser 483/// into template arguments used by semantic analysis. 484void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn, 485 TemplateArgumentListInfo &TemplateArgs) { 486 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I) 487 TemplateArgs.addArgument(translateTemplateArgument(*this, 488 TemplateArgsIn[I])); 489} 490 491/// ActOnTypeParameter - Called when a C++ template type parameter 492/// (e.g., "typename T") has been parsed. Typename specifies whether 493/// the keyword "typename" was used to declare the type parameter 494/// (otherwise, "class" was used), and KeyLoc is the location of the 495/// "class" or "typename" keyword. ParamName is the name of the 496/// parameter (NULL indicates an unnamed template parameter) and 497/// ParamName is the location of the parameter name (if any). 498/// If the type parameter has a default argument, it will be added 499/// later via ActOnTypeParameterDefault. 500Decl *Sema::ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, 501 SourceLocation EllipsisLoc, 502 SourceLocation KeyLoc, 503 IdentifierInfo *ParamName, 504 SourceLocation ParamNameLoc, 505 unsigned Depth, unsigned Position, 506 SourceLocation EqualLoc, 507 ParsedType DefaultArg) { 508 assert(S->isTemplateParamScope() && 509 "Template type parameter not in template parameter scope!"); 510 bool Invalid = false; 511 512 if (ParamName) { 513 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, ParamNameLoc, 514 LookupOrdinaryName, 515 ForRedeclaration); 516 if (PrevDecl && PrevDecl->isTemplateParameter()) 517 Invalid = Invalid || DiagnoseTemplateParameterShadow(ParamNameLoc, 518 PrevDecl); 519 } 520 521 SourceLocation Loc = ParamNameLoc; 522 if (!ParamName) 523 Loc = KeyLoc; 524 525 TemplateTypeParmDecl *Param 526 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(), 527 Loc, Depth, Position, ParamName, Typename, 528 Ellipsis); 529 if (Invalid) 530 Param->setInvalidDecl(); 531 532 if (ParamName) { 533 // Add the template parameter into the current scope. 534 S->AddDecl(Param); 535 IdResolver.AddDecl(Param); 536 } 537 538 // C++0x [temp.param]p9: 539 // A default template-argument may be specified for any kind of 540 // template-parameter that is not a template parameter pack. 541 if (DefaultArg && Ellipsis) { 542 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 543 DefaultArg = ParsedType(); 544 } 545 546 // Handle the default argument, if provided. 547 if (DefaultArg) { 548 TypeSourceInfo *DefaultTInfo; 549 GetTypeFromParser(DefaultArg, &DefaultTInfo); 550 551 assert(DefaultTInfo && "expected source information for type"); 552 553 // Check for unexpanded parameter packs. 554 if (DiagnoseUnexpandedParameterPack(Loc, DefaultTInfo, 555 UPPC_DefaultArgument)) 556 return Param; 557 558 // Check the template argument itself. 559 if (CheckTemplateArgument(Param, DefaultTInfo)) { 560 Param->setInvalidDecl(); 561 return Param; 562 } 563 564 Param->setDefaultArgument(DefaultTInfo, false); 565 } 566 567 return Param; 568} 569 570/// \brief Check that the type of a non-type template parameter is 571/// well-formed. 572/// 573/// \returns the (possibly-promoted) parameter type if valid; 574/// otherwise, produces a diagnostic and returns a NULL type. 575QualType 576Sema::CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc) { 577 // We don't allow variably-modified types as the type of non-type template 578 // parameters. 579 if (T->isVariablyModifiedType()) { 580 Diag(Loc, diag::err_variably_modified_nontype_template_param) 581 << T; 582 return QualType(); 583 } 584 585 // C++ [temp.param]p4: 586 // 587 // A non-type template-parameter shall have one of the following 588 // (optionally cv-qualified) types: 589 // 590 // -- integral or enumeration type, 591 if (T->isIntegralOrEnumerationType() || 592 // -- pointer to object or pointer to function, 593 T->isPointerType() || 594 // -- reference to object or reference to function, 595 T->isReferenceType() || 596 // -- pointer to member. 597 T->isMemberPointerType() || 598 // If T is a dependent type, we can't do the check now, so we 599 // assume that it is well-formed. 600 T->isDependentType()) 601 return T; 602 // C++ [temp.param]p8: 603 // 604 // A non-type template-parameter of type "array of T" or 605 // "function returning T" is adjusted to be of type "pointer to 606 // T" or "pointer to function returning T", respectively. 607 else if (T->isArrayType()) 608 // FIXME: Keep the type prior to promotion? 609 return Context.getArrayDecayedType(T); 610 else if (T->isFunctionType()) 611 // FIXME: Keep the type prior to promotion? 612 return Context.getPointerType(T); 613 614 Diag(Loc, diag::err_template_nontype_parm_bad_type) 615 << T; 616 617 return QualType(); 618} 619 620Decl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 621 unsigned Depth, 622 unsigned Position, 623 SourceLocation EqualLoc, 624 Expr *Default) { 625 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 626 QualType T = TInfo->getType(); 627 628 assert(S->isTemplateParamScope() && 629 "Non-type template parameter not in template parameter scope!"); 630 bool Invalid = false; 631 632 IdentifierInfo *ParamName = D.getIdentifier(); 633 if (ParamName) { 634 NamedDecl *PrevDecl = LookupSingleName(S, ParamName, D.getIdentifierLoc(), 635 LookupOrdinaryName, 636 ForRedeclaration); 637 if (PrevDecl && PrevDecl->isTemplateParameter()) 638 Invalid = Invalid || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 639 PrevDecl); 640 } 641 642 T = CheckNonTypeTemplateParameterType(T, D.getIdentifierLoc()); 643 if (T.isNull()) { 644 T = Context.IntTy; // Recover with an 'int' type. 645 Invalid = true; 646 } 647 648 bool IsParameterPack = D.hasEllipsis(); 649 NonTypeTemplateParmDecl *Param 650 = NonTypeTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), 651 D.getIdentifierLoc(), 652 Depth, Position, ParamName, T, 653 IsParameterPack, TInfo); 654 if (Invalid) 655 Param->setInvalidDecl(); 656 657 if (D.getIdentifier()) { 658 // Add the template parameter into the current scope. 659 S->AddDecl(Param); 660 IdResolver.AddDecl(Param); 661 } 662 663 // C++0x [temp.param]p9: 664 // A default template-argument may be specified for any kind of 665 // template-parameter that is not a template parameter pack. 666 if (Default && IsParameterPack) { 667 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 668 Default = 0; 669 } 670 671 // Check the well-formedness of the default template argument, if provided. 672 if (Default) { 673 // Check for unexpanded parameter packs. 674 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument)) 675 return Param; 676 677 TemplateArgument Converted; 678 if (CheckTemplateArgument(Param, Param->getType(), Default, Converted)) { 679 Param->setInvalidDecl(); 680 return Param; 681 } 682 683 Param->setDefaultArgument(Default, false); 684 } 685 686 return Param; 687} 688 689/// ActOnTemplateTemplateParameter - Called when a C++ template template 690/// parameter (e.g. T in template <template <typename> class T> class array) 691/// has been parsed. S is the current scope. 692Decl *Sema::ActOnTemplateTemplateParameter(Scope* S, 693 SourceLocation TmpLoc, 694 TemplateParamsTy *Params, 695 SourceLocation EllipsisLoc, 696 IdentifierInfo *Name, 697 SourceLocation NameLoc, 698 unsigned Depth, 699 unsigned Position, 700 SourceLocation EqualLoc, 701 ParsedTemplateArgument Default) { 702 assert(S->isTemplateParamScope() && 703 "Template template parameter not in template parameter scope!"); 704 705 // Construct the parameter object. 706 bool IsParameterPack = EllipsisLoc.isValid(); 707 // FIXME: Pack-ness is dropped 708 TemplateTemplateParmDecl *Param = 709 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), 710 NameLoc.isInvalid()? TmpLoc : NameLoc, 711 Depth, Position, IsParameterPack, 712 Name, Params); 713 714 // If the template template parameter has a name, then link the identifier 715 // into the scope and lookup mechanisms. 716 if (Name) { 717 S->AddDecl(Param); 718 IdResolver.AddDecl(Param); 719 } 720 721 if (Params->size() == 0) { 722 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms) 723 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc()); 724 Param->setInvalidDecl(); 725 } 726 727 // C++0x [temp.param]p9: 728 // A default template-argument may be specified for any kind of 729 // template-parameter that is not a template parameter pack. 730 if (IsParameterPack && !Default.isInvalid()) { 731 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 732 Default = ParsedTemplateArgument(); 733 } 734 735 if (!Default.isInvalid()) { 736 // Check only that we have a template template argument. We don't want to 737 // try to check well-formedness now, because our template template parameter 738 // might have dependent types in its template parameters, which we wouldn't 739 // be able to match now. 740 // 741 // If none of the template template parameter's template arguments mention 742 // other template parameters, we could actually perform more checking here. 743 // However, it isn't worth doing. 744 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default); 745 if (DefaultArg.getArgument().getAsTemplate().isNull()) { 746 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_class_template) 747 << DefaultArg.getSourceRange(); 748 return Param; 749 } 750 751 // Check for unexpanded parameter packs. 752 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(), 753 DefaultArg.getArgument().getAsTemplate(), 754 UPPC_DefaultArgument)) 755 return Param; 756 757 Param->setDefaultArgument(DefaultArg, false); 758 } 759 760 return Param; 761} 762 763/// ActOnTemplateParameterList - Builds a TemplateParameterList that 764/// contains the template parameters in Params/NumParams. 765Sema::TemplateParamsTy * 766Sema::ActOnTemplateParameterList(unsigned Depth, 767 SourceLocation ExportLoc, 768 SourceLocation TemplateLoc, 769 SourceLocation LAngleLoc, 770 Decl **Params, unsigned NumParams, 771 SourceLocation RAngleLoc) { 772 if (ExportLoc.isValid()) 773 Diag(ExportLoc, diag::warn_template_export_unsupported); 774 775 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc, 776 (NamedDecl**)Params, NumParams, 777 RAngleLoc); 778} 779 780static void SetNestedNameSpecifier(TagDecl *T, const CXXScopeSpec &SS) { 781 if (SS.isSet()) 782 T->setQualifierInfo(SS.getWithLocInContext(T->getASTContext())); 783} 784 785DeclResult 786Sema::CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, 787 SourceLocation KWLoc, CXXScopeSpec &SS, 788 IdentifierInfo *Name, SourceLocation NameLoc, 789 AttributeList *Attr, 790 TemplateParameterList *TemplateParams, 791 AccessSpecifier AS) { 792 assert(TemplateParams && TemplateParams->size() > 0 && 793 "No template parameters"); 794 assert(TUK != TUK_Reference && "Can only declare or define class templates"); 795 bool Invalid = false; 796 797 // Check that we can declare a template here. 798 if (CheckTemplateDeclScope(S, TemplateParams)) 799 return true; 800 801 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 802 assert(Kind != TTK_Enum && "can't build template of enumerated type"); 803 804 // There is no such thing as an unnamed class template. 805 if (!Name) { 806 Diag(KWLoc, diag::err_template_unnamed_class); 807 return true; 808 } 809 810 // Find any previous declaration with this name. 811 DeclContext *SemanticContext; 812 LookupResult Previous(*this, Name, NameLoc, LookupOrdinaryName, 813 ForRedeclaration); 814 if (SS.isNotEmpty() && !SS.isInvalid()) { 815 SemanticContext = computeDeclContext(SS, true); 816 if (!SemanticContext) { 817 // FIXME: Produce a reasonable diagnostic here 818 return true; 819 } 820 821 if (RequireCompleteDeclContext(SS, SemanticContext)) 822 return true; 823 824 LookupQualifiedName(Previous, SemanticContext); 825 } else { 826 SemanticContext = CurContext; 827 LookupName(Previous, S); 828 } 829 830 if (Previous.isAmbiguous()) 831 return true; 832 833 NamedDecl *PrevDecl = 0; 834 if (Previous.begin() != Previous.end()) 835 PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 836 837 // If there is a previous declaration with the same name, check 838 // whether this is a valid redeclaration. 839 ClassTemplateDecl *PrevClassTemplate 840 = dyn_cast_or_null<ClassTemplateDecl>(PrevDecl); 841 842 // We may have found the injected-class-name of a class template, 843 // class template partial specialization, or class template specialization. 844 // In these cases, grab the template that is being defined or specialized. 845 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) && 846 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) { 847 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext()); 848 PrevClassTemplate 849 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate(); 850 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) { 851 PrevClassTemplate 852 = cast<ClassTemplateSpecializationDecl>(PrevDecl) 853 ->getSpecializedTemplate(); 854 } 855 } 856 857 if (TUK == TUK_Friend) { 858 // C++ [namespace.memdef]p3: 859 // [...] When looking for a prior declaration of a class or a function 860 // declared as a friend, and when the name of the friend class or 861 // function is neither a qualified name nor a template-id, scopes outside 862 // the innermost enclosing namespace scope are not considered. 863 if (!SS.isSet()) { 864 DeclContext *OutermostContext = CurContext; 865 while (!OutermostContext->isFileContext()) 866 OutermostContext = OutermostContext->getLookupParent(); 867 868 if (PrevDecl && 869 (OutermostContext->Equals(PrevDecl->getDeclContext()) || 870 OutermostContext->Encloses(PrevDecl->getDeclContext()))) { 871 SemanticContext = PrevDecl->getDeclContext(); 872 } else { 873 // Declarations in outer scopes don't matter. However, the outermost 874 // context we computed is the semantic context for our new 875 // declaration. 876 PrevDecl = PrevClassTemplate = 0; 877 SemanticContext = OutermostContext; 878 } 879 } 880 881 if (CurContext->isDependentContext()) { 882 // If this is a dependent context, we don't want to link the friend 883 // class template to the template in scope, because that would perform 884 // checking of the template parameter lists that can't be performed 885 // until the outer context is instantiated. 886 PrevDecl = PrevClassTemplate = 0; 887 } 888 } else if (PrevDecl && !isDeclInScope(PrevDecl, SemanticContext, S)) 889 PrevDecl = PrevClassTemplate = 0; 890 891 if (PrevClassTemplate) { 892 // Ensure that the template parameter lists are compatible. 893 if (!TemplateParameterListsAreEqual(TemplateParams, 894 PrevClassTemplate->getTemplateParameters(), 895 /*Complain=*/true, 896 TPL_TemplateMatch)) 897 return true; 898 899 // C++ [temp.class]p4: 900 // In a redeclaration, partial specialization, explicit 901 // specialization or explicit instantiation of a class template, 902 // the class-key shall agree in kind with the original class 903 // template declaration (7.1.5.3). 904 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl(); 905 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, KWLoc, *Name)) { 906 Diag(KWLoc, diag::err_use_with_wrong_tag) 907 << Name 908 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName()); 909 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use); 910 Kind = PrevRecordDecl->getTagKind(); 911 } 912 913 // Check for redefinition of this class template. 914 if (TUK == TUK_Definition) { 915 if (TagDecl *Def = PrevRecordDecl->getDefinition()) { 916 Diag(NameLoc, diag::err_redefinition) << Name; 917 Diag(Def->getLocation(), diag::note_previous_definition); 918 // FIXME: Would it make sense to try to "forget" the previous 919 // definition, as part of error recovery? 920 return true; 921 } 922 } 923 } else if (PrevDecl && PrevDecl->isTemplateParameter()) { 924 // Maybe we will complain about the shadowed template parameter. 925 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); 926 // Just pretend that we didn't see the previous declaration. 927 PrevDecl = 0; 928 } else if (PrevDecl) { 929 // C++ [temp]p5: 930 // A class template shall not have the same name as any other 931 // template, class, function, object, enumeration, enumerator, 932 // namespace, or type in the same scope (3.3), except as specified 933 // in (14.5.4). 934 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 935 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 936 return true; 937 } 938 939 // Check the template parameter list of this declaration, possibly 940 // merging in the template parameter list from the previous class 941 // template declaration. 942 if (CheckTemplateParameterList(TemplateParams, 943 PrevClassTemplate? PrevClassTemplate->getTemplateParameters() : 0, 944 (SS.isSet() && SemanticContext && 945 SemanticContext->isRecord() && 946 SemanticContext->isDependentContext()) 947 ? TPC_ClassTemplateMember 948 : TPC_ClassTemplate)) 949 Invalid = true; 950 951 if (SS.isSet()) { 952 // If the name of the template was qualified, we must be defining the 953 // template out-of-line. 954 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate && 955 !(TUK == TUK_Friend && CurContext->isDependentContext())) 956 Diag(NameLoc, diag::err_member_def_does_not_match) 957 << Name << SemanticContext << SS.getRange(); 958 } 959 960 CXXRecordDecl *NewClass = 961 CXXRecordDecl::Create(Context, Kind, SemanticContext, NameLoc, Name, KWLoc, 962 PrevClassTemplate? 963 PrevClassTemplate->getTemplatedDecl() : 0, 964 /*DelayTypeCreation=*/true); 965 SetNestedNameSpecifier(NewClass, SS); 966 967 ClassTemplateDecl *NewTemplate 968 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc, 969 DeclarationName(Name), TemplateParams, 970 NewClass, PrevClassTemplate); 971 NewClass->setDescribedClassTemplate(NewTemplate); 972 973 // Build the type for the class template declaration now. 974 QualType T = NewTemplate->getInjectedClassNameSpecialization(); 975 T = Context.getInjectedClassNameType(NewClass, T); 976 assert(T->isDependentType() && "Class template type is not dependent?"); 977 (void)T; 978 979 // If we are providing an explicit specialization of a member that is a 980 // class template, make a note of that. 981 if (PrevClassTemplate && 982 PrevClassTemplate->getInstantiatedFromMemberTemplate()) 983 PrevClassTemplate->setMemberSpecialization(); 984 985 // Set the access specifier. 986 if (!Invalid && TUK != TUK_Friend) 987 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS); 988 989 // Set the lexical context of these templates 990 NewClass->setLexicalDeclContext(CurContext); 991 NewTemplate->setLexicalDeclContext(CurContext); 992 993 if (TUK == TUK_Definition) 994 NewClass->startDefinition(); 995 996 if (Attr) 997 ProcessDeclAttributeList(S, NewClass, Attr); 998 999 if (TUK != TUK_Friend) 1000 PushOnScopeChains(NewTemplate, S); 1001 else { 1002 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) { 1003 NewTemplate->setAccess(PrevClassTemplate->getAccess()); 1004 NewClass->setAccess(PrevClassTemplate->getAccess()); 1005 } 1006 1007 NewTemplate->setObjectOfFriendDecl(/* PreviouslyDeclared = */ 1008 PrevClassTemplate != NULL); 1009 1010 // Friend templates are visible in fairly strange ways. 1011 if (!CurContext->isDependentContext()) { 1012 DeclContext *DC = SemanticContext->getRedeclContext(); 1013 DC->makeDeclVisibleInContext(NewTemplate, /* Recoverable = */ false); 1014 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 1015 PushOnScopeChains(NewTemplate, EnclosingScope, 1016 /* AddToContext = */ false); 1017 } 1018 1019 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, 1020 NewClass->getLocation(), 1021 NewTemplate, 1022 /*FIXME:*/NewClass->getLocation()); 1023 Friend->setAccess(AS_public); 1024 CurContext->addDecl(Friend); 1025 } 1026 1027 if (Invalid) { 1028 NewTemplate->setInvalidDecl(); 1029 NewClass->setInvalidDecl(); 1030 } 1031 return NewTemplate; 1032} 1033 1034/// \brief Diagnose the presence of a default template argument on a 1035/// template parameter, which is ill-formed in certain contexts. 1036/// 1037/// \returns true if the default template argument should be dropped. 1038static bool DiagnoseDefaultTemplateArgument(Sema &S, 1039 Sema::TemplateParamListContext TPC, 1040 SourceLocation ParamLoc, 1041 SourceRange DefArgRange) { 1042 switch (TPC) { 1043 case Sema::TPC_ClassTemplate: 1044 return false; 1045 1046 case Sema::TPC_FunctionTemplate: 1047 case Sema::TPC_FriendFunctionTemplateDefinition: 1048 // C++ [temp.param]p9: 1049 // A default template-argument shall not be specified in a 1050 // function template declaration or a function template 1051 // definition [...] 1052 // If a friend function template declaration specifies a default 1053 // template-argument, that declaration shall be a definition and shall be 1054 // the only declaration of the function template in the translation unit. 1055 // (C++98/03 doesn't have this wording; see DR226). 1056 if (!S.getLangOptions().CPlusPlus0x) 1057 S.Diag(ParamLoc, 1058 diag::ext_template_parameter_default_in_function_template) 1059 << DefArgRange; 1060 return false; 1061 1062 case Sema::TPC_ClassTemplateMember: 1063 // C++0x [temp.param]p9: 1064 // A default template-argument shall not be specified in the 1065 // template-parameter-lists of the definition of a member of a 1066 // class template that appears outside of the member's class. 1067 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member) 1068 << DefArgRange; 1069 return true; 1070 1071 case Sema::TPC_FriendFunctionTemplate: 1072 // C++ [temp.param]p9: 1073 // A default template-argument shall not be specified in a 1074 // friend template declaration. 1075 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template) 1076 << DefArgRange; 1077 return true; 1078 1079 // FIXME: C++0x [temp.param]p9 allows default template-arguments 1080 // for friend function templates if there is only a single 1081 // declaration (and it is a definition). Strange! 1082 } 1083 1084 return false; 1085} 1086 1087/// \brief Check for unexpanded parameter packs within the template parameters 1088/// of a template template parameter, recursively. 1089bool DiagnoseUnexpandedParameterPacks(Sema &S, TemplateTemplateParmDecl *TTP){ 1090 TemplateParameterList *Params = TTP->getTemplateParameters(); 1091 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 1092 NamedDecl *P = Params->getParam(I); 1093 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) { 1094 if (S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(), 1095 NTTP->getTypeSourceInfo(), 1096 Sema::UPPC_NonTypeTemplateParameterType)) 1097 return true; 1098 1099 continue; 1100 } 1101 1102 if (TemplateTemplateParmDecl *InnerTTP 1103 = dyn_cast<TemplateTemplateParmDecl>(P)) 1104 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP)) 1105 return true; 1106 } 1107 1108 return false; 1109} 1110 1111/// \brief Checks the validity of a template parameter list, possibly 1112/// considering the template parameter list from a previous 1113/// declaration. 1114/// 1115/// If an "old" template parameter list is provided, it must be 1116/// equivalent (per TemplateParameterListsAreEqual) to the "new" 1117/// template parameter list. 1118/// 1119/// \param NewParams Template parameter list for a new template 1120/// declaration. This template parameter list will be updated with any 1121/// default arguments that are carried through from the previous 1122/// template parameter list. 1123/// 1124/// \param OldParams If provided, template parameter list from a 1125/// previous declaration of the same template. Default template 1126/// arguments will be merged from the old template parameter list to 1127/// the new template parameter list. 1128/// 1129/// \param TPC Describes the context in which we are checking the given 1130/// template parameter list. 1131/// 1132/// \returns true if an error occurred, false otherwise. 1133bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, 1134 TemplateParameterList *OldParams, 1135 TemplateParamListContext TPC) { 1136 bool Invalid = false; 1137 1138 // C++ [temp.param]p10: 1139 // The set of default template-arguments available for use with a 1140 // template declaration or definition is obtained by merging the 1141 // default arguments from the definition (if in scope) and all 1142 // declarations in scope in the same way default function 1143 // arguments are (8.3.6). 1144 bool SawDefaultArgument = false; 1145 SourceLocation PreviousDefaultArgLoc; 1146 1147 bool SawParameterPack = false; 1148 SourceLocation ParameterPackLoc; 1149 1150 // Dummy initialization to avoid warnings. 1151 TemplateParameterList::iterator OldParam = NewParams->end(); 1152 if (OldParams) 1153 OldParam = OldParams->begin(); 1154 1155 bool RemoveDefaultArguments = false; 1156 for (TemplateParameterList::iterator NewParam = NewParams->begin(), 1157 NewParamEnd = NewParams->end(); 1158 NewParam != NewParamEnd; ++NewParam) { 1159 // Variables used to diagnose redundant default arguments 1160 bool RedundantDefaultArg = false; 1161 SourceLocation OldDefaultLoc; 1162 SourceLocation NewDefaultLoc; 1163 1164 // Variables used to diagnose missing default arguments 1165 bool MissingDefaultArg = false; 1166 1167 // C++0x [temp.param]p11: 1168 // If a template parameter of a primary class template is a template 1169 // parameter pack, it shall be the last template parameter. 1170 if (SawParameterPack && TPC == TPC_ClassTemplate) { 1171 Diag(ParameterPackLoc, 1172 diag::err_template_param_pack_must_be_last_template_parameter); 1173 Invalid = true; 1174 } 1175 1176 if (TemplateTypeParmDecl *NewTypeParm 1177 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) { 1178 // Check the presence of a default argument here. 1179 if (NewTypeParm->hasDefaultArgument() && 1180 DiagnoseDefaultTemplateArgument(*this, TPC, 1181 NewTypeParm->getLocation(), 1182 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc() 1183 .getSourceRange())) 1184 NewTypeParm->removeDefaultArgument(); 1185 1186 // Merge default arguments for template type parameters. 1187 TemplateTypeParmDecl *OldTypeParm 1188 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : 0; 1189 1190 if (NewTypeParm->isParameterPack()) { 1191 assert(!NewTypeParm->hasDefaultArgument() && 1192 "Parameter packs can't have a default argument!"); 1193 SawParameterPack = true; 1194 ParameterPackLoc = NewTypeParm->getLocation(); 1195 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument() && 1196 NewTypeParm->hasDefaultArgument()) { 1197 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc(); 1198 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc(); 1199 SawDefaultArgument = true; 1200 RedundantDefaultArg = true; 1201 PreviousDefaultArgLoc = NewDefaultLoc; 1202 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) { 1203 // Merge the default argument from the old declaration to the 1204 // new declaration. 1205 SawDefaultArgument = true; 1206 NewTypeParm->setDefaultArgument(OldTypeParm->getDefaultArgumentInfo(), 1207 true); 1208 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc(); 1209 } else if (NewTypeParm->hasDefaultArgument()) { 1210 SawDefaultArgument = true; 1211 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc(); 1212 } else if (SawDefaultArgument) 1213 MissingDefaultArg = true; 1214 } else if (NonTypeTemplateParmDecl *NewNonTypeParm 1215 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) { 1216 // Check for unexpanded parameter packs. 1217 if (DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(), 1218 NewNonTypeParm->getTypeSourceInfo(), 1219 UPPC_NonTypeTemplateParameterType)) { 1220 Invalid = true; 1221 continue; 1222 } 1223 1224 // Check the presence of a default argument here. 1225 if (NewNonTypeParm->hasDefaultArgument() && 1226 DiagnoseDefaultTemplateArgument(*this, TPC, 1227 NewNonTypeParm->getLocation(), 1228 NewNonTypeParm->getDefaultArgument()->getSourceRange())) { 1229 NewNonTypeParm->removeDefaultArgument(); 1230 } 1231 1232 // Merge default arguments for non-type template parameters 1233 NonTypeTemplateParmDecl *OldNonTypeParm 1234 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : 0; 1235 if (NewNonTypeParm->isParameterPack()) { 1236 assert(!NewNonTypeParm->hasDefaultArgument() && 1237 "Parameter packs can't have a default argument!"); 1238 SawParameterPack = true; 1239 ParameterPackLoc = NewNonTypeParm->getLocation(); 1240 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument() && 1241 NewNonTypeParm->hasDefaultArgument()) { 1242 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc(); 1243 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc(); 1244 SawDefaultArgument = true; 1245 RedundantDefaultArg = true; 1246 PreviousDefaultArgLoc = NewDefaultLoc; 1247 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) { 1248 // Merge the default argument from the old declaration to the 1249 // new declaration. 1250 SawDefaultArgument = true; 1251 // FIXME: We need to create a new kind of "default argument" 1252 // expression that points to a previous non-type template 1253 // parameter. 1254 NewNonTypeParm->setDefaultArgument( 1255 OldNonTypeParm->getDefaultArgument(), 1256 /*Inherited=*/ true); 1257 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc(); 1258 } else if (NewNonTypeParm->hasDefaultArgument()) { 1259 SawDefaultArgument = true; 1260 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc(); 1261 } else if (SawDefaultArgument) 1262 MissingDefaultArg = true; 1263 } else { 1264 // Check the presence of a default argument here. 1265 TemplateTemplateParmDecl *NewTemplateParm 1266 = cast<TemplateTemplateParmDecl>(*NewParam); 1267 1268 // Check for unexpanded parameter packs, recursively. 1269 if (DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) { 1270 Invalid = true; 1271 continue; 1272 } 1273 1274 if (NewTemplateParm->hasDefaultArgument() && 1275 DiagnoseDefaultTemplateArgument(*this, TPC, 1276 NewTemplateParm->getLocation(), 1277 NewTemplateParm->getDefaultArgument().getSourceRange())) 1278 NewTemplateParm->removeDefaultArgument(); 1279 1280 // Merge default arguments for template template parameters 1281 TemplateTemplateParmDecl *OldTemplateParm 1282 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : 0; 1283 if (NewTemplateParm->isParameterPack()) { 1284 assert(!NewTemplateParm->hasDefaultArgument() && 1285 "Parameter packs can't have a default argument!"); 1286 SawParameterPack = true; 1287 ParameterPackLoc = NewTemplateParm->getLocation(); 1288 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument() && 1289 NewTemplateParm->hasDefaultArgument()) { 1290 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation(); 1291 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation(); 1292 SawDefaultArgument = true; 1293 RedundantDefaultArg = true; 1294 PreviousDefaultArgLoc = NewDefaultLoc; 1295 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) { 1296 // Merge the default argument from the old declaration to the 1297 // new declaration. 1298 SawDefaultArgument = true; 1299 // FIXME: We need to create a new kind of "default argument" expression 1300 // that points to a previous template template parameter. 1301 NewTemplateParm->setDefaultArgument( 1302 OldTemplateParm->getDefaultArgument(), 1303 /*Inherited=*/ true); 1304 PreviousDefaultArgLoc 1305 = OldTemplateParm->getDefaultArgument().getLocation(); 1306 } else if (NewTemplateParm->hasDefaultArgument()) { 1307 SawDefaultArgument = true; 1308 PreviousDefaultArgLoc 1309 = NewTemplateParm->getDefaultArgument().getLocation(); 1310 } else if (SawDefaultArgument) 1311 MissingDefaultArg = true; 1312 } 1313 1314 if (RedundantDefaultArg) { 1315 // C++ [temp.param]p12: 1316 // A template-parameter shall not be given default arguments 1317 // by two different declarations in the same scope. 1318 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition); 1319 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg); 1320 Invalid = true; 1321 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) { 1322 // C++ [temp.param]p11: 1323 // If a template-parameter of a class template has a default 1324 // template-argument, each subsequent template-parameter shall either 1325 // have a default template-argument supplied or be a template parameter 1326 // pack. 1327 Diag((*NewParam)->getLocation(), 1328 diag::err_template_param_default_arg_missing); 1329 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg); 1330 Invalid = true; 1331 RemoveDefaultArguments = true; 1332 } 1333 1334 // If we have an old template parameter list that we're merging 1335 // in, move on to the next parameter. 1336 if (OldParams) 1337 ++OldParam; 1338 } 1339 1340 // We were missing some default arguments at the end of the list, so remove 1341 // all of the default arguments. 1342 if (RemoveDefaultArguments) { 1343 for (TemplateParameterList::iterator NewParam = NewParams->begin(), 1344 NewParamEnd = NewParams->end(); 1345 NewParam != NewParamEnd; ++NewParam) { 1346 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam)) 1347 TTP->removeDefaultArgument(); 1348 else if (NonTypeTemplateParmDecl *NTTP 1349 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) 1350 NTTP->removeDefaultArgument(); 1351 else 1352 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument(); 1353 } 1354 } 1355 1356 return Invalid; 1357} 1358 1359namespace { 1360 1361/// A class which looks for a use of a certain level of template 1362/// parameter. 1363struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> { 1364 typedef RecursiveASTVisitor<DependencyChecker> super; 1365 1366 unsigned Depth; 1367 bool Match; 1368 1369 DependencyChecker(TemplateParameterList *Params) : Match(false) { 1370 NamedDecl *ND = Params->getParam(0); 1371 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) { 1372 Depth = PD->getDepth(); 1373 } else if (NonTypeTemplateParmDecl *PD = 1374 dyn_cast<NonTypeTemplateParmDecl>(ND)) { 1375 Depth = PD->getDepth(); 1376 } else { 1377 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth(); 1378 } 1379 } 1380 1381 bool Matches(unsigned ParmDepth) { 1382 if (ParmDepth >= Depth) { 1383 Match = true; 1384 return true; 1385 } 1386 return false; 1387 } 1388 1389 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) { 1390 return !Matches(T->getDepth()); 1391 } 1392 1393 bool TraverseTemplateName(TemplateName N) { 1394 if (TemplateTemplateParmDecl *PD = 1395 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl())) 1396 if (Matches(PD->getDepth())) return false; 1397 return super::TraverseTemplateName(N); 1398 } 1399 1400 bool VisitDeclRefExpr(DeclRefExpr *E) { 1401 if (NonTypeTemplateParmDecl *PD = 1402 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) { 1403 if (PD->getDepth() == Depth) { 1404 Match = true; 1405 return false; 1406 } 1407 } 1408 return super::VisitDeclRefExpr(E); 1409 } 1410}; 1411} 1412 1413/// Determines whether a template-id depends on the given parameter 1414/// list. 1415static bool 1416DependsOnTemplateParameters(const TemplateSpecializationType *TemplateId, 1417 TemplateParameterList *Params) { 1418 DependencyChecker Checker(Params); 1419 Checker.TraverseType(QualType(TemplateId, 0)); 1420 return Checker.Match; 1421} 1422 1423/// \brief Match the given template parameter lists to the given scope 1424/// specifier, returning the template parameter list that applies to the 1425/// name. 1426/// 1427/// \param DeclStartLoc the start of the declaration that has a scope 1428/// specifier or a template parameter list. 1429/// 1430/// \param SS the scope specifier that will be matched to the given template 1431/// parameter lists. This scope specifier precedes a qualified name that is 1432/// being declared. 1433/// 1434/// \param ParamLists the template parameter lists, from the outermost to the 1435/// innermost template parameter lists. 1436/// 1437/// \param NumParamLists the number of template parameter lists in ParamLists. 1438/// 1439/// \param IsFriend Whether to apply the slightly different rules for 1440/// matching template parameters to scope specifiers in friend 1441/// declarations. 1442/// 1443/// \param IsExplicitSpecialization will be set true if the entity being 1444/// declared is an explicit specialization, false otherwise. 1445/// 1446/// \returns the template parameter list, if any, that corresponds to the 1447/// name that is preceded by the scope specifier @p SS. This template 1448/// parameter list may be have template parameters (if we're declaring a 1449/// template) or may have no template parameters (if we're declaring a 1450/// template specialization), or may be NULL (if we were's declaring isn't 1451/// itself a template). 1452TemplateParameterList * 1453Sema::MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, 1454 const CXXScopeSpec &SS, 1455 TemplateParameterList **ParamLists, 1456 unsigned NumParamLists, 1457 bool IsFriend, 1458 bool &IsExplicitSpecialization, 1459 bool &Invalid) { 1460 IsExplicitSpecialization = false; 1461 1462 // Find the template-ids that occur within the nested-name-specifier. These 1463 // template-ids will match up with the template parameter lists. 1464 llvm::SmallVector<const TemplateSpecializationType *, 4> 1465 TemplateIdsInSpecifier; 1466 llvm::SmallVector<ClassTemplateSpecializationDecl *, 4> 1467 ExplicitSpecializationsInSpecifier; 1468 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 1469 NNS; NNS = NNS->getPrefix()) { 1470 const Type *T = NNS->getAsType(); 1471 if (!T) break; 1472 1473 // C++0x [temp.expl.spec]p17: 1474 // A member or a member template may be nested within many 1475 // enclosing class templates. In an explicit specialization for 1476 // such a member, the member declaration shall be preceded by a 1477 // template<> for each enclosing class template that is 1478 // explicitly specialized. 1479 // 1480 // Following the existing practice of GNU and EDG, we allow a typedef of a 1481 // template specialization type. 1482 while (const TypedefType *TT = dyn_cast<TypedefType>(T)) 1483 T = TT->getDecl()->getUnderlyingType().getTypePtr(); 1484 1485 if (const TemplateSpecializationType *SpecType 1486 = dyn_cast<TemplateSpecializationType>(T)) { 1487 TemplateDecl *Template = SpecType->getTemplateName().getAsTemplateDecl(); 1488 if (!Template) 1489 continue; // FIXME: should this be an error? probably... 1490 1491 if (const RecordType *Record = SpecType->getAs<RecordType>()) { 1492 ClassTemplateSpecializationDecl *SpecDecl 1493 = cast<ClassTemplateSpecializationDecl>(Record->getDecl()); 1494 // If the nested name specifier refers to an explicit specialization, 1495 // we don't need a template<> header. 1496 if (SpecDecl->getSpecializationKind() == TSK_ExplicitSpecialization) { 1497 ExplicitSpecializationsInSpecifier.push_back(SpecDecl); 1498 continue; 1499 } 1500 } 1501 1502 TemplateIdsInSpecifier.push_back(SpecType); 1503 } 1504 } 1505 1506 // Reverse the list of template-ids in the scope specifier, so that we can 1507 // more easily match up the template-ids and the template parameter lists. 1508 std::reverse(TemplateIdsInSpecifier.begin(), TemplateIdsInSpecifier.end()); 1509 1510 SourceLocation FirstTemplateLoc = DeclStartLoc; 1511 if (NumParamLists) 1512 FirstTemplateLoc = ParamLists[0]->getTemplateLoc(); 1513 1514 // Match the template-ids found in the specifier to the template parameter 1515 // lists. 1516 unsigned ParamIdx = 0, TemplateIdx = 0; 1517 for (unsigned NumTemplateIds = TemplateIdsInSpecifier.size(); 1518 TemplateIdx != NumTemplateIds; ++TemplateIdx) { 1519 const TemplateSpecializationType *TemplateId 1520 = TemplateIdsInSpecifier[TemplateIdx]; 1521 bool DependentTemplateId = TemplateId->isDependentType(); 1522 1523 // In friend declarations we can have template-ids which don't 1524 // depend on the corresponding template parameter lists. But 1525 // assume that empty parameter lists are supposed to match this 1526 // template-id. 1527 if (IsFriend && ParamIdx < NumParamLists && ParamLists[ParamIdx]->size()) { 1528 if (!DependentTemplateId || 1529 !DependsOnTemplateParameters(TemplateId, ParamLists[ParamIdx])) 1530 continue; 1531 } 1532 1533 if (ParamIdx >= NumParamLists) { 1534 // We have a template-id without a corresponding template parameter 1535 // list. 1536 1537 // ...which is fine if this is a friend declaration. 1538 if (IsFriend) { 1539 IsExplicitSpecialization = true; 1540 break; 1541 } 1542 1543 if (DependentTemplateId) { 1544 // FIXME: the location information here isn't great. 1545 Diag(SS.getRange().getBegin(), 1546 diag::err_template_spec_needs_template_parameters) 1547 << QualType(TemplateId, 0) 1548 << SS.getRange(); 1549 Invalid = true; 1550 } else { 1551 Diag(SS.getRange().getBegin(), diag::err_template_spec_needs_header) 1552 << SS.getRange() 1553 << FixItHint::CreateInsertion(FirstTemplateLoc, "template<> "); 1554 IsExplicitSpecialization = true; 1555 } 1556 return 0; 1557 } 1558 1559 // Check the template parameter list against its corresponding template-id. 1560 if (DependentTemplateId) { 1561 TemplateParameterList *ExpectedTemplateParams = 0; 1562 1563 // Are there cases in (e.g.) friends where this won't match? 1564 if (const InjectedClassNameType *Injected 1565 = TemplateId->getAs<InjectedClassNameType>()) { 1566 CXXRecordDecl *Record = Injected->getDecl(); 1567 if (ClassTemplatePartialSpecializationDecl *Partial = 1568 dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) 1569 ExpectedTemplateParams = Partial->getTemplateParameters(); 1570 else 1571 ExpectedTemplateParams = Record->getDescribedClassTemplate() 1572 ->getTemplateParameters(); 1573 } 1574 1575 if (ExpectedTemplateParams) 1576 TemplateParameterListsAreEqual(ParamLists[ParamIdx], 1577 ExpectedTemplateParams, 1578 true, TPL_TemplateMatch); 1579 1580 CheckTemplateParameterList(ParamLists[ParamIdx], 0, 1581 TPC_ClassTemplateMember); 1582 } else if (ParamLists[ParamIdx]->size() > 0) 1583 Diag(ParamLists[ParamIdx]->getTemplateLoc(), 1584 diag::err_template_param_list_matches_nontemplate) 1585 << TemplateId 1586 << ParamLists[ParamIdx]->getSourceRange(); 1587 else 1588 IsExplicitSpecialization = true; 1589 1590 ++ParamIdx; 1591 } 1592 1593 // If there were at least as many template-ids as there were template 1594 // parameter lists, then there are no template parameter lists remaining for 1595 // the declaration itself. 1596 if (ParamIdx >= NumParamLists) 1597 return 0; 1598 1599 // If there were too many template parameter lists, complain about that now. 1600 if (ParamIdx != NumParamLists - 1) { 1601 while (ParamIdx < NumParamLists - 1) { 1602 bool isExplicitSpecHeader = ParamLists[ParamIdx]->size() == 0; 1603 Diag(ParamLists[ParamIdx]->getTemplateLoc(), 1604 isExplicitSpecHeader? diag::warn_template_spec_extra_headers 1605 : diag::err_template_spec_extra_headers) 1606 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(), 1607 ParamLists[ParamIdx]->getRAngleLoc()); 1608 1609 if (isExplicitSpecHeader && !ExplicitSpecializationsInSpecifier.empty()) { 1610 Diag(ExplicitSpecializationsInSpecifier.back()->getLocation(), 1611 diag::note_explicit_template_spec_does_not_need_header) 1612 << ExplicitSpecializationsInSpecifier.back(); 1613 ExplicitSpecializationsInSpecifier.pop_back(); 1614 } 1615 1616 // We have a template parameter list with no corresponding scope, which 1617 // means that the resulting template declaration can't be instantiated 1618 // properly (we'll end up with dependent nodes when we shouldn't). 1619 if (!isExplicitSpecHeader) 1620 Invalid = true; 1621 1622 ++ParamIdx; 1623 } 1624 } 1625 1626 // Return the last template parameter list, which corresponds to the 1627 // entity being declared. 1628 return ParamLists[NumParamLists - 1]; 1629} 1630 1631QualType Sema::CheckTemplateIdType(TemplateName Name, 1632 SourceLocation TemplateLoc, 1633 const TemplateArgumentListInfo &TemplateArgs) { 1634 TemplateDecl *Template = Name.getAsTemplateDecl(); 1635 if (!Template) { 1636 // The template name does not resolve to a template, so we just 1637 // build a dependent template-id type. 1638 return Context.getTemplateSpecializationType(Name, TemplateArgs); 1639 } 1640 1641 // Check that the template argument list is well-formed for this 1642 // template. 1643 llvm::SmallVector<TemplateArgument, 4> Converted; 1644 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, 1645 false, Converted)) 1646 return QualType(); 1647 1648 assert((Converted.size() == Template->getTemplateParameters()->size()) && 1649 "Converted template argument list is too short!"); 1650 1651 QualType CanonType; 1652 1653 if (Name.isDependent() || 1654 TemplateSpecializationType::anyDependentTemplateArguments( 1655 TemplateArgs)) { 1656 // This class template specialization is a dependent 1657 // type. Therefore, its canonical type is another class template 1658 // specialization type that contains all of the converted 1659 // arguments in canonical form. This ensures that, e.g., A<T> and 1660 // A<T, T> have identical types when A is declared as: 1661 // 1662 // template<typename T, typename U = T> struct A; 1663 TemplateName CanonName = Context.getCanonicalTemplateName(Name); 1664 CanonType = Context.getTemplateSpecializationType(CanonName, 1665 Converted.data(), 1666 Converted.size()); 1667 1668 // FIXME: CanonType is not actually the canonical type, and unfortunately 1669 // it is a TemplateSpecializationType that we will never use again. 1670 // In the future, we need to teach getTemplateSpecializationType to only 1671 // build the canonical type and return that to us. 1672 CanonType = Context.getCanonicalType(CanonType); 1673 1674 // This might work out to be a current instantiation, in which 1675 // case the canonical type needs to be the InjectedClassNameType. 1676 // 1677 // TODO: in theory this could be a simple hashtable lookup; most 1678 // changes to CurContext don't change the set of current 1679 // instantiations. 1680 if (isa<ClassTemplateDecl>(Template)) { 1681 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) { 1682 // If we get out to a namespace, we're done. 1683 if (Ctx->isFileContext()) break; 1684 1685 // If this isn't a record, keep looking. 1686 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx); 1687 if (!Record) continue; 1688 1689 // Look for one of the two cases with InjectedClassNameTypes 1690 // and check whether it's the same template. 1691 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) && 1692 !Record->getDescribedClassTemplate()) 1693 continue; 1694 1695 // Fetch the injected class name type and check whether its 1696 // injected type is equal to the type we just built. 1697 QualType ICNT = Context.getTypeDeclType(Record); 1698 QualType Injected = cast<InjectedClassNameType>(ICNT) 1699 ->getInjectedSpecializationType(); 1700 1701 if (CanonType != Injected->getCanonicalTypeInternal()) 1702 continue; 1703 1704 // If so, the canonical type of this TST is the injected 1705 // class name type of the record we just found. 1706 assert(ICNT.isCanonical()); 1707 CanonType = ICNT; 1708 break; 1709 } 1710 } 1711 } else if (ClassTemplateDecl *ClassTemplate 1712 = dyn_cast<ClassTemplateDecl>(Template)) { 1713 // Find the class template specialization declaration that 1714 // corresponds to these arguments. 1715 void *InsertPos = 0; 1716 ClassTemplateSpecializationDecl *Decl 1717 = ClassTemplate->findSpecialization(Converted.data(), Converted.size(), 1718 InsertPos); 1719 if (!Decl) { 1720 // This is the first time we have referenced this class template 1721 // specialization. Create the canonical declaration and add it to 1722 // the set of specializations. 1723 Decl = ClassTemplateSpecializationDecl::Create(Context, 1724 ClassTemplate->getTemplatedDecl()->getTagKind(), 1725 ClassTemplate->getDeclContext(), 1726 ClassTemplate->getLocation(), 1727 ClassTemplate, 1728 Converted.data(), 1729 Converted.size(), 0); 1730 ClassTemplate->AddSpecialization(Decl, InsertPos); 1731 Decl->setLexicalDeclContext(CurContext); 1732 } 1733 1734 CanonType = Context.getTypeDeclType(Decl); 1735 assert(isa<RecordType>(CanonType) && 1736 "type of non-dependent specialization is not a RecordType"); 1737 } 1738 1739 // Build the fully-sugared type for this class template 1740 // specialization, which refers back to the class template 1741 // specialization we created or found. 1742 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType); 1743} 1744 1745TypeResult 1746Sema::ActOnTemplateIdType(TemplateTy TemplateD, SourceLocation TemplateLoc, 1747 SourceLocation LAngleLoc, 1748 ASTTemplateArgsPtr TemplateArgsIn, 1749 SourceLocation RAngleLoc) { 1750 TemplateName Template = TemplateD.getAsVal<TemplateName>(); 1751 1752 // Translate the parser's template argument list in our AST format. 1753 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 1754 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 1755 1756 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 1757 QualType T = Context.getDependentTemplateSpecializationType(ETK_None, 1758 DTN->getQualifier(), 1759 DTN->getIdentifier(), 1760 TemplateArgs); 1761 1762 // Build type-source information. 1763 TypeLocBuilder TLB; 1764 DependentTemplateSpecializationTypeLoc SpecTL 1765 = TLB.push<DependentTemplateSpecializationTypeLoc>(T); 1766 SpecTL.setKeywordLoc(SourceLocation()); // FIXME: 'template' location 1767 SpecTL.setNameLoc(TemplateLoc); 1768 SpecTL.setLAngleLoc(LAngleLoc); 1769 SpecTL.setRAngleLoc(RAngleLoc); 1770 SpecTL.setQualifierRange(TemplateLoc); // FIXME: nested-name-specifier loc 1771 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) 1772 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 1773 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); 1774 } 1775 1776 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); 1777 TemplateArgsIn.release(); 1778 1779 if (Result.isNull()) 1780 return true; 1781 1782 TypeSourceInfo *DI = Context.CreateTypeSourceInfo(Result); 1783 TemplateSpecializationTypeLoc TL 1784 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc()); 1785 TL.setTemplateNameLoc(TemplateLoc); 1786 TL.setLAngleLoc(LAngleLoc); 1787 TL.setRAngleLoc(RAngleLoc); 1788 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 1789 TL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); 1790 1791 return CreateParsedType(Result, DI); 1792} 1793 1794TypeResult Sema::ActOnTagTemplateIdType(CXXScopeSpec &SS, 1795 TypeResult TypeResult, 1796 TagUseKind TUK, 1797 TypeSpecifierType TagSpec, 1798 SourceLocation TagLoc) { 1799 if (TypeResult.isInvalid()) 1800 return ::TypeResult(); 1801 1802 TypeSourceInfo *DI; 1803 QualType Type = GetTypeFromParser(TypeResult.get(), &DI); 1804 1805 // Verify the tag specifier. 1806 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 1807 1808 if (const RecordType *RT = Type->getAs<RecordType>()) { 1809 RecordDecl *D = RT->getDecl(); 1810 1811 IdentifierInfo *Id = D->getIdentifier(); 1812 assert(Id && "templated class must have an identifier"); 1813 1814 if (!isAcceptableTagRedeclaration(D, TagKind, TagLoc, *Id)) { 1815 Diag(TagLoc, diag::err_use_with_wrong_tag) 1816 << Type 1817 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName()); 1818 Diag(D->getLocation(), diag::note_previous_use); 1819 } 1820 } 1821 1822 ElaboratedTypeKeyword Keyword 1823 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind); 1824 QualType ElabType = Context.getElaboratedType(Keyword, /*NNS=*/0, Type); 1825 1826 TypeSourceInfo *ElabDI = Context.CreateTypeSourceInfo(ElabType); 1827 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(ElabDI->getTypeLoc()); 1828 TL.setKeywordLoc(TagLoc); 1829 TL.setQualifierRange(SS.getRange()); 1830 TL.getNamedTypeLoc().initializeFullCopy(DI->getTypeLoc()); 1831 return CreateParsedType(ElabType, ElabDI); 1832} 1833 1834ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS, 1835 LookupResult &R, 1836 bool RequiresADL, 1837 const TemplateArgumentListInfo &TemplateArgs) { 1838 // FIXME: Can we do any checking at this point? I guess we could check the 1839 // template arguments that we have against the template name, if the template 1840 // name refers to a single template. That's not a terribly common case, 1841 // though. 1842 // foo<int> could identify a single function unambiguously 1843 // This approach does NOT work, since f<int>(1); 1844 // gets resolved prior to resorting to overload resolution 1845 // i.e., template<class T> void f(double); 1846 // vs template<class T, class U> void f(U); 1847 1848 // These should be filtered out by our callers. 1849 assert(!R.empty() && "empty lookup results when building templateid"); 1850 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid"); 1851 1852 // We don't want lookup warnings at this point. 1853 R.suppressDiagnostics(); 1854 1855 UnresolvedLookupExpr *ULE 1856 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(), 1857 SS.getWithLocInContext(Context), 1858 R.getLookupNameInfo(), 1859 RequiresADL, TemplateArgs, 1860 R.begin(), R.end()); 1861 1862 return Owned(ULE); 1863} 1864 1865// We actually only call this from template instantiation. 1866ExprResult 1867Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 1868 const DeclarationNameInfo &NameInfo, 1869 const TemplateArgumentListInfo &TemplateArgs) { 1870 DeclContext *DC; 1871 if (!(DC = computeDeclContext(SS, false)) || 1872 DC->isDependentContext() || 1873 RequireCompleteDeclContext(SS, DC)) 1874 return BuildDependentDeclRefExpr(SS, NameInfo, &TemplateArgs); 1875 1876 bool MemberOfUnknownSpecialization; 1877 LookupResult R(*this, NameInfo, LookupOrdinaryName); 1878 LookupTemplateName(R, (Scope*) 0, SS, QualType(), /*Entering*/ false, 1879 MemberOfUnknownSpecialization); 1880 1881 if (R.isAmbiguous()) 1882 return ExprError(); 1883 1884 if (R.empty()) { 1885 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_non_template) 1886 << NameInfo.getName() << SS.getRange(); 1887 return ExprError(); 1888 } 1889 1890 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) { 1891 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template) 1892 << (NestedNameSpecifier*) SS.getScopeRep() 1893 << NameInfo.getName() << SS.getRange(); 1894 Diag(Temp->getLocation(), diag::note_referenced_class_template); 1895 return ExprError(); 1896 } 1897 1898 return BuildTemplateIdExpr(SS, R, /* ADL */ false, TemplateArgs); 1899} 1900 1901/// \brief Form a dependent template name. 1902/// 1903/// This action forms a dependent template name given the template 1904/// name and its (presumably dependent) scope specifier. For 1905/// example, given "MetaFun::template apply", the scope specifier \p 1906/// SS will be "MetaFun::", \p TemplateKWLoc contains the location 1907/// of the "template" keyword, and "apply" is the \p Name. 1908TemplateNameKind Sema::ActOnDependentTemplateName(Scope *S, 1909 SourceLocation TemplateKWLoc, 1910 CXXScopeSpec &SS, 1911 UnqualifiedId &Name, 1912 ParsedType ObjectType, 1913 bool EnteringContext, 1914 TemplateTy &Result) { 1915 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent() && 1916 !getLangOptions().CPlusPlus0x) 1917 Diag(TemplateKWLoc, diag::ext_template_outside_of_template) 1918 << FixItHint::CreateRemoval(TemplateKWLoc); 1919 1920 DeclContext *LookupCtx = 0; 1921 if (SS.isSet()) 1922 LookupCtx = computeDeclContext(SS, EnteringContext); 1923 if (!LookupCtx && ObjectType) 1924 LookupCtx = computeDeclContext(ObjectType.get()); 1925 if (LookupCtx) { 1926 // C++0x [temp.names]p5: 1927 // If a name prefixed by the keyword template is not the name of 1928 // a template, the program is ill-formed. [Note: the keyword 1929 // template may not be applied to non-template members of class 1930 // templates. -end note ] [ Note: as is the case with the 1931 // typename prefix, the template prefix is allowed in cases 1932 // where it is not strictly necessary; i.e., when the 1933 // nested-name-specifier or the expression on the left of the -> 1934 // or . is not dependent on a template-parameter, or the use 1935 // does not appear in the scope of a template. -end note] 1936 // 1937 // Note: C++03 was more strict here, because it banned the use of 1938 // the "template" keyword prior to a template-name that was not a 1939 // dependent name. C++ DR468 relaxed this requirement (the 1940 // "template" keyword is now permitted). We follow the C++0x 1941 // rules, even in C++03 mode with a warning, retroactively applying the DR. 1942 bool MemberOfUnknownSpecialization; 1943 TemplateNameKind TNK = isTemplateName(0, SS, TemplateKWLoc.isValid(), Name, 1944 ObjectType, EnteringContext, Result, 1945 MemberOfUnknownSpecialization); 1946 if (TNK == TNK_Non_template && LookupCtx->isDependentContext() && 1947 isa<CXXRecordDecl>(LookupCtx) && 1948 cast<CXXRecordDecl>(LookupCtx)->hasAnyDependentBases()) { 1949 // This is a dependent template. Handle it below. 1950 } else if (TNK == TNK_Non_template) { 1951 Diag(Name.getSourceRange().getBegin(), 1952 diag::err_template_kw_refers_to_non_template) 1953 << GetNameFromUnqualifiedId(Name).getName() 1954 << Name.getSourceRange() 1955 << TemplateKWLoc; 1956 return TNK_Non_template; 1957 } else { 1958 // We found something; return it. 1959 return TNK; 1960 } 1961 } 1962 1963 NestedNameSpecifier *Qualifier 1964 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 1965 1966 switch (Name.getKind()) { 1967 case UnqualifiedId::IK_Identifier: 1968 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier, 1969 Name.Identifier)); 1970 return TNK_Dependent_template_name; 1971 1972 case UnqualifiedId::IK_OperatorFunctionId: 1973 Result = TemplateTy::make(Context.getDependentTemplateName(Qualifier, 1974 Name.OperatorFunctionId.Operator)); 1975 return TNK_Dependent_template_name; 1976 1977 case UnqualifiedId::IK_LiteralOperatorId: 1978 assert(false && "We don't support these; Parse shouldn't have allowed propagation"); 1979 1980 default: 1981 break; 1982 } 1983 1984 Diag(Name.getSourceRange().getBegin(), 1985 diag::err_template_kw_refers_to_non_template) 1986 << GetNameFromUnqualifiedId(Name).getName() 1987 << Name.getSourceRange() 1988 << TemplateKWLoc; 1989 return TNK_Non_template; 1990} 1991 1992bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 1993 const TemplateArgumentLoc &AL, 1994 llvm::SmallVectorImpl<TemplateArgument> &Converted) { 1995 const TemplateArgument &Arg = AL.getArgument(); 1996 1997 // Check template type parameter. 1998 switch(Arg.getKind()) { 1999 case TemplateArgument::Type: 2000 // C++ [temp.arg.type]p1: 2001 // A template-argument for a template-parameter which is a 2002 // type shall be a type-id. 2003 break; 2004 case TemplateArgument::Template: { 2005 // We have a template type parameter but the template argument 2006 // is a template without any arguments. 2007 SourceRange SR = AL.getSourceRange(); 2008 TemplateName Name = Arg.getAsTemplate(); 2009 Diag(SR.getBegin(), diag::err_template_missing_args) 2010 << Name << SR; 2011 if (TemplateDecl *Decl = Name.getAsTemplateDecl()) 2012 Diag(Decl->getLocation(), diag::note_template_decl_here); 2013 2014 return true; 2015 } 2016 default: { 2017 // We have a template type parameter but the template argument 2018 // is not a type. 2019 SourceRange SR = AL.getSourceRange(); 2020 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR; 2021 Diag(Param->getLocation(), diag::note_template_param_here); 2022 2023 return true; 2024 } 2025 } 2026 2027 if (CheckTemplateArgument(Param, AL.getTypeSourceInfo())) 2028 return true; 2029 2030 // Add the converted template type argument. 2031 Converted.push_back( 2032 TemplateArgument(Context.getCanonicalType(Arg.getAsType()))); 2033 return false; 2034} 2035 2036/// \brief Substitute template arguments into the default template argument for 2037/// the given template type parameter. 2038/// 2039/// \param SemaRef the semantic analysis object for which we are performing 2040/// the substitution. 2041/// 2042/// \param Template the template that we are synthesizing template arguments 2043/// for. 2044/// 2045/// \param TemplateLoc the location of the template name that started the 2046/// template-id we are checking. 2047/// 2048/// \param RAngleLoc the location of the right angle bracket ('>') that 2049/// terminates the template-id. 2050/// 2051/// \param Param the template template parameter whose default we are 2052/// substituting into. 2053/// 2054/// \param Converted the list of template arguments provided for template 2055/// parameters that precede \p Param in the template parameter list. 2056/// 2057/// \returns the substituted template argument, or NULL if an error occurred. 2058static TypeSourceInfo * 2059SubstDefaultTemplateArgument(Sema &SemaRef, 2060 TemplateDecl *Template, 2061 SourceLocation TemplateLoc, 2062 SourceLocation RAngleLoc, 2063 TemplateTypeParmDecl *Param, 2064 llvm::SmallVectorImpl<TemplateArgument> &Converted) { 2065 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo(); 2066 2067 // If the argument type is dependent, instantiate it now based 2068 // on the previously-computed template arguments. 2069 if (ArgType->getType()->isDependentType()) { 2070 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2071 Converted.data(), Converted.size()); 2072 2073 MultiLevelTemplateArgumentList AllTemplateArgs 2074 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 2075 2076 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 2077 Template, Converted.data(), 2078 Converted.size(), 2079 SourceRange(TemplateLoc, RAngleLoc)); 2080 2081 ArgType = SemaRef.SubstType(ArgType, AllTemplateArgs, 2082 Param->getDefaultArgumentLoc(), 2083 Param->getDeclName()); 2084 } 2085 2086 return ArgType; 2087} 2088 2089/// \brief Substitute template arguments into the default template argument for 2090/// the given non-type template parameter. 2091/// 2092/// \param SemaRef the semantic analysis object for which we are performing 2093/// the substitution. 2094/// 2095/// \param Template the template that we are synthesizing template arguments 2096/// for. 2097/// 2098/// \param TemplateLoc the location of the template name that started the 2099/// template-id we are checking. 2100/// 2101/// \param RAngleLoc the location of the right angle bracket ('>') that 2102/// terminates the template-id. 2103/// 2104/// \param Param the non-type template parameter whose default we are 2105/// substituting into. 2106/// 2107/// \param Converted the list of template arguments provided for template 2108/// parameters that precede \p Param in the template parameter list. 2109/// 2110/// \returns the substituted template argument, or NULL if an error occurred. 2111static ExprResult 2112SubstDefaultTemplateArgument(Sema &SemaRef, 2113 TemplateDecl *Template, 2114 SourceLocation TemplateLoc, 2115 SourceLocation RAngleLoc, 2116 NonTypeTemplateParmDecl *Param, 2117 llvm::SmallVectorImpl<TemplateArgument> &Converted) { 2118 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2119 Converted.data(), Converted.size()); 2120 2121 MultiLevelTemplateArgumentList AllTemplateArgs 2122 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 2123 2124 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 2125 Template, Converted.data(), 2126 Converted.size(), 2127 SourceRange(TemplateLoc, RAngleLoc)); 2128 2129 return SemaRef.SubstExpr(Param->getDefaultArgument(), AllTemplateArgs); 2130} 2131 2132/// \brief Substitute template arguments into the default template argument for 2133/// the given template template parameter. 2134/// 2135/// \param SemaRef the semantic analysis object for which we are performing 2136/// the substitution. 2137/// 2138/// \param Template the template that we are synthesizing template arguments 2139/// for. 2140/// 2141/// \param TemplateLoc the location of the template name that started the 2142/// template-id we are checking. 2143/// 2144/// \param RAngleLoc the location of the right angle bracket ('>') that 2145/// terminates the template-id. 2146/// 2147/// \param Param the template template parameter whose default we are 2148/// substituting into. 2149/// 2150/// \param Converted the list of template arguments provided for template 2151/// parameters that precede \p Param in the template parameter list. 2152/// 2153/// \returns the substituted template argument, or NULL if an error occurred. 2154static TemplateName 2155SubstDefaultTemplateArgument(Sema &SemaRef, 2156 TemplateDecl *Template, 2157 SourceLocation TemplateLoc, 2158 SourceLocation RAngleLoc, 2159 TemplateTemplateParmDecl *Param, 2160 llvm::SmallVectorImpl<TemplateArgument> &Converted) { 2161 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2162 Converted.data(), Converted.size()); 2163 2164 MultiLevelTemplateArgumentList AllTemplateArgs 2165 = SemaRef.getTemplateInstantiationArgs(Template, &TemplateArgs); 2166 2167 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, 2168 Template, Converted.data(), 2169 Converted.size(), 2170 SourceRange(TemplateLoc, RAngleLoc)); 2171 2172 return SemaRef.SubstTemplateName( 2173 Param->getDefaultArgument().getArgument().getAsTemplate(), 2174 Param->getDefaultArgument().getTemplateNameLoc(), 2175 AllTemplateArgs); 2176} 2177 2178/// \brief If the given template parameter has a default template 2179/// argument, substitute into that default template argument and 2180/// return the corresponding template argument. 2181TemplateArgumentLoc 2182Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 2183 SourceLocation TemplateLoc, 2184 SourceLocation RAngleLoc, 2185 Decl *Param, 2186 llvm::SmallVectorImpl<TemplateArgument> &Converted) { 2187 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) { 2188 if (!TypeParm->hasDefaultArgument()) 2189 return TemplateArgumentLoc(); 2190 2191 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template, 2192 TemplateLoc, 2193 RAngleLoc, 2194 TypeParm, 2195 Converted); 2196 if (DI) 2197 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI); 2198 2199 return TemplateArgumentLoc(); 2200 } 2201 2202 if (NonTypeTemplateParmDecl *NonTypeParm 2203 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 2204 if (!NonTypeParm->hasDefaultArgument()) 2205 return TemplateArgumentLoc(); 2206 2207 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template, 2208 TemplateLoc, 2209 RAngleLoc, 2210 NonTypeParm, 2211 Converted); 2212 if (Arg.isInvalid()) 2213 return TemplateArgumentLoc(); 2214 2215 Expr *ArgE = Arg.takeAs<Expr>(); 2216 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE); 2217 } 2218 2219 TemplateTemplateParmDecl *TempTempParm 2220 = cast<TemplateTemplateParmDecl>(Param); 2221 if (!TempTempParm->hasDefaultArgument()) 2222 return TemplateArgumentLoc(); 2223 2224 TemplateName TName = SubstDefaultTemplateArgument(*this, Template, 2225 TemplateLoc, 2226 RAngleLoc, 2227 TempTempParm, 2228 Converted); 2229 if (TName.isNull()) 2230 return TemplateArgumentLoc(); 2231 2232 return TemplateArgumentLoc(TemplateArgument(TName), 2233 TempTempParm->getDefaultArgument().getTemplateQualifierRange(), 2234 TempTempParm->getDefaultArgument().getTemplateNameLoc()); 2235} 2236 2237/// \brief Check that the given template argument corresponds to the given 2238/// template parameter. 2239/// 2240/// \param Param The template parameter against which the argument will be 2241/// checked. 2242/// 2243/// \param Arg The template argument. 2244/// 2245/// \param Template The template in which the template argument resides. 2246/// 2247/// \param TemplateLoc The location of the template name for the template 2248/// whose argument list we're matching. 2249/// 2250/// \param RAngleLoc The location of the right angle bracket ('>') that closes 2251/// the template argument list. 2252/// 2253/// \param ArgumentPackIndex The index into the argument pack where this 2254/// argument will be placed. Only valid if the parameter is a parameter pack. 2255/// 2256/// \param Converted The checked, converted argument will be added to the 2257/// end of this small vector. 2258/// 2259/// \param CTAK Describes how we arrived at this particular template argument: 2260/// explicitly written, deduced, etc. 2261/// 2262/// \returns true on error, false otherwise. 2263bool Sema::CheckTemplateArgument(NamedDecl *Param, 2264 const TemplateArgumentLoc &Arg, 2265 NamedDecl *Template, 2266 SourceLocation TemplateLoc, 2267 SourceLocation RAngleLoc, 2268 unsigned ArgumentPackIndex, 2269 llvm::SmallVectorImpl<TemplateArgument> &Converted, 2270 CheckTemplateArgumentKind CTAK) { 2271 // Check template type parameters. 2272 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 2273 return CheckTemplateTypeArgument(TTP, Arg, Converted); 2274 2275 // Check non-type template parameters. 2276 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) { 2277 // Do substitution on the type of the non-type template parameter 2278 // with the template arguments we've seen thus far. But if the 2279 // template has a dependent context then we cannot substitute yet. 2280 QualType NTTPType = NTTP->getType(); 2281 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack()) 2282 NTTPType = NTTP->getExpansionType(ArgumentPackIndex); 2283 2284 if (NTTPType->isDependentType() && 2285 !isa<TemplateTemplateParmDecl>(Template) && 2286 !Template->getDeclContext()->isDependentContext()) { 2287 // Do substitution on the type of the non-type template parameter. 2288 InstantiatingTemplate Inst(*this, TemplateLoc, Template, 2289 NTTP, Converted.data(), Converted.size(), 2290 SourceRange(TemplateLoc, RAngleLoc)); 2291 2292 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2293 Converted.data(), Converted.size()); 2294 NTTPType = SubstType(NTTPType, 2295 MultiLevelTemplateArgumentList(TemplateArgs), 2296 NTTP->getLocation(), 2297 NTTP->getDeclName()); 2298 // If that worked, check the non-type template parameter type 2299 // for validity. 2300 if (!NTTPType.isNull()) 2301 NTTPType = CheckNonTypeTemplateParameterType(NTTPType, 2302 NTTP->getLocation()); 2303 if (NTTPType.isNull()) 2304 return true; 2305 } 2306 2307 switch (Arg.getArgument().getKind()) { 2308 case TemplateArgument::Null: 2309 assert(false && "Should never see a NULL template argument here"); 2310 return true; 2311 2312 case TemplateArgument::Expression: { 2313 Expr *E = Arg.getArgument().getAsExpr(); 2314 TemplateArgument Result; 2315 if (CheckTemplateArgument(NTTP, NTTPType, E, Result, CTAK)) 2316 return true; 2317 2318 Converted.push_back(Result); 2319 break; 2320 } 2321 2322 case TemplateArgument::Declaration: 2323 case TemplateArgument::Integral: 2324 // We've already checked this template argument, so just copy 2325 // it to the list of converted arguments. 2326 Converted.push_back(Arg.getArgument()); 2327 break; 2328 2329 case TemplateArgument::Template: 2330 case TemplateArgument::TemplateExpansion: 2331 // We were given a template template argument. It may not be ill-formed; 2332 // see below. 2333 if (DependentTemplateName *DTN 2334 = Arg.getArgument().getAsTemplateOrTemplatePattern() 2335 .getAsDependentTemplateName()) { 2336 // We have a template argument such as \c T::template X, which we 2337 // parsed as a template template argument. However, since we now 2338 // know that we need a non-type template argument, convert this 2339 // template name into an expression. 2340 2341 DeclarationNameInfo NameInfo(DTN->getIdentifier(), 2342 Arg.getTemplateNameLoc()); 2343 2344 // FIXME: TemplateArgumentLoc should store a NestedNameSpecifierLoc 2345 // for the template name. 2346 CXXScopeSpec SS; 2347 SS.MakeTrivial(Context, DTN->getQualifier(), 2348 Arg.getTemplateQualifierRange()); 2349 Expr *E = DependentScopeDeclRefExpr::Create(Context, 2350 SS.getWithLocInContext(Context), 2351 NameInfo); 2352 2353 // If we parsed the template argument as a pack expansion, create a 2354 // pack expansion expression. 2355 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){ 2356 ExprResult Expansion = ActOnPackExpansion(E, 2357 Arg.getTemplateEllipsisLoc()); 2358 if (Expansion.isInvalid()) 2359 return true; 2360 2361 E = Expansion.get(); 2362 } 2363 2364 TemplateArgument Result; 2365 if (CheckTemplateArgument(NTTP, NTTPType, E, Result)) 2366 return true; 2367 2368 Converted.push_back(Result); 2369 break; 2370 } 2371 2372 // We have a template argument that actually does refer to a class 2373 // template, template alias, or template template parameter, and 2374 // therefore cannot be a non-type template argument. 2375 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr) 2376 << Arg.getSourceRange(); 2377 2378 Diag(Param->getLocation(), diag::note_template_param_here); 2379 return true; 2380 2381 case TemplateArgument::Type: { 2382 // We have a non-type template parameter but the template 2383 // argument is a type. 2384 2385 // C++ [temp.arg]p2: 2386 // In a template-argument, an ambiguity between a type-id and 2387 // an expression is resolved to a type-id, regardless of the 2388 // form of the corresponding template-parameter. 2389 // 2390 // We warn specifically about this case, since it can be rather 2391 // confusing for users. 2392 QualType T = Arg.getArgument().getAsType(); 2393 SourceRange SR = Arg.getSourceRange(); 2394 if (T->isFunctionType()) 2395 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T; 2396 else 2397 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR; 2398 Diag(Param->getLocation(), diag::note_template_param_here); 2399 return true; 2400 } 2401 2402 case TemplateArgument::Pack: 2403 llvm_unreachable("Caller must expand template argument packs"); 2404 break; 2405 } 2406 2407 return false; 2408 } 2409 2410 2411 // Check template template parameters. 2412 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param); 2413 2414 // Substitute into the template parameter list of the template 2415 // template parameter, since previously-supplied template arguments 2416 // may appear within the template template parameter. 2417 { 2418 // Set up a template instantiation context. 2419 LocalInstantiationScope Scope(*this); 2420 InstantiatingTemplate Inst(*this, TemplateLoc, Template, 2421 TempParm, Converted.data(), Converted.size(), 2422 SourceRange(TemplateLoc, RAngleLoc)); 2423 2424 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, 2425 Converted.data(), Converted.size()); 2426 TempParm = cast_or_null<TemplateTemplateParmDecl>( 2427 SubstDecl(TempParm, CurContext, 2428 MultiLevelTemplateArgumentList(TemplateArgs))); 2429 if (!TempParm) 2430 return true; 2431 } 2432 2433 switch (Arg.getArgument().getKind()) { 2434 case TemplateArgument::Null: 2435 assert(false && "Should never see a NULL template argument here"); 2436 return true; 2437 2438 case TemplateArgument::Template: 2439 case TemplateArgument::TemplateExpansion: 2440 if (CheckTemplateArgument(TempParm, Arg)) 2441 return true; 2442 2443 Converted.push_back(Arg.getArgument()); 2444 break; 2445 2446 case TemplateArgument::Expression: 2447 case TemplateArgument::Type: 2448 // We have a template template parameter but the template 2449 // argument does not refer to a template. 2450 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template); 2451 return true; 2452 2453 case TemplateArgument::Declaration: 2454 llvm_unreachable( 2455 "Declaration argument with template template parameter"); 2456 break; 2457 case TemplateArgument::Integral: 2458 llvm_unreachable( 2459 "Integral argument with template template parameter"); 2460 break; 2461 2462 case TemplateArgument::Pack: 2463 llvm_unreachable("Caller must expand template argument packs"); 2464 break; 2465 } 2466 2467 return false; 2468} 2469 2470/// \brief Check that the given template argument list is well-formed 2471/// for specializing the given template. 2472bool Sema::CheckTemplateArgumentList(TemplateDecl *Template, 2473 SourceLocation TemplateLoc, 2474 const TemplateArgumentListInfo &TemplateArgs, 2475 bool PartialTemplateArgs, 2476 llvm::SmallVectorImpl<TemplateArgument> &Converted) { 2477 TemplateParameterList *Params = Template->getTemplateParameters(); 2478 unsigned NumParams = Params->size(); 2479 unsigned NumArgs = TemplateArgs.size(); 2480 bool Invalid = false; 2481 2482 SourceLocation RAngleLoc = TemplateArgs.getRAngleLoc(); 2483 2484 bool HasParameterPack = 2485 NumParams > 0 && Params->getParam(NumParams - 1)->isTemplateParameterPack(); 2486 2487 if ((NumArgs > NumParams && !HasParameterPack) || 2488 (NumArgs < Params->getMinRequiredArguments() && 2489 !PartialTemplateArgs)) { 2490 // FIXME: point at either the first arg beyond what we can handle, 2491 // or the '>', depending on whether we have too many or too few 2492 // arguments. 2493 SourceRange Range; 2494 if (NumArgs > NumParams) 2495 Range = SourceRange(TemplateArgs[NumParams].getLocation(), RAngleLoc); 2496 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 2497 << (NumArgs > NumParams) 2498 << (isa<ClassTemplateDecl>(Template)? 0 : 2499 isa<FunctionTemplateDecl>(Template)? 1 : 2500 isa<TemplateTemplateParmDecl>(Template)? 2 : 3) 2501 << Template << Range; 2502 Diag(Template->getLocation(), diag::note_template_decl_here) 2503 << Params->getSourceRange(); 2504 Invalid = true; 2505 } 2506 2507 // C++ [temp.arg]p1: 2508 // [...] The type and form of each template-argument specified in 2509 // a template-id shall match the type and form specified for the 2510 // corresponding parameter declared by the template in its 2511 // template-parameter-list. 2512 llvm::SmallVector<TemplateArgument, 2> ArgumentPack; 2513 TemplateParameterList::iterator Param = Params->begin(), 2514 ParamEnd = Params->end(); 2515 unsigned ArgIdx = 0; 2516 LocalInstantiationScope InstScope(*this, true); 2517 while (Param != ParamEnd) { 2518 if (ArgIdx > NumArgs && PartialTemplateArgs) 2519 break; 2520 2521 if (ArgIdx < NumArgs) { 2522 // If we have an expanded parameter pack, make sure we don't have too 2523 // many arguments. 2524 if (NonTypeTemplateParmDecl *NTTP 2525 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 2526 if (NTTP->isExpandedParameterPack() && 2527 ArgumentPack.size() >= NTTP->getNumExpansionTypes()) { 2528 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 2529 << true 2530 << (isa<ClassTemplateDecl>(Template)? 0 : 2531 isa<FunctionTemplateDecl>(Template)? 1 : 2532 isa<TemplateTemplateParmDecl>(Template)? 2 : 3) 2533 << Template; 2534 Diag(Template->getLocation(), diag::note_template_decl_here) 2535 << Params->getSourceRange(); 2536 return true; 2537 } 2538 } 2539 2540 // Check the template argument we were given. 2541 if (CheckTemplateArgument(*Param, TemplateArgs[ArgIdx], Template, 2542 TemplateLoc, RAngleLoc, 2543 ArgumentPack.size(), Converted)) 2544 return true; 2545 2546 if ((*Param)->isTemplateParameterPack()) { 2547 // The template parameter was a template parameter pack, so take the 2548 // deduced argument and place it on the argument pack. Note that we 2549 // stay on the same template parameter so that we can deduce more 2550 // arguments. 2551 ArgumentPack.push_back(Converted.back()); 2552 Converted.pop_back(); 2553 } else { 2554 // Move to the next template parameter. 2555 ++Param; 2556 } 2557 ++ArgIdx; 2558 continue; 2559 } 2560 2561 // If we have a template parameter pack with no more corresponding 2562 // arguments, just break out now and we'll fill in the argument pack below. 2563 if ((*Param)->isTemplateParameterPack()) 2564 break; 2565 2566 // We have a default template argument that we will use. 2567 TemplateArgumentLoc Arg; 2568 2569 // Retrieve the default template argument from the template 2570 // parameter. For each kind of template parameter, we substitute the 2571 // template arguments provided thus far and any "outer" template arguments 2572 // (when the template parameter was part of a nested template) into 2573 // the default argument. 2574 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { 2575 if (!TTP->hasDefaultArgument()) { 2576 assert((Invalid || PartialTemplateArgs) && "Missing default argument"); 2577 break; 2578 } 2579 2580 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this, 2581 Template, 2582 TemplateLoc, 2583 RAngleLoc, 2584 TTP, 2585 Converted); 2586 if (!ArgType) 2587 return true; 2588 2589 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()), 2590 ArgType); 2591 } else if (NonTypeTemplateParmDecl *NTTP 2592 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 2593 if (!NTTP->hasDefaultArgument()) { 2594 assert((Invalid || PartialTemplateArgs) && "Missing default argument"); 2595 break; 2596 } 2597 2598 ExprResult E = SubstDefaultTemplateArgument(*this, Template, 2599 TemplateLoc, 2600 RAngleLoc, 2601 NTTP, 2602 Converted); 2603 if (E.isInvalid()) 2604 return true; 2605 2606 Expr *Ex = E.takeAs<Expr>(); 2607 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex); 2608 } else { 2609 TemplateTemplateParmDecl *TempParm 2610 = cast<TemplateTemplateParmDecl>(*Param); 2611 2612 if (!TempParm->hasDefaultArgument()) { 2613 assert((Invalid || PartialTemplateArgs) && "Missing default argument"); 2614 break; 2615 } 2616 2617 TemplateName Name = SubstDefaultTemplateArgument(*this, Template, 2618 TemplateLoc, 2619 RAngleLoc, 2620 TempParm, 2621 Converted); 2622 if (Name.isNull()) 2623 return true; 2624 2625 Arg = TemplateArgumentLoc(TemplateArgument(Name), 2626 TempParm->getDefaultArgument().getTemplateQualifierRange(), 2627 TempParm->getDefaultArgument().getTemplateNameLoc()); 2628 } 2629 2630 // Introduce an instantiation record that describes where we are using 2631 // the default template argument. 2632 InstantiatingTemplate Instantiating(*this, RAngleLoc, Template, *Param, 2633 Converted.data(), Converted.size(), 2634 SourceRange(TemplateLoc, RAngleLoc)); 2635 2636 // Check the default template argument. 2637 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, 2638 RAngleLoc, 0, Converted)) 2639 return true; 2640 2641 // Move to the next template parameter and argument. 2642 ++Param; 2643 ++ArgIdx; 2644 } 2645 2646 // Form argument packs for each of the parameter packs remaining. 2647 while (Param != ParamEnd) { 2648 // If we're checking a partial list of template arguments, don't fill 2649 // in arguments for non-template parameter packs. 2650 2651 if ((*Param)->isTemplateParameterPack()) { 2652 if (PartialTemplateArgs && ArgumentPack.empty()) { 2653 Converted.push_back(TemplateArgument()); 2654 } else if (ArgumentPack.empty()) 2655 Converted.push_back(TemplateArgument(0, 0)); 2656 else { 2657 Converted.push_back(TemplateArgument::CreatePackCopy(Context, 2658 ArgumentPack.data(), 2659 ArgumentPack.size())); 2660 ArgumentPack.clear(); 2661 } 2662 } 2663 2664 ++Param; 2665 } 2666 2667 return Invalid; 2668} 2669 2670namespace { 2671 class UnnamedLocalNoLinkageFinder 2672 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool> 2673 { 2674 Sema &S; 2675 SourceRange SR; 2676 2677 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited; 2678 2679 public: 2680 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { } 2681 2682 bool Visit(QualType T) { 2683 return inherited::Visit(T.getTypePtr()); 2684 } 2685 2686#define TYPE(Class, Parent) \ 2687 bool Visit##Class##Type(const Class##Type *); 2688#define ABSTRACT_TYPE(Class, Parent) \ 2689 bool Visit##Class##Type(const Class##Type *) { return false; } 2690#define NON_CANONICAL_TYPE(Class, Parent) \ 2691 bool Visit##Class##Type(const Class##Type *) { return false; } 2692#include "clang/AST/TypeNodes.def" 2693 2694 bool VisitTagDecl(const TagDecl *Tag); 2695 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS); 2696 }; 2697} 2698 2699bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) { 2700 return false; 2701} 2702 2703bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) { 2704 return Visit(T->getElementType()); 2705} 2706 2707bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) { 2708 return Visit(T->getPointeeType()); 2709} 2710 2711bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType( 2712 const BlockPointerType* T) { 2713 return Visit(T->getPointeeType()); 2714} 2715 2716bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType( 2717 const LValueReferenceType* T) { 2718 return Visit(T->getPointeeType()); 2719} 2720 2721bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType( 2722 const RValueReferenceType* T) { 2723 return Visit(T->getPointeeType()); 2724} 2725 2726bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType( 2727 const MemberPointerType* T) { 2728 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0)); 2729} 2730 2731bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType( 2732 const ConstantArrayType* T) { 2733 return Visit(T->getElementType()); 2734} 2735 2736bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType( 2737 const IncompleteArrayType* T) { 2738 return Visit(T->getElementType()); 2739} 2740 2741bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType( 2742 const VariableArrayType* T) { 2743 return Visit(T->getElementType()); 2744} 2745 2746bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType( 2747 const DependentSizedArrayType* T) { 2748 return Visit(T->getElementType()); 2749} 2750 2751bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType( 2752 const DependentSizedExtVectorType* T) { 2753 return Visit(T->getElementType()); 2754} 2755 2756bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) { 2757 return Visit(T->getElementType()); 2758} 2759 2760bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) { 2761 return Visit(T->getElementType()); 2762} 2763 2764bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType( 2765 const FunctionProtoType* T) { 2766 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(), 2767 AEnd = T->arg_type_end(); 2768 A != AEnd; ++A) { 2769 if (Visit(*A)) 2770 return true; 2771 } 2772 2773 return Visit(T->getResultType()); 2774} 2775 2776bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType( 2777 const FunctionNoProtoType* T) { 2778 return Visit(T->getResultType()); 2779} 2780 2781bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType( 2782 const UnresolvedUsingType*) { 2783 return false; 2784} 2785 2786bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) { 2787 return false; 2788} 2789 2790bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) { 2791 return Visit(T->getUnderlyingType()); 2792} 2793 2794bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) { 2795 return false; 2796} 2797 2798bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) { 2799 return Visit(T->getDeducedType()); 2800} 2801 2802bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) { 2803 return VisitTagDecl(T->getDecl()); 2804} 2805 2806bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) { 2807 return VisitTagDecl(T->getDecl()); 2808} 2809 2810bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType( 2811 const TemplateTypeParmType*) { 2812 return false; 2813} 2814 2815bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType( 2816 const SubstTemplateTypeParmPackType *) { 2817 return false; 2818} 2819 2820bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType( 2821 const TemplateSpecializationType*) { 2822 return false; 2823} 2824 2825bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType( 2826 const InjectedClassNameType* T) { 2827 return VisitTagDecl(T->getDecl()); 2828} 2829 2830bool UnnamedLocalNoLinkageFinder::VisitDependentNameType( 2831 const DependentNameType* T) { 2832 return VisitNestedNameSpecifier(T->getQualifier()); 2833} 2834 2835bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType( 2836 const DependentTemplateSpecializationType* T) { 2837 return VisitNestedNameSpecifier(T->getQualifier()); 2838} 2839 2840bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType( 2841 const PackExpansionType* T) { 2842 return Visit(T->getPattern()); 2843} 2844 2845bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) { 2846 return false; 2847} 2848 2849bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType( 2850 const ObjCInterfaceType *) { 2851 return false; 2852} 2853 2854bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType( 2855 const ObjCObjectPointerType *) { 2856 return false; 2857} 2858 2859bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) { 2860 if (Tag->getDeclContext()->isFunctionOrMethod()) { 2861 S.Diag(SR.getBegin(), diag::ext_template_arg_local_type) 2862 << S.Context.getTypeDeclType(Tag) << SR; 2863 return true; 2864 } 2865 2866 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) { 2867 S.Diag(SR.getBegin(), diag::ext_template_arg_unnamed_type) << SR; 2868 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here); 2869 return true; 2870 } 2871 2872 return false; 2873} 2874 2875bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier( 2876 NestedNameSpecifier *NNS) { 2877 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix())) 2878 return true; 2879 2880 switch (NNS->getKind()) { 2881 case NestedNameSpecifier::Identifier: 2882 case NestedNameSpecifier::Namespace: 2883 case NestedNameSpecifier::NamespaceAlias: 2884 case NestedNameSpecifier::Global: 2885 return false; 2886 2887 case NestedNameSpecifier::TypeSpec: 2888 case NestedNameSpecifier::TypeSpecWithTemplate: 2889 return Visit(QualType(NNS->getAsType(), 0)); 2890 } 2891 return false; 2892} 2893 2894 2895/// \brief Check a template argument against its corresponding 2896/// template type parameter. 2897/// 2898/// This routine implements the semantics of C++ [temp.arg.type]. It 2899/// returns true if an error occurred, and false otherwise. 2900bool Sema::CheckTemplateArgument(TemplateTypeParmDecl *Param, 2901 TypeSourceInfo *ArgInfo) { 2902 assert(ArgInfo && "invalid TypeSourceInfo"); 2903 QualType Arg = ArgInfo->getType(); 2904 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange(); 2905 2906 if (Arg->isVariablyModifiedType()) { 2907 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg; 2908 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) { 2909 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR; 2910 } 2911 2912 // C++03 [temp.arg.type]p2: 2913 // A local type, a type with no linkage, an unnamed type or a type 2914 // compounded from any of these types shall not be used as a 2915 // template-argument for a template type-parameter. 2916 // 2917 // C++0x allows these, and even in C++03 we allow them as an extension with 2918 // a warning. 2919 if (!LangOpts.CPlusPlus0x && Arg->hasUnnamedOrLocalType()) { 2920 UnnamedLocalNoLinkageFinder Finder(*this, SR); 2921 (void)Finder.Visit(Context.getCanonicalType(Arg)); 2922 } 2923 2924 return false; 2925} 2926 2927/// \brief Checks whether the given template argument is the address 2928/// of an object or function according to C++ [temp.arg.nontype]p1. 2929static bool 2930CheckTemplateArgumentAddressOfObjectOrFunction(Sema &S, 2931 NonTypeTemplateParmDecl *Param, 2932 QualType ParamType, 2933 Expr *ArgIn, 2934 TemplateArgument &Converted) { 2935 bool Invalid = false; 2936 Expr *Arg = ArgIn; 2937 QualType ArgType = Arg->getType(); 2938 2939 // See through any implicit casts we added to fix the type. 2940 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) 2941 Arg = Cast->getSubExpr(); 2942 2943 // C++ [temp.arg.nontype]p1: 2944 // 2945 // A template-argument for a non-type, non-template 2946 // template-parameter shall be one of: [...] 2947 // 2948 // -- the address of an object or function with external 2949 // linkage, including function templates and function 2950 // template-ids but excluding non-static class members, 2951 // expressed as & id-expression where the & is optional if 2952 // the name refers to a function or array, or if the 2953 // corresponding template-parameter is a reference; or 2954 DeclRefExpr *DRE = 0; 2955 2956 // In C++98/03 mode, give an extension warning on any extra parentheses. 2957 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 2958 bool ExtraParens = false; 2959 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 2960 if (!Invalid && !ExtraParens && !S.getLangOptions().CPlusPlus0x) { 2961 S.Diag(Arg->getSourceRange().getBegin(), 2962 diag::ext_template_arg_extra_parens) 2963 << Arg->getSourceRange(); 2964 ExtraParens = true; 2965 } 2966 2967 Arg = Parens->getSubExpr(); 2968 } 2969 2970 bool AddressTaken = false; 2971 SourceLocation AddrOpLoc; 2972 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 2973 if (UnOp->getOpcode() == UO_AddrOf) { 2974 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 2975 AddressTaken = true; 2976 AddrOpLoc = UnOp->getOperatorLoc(); 2977 } 2978 } else 2979 DRE = dyn_cast<DeclRefExpr>(Arg); 2980 2981 if (!DRE) { 2982 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_decl_ref) 2983 << Arg->getSourceRange(); 2984 S.Diag(Param->getLocation(), diag::note_template_param_here); 2985 return true; 2986 } 2987 2988 // Stop checking the precise nature of the argument if it is value dependent, 2989 // it should be checked when instantiated. 2990 if (Arg->isValueDependent()) { 2991 Converted = TemplateArgument(ArgIn); 2992 return false; 2993 } 2994 2995 if (!isa<ValueDecl>(DRE->getDecl())) { 2996 S.Diag(Arg->getSourceRange().getBegin(), 2997 diag::err_template_arg_not_object_or_func_form) 2998 << Arg->getSourceRange(); 2999 S.Diag(Param->getLocation(), diag::note_template_param_here); 3000 return true; 3001 } 3002 3003 NamedDecl *Entity = 0; 3004 3005 // Cannot refer to non-static data members 3006 if (FieldDecl *Field = dyn_cast<FieldDecl>(DRE->getDecl())) { 3007 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_field) 3008 << Field << Arg->getSourceRange(); 3009 S.Diag(Param->getLocation(), diag::note_template_param_here); 3010 return true; 3011 } 3012 3013 // Cannot refer to non-static member functions 3014 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(DRE->getDecl())) 3015 if (!Method->isStatic()) { 3016 S.Diag(Arg->getSourceRange().getBegin(), diag::err_template_arg_method) 3017 << Method << Arg->getSourceRange(); 3018 S.Diag(Param->getLocation(), diag::note_template_param_here); 3019 return true; 3020 } 3021 3022 // Functions must have external linkage. 3023 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(DRE->getDecl())) { 3024 if (!isExternalLinkage(Func->getLinkage())) { 3025 S.Diag(Arg->getSourceRange().getBegin(), 3026 diag::err_template_arg_function_not_extern) 3027 << Func << Arg->getSourceRange(); 3028 S.Diag(Func->getLocation(), diag::note_template_arg_internal_object) 3029 << true; 3030 return true; 3031 } 3032 3033 // Okay: we've named a function with external linkage. 3034 Entity = Func; 3035 3036 // If the template parameter has pointer type, the function decays. 3037 if (ParamType->isPointerType() && !AddressTaken) 3038 ArgType = S.Context.getPointerType(Func->getType()); 3039 else if (AddressTaken && ParamType->isReferenceType()) { 3040 // If we originally had an address-of operator, but the 3041 // parameter has reference type, complain and (if things look 3042 // like they will work) drop the address-of operator. 3043 if (!S.Context.hasSameUnqualifiedType(Func->getType(), 3044 ParamType.getNonReferenceType())) { 3045 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 3046 << ParamType; 3047 S.Diag(Param->getLocation(), diag::note_template_param_here); 3048 return true; 3049 } 3050 3051 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 3052 << ParamType 3053 << FixItHint::CreateRemoval(AddrOpLoc); 3054 S.Diag(Param->getLocation(), diag::note_template_param_here); 3055 3056 ArgType = Func->getType(); 3057 } 3058 } else if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) { 3059 if (!isExternalLinkage(Var->getLinkage())) { 3060 S.Diag(Arg->getSourceRange().getBegin(), 3061 diag::err_template_arg_object_not_extern) 3062 << Var << Arg->getSourceRange(); 3063 S.Diag(Var->getLocation(), diag::note_template_arg_internal_object) 3064 << true; 3065 return true; 3066 } 3067 3068 // A value of reference type is not an object. 3069 if (Var->getType()->isReferenceType()) { 3070 S.Diag(Arg->getSourceRange().getBegin(), 3071 diag::err_template_arg_reference_var) 3072 << Var->getType() << Arg->getSourceRange(); 3073 S.Diag(Param->getLocation(), diag::note_template_param_here); 3074 return true; 3075 } 3076 3077 // Okay: we've named an object with external linkage 3078 Entity = Var; 3079 3080 // If the template parameter has pointer type, we must have taken 3081 // the address of this object. 3082 if (ParamType->isReferenceType()) { 3083 if (AddressTaken) { 3084 // If we originally had an address-of operator, but the 3085 // parameter has reference type, complain and (if things look 3086 // like they will work) drop the address-of operator. 3087 if (!S.Context.hasSameUnqualifiedType(Var->getType(), 3088 ParamType.getNonReferenceType())) { 3089 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 3090 << ParamType; 3091 S.Diag(Param->getLocation(), diag::note_template_param_here); 3092 return true; 3093 } 3094 3095 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 3096 << ParamType 3097 << FixItHint::CreateRemoval(AddrOpLoc); 3098 S.Diag(Param->getLocation(), diag::note_template_param_here); 3099 3100 ArgType = Var->getType(); 3101 } 3102 } else if (!AddressTaken && ParamType->isPointerType()) { 3103 if (Var->getType()->isArrayType()) { 3104 // Array-to-pointer decay. 3105 ArgType = S.Context.getArrayDecayedType(Var->getType()); 3106 } else { 3107 // If the template parameter has pointer type but the address of 3108 // this object was not taken, complain and (possibly) recover by 3109 // taking the address of the entity. 3110 ArgType = S.Context.getPointerType(Var->getType()); 3111 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) { 3112 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of) 3113 << ParamType; 3114 S.Diag(Param->getLocation(), diag::note_template_param_here); 3115 return true; 3116 } 3117 3118 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_address_of) 3119 << ParamType 3120 << FixItHint::CreateInsertion(Arg->getLocStart(), "&"); 3121 3122 S.Diag(Param->getLocation(), diag::note_template_param_here); 3123 } 3124 } 3125 } else { 3126 // We found something else, but we don't know specifically what it is. 3127 S.Diag(Arg->getSourceRange().getBegin(), 3128 diag::err_template_arg_not_object_or_func) 3129 << Arg->getSourceRange(); 3130 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here); 3131 return true; 3132 } 3133 3134 if (ParamType->isPointerType() && 3135 !ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType() && 3136 S.IsQualificationConversion(ArgType, ParamType, false)) { 3137 // For pointer-to-object types, qualification conversions are 3138 // permitted. 3139 } else { 3140 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) { 3141 if (!ParamRef->getPointeeType()->isFunctionType()) { 3142 // C++ [temp.arg.nontype]p5b3: 3143 // For a non-type template-parameter of type reference to 3144 // object, no conversions apply. The type referred to by the 3145 // reference may be more cv-qualified than the (otherwise 3146 // identical) type of the template- argument. The 3147 // template-parameter is bound directly to the 3148 // template-argument, which shall be an lvalue. 3149 3150 // FIXME: Other qualifiers? 3151 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers(); 3152 unsigned ArgQuals = ArgType.getCVRQualifiers(); 3153 3154 if ((ParamQuals | ArgQuals) != ParamQuals) { 3155 S.Diag(Arg->getSourceRange().getBegin(), 3156 diag::err_template_arg_ref_bind_ignores_quals) 3157 << ParamType << Arg->getType() 3158 << Arg->getSourceRange(); 3159 S.Diag(Param->getLocation(), diag::note_template_param_here); 3160 return true; 3161 } 3162 } 3163 } 3164 3165 // At this point, the template argument refers to an object or 3166 // function with external linkage. We now need to check whether the 3167 // argument and parameter types are compatible. 3168 if (!S.Context.hasSameUnqualifiedType(ArgType, 3169 ParamType.getNonReferenceType())) { 3170 // We can't perform this conversion or binding. 3171 if (ParamType->isReferenceType()) 3172 S.Diag(Arg->getLocStart(), diag::err_template_arg_no_ref_bind) 3173 << ParamType << Arg->getType() << Arg->getSourceRange(); 3174 else 3175 S.Diag(Arg->getLocStart(), diag::err_template_arg_not_convertible) 3176 << Arg->getType() << ParamType << Arg->getSourceRange(); 3177 S.Diag(Param->getLocation(), diag::note_template_param_here); 3178 return true; 3179 } 3180 } 3181 3182 // Create the template argument. 3183 Converted = TemplateArgument(Entity->getCanonicalDecl()); 3184 S.MarkDeclarationReferenced(Arg->getLocStart(), Entity); 3185 return false; 3186} 3187 3188/// \brief Checks whether the given template argument is a pointer to 3189/// member constant according to C++ [temp.arg.nontype]p1. 3190bool Sema::CheckTemplateArgumentPointerToMember(Expr *Arg, 3191 TemplateArgument &Converted) { 3192 bool Invalid = false; 3193 3194 // See through any implicit casts we added to fix the type. 3195 while (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Arg)) 3196 Arg = Cast->getSubExpr(); 3197 3198 // C++ [temp.arg.nontype]p1: 3199 // 3200 // A template-argument for a non-type, non-template 3201 // template-parameter shall be one of: [...] 3202 // 3203 // -- a pointer to member expressed as described in 5.3.1. 3204 DeclRefExpr *DRE = 0; 3205 3206 // In C++98/03 mode, give an extension warning on any extra parentheses. 3207 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 3208 bool ExtraParens = false; 3209 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 3210 if (!Invalid && !ExtraParens && !getLangOptions().CPlusPlus0x) { 3211 Diag(Arg->getSourceRange().getBegin(), 3212 diag::ext_template_arg_extra_parens) 3213 << Arg->getSourceRange(); 3214 ExtraParens = true; 3215 } 3216 3217 Arg = Parens->getSubExpr(); 3218 } 3219 3220 // A pointer-to-member constant written &Class::member. 3221 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 3222 if (UnOp->getOpcode() == UO_AddrOf) { 3223 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 3224 if (DRE && !DRE->getQualifier()) 3225 DRE = 0; 3226 } 3227 } 3228 // A constant of pointer-to-member type. 3229 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) { 3230 if (ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) { 3231 if (VD->getType()->isMemberPointerType()) { 3232 if (isa<NonTypeTemplateParmDecl>(VD) || 3233 (isa<VarDecl>(VD) && 3234 Context.getCanonicalType(VD->getType()).isConstQualified())) { 3235 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3236 Converted = TemplateArgument(Arg); 3237 else 3238 Converted = TemplateArgument(VD->getCanonicalDecl()); 3239 return Invalid; 3240 } 3241 } 3242 } 3243 3244 DRE = 0; 3245 } 3246 3247 if (!DRE) 3248 return Diag(Arg->getSourceRange().getBegin(), 3249 diag::err_template_arg_not_pointer_to_member_form) 3250 << Arg->getSourceRange(); 3251 3252 if (isa<FieldDecl>(DRE->getDecl()) || isa<CXXMethodDecl>(DRE->getDecl())) { 3253 assert((isa<FieldDecl>(DRE->getDecl()) || 3254 !cast<CXXMethodDecl>(DRE->getDecl())->isStatic()) && 3255 "Only non-static member pointers can make it here"); 3256 3257 // Okay: this is the address of a non-static member, and therefore 3258 // a member pointer constant. 3259 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3260 Converted = TemplateArgument(Arg); 3261 else 3262 Converted = TemplateArgument(DRE->getDecl()->getCanonicalDecl()); 3263 return Invalid; 3264 } 3265 3266 // We found something else, but we don't know specifically what it is. 3267 Diag(Arg->getSourceRange().getBegin(), 3268 diag::err_template_arg_not_pointer_to_member_form) 3269 << Arg->getSourceRange(); 3270 Diag(DRE->getDecl()->getLocation(), 3271 diag::note_template_arg_refers_here); 3272 return true; 3273} 3274 3275/// \brief Check a template argument against its corresponding 3276/// non-type template parameter. 3277/// 3278/// This routine implements the semantics of C++ [temp.arg.nontype]. 3279/// It returns true if an error occurred, and false otherwise. \p 3280/// InstantiatedParamType is the type of the non-type template 3281/// parameter after it has been instantiated. 3282/// 3283/// If no error was detected, Converted receives the converted template argument. 3284bool Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 3285 QualType InstantiatedParamType, Expr *&Arg, 3286 TemplateArgument &Converted, 3287 CheckTemplateArgumentKind CTAK) { 3288 SourceLocation StartLoc = Arg->getSourceRange().getBegin(); 3289 3290 // If either the parameter has a dependent type or the argument is 3291 // type-dependent, there's nothing we can check now. 3292 if (InstantiatedParamType->isDependentType() || Arg->isTypeDependent()) { 3293 // FIXME: Produce a cloned, canonical expression? 3294 Converted = TemplateArgument(Arg); 3295 return false; 3296 } 3297 3298 // C++ [temp.arg.nontype]p5: 3299 // The following conversions are performed on each expression used 3300 // as a non-type template-argument. If a non-type 3301 // template-argument cannot be converted to the type of the 3302 // corresponding template-parameter then the program is 3303 // ill-formed. 3304 // 3305 // -- for a non-type template-parameter of integral or 3306 // enumeration type, integral promotions (4.5) and integral 3307 // conversions (4.7) are applied. 3308 QualType ParamType = InstantiatedParamType; 3309 QualType ArgType = Arg->getType(); 3310 if (ParamType->isIntegralOrEnumerationType()) { 3311 // C++ [temp.arg.nontype]p1: 3312 // A template-argument for a non-type, non-template 3313 // template-parameter shall be one of: 3314 // 3315 // -- an integral constant-expression of integral or enumeration 3316 // type; or 3317 // -- the name of a non-type template-parameter; or 3318 SourceLocation NonConstantLoc; 3319 llvm::APSInt Value; 3320 if (!ArgType->isIntegralOrEnumerationType()) { 3321 Diag(Arg->getSourceRange().getBegin(), 3322 diag::err_template_arg_not_integral_or_enumeral) 3323 << ArgType << Arg->getSourceRange(); 3324 Diag(Param->getLocation(), diag::note_template_param_here); 3325 return true; 3326 } else if (!Arg->isValueDependent() && 3327 !Arg->isIntegerConstantExpr(Value, Context, &NonConstantLoc)) { 3328 Diag(NonConstantLoc, diag::err_template_arg_not_ice) 3329 << ArgType << Arg->getSourceRange(); 3330 return true; 3331 } 3332 3333 // From here on out, all we care about are the unqualified forms 3334 // of the parameter and argument types. 3335 ParamType = ParamType.getUnqualifiedType(); 3336 ArgType = ArgType.getUnqualifiedType(); 3337 3338 // Try to convert the argument to the parameter's type. 3339 if (Context.hasSameType(ParamType, ArgType)) { 3340 // Okay: no conversion necessary 3341 } else if (CTAK == CTAK_Deduced) { 3342 // C++ [temp.deduct.type]p17: 3343 // If, in the declaration of a function template with a non-type 3344 // template-parameter, the non-type template- parameter is used 3345 // in an expression in the function parameter-list and, if the 3346 // corresponding template-argument is deduced, the 3347 // template-argument type shall match the type of the 3348 // template-parameter exactly, except that a template-argument 3349 // deduced from an array bound may be of any integral type. 3350 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch) 3351 << ArgType << ParamType; 3352 Diag(Param->getLocation(), diag::note_template_param_here); 3353 return true; 3354 } else if (ParamType->isBooleanType()) { 3355 // This is an integral-to-boolean conversion. 3356 ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean); 3357 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) || 3358 !ParamType->isEnumeralType()) { 3359 // This is an integral promotion or conversion. 3360 ImpCastExprToType(Arg, ParamType, CK_IntegralCast); 3361 } else { 3362 // We can't perform this conversion. 3363 Diag(Arg->getSourceRange().getBegin(), 3364 diag::err_template_arg_not_convertible) 3365 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 3366 Diag(Param->getLocation(), diag::note_template_param_here); 3367 return true; 3368 } 3369 3370 QualType IntegerType = Context.getCanonicalType(ParamType); 3371 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) 3372 IntegerType = Context.getCanonicalType(Enum->getDecl()->getIntegerType()); 3373 3374 if (!Arg->isValueDependent()) { 3375 llvm::APSInt OldValue = Value; 3376 3377 // Coerce the template argument's value to the value it will have 3378 // based on the template parameter's type. 3379 unsigned AllowedBits = Context.getTypeSize(IntegerType); 3380 if (Value.getBitWidth() != AllowedBits) 3381 Value = Value.extOrTrunc(AllowedBits); 3382 Value.setIsSigned(IntegerType->isSignedIntegerType()); 3383 3384 // Complain if an unsigned parameter received a negative value. 3385 if (IntegerType->isUnsignedIntegerType() 3386 && (OldValue.isSigned() && OldValue.isNegative())) { 3387 Diag(Arg->getSourceRange().getBegin(), diag::warn_template_arg_negative) 3388 << OldValue.toString(10) << Value.toString(10) << Param->getType() 3389 << Arg->getSourceRange(); 3390 Diag(Param->getLocation(), diag::note_template_param_here); 3391 } 3392 3393 // Complain if we overflowed the template parameter's type. 3394 unsigned RequiredBits; 3395 if (IntegerType->isUnsignedIntegerType()) 3396 RequiredBits = OldValue.getActiveBits(); 3397 else if (OldValue.isUnsigned()) 3398 RequiredBits = OldValue.getActiveBits() + 1; 3399 else 3400 RequiredBits = OldValue.getMinSignedBits(); 3401 if (RequiredBits > AllowedBits) { 3402 Diag(Arg->getSourceRange().getBegin(), 3403 diag::warn_template_arg_too_large) 3404 << OldValue.toString(10) << Value.toString(10) << Param->getType() 3405 << Arg->getSourceRange(); 3406 Diag(Param->getLocation(), diag::note_template_param_here); 3407 } 3408 } 3409 3410 // Add the value of this argument to the list of converted 3411 // arguments. We use the bitwidth and signedness of the template 3412 // parameter. 3413 if (Arg->isValueDependent()) { 3414 // The argument is value-dependent. Create a new 3415 // TemplateArgument with the converted expression. 3416 Converted = TemplateArgument(Arg); 3417 return false; 3418 } 3419 3420 Converted = TemplateArgument(Value, 3421 ParamType->isEnumeralType() ? ParamType 3422 : IntegerType); 3423 return false; 3424 } 3425 3426 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction 3427 3428 // C++0x [temp.arg.nontype]p5 bullets 2, 4 and 6 permit conversion 3429 // from a template argument of type std::nullptr_t to a non-type 3430 // template parameter of type pointer to object, pointer to 3431 // function, or pointer-to-member, respectively. 3432 if (ArgType->isNullPtrType() && 3433 (ParamType->isPointerType() || ParamType->isMemberPointerType())) { 3434 Converted = TemplateArgument((NamedDecl *)0); 3435 return false; 3436 } 3437 3438 // Handle pointer-to-function, reference-to-function, and 3439 // pointer-to-member-function all in (roughly) the same way. 3440 if (// -- For a non-type template-parameter of type pointer to 3441 // function, only the function-to-pointer conversion (4.3) is 3442 // applied. If the template-argument represents a set of 3443 // overloaded functions (or a pointer to such), the matching 3444 // function is selected from the set (13.4). 3445 (ParamType->isPointerType() && 3446 ParamType->getAs<PointerType>()->getPointeeType()->isFunctionType()) || 3447 // -- For a non-type template-parameter of type reference to 3448 // function, no conversions apply. If the template-argument 3449 // represents a set of overloaded functions, the matching 3450 // function is selected from the set (13.4). 3451 (ParamType->isReferenceType() && 3452 ParamType->getAs<ReferenceType>()->getPointeeType()->isFunctionType()) || 3453 // -- For a non-type template-parameter of type pointer to 3454 // member function, no conversions apply. If the 3455 // template-argument represents a set of overloaded member 3456 // functions, the matching member function is selected from 3457 // the set (13.4). 3458 (ParamType->isMemberPointerType() && 3459 ParamType->getAs<MemberPointerType>()->getPointeeType() 3460 ->isFunctionType())) { 3461 3462 if (Arg->getType() == Context.OverloadTy) { 3463 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType, 3464 true, 3465 FoundResult)) { 3466 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin())) 3467 return true; 3468 3469 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn); 3470 ArgType = Arg->getType(); 3471 } else 3472 return true; 3473 } 3474 3475 if (!ParamType->isMemberPointerType()) 3476 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, 3477 ParamType, 3478 Arg, Converted); 3479 3480 if (IsQualificationConversion(ArgType, ParamType.getNonReferenceType(), 3481 false)) { 3482 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg)); 3483 } else if (!Context.hasSameUnqualifiedType(ArgType, 3484 ParamType.getNonReferenceType())) { 3485 // We can't perform this conversion. 3486 Diag(Arg->getSourceRange().getBegin(), 3487 diag::err_template_arg_not_convertible) 3488 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 3489 Diag(Param->getLocation(), diag::note_template_param_here); 3490 return true; 3491 } 3492 3493 return CheckTemplateArgumentPointerToMember(Arg, Converted); 3494 } 3495 3496 if (ParamType->isPointerType()) { 3497 // -- for a non-type template-parameter of type pointer to 3498 // object, qualification conversions (4.4) and the 3499 // array-to-pointer conversion (4.2) are applied. 3500 // C++0x also allows a value of std::nullptr_t. 3501 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() && 3502 "Only object pointers allowed here"); 3503 3504 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, 3505 ParamType, 3506 Arg, Converted); 3507 } 3508 3509 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) { 3510 // -- For a non-type template-parameter of type reference to 3511 // object, no conversions apply. The type referred to by the 3512 // reference may be more cv-qualified than the (otherwise 3513 // identical) type of the template-argument. The 3514 // template-parameter is bound directly to the 3515 // template-argument, which must be an lvalue. 3516 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() && 3517 "Only object references allowed here"); 3518 3519 if (Arg->getType() == Context.OverloadTy) { 3520 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, 3521 ParamRefType->getPointeeType(), 3522 true, 3523 FoundResult)) { 3524 if (DiagnoseUseOfDecl(Fn, Arg->getSourceRange().getBegin())) 3525 return true; 3526 3527 Arg = FixOverloadedFunctionReference(Arg, FoundResult, Fn); 3528 ArgType = Arg->getType(); 3529 } else 3530 return true; 3531 } 3532 3533 return CheckTemplateArgumentAddressOfObjectOrFunction(*this, Param, 3534 ParamType, 3535 Arg, Converted); 3536 } 3537 3538 // -- For a non-type template-parameter of type pointer to data 3539 // member, qualification conversions (4.4) are applied. 3540 assert(ParamType->isMemberPointerType() && "Only pointers to members remain"); 3541 3542 if (Context.hasSameUnqualifiedType(ParamType, ArgType)) { 3543 // Types match exactly: nothing more to do here. 3544 } else if (IsQualificationConversion(ArgType, ParamType, false)) { 3545 ImpCastExprToType(Arg, ParamType, CK_NoOp, CastCategory(Arg)); 3546 } else { 3547 // We can't perform this conversion. 3548 Diag(Arg->getSourceRange().getBegin(), 3549 diag::err_template_arg_not_convertible) 3550 << Arg->getType() << InstantiatedParamType << Arg->getSourceRange(); 3551 Diag(Param->getLocation(), diag::note_template_param_here); 3552 return true; 3553 } 3554 3555 return CheckTemplateArgumentPointerToMember(Arg, Converted); 3556} 3557 3558/// \brief Check a template argument against its corresponding 3559/// template template parameter. 3560/// 3561/// This routine implements the semantics of C++ [temp.arg.template]. 3562/// It returns true if an error occurred, and false otherwise. 3563bool Sema::CheckTemplateArgument(TemplateTemplateParmDecl *Param, 3564 const TemplateArgumentLoc &Arg) { 3565 TemplateName Name = Arg.getArgument().getAsTemplate(); 3566 TemplateDecl *Template = Name.getAsTemplateDecl(); 3567 if (!Template) { 3568 // Any dependent template name is fine. 3569 assert(Name.isDependent() && "Non-dependent template isn't a declaration?"); 3570 return false; 3571 } 3572 3573 // C++ [temp.arg.template]p1: 3574 // A template-argument for a template template-parameter shall be 3575 // the name of a class template, expressed as id-expression. Only 3576 // primary class templates are considered when matching the 3577 // template template argument with the corresponding parameter; 3578 // partial specializations are not considered even if their 3579 // parameter lists match that of the template template parameter. 3580 // 3581 // Note that we also allow template template parameters here, which 3582 // will happen when we are dealing with, e.g., class template 3583 // partial specializations. 3584 if (!isa<ClassTemplateDecl>(Template) && 3585 !isa<TemplateTemplateParmDecl>(Template)) { 3586 assert(isa<FunctionTemplateDecl>(Template) && 3587 "Only function templates are possible here"); 3588 Diag(Arg.getLocation(), diag::err_template_arg_not_class_template); 3589 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func) 3590 << Template; 3591 } 3592 3593 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(), 3594 Param->getTemplateParameters(), 3595 true, 3596 TPL_TemplateTemplateArgumentMatch, 3597 Arg.getLocation()); 3598} 3599 3600/// \brief Given a non-type template argument that refers to a 3601/// declaration and the type of its corresponding non-type template 3602/// parameter, produce an expression that properly refers to that 3603/// declaration. 3604ExprResult 3605Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 3606 QualType ParamType, 3607 SourceLocation Loc) { 3608 assert(Arg.getKind() == TemplateArgument::Declaration && 3609 "Only declaration template arguments permitted here"); 3610 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl()); 3611 3612 if (VD->getDeclContext()->isRecord() && 3613 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD))) { 3614 // If the value is a class member, we might have a pointer-to-member. 3615 // Determine whether the non-type template template parameter is of 3616 // pointer-to-member type. If so, we need to build an appropriate 3617 // expression for a pointer-to-member, since a "normal" DeclRefExpr 3618 // would refer to the member itself. 3619 if (ParamType->isMemberPointerType()) { 3620 QualType ClassType 3621 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext())); 3622 NestedNameSpecifier *Qualifier 3623 = NestedNameSpecifier::Create(Context, 0, false, 3624 ClassType.getTypePtr()); 3625 CXXScopeSpec SS; 3626 SS.MakeTrivial(Context, Qualifier, Loc); 3627 3628 // The actual value-ness of this is unimportant, but for 3629 // internal consistency's sake, references to instance methods 3630 // are r-values. 3631 ExprValueKind VK = VK_LValue; 3632 if (isa<CXXMethodDecl>(VD) && cast<CXXMethodDecl>(VD)->isInstance()) 3633 VK = VK_RValue; 3634 3635 ExprResult RefExpr = BuildDeclRefExpr(VD, 3636 VD->getType().getNonReferenceType(), 3637 VK, 3638 Loc, 3639 &SS); 3640 if (RefExpr.isInvalid()) 3641 return ExprError(); 3642 3643 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get()); 3644 3645 // We might need to perform a trailing qualification conversion, since 3646 // the element type on the parameter could be more qualified than the 3647 // element type in the expression we constructed. 3648 if (IsQualificationConversion(((Expr*) RefExpr.get())->getType(), 3649 ParamType.getUnqualifiedType(), false)) { 3650 Expr *RefE = RefExpr.takeAs<Expr>(); 3651 ImpCastExprToType(RefE, ParamType.getUnqualifiedType(), CK_NoOp); 3652 RefExpr = Owned(RefE); 3653 } 3654 3655 assert(!RefExpr.isInvalid() && 3656 Context.hasSameType(((Expr*) RefExpr.get())->getType(), 3657 ParamType.getUnqualifiedType())); 3658 return move(RefExpr); 3659 } 3660 } 3661 3662 QualType T = VD->getType().getNonReferenceType(); 3663 if (ParamType->isPointerType()) { 3664 // When the non-type template parameter is a pointer, take the 3665 // address of the declaration. 3666 ExprResult RefExpr = BuildDeclRefExpr(VD, T, VK_LValue, Loc); 3667 if (RefExpr.isInvalid()) 3668 return ExprError(); 3669 3670 if (T->isFunctionType() || T->isArrayType()) { 3671 // Decay functions and arrays. 3672 Expr *RefE = (Expr *)RefExpr.get(); 3673 DefaultFunctionArrayConversion(RefE); 3674 if (RefE != RefExpr.get()) { 3675 RefExpr.release(); 3676 RefExpr = Owned(RefE); 3677 } 3678 3679 return move(RefExpr); 3680 } 3681 3682 // Take the address of everything else 3683 return CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get()); 3684 } 3685 3686 ExprValueKind VK = VK_RValue; 3687 3688 // If the non-type template parameter has reference type, qualify the 3689 // resulting declaration reference with the extra qualifiers on the 3690 // type that the reference refers to. 3691 if (const ReferenceType *TargetRef = ParamType->getAs<ReferenceType>()) { 3692 VK = VK_LValue; 3693 T = Context.getQualifiedType(T, 3694 TargetRef->getPointeeType().getQualifiers()); 3695 } 3696 3697 return BuildDeclRefExpr(VD, T, VK, Loc); 3698} 3699 3700/// \brief Construct a new expression that refers to the given 3701/// integral template argument with the given source-location 3702/// information. 3703/// 3704/// This routine takes care of the mapping from an integral template 3705/// argument (which may have any integral type) to the appropriate 3706/// literal value. 3707ExprResult 3708Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 3709 SourceLocation Loc) { 3710 assert(Arg.getKind() == TemplateArgument::Integral && 3711 "Operation is only valid for integral template arguments"); 3712 QualType T = Arg.getIntegralType(); 3713 if (T->isCharType() || T->isWideCharType()) 3714 return Owned(new (Context) CharacterLiteral( 3715 Arg.getAsIntegral()->getZExtValue(), 3716 T->isWideCharType(), 3717 T, 3718 Loc)); 3719 if (T->isBooleanType()) 3720 return Owned(new (Context) CXXBoolLiteralExpr( 3721 Arg.getAsIntegral()->getBoolValue(), 3722 T, 3723 Loc)); 3724 3725 QualType BT; 3726 if (const EnumType *ET = T->getAs<EnumType>()) 3727 BT = ET->getDecl()->getPromotionType(); 3728 else 3729 BT = T; 3730 3731 Expr *E = IntegerLiteral::Create(Context, *Arg.getAsIntegral(), BT, Loc); 3732 if (T->isEnumeralType()) { 3733 // FIXME: This is a hack. We need a better way to handle substituted 3734 // non-type template parameters. 3735 E = CStyleCastExpr::Create(Context, T, VK_RValue, CK_IntegralCast, 3736 E, 0, 3737 Context.getTrivialTypeSourceInfo(T, Loc), 3738 Loc, Loc); 3739 } 3740 3741 return Owned(E); 3742} 3743 3744/// \brief Match two template parameters within template parameter lists. 3745static bool MatchTemplateParameterKind(Sema &S, NamedDecl *New, NamedDecl *Old, 3746 bool Complain, 3747 Sema::TemplateParameterListEqualKind Kind, 3748 SourceLocation TemplateArgLoc) { 3749 // Check the actual kind (type, non-type, template). 3750 if (Old->getKind() != New->getKind()) { 3751 if (Complain) { 3752 unsigned NextDiag = diag::err_template_param_different_kind; 3753 if (TemplateArgLoc.isValid()) { 3754 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 3755 NextDiag = diag::note_template_param_different_kind; 3756 } 3757 S.Diag(New->getLocation(), NextDiag) 3758 << (Kind != Sema::TPL_TemplateMatch); 3759 S.Diag(Old->getLocation(), diag::note_template_prev_declaration) 3760 << (Kind != Sema::TPL_TemplateMatch); 3761 } 3762 3763 return false; 3764 } 3765 3766 // Check that both are parameter packs are neither are parameter packs. 3767 // However, if we are matching a template template argument to a 3768 // template template parameter, the template template parameter can have 3769 // a parameter pack where the template template argument does not. 3770 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() && 3771 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch && 3772 Old->isTemplateParameterPack())) { 3773 if (Complain) { 3774 unsigned NextDiag = diag::err_template_parameter_pack_non_pack; 3775 if (TemplateArgLoc.isValid()) { 3776 S.Diag(TemplateArgLoc, 3777 diag::err_template_arg_template_params_mismatch); 3778 NextDiag = diag::note_template_parameter_pack_non_pack; 3779 } 3780 3781 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0 3782 : isa<NonTypeTemplateParmDecl>(New)? 1 3783 : 2; 3784 S.Diag(New->getLocation(), NextDiag) 3785 << ParamKind << New->isParameterPack(); 3786 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here) 3787 << ParamKind << Old->isParameterPack(); 3788 } 3789 3790 return false; 3791 } 3792 3793 // For non-type template parameters, check the type of the parameter. 3794 if (NonTypeTemplateParmDecl *OldNTTP 3795 = dyn_cast<NonTypeTemplateParmDecl>(Old)) { 3796 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New); 3797 3798 // If we are matching a template template argument to a template 3799 // template parameter and one of the non-type template parameter types 3800 // is dependent, then we must wait until template instantiation time 3801 // to actually compare the arguments. 3802 if (Kind == Sema::TPL_TemplateTemplateArgumentMatch && 3803 (OldNTTP->getType()->isDependentType() || 3804 NewNTTP->getType()->isDependentType())) 3805 return true; 3806 3807 if (!S.Context.hasSameType(OldNTTP->getType(), NewNTTP->getType())) { 3808 if (Complain) { 3809 unsigned NextDiag = diag::err_template_nontype_parm_different_type; 3810 if (TemplateArgLoc.isValid()) { 3811 S.Diag(TemplateArgLoc, 3812 diag::err_template_arg_template_params_mismatch); 3813 NextDiag = diag::note_template_nontype_parm_different_type; 3814 } 3815 S.Diag(NewNTTP->getLocation(), NextDiag) 3816 << NewNTTP->getType() 3817 << (Kind != Sema::TPL_TemplateMatch); 3818 S.Diag(OldNTTP->getLocation(), 3819 diag::note_template_nontype_parm_prev_declaration) 3820 << OldNTTP->getType(); 3821 } 3822 3823 return false; 3824 } 3825 3826 return true; 3827 } 3828 3829 // For template template parameters, check the template parameter types. 3830 // The template parameter lists of template template 3831 // parameters must agree. 3832 if (TemplateTemplateParmDecl *OldTTP 3833 = dyn_cast<TemplateTemplateParmDecl>(Old)) { 3834 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New); 3835 return S.TemplateParameterListsAreEqual(NewTTP->getTemplateParameters(), 3836 OldTTP->getTemplateParameters(), 3837 Complain, 3838 (Kind == Sema::TPL_TemplateMatch 3839 ? Sema::TPL_TemplateTemplateParmMatch 3840 : Kind), 3841 TemplateArgLoc); 3842 } 3843 3844 return true; 3845} 3846 3847/// \brief Diagnose a known arity mismatch when comparing template argument 3848/// lists. 3849static 3850void DiagnoseTemplateParameterListArityMismatch(Sema &S, 3851 TemplateParameterList *New, 3852 TemplateParameterList *Old, 3853 Sema::TemplateParameterListEqualKind Kind, 3854 SourceLocation TemplateArgLoc) { 3855 unsigned NextDiag = diag::err_template_param_list_different_arity; 3856 if (TemplateArgLoc.isValid()) { 3857 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 3858 NextDiag = diag::note_template_param_list_different_arity; 3859 } 3860 S.Diag(New->getTemplateLoc(), NextDiag) 3861 << (New->size() > Old->size()) 3862 << (Kind != Sema::TPL_TemplateMatch) 3863 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc()); 3864 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration) 3865 << (Kind != Sema::TPL_TemplateMatch) 3866 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc()); 3867} 3868 3869/// \brief Determine whether the given template parameter lists are 3870/// equivalent. 3871/// 3872/// \param New The new template parameter list, typically written in the 3873/// source code as part of a new template declaration. 3874/// 3875/// \param Old The old template parameter list, typically found via 3876/// name lookup of the template declared with this template parameter 3877/// list. 3878/// 3879/// \param Complain If true, this routine will produce a diagnostic if 3880/// the template parameter lists are not equivalent. 3881/// 3882/// \param Kind describes how we are to match the template parameter lists. 3883/// 3884/// \param TemplateArgLoc If this source location is valid, then we 3885/// are actually checking the template parameter list of a template 3886/// argument (New) against the template parameter list of its 3887/// corresponding template template parameter (Old). We produce 3888/// slightly different diagnostics in this scenario. 3889/// 3890/// \returns True if the template parameter lists are equal, false 3891/// otherwise. 3892bool 3893Sema::TemplateParameterListsAreEqual(TemplateParameterList *New, 3894 TemplateParameterList *Old, 3895 bool Complain, 3896 TemplateParameterListEqualKind Kind, 3897 SourceLocation TemplateArgLoc) { 3898 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) { 3899 if (Complain) 3900 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 3901 TemplateArgLoc); 3902 3903 return false; 3904 } 3905 3906 // C++0x [temp.arg.template]p3: 3907 // A template-argument matches a template template-parameter (call it P) 3908 // when each of the template parameters in the template-parameter-list of 3909 // the template-argument's corresponding class template or template alias 3910 // (call it A) matches the corresponding template parameter in the 3911 // template-parameter-list of P. [...] 3912 TemplateParameterList::iterator NewParm = New->begin(); 3913 TemplateParameterList::iterator NewParmEnd = New->end(); 3914 for (TemplateParameterList::iterator OldParm = Old->begin(), 3915 OldParmEnd = Old->end(); 3916 OldParm != OldParmEnd; ++OldParm) { 3917 if (Kind != TPL_TemplateTemplateArgumentMatch || 3918 !(*OldParm)->isTemplateParameterPack()) { 3919 if (NewParm == NewParmEnd) { 3920 if (Complain) 3921 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 3922 TemplateArgLoc); 3923 3924 return false; 3925 } 3926 3927 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain, 3928 Kind, TemplateArgLoc)) 3929 return false; 3930 3931 ++NewParm; 3932 continue; 3933 } 3934 3935 // C++0x [temp.arg.template]p3: 3936 // [...] When P's template- parameter-list contains a template parameter 3937 // pack (14.5.3), the template parameter pack will match zero or more 3938 // template parameters or template parameter packs in the 3939 // template-parameter-list of A with the same type and form as the 3940 // template parameter pack in P (ignoring whether those template 3941 // parameters are template parameter packs). 3942 for (; NewParm != NewParmEnd; ++NewParm) { 3943 if (!MatchTemplateParameterKind(*this, *NewParm, *OldParm, Complain, 3944 Kind, TemplateArgLoc)) 3945 return false; 3946 } 3947 } 3948 3949 // Make sure we exhausted all of the arguments. 3950 if (NewParm != NewParmEnd) { 3951 if (Complain) 3952 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 3953 TemplateArgLoc); 3954 3955 return false; 3956 } 3957 3958 return true; 3959} 3960 3961/// \brief Check whether a template can be declared within this scope. 3962/// 3963/// If the template declaration is valid in this scope, returns 3964/// false. Otherwise, issues a diagnostic and returns true. 3965bool 3966Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) { 3967 // Find the nearest enclosing declaration scope. 3968 while ((S->getFlags() & Scope::DeclScope) == 0 || 3969 (S->getFlags() & Scope::TemplateParamScope) != 0) 3970 S = S->getParent(); 3971 3972 // C++ [temp]p2: 3973 // A template-declaration can appear only as a namespace scope or 3974 // class scope declaration. 3975 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity()); 3976 if (Ctx && isa<LinkageSpecDecl>(Ctx) && 3977 cast<LinkageSpecDecl>(Ctx)->getLanguage() != LinkageSpecDecl::lang_cxx) 3978 return Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage) 3979 << TemplateParams->getSourceRange(); 3980 3981 while (Ctx && isa<LinkageSpecDecl>(Ctx)) 3982 Ctx = Ctx->getParent(); 3983 3984 if (Ctx && (Ctx->isFileContext() || Ctx->isRecord())) 3985 return false; 3986 3987 return Diag(TemplateParams->getTemplateLoc(), 3988 diag::err_template_outside_namespace_or_class_scope) 3989 << TemplateParams->getSourceRange(); 3990} 3991 3992/// \brief Determine what kind of template specialization the given declaration 3993/// is. 3994static TemplateSpecializationKind getTemplateSpecializationKind(NamedDecl *D) { 3995 if (!D) 3996 return TSK_Undeclared; 3997 3998 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) 3999 return Record->getTemplateSpecializationKind(); 4000 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) 4001 return Function->getTemplateSpecializationKind(); 4002 if (VarDecl *Var = dyn_cast<VarDecl>(D)) 4003 return Var->getTemplateSpecializationKind(); 4004 4005 return TSK_Undeclared; 4006} 4007 4008/// \brief Check whether a specialization is well-formed in the current 4009/// context. 4010/// 4011/// This routine determines whether a template specialization can be declared 4012/// in the current context (C++ [temp.expl.spec]p2). 4013/// 4014/// \param S the semantic analysis object for which this check is being 4015/// performed. 4016/// 4017/// \param Specialized the entity being specialized or instantiated, which 4018/// may be a kind of template (class template, function template, etc.) or 4019/// a member of a class template (member function, static data member, 4020/// member class). 4021/// 4022/// \param PrevDecl the previous declaration of this entity, if any. 4023/// 4024/// \param Loc the location of the explicit specialization or instantiation of 4025/// this entity. 4026/// 4027/// \param IsPartialSpecialization whether this is a partial specialization of 4028/// a class template. 4029/// 4030/// \returns true if there was an error that we cannot recover from, false 4031/// otherwise. 4032static bool CheckTemplateSpecializationScope(Sema &S, 4033 NamedDecl *Specialized, 4034 NamedDecl *PrevDecl, 4035 SourceLocation Loc, 4036 bool IsPartialSpecialization) { 4037 // Keep these "kind" numbers in sync with the %select statements in the 4038 // various diagnostics emitted by this routine. 4039 int EntityKind = 0; 4040 if (isa<ClassTemplateDecl>(Specialized)) 4041 EntityKind = IsPartialSpecialization? 1 : 0; 4042 else if (isa<FunctionTemplateDecl>(Specialized)) 4043 EntityKind = 2; 4044 else if (isa<CXXMethodDecl>(Specialized)) 4045 EntityKind = 3; 4046 else if (isa<VarDecl>(Specialized)) 4047 EntityKind = 4; 4048 else if (isa<RecordDecl>(Specialized)) 4049 EntityKind = 5; 4050 else { 4051 S.Diag(Loc, diag::err_template_spec_unknown_kind); 4052 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 4053 return true; 4054 } 4055 4056 // C++ [temp.expl.spec]p2: 4057 // An explicit specialization shall be declared in the namespace 4058 // of which the template is a member, or, for member templates, in 4059 // the namespace of which the enclosing class or enclosing class 4060 // template is a member. An explicit specialization of a member 4061 // function, member class or static data member of a class 4062 // template shall be declared in the namespace of which the class 4063 // template is a member. Such a declaration may also be a 4064 // definition. If the declaration is not a definition, the 4065 // specialization may be defined later in the name- space in which 4066 // the explicit specialization was declared, or in a namespace 4067 // that encloses the one in which the explicit specialization was 4068 // declared. 4069 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) { 4070 S.Diag(Loc, diag::err_template_spec_decl_function_scope) 4071 << Specialized; 4072 return true; 4073 } 4074 4075 if (S.CurContext->isRecord() && !IsPartialSpecialization) { 4076 S.Diag(Loc, diag::err_template_spec_decl_class_scope) 4077 << Specialized; 4078 return true; 4079 } 4080 4081 // C++ [temp.class.spec]p6: 4082 // A class template partial specialization may be declared or redeclared 4083 // in any namespace scope in which its definition may be defined (14.5.1 4084 // and 14.5.2). 4085 bool ComplainedAboutScope = false; 4086 DeclContext *SpecializedContext 4087 = Specialized->getDeclContext()->getEnclosingNamespaceContext(); 4088 DeclContext *DC = S.CurContext->getEnclosingNamespaceContext(); 4089 if ((!PrevDecl || 4090 getTemplateSpecializationKind(PrevDecl) == TSK_Undeclared || 4091 getTemplateSpecializationKind(PrevDecl) == TSK_ImplicitInstantiation)){ 4092 // C++ [temp.exp.spec]p2: 4093 // An explicit specialization shall be declared in the namespace of which 4094 // the template is a member, or, for member templates, in the namespace 4095 // of which the enclosing class or enclosing class template is a member. 4096 // An explicit specialization of a member function, member class or 4097 // static data member of a class template shall be declared in the 4098 // namespace of which the class template is a member. 4099 // 4100 // C++0x [temp.expl.spec]p2: 4101 // An explicit specialization shall be declared in a namespace enclosing 4102 // the specialized template. 4103 if (!DC->InEnclosingNamespaceSetOf(SpecializedContext) && 4104 !(S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext))) { 4105 bool IsCPlusPlus0xExtension 4106 = !S.getLangOptions().CPlusPlus0x && DC->Encloses(SpecializedContext); 4107 if (isa<TranslationUnitDecl>(SpecializedContext)) 4108 S.Diag(Loc, IsCPlusPlus0xExtension 4109 ? diag::ext_template_spec_decl_out_of_scope_global 4110 : diag::err_template_spec_decl_out_of_scope_global) 4111 << EntityKind << Specialized; 4112 else if (isa<NamespaceDecl>(SpecializedContext)) 4113 S.Diag(Loc, IsCPlusPlus0xExtension 4114 ? diag::ext_template_spec_decl_out_of_scope 4115 : diag::err_template_spec_decl_out_of_scope) 4116 << EntityKind << Specialized 4117 << cast<NamedDecl>(SpecializedContext); 4118 4119 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 4120 ComplainedAboutScope = true; 4121 } 4122 } 4123 4124 // Make sure that this redeclaration (or definition) occurs in an enclosing 4125 // namespace. 4126 // Note that HandleDeclarator() performs this check for explicit 4127 // specializations of function templates, static data members, and member 4128 // functions, so we skip the check here for those kinds of entities. 4129 // FIXME: HandleDeclarator's diagnostics aren't quite as good, though. 4130 // Should we refactor that check, so that it occurs later? 4131 if (!ComplainedAboutScope && !DC->Encloses(SpecializedContext) && 4132 !(isa<FunctionTemplateDecl>(Specialized) || isa<VarDecl>(Specialized) || 4133 isa<FunctionDecl>(Specialized))) { 4134 if (isa<TranslationUnitDecl>(SpecializedContext)) 4135 S.Diag(Loc, diag::err_template_spec_redecl_global_scope) 4136 << EntityKind << Specialized; 4137 else if (isa<NamespaceDecl>(SpecializedContext)) 4138 S.Diag(Loc, diag::err_template_spec_redecl_out_of_scope) 4139 << EntityKind << Specialized 4140 << cast<NamedDecl>(SpecializedContext); 4141 4142 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 4143 } 4144 4145 // FIXME: check for specialization-after-instantiation errors and such. 4146 4147 return false; 4148} 4149 4150/// \brief Subroutine of Sema::CheckClassTemplatePartialSpecializationArgs 4151/// that checks non-type template partial specialization arguments. 4152static bool CheckNonTypeClassTemplatePartialSpecializationArgs(Sema &S, 4153 NonTypeTemplateParmDecl *Param, 4154 const TemplateArgument *Args, 4155 unsigned NumArgs) { 4156 for (unsigned I = 0; I != NumArgs; ++I) { 4157 if (Args[I].getKind() == TemplateArgument::Pack) { 4158 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param, 4159 Args[I].pack_begin(), 4160 Args[I].pack_size())) 4161 return true; 4162 4163 continue; 4164 } 4165 4166 Expr *ArgExpr = Args[I].getAsExpr(); 4167 if (!ArgExpr) { 4168 continue; 4169 } 4170 4171 // We can have a pack expansion of any of the bullets below. 4172 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr)) 4173 ArgExpr = Expansion->getPattern(); 4174 4175 // Strip off any implicit casts we added as part of type checking. 4176 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 4177 ArgExpr = ICE->getSubExpr(); 4178 4179 // C++ [temp.class.spec]p8: 4180 // A non-type argument is non-specialized if it is the name of a 4181 // non-type parameter. All other non-type arguments are 4182 // specialized. 4183 // 4184 // Below, we check the two conditions that only apply to 4185 // specialized non-type arguments, so skip any non-specialized 4186 // arguments. 4187 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr)) 4188 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl())) 4189 continue; 4190 4191 // C++ [temp.class.spec]p9: 4192 // Within the argument list of a class template partial 4193 // specialization, the following restrictions apply: 4194 // -- A partially specialized non-type argument expression 4195 // shall not involve a template parameter of the partial 4196 // specialization except when the argument expression is a 4197 // simple identifier. 4198 if (ArgExpr->isTypeDependent() || ArgExpr->isValueDependent()) { 4199 S.Diag(ArgExpr->getLocStart(), 4200 diag::err_dependent_non_type_arg_in_partial_spec) 4201 << ArgExpr->getSourceRange(); 4202 return true; 4203 } 4204 4205 // -- The type of a template parameter corresponding to a 4206 // specialized non-type argument shall not be dependent on a 4207 // parameter of the specialization. 4208 if (Param->getType()->isDependentType()) { 4209 S.Diag(ArgExpr->getLocStart(), 4210 diag::err_dependent_typed_non_type_arg_in_partial_spec) 4211 << Param->getType() 4212 << ArgExpr->getSourceRange(); 4213 S.Diag(Param->getLocation(), diag::note_template_param_here); 4214 return true; 4215 } 4216 } 4217 4218 return false; 4219} 4220 4221/// \brief Check the non-type template arguments of a class template 4222/// partial specialization according to C++ [temp.class.spec]p9. 4223/// 4224/// \param TemplateParams the template parameters of the primary class 4225/// template. 4226/// 4227/// \param TemplateArg the template arguments of the class template 4228/// partial specialization. 4229/// 4230/// \returns true if there was an error, false otherwise. 4231static bool CheckClassTemplatePartialSpecializationArgs(Sema &S, 4232 TemplateParameterList *TemplateParams, 4233 llvm::SmallVectorImpl<TemplateArgument> &TemplateArgs) { 4234 const TemplateArgument *ArgList = TemplateArgs.data(); 4235 4236 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 4237 NonTypeTemplateParmDecl *Param 4238 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I)); 4239 if (!Param) 4240 continue; 4241 4242 if (CheckNonTypeClassTemplatePartialSpecializationArgs(S, Param, 4243 &ArgList[I], 1)) 4244 return true; 4245 } 4246 4247 return false; 4248} 4249 4250/// \brief Retrieve the previous declaration of the given declaration. 4251static NamedDecl *getPreviousDecl(NamedDecl *ND) { 4252 if (VarDecl *VD = dyn_cast<VarDecl>(ND)) 4253 return VD->getPreviousDeclaration(); 4254 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) 4255 return FD->getPreviousDeclaration(); 4256 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) 4257 return TD->getPreviousDeclaration(); 4258 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 4259 return TD->getPreviousDeclaration(); 4260 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 4261 return FTD->getPreviousDeclaration(); 4262 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(ND)) 4263 return CTD->getPreviousDeclaration(); 4264 return 0; 4265} 4266 4267DeclResult 4268Sema::ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, 4269 TagUseKind TUK, 4270 SourceLocation KWLoc, 4271 CXXScopeSpec &SS, 4272 TemplateTy TemplateD, 4273 SourceLocation TemplateNameLoc, 4274 SourceLocation LAngleLoc, 4275 ASTTemplateArgsPtr TemplateArgsIn, 4276 SourceLocation RAngleLoc, 4277 AttributeList *Attr, 4278 MultiTemplateParamsArg TemplateParameterLists) { 4279 assert(TUK != TUK_Reference && "References are not specializations"); 4280 4281 // Find the class template we're specializing 4282 TemplateName Name = TemplateD.getAsVal<TemplateName>(); 4283 ClassTemplateDecl *ClassTemplate 4284 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl()); 4285 4286 if (!ClassTemplate) { 4287 Diag(TemplateNameLoc, diag::err_not_class_template_specialization) 4288 << (Name.getAsTemplateDecl() && 4289 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())); 4290 return true; 4291 } 4292 4293 bool isExplicitSpecialization = false; 4294 bool isPartialSpecialization = false; 4295 4296 // Check the validity of the template headers that introduce this 4297 // template. 4298 // FIXME: We probably shouldn't complain about these headers for 4299 // friend declarations. 4300 bool Invalid = false; 4301 TemplateParameterList *TemplateParams 4302 = MatchTemplateParametersToScopeSpecifier(TemplateNameLoc, SS, 4303 (TemplateParameterList**)TemplateParameterLists.get(), 4304 TemplateParameterLists.size(), 4305 TUK == TUK_Friend, 4306 isExplicitSpecialization, 4307 Invalid); 4308 if (Invalid) 4309 return true; 4310 4311 unsigned NumMatchedTemplateParamLists = TemplateParameterLists.size(); 4312 if (TemplateParams) 4313 --NumMatchedTemplateParamLists; 4314 4315 if (TemplateParams && TemplateParams->size() > 0) { 4316 isPartialSpecialization = true; 4317 4318 if (TUK == TUK_Friend) { 4319 Diag(KWLoc, diag::err_partial_specialization_friend) 4320 << SourceRange(LAngleLoc, RAngleLoc); 4321 return true; 4322 } 4323 4324 // C++ [temp.class.spec]p10: 4325 // The template parameter list of a specialization shall not 4326 // contain default template argument values. 4327 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 4328 Decl *Param = TemplateParams->getParam(I); 4329 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 4330 if (TTP->hasDefaultArgument()) { 4331 Diag(TTP->getDefaultArgumentLoc(), 4332 diag::err_default_arg_in_partial_spec); 4333 TTP->removeDefaultArgument(); 4334 } 4335 } else if (NonTypeTemplateParmDecl *NTTP 4336 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 4337 if (Expr *DefArg = NTTP->getDefaultArgument()) { 4338 Diag(NTTP->getDefaultArgumentLoc(), 4339 diag::err_default_arg_in_partial_spec) 4340 << DefArg->getSourceRange(); 4341 NTTP->removeDefaultArgument(); 4342 } 4343 } else { 4344 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param); 4345 if (TTP->hasDefaultArgument()) { 4346 Diag(TTP->getDefaultArgument().getLocation(), 4347 diag::err_default_arg_in_partial_spec) 4348 << TTP->getDefaultArgument().getSourceRange(); 4349 TTP->removeDefaultArgument(); 4350 } 4351 } 4352 } 4353 } else if (TemplateParams) { 4354 if (TUK == TUK_Friend) 4355 Diag(KWLoc, diag::err_template_spec_friend) 4356 << FixItHint::CreateRemoval( 4357 SourceRange(TemplateParams->getTemplateLoc(), 4358 TemplateParams->getRAngleLoc())) 4359 << SourceRange(LAngleLoc, RAngleLoc); 4360 else 4361 isExplicitSpecialization = true; 4362 } else if (TUK != TUK_Friend) { 4363 Diag(KWLoc, diag::err_template_spec_needs_header) 4364 << FixItHint::CreateInsertion(KWLoc, "template<> "); 4365 isExplicitSpecialization = true; 4366 } 4367 4368 // Check that the specialization uses the same tag kind as the 4369 // original template. 4370 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 4371 assert(Kind != TTK_Enum && "Invalid enum tag in class template spec!"); 4372 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 4373 Kind, KWLoc, 4374 *ClassTemplate->getIdentifier())) { 4375 Diag(KWLoc, diag::err_use_with_wrong_tag) 4376 << ClassTemplate 4377 << FixItHint::CreateReplacement(KWLoc, 4378 ClassTemplate->getTemplatedDecl()->getKindName()); 4379 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 4380 diag::note_previous_use); 4381 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 4382 } 4383 4384 // Translate the parser's template argument list in our AST format. 4385 TemplateArgumentListInfo TemplateArgs; 4386 TemplateArgs.setLAngleLoc(LAngleLoc); 4387 TemplateArgs.setRAngleLoc(RAngleLoc); 4388 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 4389 4390 // Check for unexpanded parameter packs in any of the template arguments. 4391 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 4392 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I], 4393 UPPC_PartialSpecialization)) 4394 return true; 4395 4396 // Check that the template argument list is well-formed for this 4397 // template. 4398 llvm::SmallVector<TemplateArgument, 4> Converted; 4399 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, 4400 TemplateArgs, false, Converted)) 4401 return true; 4402 4403 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) && 4404 "Converted template argument list is too short!"); 4405 4406 // Find the class template (partial) specialization declaration that 4407 // corresponds to these arguments. 4408 if (isPartialSpecialization) { 4409 if (CheckClassTemplatePartialSpecializationArgs(*this, 4410 ClassTemplate->getTemplateParameters(), 4411 Converted)) 4412 return true; 4413 4414 if (!Name.isDependent() && 4415 !TemplateSpecializationType::anyDependentTemplateArguments( 4416 TemplateArgs.getArgumentArray(), 4417 TemplateArgs.size())) { 4418 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized) 4419 << ClassTemplate->getDeclName(); 4420 isPartialSpecialization = false; 4421 } 4422 } 4423 4424 void *InsertPos = 0; 4425 ClassTemplateSpecializationDecl *PrevDecl = 0; 4426 4427 if (isPartialSpecialization) 4428 // FIXME: Template parameter list matters, too 4429 PrevDecl 4430 = ClassTemplate->findPartialSpecialization(Converted.data(), 4431 Converted.size(), 4432 InsertPos); 4433 else 4434 PrevDecl 4435 = ClassTemplate->findSpecialization(Converted.data(), 4436 Converted.size(), InsertPos); 4437 4438 ClassTemplateSpecializationDecl *Specialization = 0; 4439 4440 // Check whether we can declare a class template specialization in 4441 // the current scope. 4442 if (TUK != TUK_Friend && 4443 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl, 4444 TemplateNameLoc, 4445 isPartialSpecialization)) 4446 return true; 4447 4448 // The canonical type 4449 QualType CanonType; 4450 if (PrevDecl && 4451 (PrevDecl->getSpecializationKind() == TSK_Undeclared || 4452 TUK == TUK_Friend)) { 4453 // Since the only prior class template specialization with these 4454 // arguments was referenced but not declared, or we're only 4455 // referencing this specialization as a friend, reuse that 4456 // declaration node as our own, updating its source location to 4457 // reflect our new declaration. 4458 Specialization = PrevDecl; 4459 Specialization->setLocation(TemplateNameLoc); 4460 PrevDecl = 0; 4461 CanonType = Context.getTypeDeclType(Specialization); 4462 } else if (isPartialSpecialization) { 4463 // Build the canonical type that describes the converted template 4464 // arguments of the class template partial specialization. 4465 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); 4466 CanonType = Context.getTemplateSpecializationType(CanonTemplate, 4467 Converted.data(), 4468 Converted.size()); 4469 4470 if (Context.hasSameType(CanonType, 4471 ClassTemplate->getInjectedClassNameSpecialization())) { 4472 // C++ [temp.class.spec]p9b3: 4473 // 4474 // -- The argument list of the specialization shall not be identical 4475 // to the implicit argument list of the primary template. 4476 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) 4477 << (TUK == TUK_Definition) 4478 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc)); 4479 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS, 4480 ClassTemplate->getIdentifier(), 4481 TemplateNameLoc, 4482 Attr, 4483 TemplateParams, 4484 AS_none); 4485 } 4486 4487 // Create a new class template partial specialization declaration node. 4488 ClassTemplatePartialSpecializationDecl *PrevPartial 4489 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl); 4490 unsigned SequenceNumber = PrevPartial? PrevPartial->getSequenceNumber() 4491 : ClassTemplate->getNextPartialSpecSequenceNumber(); 4492 ClassTemplatePartialSpecializationDecl *Partial 4493 = ClassTemplatePartialSpecializationDecl::Create(Context, Kind, 4494 ClassTemplate->getDeclContext(), 4495 TemplateNameLoc, 4496 TemplateParams, 4497 ClassTemplate, 4498 Converted.data(), 4499 Converted.size(), 4500 TemplateArgs, 4501 CanonType, 4502 PrevPartial, 4503 SequenceNumber); 4504 SetNestedNameSpecifier(Partial, SS); 4505 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) { 4506 Partial->setTemplateParameterListsInfo(Context, 4507 NumMatchedTemplateParamLists, 4508 (TemplateParameterList**) TemplateParameterLists.release()); 4509 } 4510 4511 if (!PrevPartial) 4512 ClassTemplate->AddPartialSpecialization(Partial, InsertPos); 4513 Specialization = Partial; 4514 4515 // If we are providing an explicit specialization of a member class 4516 // template specialization, make a note of that. 4517 if (PrevPartial && PrevPartial->getInstantiatedFromMember()) 4518 PrevPartial->setMemberSpecialization(); 4519 4520 // Check that all of the template parameters of the class template 4521 // partial specialization are deducible from the template 4522 // arguments. If not, this class template partial specialization 4523 // will never be used. 4524 llvm::SmallVector<bool, 8> DeducibleParams; 4525 DeducibleParams.resize(TemplateParams->size()); 4526 MarkUsedTemplateParameters(Partial->getTemplateArgs(), true, 4527 TemplateParams->getDepth(), 4528 DeducibleParams); 4529 unsigned NumNonDeducible = 0; 4530 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) 4531 if (!DeducibleParams[I]) 4532 ++NumNonDeducible; 4533 4534 if (NumNonDeducible) { 4535 Diag(TemplateNameLoc, diag::warn_partial_specs_not_deducible) 4536 << (NumNonDeducible > 1) 4537 << SourceRange(TemplateNameLoc, RAngleLoc); 4538 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) { 4539 if (!DeducibleParams[I]) { 4540 NamedDecl *Param = cast<NamedDecl>(TemplateParams->getParam(I)); 4541 if (Param->getDeclName()) 4542 Diag(Param->getLocation(), 4543 diag::note_partial_spec_unused_parameter) 4544 << Param->getDeclName(); 4545 else 4546 Diag(Param->getLocation(), 4547 diag::note_partial_spec_unused_parameter) 4548 << "<anonymous>"; 4549 } 4550 } 4551 } 4552 } else { 4553 // Create a new class template specialization declaration node for 4554 // this explicit specialization or friend declaration. 4555 Specialization 4556 = ClassTemplateSpecializationDecl::Create(Context, Kind, 4557 ClassTemplate->getDeclContext(), 4558 TemplateNameLoc, 4559 ClassTemplate, 4560 Converted.data(), 4561 Converted.size(), 4562 PrevDecl); 4563 SetNestedNameSpecifier(Specialization, SS); 4564 if (NumMatchedTemplateParamLists > 0 && SS.isSet()) { 4565 Specialization->setTemplateParameterListsInfo(Context, 4566 NumMatchedTemplateParamLists, 4567 (TemplateParameterList**) TemplateParameterLists.release()); 4568 } 4569 4570 if (!PrevDecl) 4571 ClassTemplate->AddSpecialization(Specialization, InsertPos); 4572 4573 CanonType = Context.getTypeDeclType(Specialization); 4574 } 4575 4576 // C++ [temp.expl.spec]p6: 4577 // If a template, a member template or the member of a class template is 4578 // explicitly specialized then that specialization shall be declared 4579 // before the first use of that specialization that would cause an implicit 4580 // instantiation to take place, in every translation unit in which such a 4581 // use occurs; no diagnostic is required. 4582 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { 4583 bool Okay = false; 4584 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) { 4585 // Is there any previous explicit specialization declaration? 4586 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { 4587 Okay = true; 4588 break; 4589 } 4590 } 4591 4592 if (!Okay) { 4593 SourceRange Range(TemplateNameLoc, RAngleLoc); 4594 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) 4595 << Context.getTypeDeclType(Specialization) << Range; 4596 4597 Diag(PrevDecl->getPointOfInstantiation(), 4598 diag::note_instantiation_required_here) 4599 << (PrevDecl->getTemplateSpecializationKind() 4600 != TSK_ImplicitInstantiation); 4601 return true; 4602 } 4603 } 4604 4605 // If this is not a friend, note that this is an explicit specialization. 4606 if (TUK != TUK_Friend) 4607 Specialization->setSpecializationKind(TSK_ExplicitSpecialization); 4608 4609 // Check that this isn't a redefinition of this specialization. 4610 if (TUK == TUK_Definition) { 4611 if (RecordDecl *Def = Specialization->getDefinition()) { 4612 SourceRange Range(TemplateNameLoc, RAngleLoc); 4613 Diag(TemplateNameLoc, diag::err_redefinition) 4614 << Context.getTypeDeclType(Specialization) << Range; 4615 Diag(Def->getLocation(), diag::note_previous_definition); 4616 Specialization->setInvalidDecl(); 4617 return true; 4618 } 4619 } 4620 4621 if (Attr) 4622 ProcessDeclAttributeList(S, Specialization, Attr); 4623 4624 // Build the fully-sugared type for this class template 4625 // specialization as the user wrote in the specialization 4626 // itself. This means that we'll pretty-print the type retrieved 4627 // from the specialization's declaration the way that the user 4628 // actually wrote the specialization, rather than formatting the 4629 // name based on the "canonical" representation used to store the 4630 // template arguments in the specialization. 4631 TypeSourceInfo *WrittenTy 4632 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc, 4633 TemplateArgs, CanonType); 4634 if (TUK != TUK_Friend) { 4635 Specialization->setTypeAsWritten(WrittenTy); 4636 if (TemplateParams) 4637 Specialization->setTemplateKeywordLoc(TemplateParams->getTemplateLoc()); 4638 } 4639 TemplateArgsIn.release(); 4640 4641 // C++ [temp.expl.spec]p9: 4642 // A template explicit specialization is in the scope of the 4643 // namespace in which the template was defined. 4644 // 4645 // We actually implement this paragraph where we set the semantic 4646 // context (in the creation of the ClassTemplateSpecializationDecl), 4647 // but we also maintain the lexical context where the actual 4648 // definition occurs. 4649 Specialization->setLexicalDeclContext(CurContext); 4650 4651 // We may be starting the definition of this specialization. 4652 if (TUK == TUK_Definition) 4653 Specialization->startDefinition(); 4654 4655 if (TUK == TUK_Friend) { 4656 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, 4657 TemplateNameLoc, 4658 WrittenTy, 4659 /*FIXME:*/KWLoc); 4660 Friend->setAccess(AS_public); 4661 CurContext->addDecl(Friend); 4662 } else { 4663 // Add the specialization into its lexical context, so that it can 4664 // be seen when iterating through the list of declarations in that 4665 // context. However, specializations are not found by name lookup. 4666 CurContext->addDecl(Specialization); 4667 } 4668 return Specialization; 4669} 4670 4671Decl *Sema::ActOnTemplateDeclarator(Scope *S, 4672 MultiTemplateParamsArg TemplateParameterLists, 4673 Declarator &D) { 4674 return HandleDeclarator(S, D, move(TemplateParameterLists), false); 4675} 4676 4677Decl *Sema::ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 4678 MultiTemplateParamsArg TemplateParameterLists, 4679 Declarator &D) { 4680 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 4681 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 4682 4683 if (FTI.hasPrototype) { 4684 // FIXME: Diagnose arguments without names in C. 4685 } 4686 4687 Scope *ParentScope = FnBodyScope->getParent(); 4688 4689 Decl *DP = HandleDeclarator(ParentScope, D, 4690 move(TemplateParameterLists), 4691 /*IsFunctionDefinition=*/true); 4692 if (FunctionTemplateDecl *FunctionTemplate 4693 = dyn_cast_or_null<FunctionTemplateDecl>(DP)) 4694 return ActOnStartOfFunctionDef(FnBodyScope, 4695 FunctionTemplate->getTemplatedDecl()); 4696 if (FunctionDecl *Function = dyn_cast_or_null<FunctionDecl>(DP)) 4697 return ActOnStartOfFunctionDef(FnBodyScope, Function); 4698 return 0; 4699} 4700 4701/// \brief Strips various properties off an implicit instantiation 4702/// that has just been explicitly specialized. 4703static void StripImplicitInstantiation(NamedDecl *D) { 4704 D->dropAttrs(); 4705 4706 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 4707 FD->setInlineSpecified(false); 4708 } 4709} 4710 4711/// \brief Diagnose cases where we have an explicit template specialization 4712/// before/after an explicit template instantiation, producing diagnostics 4713/// for those cases where they are required and determining whether the 4714/// new specialization/instantiation will have any effect. 4715/// 4716/// \param NewLoc the location of the new explicit specialization or 4717/// instantiation. 4718/// 4719/// \param NewTSK the kind of the new explicit specialization or instantiation. 4720/// 4721/// \param PrevDecl the previous declaration of the entity. 4722/// 4723/// \param PrevTSK the kind of the old explicit specialization or instantiatin. 4724/// 4725/// \param PrevPointOfInstantiation if valid, indicates where the previus 4726/// declaration was instantiated (either implicitly or explicitly). 4727/// 4728/// \param HasNoEffect will be set to true to indicate that the new 4729/// specialization or instantiation has no effect and should be ignored. 4730/// 4731/// \returns true if there was an error that should prevent the introduction of 4732/// the new declaration into the AST, false otherwise. 4733bool 4734Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 4735 TemplateSpecializationKind NewTSK, 4736 NamedDecl *PrevDecl, 4737 TemplateSpecializationKind PrevTSK, 4738 SourceLocation PrevPointOfInstantiation, 4739 bool &HasNoEffect) { 4740 HasNoEffect = false; 4741 4742 switch (NewTSK) { 4743 case TSK_Undeclared: 4744 case TSK_ImplicitInstantiation: 4745 assert(false && "Don't check implicit instantiations here"); 4746 return false; 4747 4748 case TSK_ExplicitSpecialization: 4749 switch (PrevTSK) { 4750 case TSK_Undeclared: 4751 case TSK_ExplicitSpecialization: 4752 // Okay, we're just specializing something that is either already 4753 // explicitly specialized or has merely been mentioned without any 4754 // instantiation. 4755 return false; 4756 4757 case TSK_ImplicitInstantiation: 4758 if (PrevPointOfInstantiation.isInvalid()) { 4759 // The declaration itself has not actually been instantiated, so it is 4760 // still okay to specialize it. 4761 StripImplicitInstantiation(PrevDecl); 4762 return false; 4763 } 4764 // Fall through 4765 4766 case TSK_ExplicitInstantiationDeclaration: 4767 case TSK_ExplicitInstantiationDefinition: 4768 assert((PrevTSK == TSK_ImplicitInstantiation || 4769 PrevPointOfInstantiation.isValid()) && 4770 "Explicit instantiation without point of instantiation?"); 4771 4772 // C++ [temp.expl.spec]p6: 4773 // If a template, a member template or the member of a class template 4774 // is explicitly specialized then that specialization shall be declared 4775 // before the first use of that specialization that would cause an 4776 // implicit instantiation to take place, in every translation unit in 4777 // which such a use occurs; no diagnostic is required. 4778 for (NamedDecl *Prev = PrevDecl; Prev; Prev = getPreviousDecl(Prev)) { 4779 // Is there any previous explicit specialization declaration? 4780 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) 4781 return false; 4782 } 4783 4784 Diag(NewLoc, diag::err_specialization_after_instantiation) 4785 << PrevDecl; 4786 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here) 4787 << (PrevTSK != TSK_ImplicitInstantiation); 4788 4789 return true; 4790 } 4791 break; 4792 4793 case TSK_ExplicitInstantiationDeclaration: 4794 switch (PrevTSK) { 4795 case TSK_ExplicitInstantiationDeclaration: 4796 // This explicit instantiation declaration is redundant (that's okay). 4797 HasNoEffect = true; 4798 return false; 4799 4800 case TSK_Undeclared: 4801 case TSK_ImplicitInstantiation: 4802 // We're explicitly instantiating something that may have already been 4803 // implicitly instantiated; that's fine. 4804 return false; 4805 4806 case TSK_ExplicitSpecialization: 4807 // C++0x [temp.explicit]p4: 4808 // For a given set of template parameters, if an explicit instantiation 4809 // of a template appears after a declaration of an explicit 4810 // specialization for that template, the explicit instantiation has no 4811 // effect. 4812 HasNoEffect = true; 4813 return false; 4814 4815 case TSK_ExplicitInstantiationDefinition: 4816 // C++0x [temp.explicit]p10: 4817 // If an entity is the subject of both an explicit instantiation 4818 // declaration and an explicit instantiation definition in the same 4819 // translation unit, the definition shall follow the declaration. 4820 Diag(NewLoc, 4821 diag::err_explicit_instantiation_declaration_after_definition); 4822 Diag(PrevPointOfInstantiation, 4823 diag::note_explicit_instantiation_definition_here); 4824 assert(PrevPointOfInstantiation.isValid() && 4825 "Explicit instantiation without point of instantiation?"); 4826 HasNoEffect = true; 4827 return false; 4828 } 4829 break; 4830 4831 case TSK_ExplicitInstantiationDefinition: 4832 switch (PrevTSK) { 4833 case TSK_Undeclared: 4834 case TSK_ImplicitInstantiation: 4835 // We're explicitly instantiating something that may have already been 4836 // implicitly instantiated; that's fine. 4837 return false; 4838 4839 case TSK_ExplicitSpecialization: 4840 // C++ DR 259, C++0x [temp.explicit]p4: 4841 // For a given set of template parameters, if an explicit 4842 // instantiation of a template appears after a declaration of 4843 // an explicit specialization for that template, the explicit 4844 // instantiation has no effect. 4845 // 4846 // In C++98/03 mode, we only give an extension warning here, because it 4847 // is not harmful to try to explicitly instantiate something that 4848 // has been explicitly specialized. 4849 if (!getLangOptions().CPlusPlus0x) { 4850 Diag(NewLoc, diag::ext_explicit_instantiation_after_specialization) 4851 << PrevDecl; 4852 Diag(PrevDecl->getLocation(), 4853 diag::note_previous_template_specialization); 4854 } 4855 HasNoEffect = true; 4856 return false; 4857 4858 case TSK_ExplicitInstantiationDeclaration: 4859 // We're explicity instantiating a definition for something for which we 4860 // were previously asked to suppress instantiations. That's fine. 4861 return false; 4862 4863 case TSK_ExplicitInstantiationDefinition: 4864 // C++0x [temp.spec]p5: 4865 // For a given template and a given set of template-arguments, 4866 // - an explicit instantiation definition shall appear at most once 4867 // in a program, 4868 Diag(NewLoc, diag::err_explicit_instantiation_duplicate) 4869 << PrevDecl; 4870 Diag(PrevPointOfInstantiation, 4871 diag::note_previous_explicit_instantiation); 4872 HasNoEffect = true; 4873 return false; 4874 } 4875 break; 4876 } 4877 4878 assert(false && "Missing specialization/instantiation case?"); 4879 4880 return false; 4881} 4882 4883/// \brief Perform semantic analysis for the given dependent function 4884/// template specialization. The only possible way to get a dependent 4885/// function template specialization is with a friend declaration, 4886/// like so: 4887/// 4888/// template <class T> void foo(T); 4889/// template <class T> class A { 4890/// friend void foo<>(T); 4891/// }; 4892/// 4893/// There really isn't any useful analysis we can do here, so we 4894/// just store the information. 4895bool 4896Sema::CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 4897 const TemplateArgumentListInfo &ExplicitTemplateArgs, 4898 LookupResult &Previous) { 4899 // Remove anything from Previous that isn't a function template in 4900 // the correct context. 4901 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext(); 4902 LookupResult::Filter F = Previous.makeFilter(); 4903 while (F.hasNext()) { 4904 NamedDecl *D = F.next()->getUnderlyingDecl(); 4905 if (!isa<FunctionTemplateDecl>(D) || 4906 !FDLookupContext->InEnclosingNamespaceSetOf( 4907 D->getDeclContext()->getRedeclContext())) 4908 F.erase(); 4909 } 4910 F.done(); 4911 4912 // Should this be diagnosed here? 4913 if (Previous.empty()) return true; 4914 4915 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(), 4916 ExplicitTemplateArgs); 4917 return false; 4918} 4919 4920/// \brief Perform semantic analysis for the given function template 4921/// specialization. 4922/// 4923/// This routine performs all of the semantic analysis required for an 4924/// explicit function template specialization. On successful completion, 4925/// the function declaration \p FD will become a function template 4926/// specialization. 4927/// 4928/// \param FD the function declaration, which will be updated to become a 4929/// function template specialization. 4930/// 4931/// \param ExplicitTemplateArgs the explicitly-provided template arguments, 4932/// if any. Note that this may be valid info even when 0 arguments are 4933/// explicitly provided as in, e.g., \c void sort<>(char*, char*); 4934/// as it anyway contains info on the angle brackets locations. 4935/// 4936/// \param PrevDecl the set of declarations that may be specialized by 4937/// this function specialization. 4938bool 4939Sema::CheckFunctionTemplateSpecialization(FunctionDecl *FD, 4940 const TemplateArgumentListInfo *ExplicitTemplateArgs, 4941 LookupResult &Previous) { 4942 // The set of function template specializations that could match this 4943 // explicit function template specialization. 4944 UnresolvedSet<8> Candidates; 4945 4946 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext(); 4947 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 4948 I != E; ++I) { 4949 NamedDecl *Ovl = (*I)->getUnderlyingDecl(); 4950 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) { 4951 // Only consider templates found within the same semantic lookup scope as 4952 // FD. 4953 if (!FDLookupContext->InEnclosingNamespaceSetOf( 4954 Ovl->getDeclContext()->getRedeclContext())) 4955 continue; 4956 4957 // C++ [temp.expl.spec]p11: 4958 // A trailing template-argument can be left unspecified in the 4959 // template-id naming an explicit function template specialization 4960 // provided it can be deduced from the function argument type. 4961 // Perform template argument deduction to determine whether we may be 4962 // specializing this template. 4963 // FIXME: It is somewhat wasteful to build 4964 TemplateDeductionInfo Info(Context, FD->getLocation()); 4965 FunctionDecl *Specialization = 0; 4966 if (TemplateDeductionResult TDK 4967 = DeduceTemplateArguments(FunTmpl, ExplicitTemplateArgs, 4968 FD->getType(), 4969 Specialization, 4970 Info)) { 4971 // FIXME: Template argument deduction failed; record why it failed, so 4972 // that we can provide nifty diagnostics. 4973 (void)TDK; 4974 continue; 4975 } 4976 4977 // Record this candidate. 4978 Candidates.addDecl(Specialization, I.getAccess()); 4979 } 4980 } 4981 4982 // Find the most specialized function template. 4983 UnresolvedSetIterator Result 4984 = getMostSpecialized(Candidates.begin(), Candidates.end(), 4985 TPOC_Other, 0, FD->getLocation(), 4986 PDiag(diag::err_function_template_spec_no_match) 4987 << FD->getDeclName(), 4988 PDiag(diag::err_function_template_spec_ambiguous) 4989 << FD->getDeclName() << (ExplicitTemplateArgs != 0), 4990 PDiag(diag::note_function_template_spec_matched)); 4991 if (Result == Candidates.end()) 4992 return true; 4993 4994 // Ignore access information; it doesn't figure into redeclaration checking. 4995 FunctionDecl *Specialization = cast<FunctionDecl>(*Result); 4996 Specialization->setLocation(FD->getLocation()); 4997 4998 // FIXME: Check if the prior specialization has a point of instantiation. 4999 // If so, we have run afoul of . 5000 5001 // If this is a friend declaration, then we're not really declaring 5002 // an explicit specialization. 5003 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None); 5004 5005 // Check the scope of this explicit specialization. 5006 if (!isFriend && 5007 CheckTemplateSpecializationScope(*this, 5008 Specialization->getPrimaryTemplate(), 5009 Specialization, FD->getLocation(), 5010 false)) 5011 return true; 5012 5013 // C++ [temp.expl.spec]p6: 5014 // If a template, a member template or the member of a class template is 5015 // explicitly specialized then that specialization shall be declared 5016 // before the first use of that specialization that would cause an implicit 5017 // instantiation to take place, in every translation unit in which such a 5018 // use occurs; no diagnostic is required. 5019 FunctionTemplateSpecializationInfo *SpecInfo 5020 = Specialization->getTemplateSpecializationInfo(); 5021 assert(SpecInfo && "Function template specialization info missing?"); 5022 5023 bool HasNoEffect = false; 5024 if (!isFriend && 5025 CheckSpecializationInstantiationRedecl(FD->getLocation(), 5026 TSK_ExplicitSpecialization, 5027 Specialization, 5028 SpecInfo->getTemplateSpecializationKind(), 5029 SpecInfo->getPointOfInstantiation(), 5030 HasNoEffect)) 5031 return true; 5032 5033 // Mark the prior declaration as an explicit specialization, so that later 5034 // clients know that this is an explicit specialization. 5035 if (!isFriend) { 5036 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization); 5037 MarkUnusedFileScopedDecl(Specialization); 5038 } 5039 5040 // Turn the given function declaration into a function template 5041 // specialization, with the template arguments from the previous 5042 // specialization. 5043 // Take copies of (semantic and syntactic) template argument lists. 5044 const TemplateArgumentList* TemplArgs = new (Context) 5045 TemplateArgumentList(Specialization->getTemplateSpecializationArgs()); 5046 const TemplateArgumentListInfo* TemplArgsAsWritten = ExplicitTemplateArgs 5047 ? new (Context) TemplateArgumentListInfo(*ExplicitTemplateArgs) : 0; 5048 FD->setFunctionTemplateSpecialization(Specialization->getPrimaryTemplate(), 5049 TemplArgs, /*InsertPos=*/0, 5050 SpecInfo->getTemplateSpecializationKind(), 5051 TemplArgsAsWritten); 5052 5053 // The "previous declaration" for this function template specialization is 5054 // the prior function template specialization. 5055 Previous.clear(); 5056 Previous.addDecl(Specialization); 5057 return false; 5058} 5059 5060/// \brief Perform semantic analysis for the given non-template member 5061/// specialization. 5062/// 5063/// This routine performs all of the semantic analysis required for an 5064/// explicit member function specialization. On successful completion, 5065/// the function declaration \p FD will become a member function 5066/// specialization. 5067/// 5068/// \param Member the member declaration, which will be updated to become a 5069/// specialization. 5070/// 5071/// \param Previous the set of declarations, one of which may be specialized 5072/// by this function specialization; the set will be modified to contain the 5073/// redeclared member. 5074bool 5075Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) { 5076 assert(!isa<TemplateDecl>(Member) && "Only for non-template members"); 5077 5078 // Try to find the member we are instantiating. 5079 NamedDecl *Instantiation = 0; 5080 NamedDecl *InstantiatedFrom = 0; 5081 MemberSpecializationInfo *MSInfo = 0; 5082 5083 if (Previous.empty()) { 5084 // Nowhere to look anyway. 5085 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) { 5086 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5087 I != E; ++I) { 5088 NamedDecl *D = (*I)->getUnderlyingDecl(); 5089 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 5090 if (Context.hasSameType(Function->getType(), Method->getType())) { 5091 Instantiation = Method; 5092 InstantiatedFrom = Method->getInstantiatedFromMemberFunction(); 5093 MSInfo = Method->getMemberSpecializationInfo(); 5094 break; 5095 } 5096 } 5097 } 5098 } else if (isa<VarDecl>(Member)) { 5099 VarDecl *PrevVar; 5100 if (Previous.isSingleResult() && 5101 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl()))) 5102 if (PrevVar->isStaticDataMember()) { 5103 Instantiation = PrevVar; 5104 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember(); 5105 MSInfo = PrevVar->getMemberSpecializationInfo(); 5106 } 5107 } else if (isa<RecordDecl>(Member)) { 5108 CXXRecordDecl *PrevRecord; 5109 if (Previous.isSingleResult() && 5110 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) { 5111 Instantiation = PrevRecord; 5112 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass(); 5113 MSInfo = PrevRecord->getMemberSpecializationInfo(); 5114 } 5115 } 5116 5117 if (!Instantiation) { 5118 // There is no previous declaration that matches. Since member 5119 // specializations are always out-of-line, the caller will complain about 5120 // this mismatch later. 5121 return false; 5122 } 5123 5124 // If this is a friend, just bail out here before we start turning 5125 // things into explicit specializations. 5126 if (Member->getFriendObjectKind() != Decl::FOK_None) { 5127 // Preserve instantiation information. 5128 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) { 5129 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction( 5130 cast<CXXMethodDecl>(InstantiatedFrom), 5131 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind()); 5132 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) { 5133 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass( 5134 cast<CXXRecordDecl>(InstantiatedFrom), 5135 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind()); 5136 } 5137 5138 Previous.clear(); 5139 Previous.addDecl(Instantiation); 5140 return false; 5141 } 5142 5143 // Make sure that this is a specialization of a member. 5144 if (!InstantiatedFrom) { 5145 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated) 5146 << Member; 5147 Diag(Instantiation->getLocation(), diag::note_specialized_decl); 5148 return true; 5149 } 5150 5151 // C++ [temp.expl.spec]p6: 5152 // If a template, a member template or the member of a class template is 5153 // explicitly specialized then that spe- cialization shall be declared 5154 // before the first use of that specialization that would cause an implicit 5155 // instantiation to take place, in every translation unit in which such a 5156 // use occurs; no diagnostic is required. 5157 assert(MSInfo && "Member specialization info missing?"); 5158 5159 bool HasNoEffect = false; 5160 if (CheckSpecializationInstantiationRedecl(Member->getLocation(), 5161 TSK_ExplicitSpecialization, 5162 Instantiation, 5163 MSInfo->getTemplateSpecializationKind(), 5164 MSInfo->getPointOfInstantiation(), 5165 HasNoEffect)) 5166 return true; 5167 5168 // Check the scope of this explicit specialization. 5169 if (CheckTemplateSpecializationScope(*this, 5170 InstantiatedFrom, 5171 Instantiation, Member->getLocation(), 5172 false)) 5173 return true; 5174 5175 // Note that this is an explicit instantiation of a member. 5176 // the original declaration to note that it is an explicit specialization 5177 // (if it was previously an implicit instantiation). This latter step 5178 // makes bookkeeping easier. 5179 if (isa<FunctionDecl>(Member)) { 5180 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation); 5181 if (InstantiationFunction->getTemplateSpecializationKind() == 5182 TSK_ImplicitInstantiation) { 5183 InstantiationFunction->setTemplateSpecializationKind( 5184 TSK_ExplicitSpecialization); 5185 InstantiationFunction->setLocation(Member->getLocation()); 5186 } 5187 5188 cast<FunctionDecl>(Member)->setInstantiationOfMemberFunction( 5189 cast<CXXMethodDecl>(InstantiatedFrom), 5190 TSK_ExplicitSpecialization); 5191 MarkUnusedFileScopedDecl(InstantiationFunction); 5192 } else if (isa<VarDecl>(Member)) { 5193 VarDecl *InstantiationVar = cast<VarDecl>(Instantiation); 5194 if (InstantiationVar->getTemplateSpecializationKind() == 5195 TSK_ImplicitInstantiation) { 5196 InstantiationVar->setTemplateSpecializationKind( 5197 TSK_ExplicitSpecialization); 5198 InstantiationVar->setLocation(Member->getLocation()); 5199 } 5200 5201 Context.setInstantiatedFromStaticDataMember(cast<VarDecl>(Member), 5202 cast<VarDecl>(InstantiatedFrom), 5203 TSK_ExplicitSpecialization); 5204 MarkUnusedFileScopedDecl(InstantiationVar); 5205 } else { 5206 assert(isa<CXXRecordDecl>(Member) && "Only member classes remain"); 5207 CXXRecordDecl *InstantiationClass = cast<CXXRecordDecl>(Instantiation); 5208 if (InstantiationClass->getTemplateSpecializationKind() == 5209 TSK_ImplicitInstantiation) { 5210 InstantiationClass->setTemplateSpecializationKind( 5211 TSK_ExplicitSpecialization); 5212 InstantiationClass->setLocation(Member->getLocation()); 5213 } 5214 5215 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass( 5216 cast<CXXRecordDecl>(InstantiatedFrom), 5217 TSK_ExplicitSpecialization); 5218 } 5219 5220 // Save the caller the trouble of having to figure out which declaration 5221 // this specialization matches. 5222 Previous.clear(); 5223 Previous.addDecl(Instantiation); 5224 return false; 5225} 5226 5227/// \brief Check the scope of an explicit instantiation. 5228/// 5229/// \returns true if a serious error occurs, false otherwise. 5230static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, 5231 SourceLocation InstLoc, 5232 bool WasQualifiedName) { 5233 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext(); 5234 DeclContext *CurContext = S.CurContext->getRedeclContext(); 5235 5236 if (CurContext->isRecord()) { 5237 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class) 5238 << D; 5239 return true; 5240 } 5241 5242 // C++0x [temp.explicit]p2: 5243 // An explicit instantiation shall appear in an enclosing namespace of its 5244 // template. 5245 // 5246 // This is DR275, which we do not retroactively apply to C++98/03. 5247 if (S.getLangOptions().CPlusPlus0x && 5248 !CurContext->Encloses(OrigContext)) { 5249 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) 5250 S.Diag(InstLoc, 5251 S.getLangOptions().CPlusPlus0x? 5252 diag::err_explicit_instantiation_out_of_scope 5253 : diag::warn_explicit_instantiation_out_of_scope_0x) 5254 << D << NS; 5255 else 5256 S.Diag(InstLoc, 5257 S.getLangOptions().CPlusPlus0x? 5258 diag::err_explicit_instantiation_must_be_global 5259 : diag::warn_explicit_instantiation_out_of_scope_0x) 5260 << D; 5261 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here); 5262 return false; 5263 } 5264 5265 // C++0x [temp.explicit]p2: 5266 // If the name declared in the explicit instantiation is an unqualified 5267 // name, the explicit instantiation shall appear in the namespace where 5268 // its template is declared or, if that namespace is inline (7.3.1), any 5269 // namespace from its enclosing namespace set. 5270 if (WasQualifiedName) 5271 return false; 5272 5273 if (CurContext->InEnclosingNamespaceSetOf(OrigContext)) 5274 return false; 5275 5276 S.Diag(InstLoc, 5277 S.getLangOptions().CPlusPlus0x? 5278 diag::err_explicit_instantiation_unqualified_wrong_namespace 5279 : diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x) 5280 << D << OrigContext; 5281 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here); 5282 return false; 5283} 5284 5285/// \brief Determine whether the given scope specifier has a template-id in it. 5286static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) { 5287 if (!SS.isSet()) 5288 return false; 5289 5290 // C++0x [temp.explicit]p2: 5291 // If the explicit instantiation is for a member function, a member class 5292 // or a static data member of a class template specialization, the name of 5293 // the class template specialization in the qualified-id for the member 5294 // name shall be a simple-template-id. 5295 // 5296 // C++98 has the same restriction, just worded differently. 5297 for (NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep(); 5298 NNS; NNS = NNS->getPrefix()) 5299 if (const Type *T = NNS->getAsType()) 5300 if (isa<TemplateSpecializationType>(T)) 5301 return true; 5302 5303 return false; 5304} 5305 5306// Explicit instantiation of a class template specialization 5307DeclResult 5308Sema::ActOnExplicitInstantiation(Scope *S, 5309 SourceLocation ExternLoc, 5310 SourceLocation TemplateLoc, 5311 unsigned TagSpec, 5312 SourceLocation KWLoc, 5313 const CXXScopeSpec &SS, 5314 TemplateTy TemplateD, 5315 SourceLocation TemplateNameLoc, 5316 SourceLocation LAngleLoc, 5317 ASTTemplateArgsPtr TemplateArgsIn, 5318 SourceLocation RAngleLoc, 5319 AttributeList *Attr) { 5320 // Find the class template we're specializing 5321 TemplateName Name = TemplateD.getAsVal<TemplateName>(); 5322 ClassTemplateDecl *ClassTemplate 5323 = cast<ClassTemplateDecl>(Name.getAsTemplateDecl()); 5324 5325 // Check that the specialization uses the same tag kind as the 5326 // original template. 5327 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 5328 assert(Kind != TTK_Enum && 5329 "Invalid enum tag in class template explicit instantiation!"); 5330 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 5331 Kind, KWLoc, 5332 *ClassTemplate->getIdentifier())) { 5333 Diag(KWLoc, diag::err_use_with_wrong_tag) 5334 << ClassTemplate 5335 << FixItHint::CreateReplacement(KWLoc, 5336 ClassTemplate->getTemplatedDecl()->getKindName()); 5337 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 5338 diag::note_previous_use); 5339 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 5340 } 5341 5342 // C++0x [temp.explicit]p2: 5343 // There are two forms of explicit instantiation: an explicit instantiation 5344 // definition and an explicit instantiation declaration. An explicit 5345 // instantiation declaration begins with the extern keyword. [...] 5346 TemplateSpecializationKind TSK 5347 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 5348 : TSK_ExplicitInstantiationDeclaration; 5349 5350 // Translate the parser's template argument list in our AST format. 5351 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 5352 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 5353 5354 // Check that the template argument list is well-formed for this 5355 // template. 5356 llvm::SmallVector<TemplateArgument, 4> Converted; 5357 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, 5358 TemplateArgs, false, Converted)) 5359 return true; 5360 5361 assert((Converted.size() == ClassTemplate->getTemplateParameters()->size()) && 5362 "Converted template argument list is too short!"); 5363 5364 // Find the class template specialization declaration that 5365 // corresponds to these arguments. 5366 void *InsertPos = 0; 5367 ClassTemplateSpecializationDecl *PrevDecl 5368 = ClassTemplate->findSpecialization(Converted.data(), 5369 Converted.size(), InsertPos); 5370 5371 TemplateSpecializationKind PrevDecl_TSK 5372 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared; 5373 5374 // C++0x [temp.explicit]p2: 5375 // [...] An explicit instantiation shall appear in an enclosing 5376 // namespace of its template. [...] 5377 // 5378 // This is C++ DR 275. 5379 if (CheckExplicitInstantiationScope(*this, ClassTemplate, TemplateNameLoc, 5380 SS.isSet())) 5381 return true; 5382 5383 ClassTemplateSpecializationDecl *Specialization = 0; 5384 5385 bool HasNoEffect = false; 5386 if (PrevDecl) { 5387 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK, 5388 PrevDecl, PrevDecl_TSK, 5389 PrevDecl->getPointOfInstantiation(), 5390 HasNoEffect)) 5391 return PrevDecl; 5392 5393 // Even though HasNoEffect == true means that this explicit instantiation 5394 // has no effect on semantics, we go on to put its syntax in the AST. 5395 5396 if (PrevDecl_TSK == TSK_ImplicitInstantiation || 5397 PrevDecl_TSK == TSK_Undeclared) { 5398 // Since the only prior class template specialization with these 5399 // arguments was referenced but not declared, reuse that 5400 // declaration node as our own, updating the source location 5401 // for the template name to reflect our new declaration. 5402 // (Other source locations will be updated later.) 5403 Specialization = PrevDecl; 5404 Specialization->setLocation(TemplateNameLoc); 5405 PrevDecl = 0; 5406 } 5407 } 5408 5409 if (!Specialization) { 5410 // Create a new class template specialization declaration node for 5411 // this explicit specialization. 5412 Specialization 5413 = ClassTemplateSpecializationDecl::Create(Context, Kind, 5414 ClassTemplate->getDeclContext(), 5415 TemplateNameLoc, 5416 ClassTemplate, 5417 Converted.data(), 5418 Converted.size(), 5419 PrevDecl); 5420 SetNestedNameSpecifier(Specialization, SS); 5421 5422 if (!HasNoEffect && !PrevDecl) { 5423 // Insert the new specialization. 5424 ClassTemplate->AddSpecialization(Specialization, InsertPos); 5425 } 5426 } 5427 5428 // Build the fully-sugared type for this explicit instantiation as 5429 // the user wrote in the explicit instantiation itself. This means 5430 // that we'll pretty-print the type retrieved from the 5431 // specialization's declaration the way that the user actually wrote 5432 // the explicit instantiation, rather than formatting the name based 5433 // on the "canonical" representation used to store the template 5434 // arguments in the specialization. 5435 TypeSourceInfo *WrittenTy 5436 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc, 5437 TemplateArgs, 5438 Context.getTypeDeclType(Specialization)); 5439 Specialization->setTypeAsWritten(WrittenTy); 5440 TemplateArgsIn.release(); 5441 5442 // Set source locations for keywords. 5443 Specialization->setExternLoc(ExternLoc); 5444 Specialization->setTemplateKeywordLoc(TemplateLoc); 5445 5446 // Add the explicit instantiation into its lexical context. However, 5447 // since explicit instantiations are never found by name lookup, we 5448 // just put it into the declaration context directly. 5449 Specialization->setLexicalDeclContext(CurContext); 5450 CurContext->addDecl(Specialization); 5451 5452 // Syntax is now OK, so return if it has no other effect on semantics. 5453 if (HasNoEffect) { 5454 // Set the template specialization kind. 5455 Specialization->setTemplateSpecializationKind(TSK); 5456 return Specialization; 5457 } 5458 5459 // C++ [temp.explicit]p3: 5460 // A definition of a class template or class member template 5461 // shall be in scope at the point of the explicit instantiation of 5462 // the class template or class member template. 5463 // 5464 // This check comes when we actually try to perform the 5465 // instantiation. 5466 ClassTemplateSpecializationDecl *Def 5467 = cast_or_null<ClassTemplateSpecializationDecl>( 5468 Specialization->getDefinition()); 5469 if (!Def) 5470 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK); 5471 else if (TSK == TSK_ExplicitInstantiationDefinition) { 5472 MarkVTableUsed(TemplateNameLoc, Specialization, true); 5473 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation()); 5474 } 5475 5476 // Instantiate the members of this class template specialization. 5477 Def = cast_or_null<ClassTemplateSpecializationDecl>( 5478 Specialization->getDefinition()); 5479 if (Def) { 5480 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind(); 5481 5482 // Fix a TSK_ExplicitInstantiationDeclaration followed by a 5483 // TSK_ExplicitInstantiationDefinition 5484 if (Old_TSK == TSK_ExplicitInstantiationDeclaration && 5485 TSK == TSK_ExplicitInstantiationDefinition) 5486 Def->setTemplateSpecializationKind(TSK); 5487 5488 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK); 5489 } 5490 5491 // Set the template specialization kind. 5492 Specialization->setTemplateSpecializationKind(TSK); 5493 return Specialization; 5494} 5495 5496// Explicit instantiation of a member class of a class template. 5497DeclResult 5498Sema::ActOnExplicitInstantiation(Scope *S, 5499 SourceLocation ExternLoc, 5500 SourceLocation TemplateLoc, 5501 unsigned TagSpec, 5502 SourceLocation KWLoc, 5503 CXXScopeSpec &SS, 5504 IdentifierInfo *Name, 5505 SourceLocation NameLoc, 5506 AttributeList *Attr) { 5507 5508 bool Owned = false; 5509 bool IsDependent = false; 5510 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, 5511 KWLoc, SS, Name, NameLoc, Attr, AS_none, 5512 MultiTemplateParamsArg(*this, 0, 0), 5513 Owned, IsDependent, false, false, 5514 TypeResult()); 5515 assert(!IsDependent && "explicit instantiation of dependent name not yet handled"); 5516 5517 if (!TagD) 5518 return true; 5519 5520 TagDecl *Tag = cast<TagDecl>(TagD); 5521 if (Tag->isEnum()) { 5522 Diag(TemplateLoc, diag::err_explicit_instantiation_enum) 5523 << Context.getTypeDeclType(Tag); 5524 return true; 5525 } 5526 5527 if (Tag->isInvalidDecl()) 5528 return true; 5529 5530 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag); 5531 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 5532 if (!Pattern) { 5533 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type) 5534 << Context.getTypeDeclType(Record); 5535 Diag(Record->getLocation(), diag::note_nontemplate_decl_here); 5536 return true; 5537 } 5538 5539 // C++0x [temp.explicit]p2: 5540 // If the explicit instantiation is for a class or member class, the 5541 // elaborated-type-specifier in the declaration shall include a 5542 // simple-template-id. 5543 // 5544 // C++98 has the same restriction, just worded differently. 5545 if (!ScopeSpecifierHasTemplateId(SS)) 5546 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id) 5547 << Record << SS.getRange(); 5548 5549 // C++0x [temp.explicit]p2: 5550 // There are two forms of explicit instantiation: an explicit instantiation 5551 // definition and an explicit instantiation declaration. An explicit 5552 // instantiation declaration begins with the extern keyword. [...] 5553 TemplateSpecializationKind TSK 5554 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 5555 : TSK_ExplicitInstantiationDeclaration; 5556 5557 // C++0x [temp.explicit]p2: 5558 // [...] An explicit instantiation shall appear in an enclosing 5559 // namespace of its template. [...] 5560 // 5561 // This is C++ DR 275. 5562 CheckExplicitInstantiationScope(*this, Record, NameLoc, true); 5563 5564 // Verify that it is okay to explicitly instantiate here. 5565 CXXRecordDecl *PrevDecl 5566 = cast_or_null<CXXRecordDecl>(Record->getPreviousDeclaration()); 5567 if (!PrevDecl && Record->getDefinition()) 5568 PrevDecl = Record; 5569 if (PrevDecl) { 5570 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo(); 5571 bool HasNoEffect = false; 5572 assert(MSInfo && "No member specialization information?"); 5573 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK, 5574 PrevDecl, 5575 MSInfo->getTemplateSpecializationKind(), 5576 MSInfo->getPointOfInstantiation(), 5577 HasNoEffect)) 5578 return true; 5579 if (HasNoEffect) 5580 return TagD; 5581 } 5582 5583 CXXRecordDecl *RecordDef 5584 = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 5585 if (!RecordDef) { 5586 // C++ [temp.explicit]p3: 5587 // A definition of a member class of a class template shall be in scope 5588 // at the point of an explicit instantiation of the member class. 5589 CXXRecordDecl *Def 5590 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition()); 5591 if (!Def) { 5592 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member) 5593 << 0 << Record->getDeclName() << Record->getDeclContext(); 5594 Diag(Pattern->getLocation(), diag::note_forward_declaration) 5595 << Pattern; 5596 return true; 5597 } else { 5598 if (InstantiateClass(NameLoc, Record, Def, 5599 getTemplateInstantiationArgs(Record), 5600 TSK)) 5601 return true; 5602 5603 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 5604 if (!RecordDef) 5605 return true; 5606 } 5607 } 5608 5609 // Instantiate all of the members of the class. 5610 InstantiateClassMembers(NameLoc, RecordDef, 5611 getTemplateInstantiationArgs(Record), TSK); 5612 5613 if (TSK == TSK_ExplicitInstantiationDefinition) 5614 MarkVTableUsed(NameLoc, RecordDef, true); 5615 5616 // FIXME: We don't have any representation for explicit instantiations of 5617 // member classes. Such a representation is not needed for compilation, but it 5618 // should be available for clients that want to see all of the declarations in 5619 // the source code. 5620 return TagD; 5621} 5622 5623DeclResult Sema::ActOnExplicitInstantiation(Scope *S, 5624 SourceLocation ExternLoc, 5625 SourceLocation TemplateLoc, 5626 Declarator &D) { 5627 // Explicit instantiations always require a name. 5628 // TODO: check if/when DNInfo should replace Name. 5629 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5630 DeclarationName Name = NameInfo.getName(); 5631 if (!Name) { 5632 if (!D.isInvalidType()) 5633 Diag(D.getDeclSpec().getSourceRange().getBegin(), 5634 diag::err_explicit_instantiation_requires_name) 5635 << D.getDeclSpec().getSourceRange() 5636 << D.getSourceRange(); 5637 5638 return true; 5639 } 5640 5641 // The scope passed in may not be a decl scope. Zip up the scope tree until 5642 // we find one that is. 5643 while ((S->getFlags() & Scope::DeclScope) == 0 || 5644 (S->getFlags() & Scope::TemplateParamScope) != 0) 5645 S = S->getParent(); 5646 5647 // Determine the type of the declaration. 5648 TypeSourceInfo *T = GetTypeForDeclarator(D, S); 5649 QualType R = T->getType(); 5650 if (R.isNull()) 5651 return true; 5652 5653 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5654 // Cannot explicitly instantiate a typedef. 5655 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef) 5656 << Name; 5657 return true; 5658 } 5659 5660 // C++0x [temp.explicit]p1: 5661 // [...] An explicit instantiation of a function template shall not use the 5662 // inline or constexpr specifiers. 5663 // Presumably, this also applies to member functions of class templates as 5664 // well. 5665 if (D.getDeclSpec().isInlineSpecified() && getLangOptions().CPlusPlus0x) 5666 Diag(D.getDeclSpec().getInlineSpecLoc(), 5667 diag::err_explicit_instantiation_inline) 5668 <<FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 5669 5670 // FIXME: check for constexpr specifier. 5671 5672 // C++0x [temp.explicit]p2: 5673 // There are two forms of explicit instantiation: an explicit instantiation 5674 // definition and an explicit instantiation declaration. An explicit 5675 // instantiation declaration begins with the extern keyword. [...] 5676 TemplateSpecializationKind TSK 5677 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 5678 : TSK_ExplicitInstantiationDeclaration; 5679 5680 LookupResult Previous(*this, NameInfo, LookupOrdinaryName); 5681 LookupParsedName(Previous, S, &D.getCXXScopeSpec()); 5682 5683 if (!R->isFunctionType()) { 5684 // C++ [temp.explicit]p1: 5685 // A [...] static data member of a class template can be explicitly 5686 // instantiated from the member definition associated with its class 5687 // template. 5688 if (Previous.isAmbiguous()) 5689 return true; 5690 5691 VarDecl *Prev = Previous.getAsSingle<VarDecl>(); 5692 if (!Prev || !Prev->isStaticDataMember()) { 5693 // We expect to see a data data member here. 5694 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known) 5695 << Name; 5696 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 5697 P != PEnd; ++P) 5698 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here); 5699 return true; 5700 } 5701 5702 if (!Prev->getInstantiatedFromStaticDataMember()) { 5703 // FIXME: Check for explicit specialization? 5704 Diag(D.getIdentifierLoc(), 5705 diag::err_explicit_instantiation_data_member_not_instantiated) 5706 << Prev; 5707 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here); 5708 // FIXME: Can we provide a note showing where this was declared? 5709 return true; 5710 } 5711 5712 // C++0x [temp.explicit]p2: 5713 // If the explicit instantiation is for a member function, a member class 5714 // or a static data member of a class template specialization, the name of 5715 // the class template specialization in the qualified-id for the member 5716 // name shall be a simple-template-id. 5717 // 5718 // C++98 has the same restriction, just worded differently. 5719 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec())) 5720 Diag(D.getIdentifierLoc(), 5721 diag::ext_explicit_instantiation_without_qualified_id) 5722 << Prev << D.getCXXScopeSpec().getRange(); 5723 5724 // Check the scope of this explicit instantiation. 5725 CheckExplicitInstantiationScope(*this, Prev, D.getIdentifierLoc(), true); 5726 5727 // Verify that it is okay to explicitly instantiate here. 5728 MemberSpecializationInfo *MSInfo = Prev->getMemberSpecializationInfo(); 5729 assert(MSInfo && "Missing static data member specialization info?"); 5730 bool HasNoEffect = false; 5731 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev, 5732 MSInfo->getTemplateSpecializationKind(), 5733 MSInfo->getPointOfInstantiation(), 5734 HasNoEffect)) 5735 return true; 5736 if (HasNoEffect) 5737 return (Decl*) 0; 5738 5739 // Instantiate static data member. 5740 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 5741 if (TSK == TSK_ExplicitInstantiationDefinition) 5742 InstantiateStaticDataMemberDefinition(D.getIdentifierLoc(), Prev); 5743 5744 // FIXME: Create an ExplicitInstantiation node? 5745 return (Decl*) 0; 5746 } 5747 5748 // If the declarator is a template-id, translate the parser's template 5749 // argument list into our AST format. 5750 bool HasExplicitTemplateArgs = false; 5751 TemplateArgumentListInfo TemplateArgs; 5752 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5753 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 5754 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 5755 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 5756 ASTTemplateArgsPtr TemplateArgsPtr(*this, 5757 TemplateId->getTemplateArgs(), 5758 TemplateId->NumArgs); 5759 translateTemplateArguments(TemplateArgsPtr, TemplateArgs); 5760 HasExplicitTemplateArgs = true; 5761 TemplateArgsPtr.release(); 5762 } 5763 5764 // C++ [temp.explicit]p1: 5765 // A [...] function [...] can be explicitly instantiated from its template. 5766 // A member function [...] of a class template can be explicitly 5767 // instantiated from the member definition associated with its class 5768 // template. 5769 UnresolvedSet<8> Matches; 5770 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 5771 P != PEnd; ++P) { 5772 NamedDecl *Prev = *P; 5773 if (!HasExplicitTemplateArgs) { 5774 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) { 5775 if (Context.hasSameUnqualifiedType(Method->getType(), R)) { 5776 Matches.clear(); 5777 5778 Matches.addDecl(Method, P.getAccess()); 5779 if (Method->getTemplateSpecializationKind() == TSK_Undeclared) 5780 break; 5781 } 5782 } 5783 } 5784 5785 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev); 5786 if (!FunTmpl) 5787 continue; 5788 5789 TemplateDeductionInfo Info(Context, D.getIdentifierLoc()); 5790 FunctionDecl *Specialization = 0; 5791 if (TemplateDeductionResult TDK 5792 = DeduceTemplateArguments(FunTmpl, 5793 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 5794 R, Specialization, Info)) { 5795 // FIXME: Keep track of almost-matches? 5796 (void)TDK; 5797 continue; 5798 } 5799 5800 Matches.addDecl(Specialization, P.getAccess()); 5801 } 5802 5803 // Find the most specialized function template specialization. 5804 UnresolvedSetIterator Result 5805 = getMostSpecialized(Matches.begin(), Matches.end(), TPOC_Other, 0, 5806 D.getIdentifierLoc(), 5807 PDiag(diag::err_explicit_instantiation_not_known) << Name, 5808 PDiag(diag::err_explicit_instantiation_ambiguous) << Name, 5809 PDiag(diag::note_explicit_instantiation_candidate)); 5810 5811 if (Result == Matches.end()) 5812 return true; 5813 5814 // Ignore access control bits, we don't need them for redeclaration checking. 5815 FunctionDecl *Specialization = cast<FunctionDecl>(*Result); 5816 5817 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) { 5818 Diag(D.getIdentifierLoc(), 5819 diag::err_explicit_instantiation_member_function_not_instantiated) 5820 << Specialization 5821 << (Specialization->getTemplateSpecializationKind() == 5822 TSK_ExplicitSpecialization); 5823 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here); 5824 return true; 5825 } 5826 5827 FunctionDecl *PrevDecl = Specialization->getPreviousDeclaration(); 5828 if (!PrevDecl && Specialization->isThisDeclarationADefinition()) 5829 PrevDecl = Specialization; 5830 5831 if (PrevDecl) { 5832 bool HasNoEffect = false; 5833 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, 5834 PrevDecl, 5835 PrevDecl->getTemplateSpecializationKind(), 5836 PrevDecl->getPointOfInstantiation(), 5837 HasNoEffect)) 5838 return true; 5839 5840 // FIXME: We may still want to build some representation of this 5841 // explicit specialization. 5842 if (HasNoEffect) 5843 return (Decl*) 0; 5844 } 5845 5846 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 5847 5848 if (TSK == TSK_ExplicitInstantiationDefinition) 5849 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization); 5850 5851 // C++0x [temp.explicit]p2: 5852 // If the explicit instantiation is for a member function, a member class 5853 // or a static data member of a class template specialization, the name of 5854 // the class template specialization in the qualified-id for the member 5855 // name shall be a simple-template-id. 5856 // 5857 // C++98 has the same restriction, just worded differently. 5858 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate(); 5859 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId && !FunTmpl && 5860 D.getCXXScopeSpec().isSet() && 5861 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec())) 5862 Diag(D.getIdentifierLoc(), 5863 diag::ext_explicit_instantiation_without_qualified_id) 5864 << Specialization << D.getCXXScopeSpec().getRange(); 5865 5866 CheckExplicitInstantiationScope(*this, 5867 FunTmpl? (NamedDecl *)FunTmpl 5868 : Specialization->getInstantiatedFromMemberFunction(), 5869 D.getIdentifierLoc(), 5870 D.getCXXScopeSpec().isSet()); 5871 5872 // FIXME: Create some kind of ExplicitInstantiationDecl here. 5873 return (Decl*) 0; 5874} 5875 5876TypeResult 5877Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 5878 const CXXScopeSpec &SS, IdentifierInfo *Name, 5879 SourceLocation TagLoc, SourceLocation NameLoc) { 5880 // This has to hold, because SS is expected to be defined. 5881 assert(Name && "Expected a name in a dependent tag"); 5882 5883 NestedNameSpecifier *NNS 5884 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 5885 if (!NNS) 5886 return true; 5887 5888 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 5889 5890 if (TUK == TUK_Declaration || TUK == TUK_Definition) { 5891 Diag(NameLoc, diag::err_dependent_tag_decl) 5892 << (TUK == TUK_Definition) << Kind << SS.getRange(); 5893 return true; 5894 } 5895 5896 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 5897 return ParsedType::make(Context.getDependentNameType(Kwd, NNS, Name)); 5898} 5899 5900TypeResult 5901Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 5902 const CXXScopeSpec &SS, const IdentifierInfo &II, 5903 SourceLocation IdLoc) { 5904 NestedNameSpecifier *NNS 5905 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 5906 if (!NNS) 5907 return true; 5908 5909 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() && 5910 !getLangOptions().CPlusPlus0x) 5911 Diag(TypenameLoc, diag::ext_typename_outside_of_template) 5912 << FixItHint::CreateRemoval(TypenameLoc); 5913 5914 QualType T = CheckTypenameType(ETK_Typename, NNS, II, 5915 TypenameLoc, SS.getRange(), IdLoc); 5916 if (T.isNull()) 5917 return true; 5918 5919 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T); 5920 if (isa<DependentNameType>(T)) { 5921 DependentNameTypeLoc TL = cast<DependentNameTypeLoc>(TSI->getTypeLoc()); 5922 TL.setKeywordLoc(TypenameLoc); 5923 TL.setQualifierRange(SS.getRange()); 5924 TL.setNameLoc(IdLoc); 5925 } else { 5926 ElaboratedTypeLoc TL = cast<ElaboratedTypeLoc>(TSI->getTypeLoc()); 5927 TL.setKeywordLoc(TypenameLoc); 5928 TL.setQualifierRange(SS.getRange()); 5929 cast<TypeSpecTypeLoc>(TL.getNamedTypeLoc()).setNameLoc(IdLoc); 5930 } 5931 5932 return CreateParsedType(T, TSI); 5933} 5934 5935TypeResult 5936Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 5937 const CXXScopeSpec &SS, 5938 SourceLocation TemplateLoc, 5939 TemplateTy TemplateIn, 5940 SourceLocation TemplateNameLoc, 5941 SourceLocation LAngleLoc, 5942 ASTTemplateArgsPtr TemplateArgsIn, 5943 SourceLocation RAngleLoc) { 5944 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent() && 5945 !getLangOptions().CPlusPlus0x) 5946 Diag(TypenameLoc, diag::ext_typename_outside_of_template) 5947 << FixItHint::CreateRemoval(TypenameLoc); 5948 5949 // Translate the parser's template argument list in our AST format. 5950 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 5951 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 5952 5953 TemplateName Template = TemplateIn.get(); 5954 5955 if (computeDeclContext(SS, false)) { 5956 // If we can compute a declaration context, then the "typename" 5957 // keyword was superfluous. Just build an ElaboratedType to keep 5958 // track of the nested-name-specifier. 5959 5960 QualType T = CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs); 5961 if (T.isNull()) 5962 return true; 5963 5964 // Provide source-location information for the template specialization 5965 // type. 5966 TypeLocBuilder Builder; 5967 TemplateSpecializationTypeLoc SpecTL 5968 = Builder.push<TemplateSpecializationTypeLoc>(T); 5969 5970 // FIXME: No place to set the location of the 'template' keyword! 5971 SpecTL.setLAngleLoc(LAngleLoc); 5972 SpecTL.setRAngleLoc(RAngleLoc); 5973 SpecTL.setTemplateNameLoc(TemplateNameLoc); 5974 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 5975 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 5976 5977 // FIXME: This is a hack. We really want to push the nested-name-specifier 5978 // into TemplateSpecializationType. 5979 5980 /* Note: NNS already embedded in template specialization type T. */ 5981 T = Context.getElaboratedType(ETK_Typename, /*NNS=*/0, T); 5982 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T); 5983 TL.setKeywordLoc(TypenameLoc); 5984 TL.setQualifierRange(SS.getRange()); 5985 5986 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T); 5987 return CreateParsedType(T, TSI); 5988 } 5989 5990 // Construct a dependent template specialization type. 5991 DependentTemplateName *DTN = Template.getAsDependentTemplateName(); 5992 assert(DTN && "dependent template has non-dependent name?"); 5993 assert(DTN->getQualifier() 5994 == static_cast<NestedNameSpecifier*>(SS.getScopeRep())); 5995 QualType T = Context.getDependentTemplateSpecializationType(ETK_Typename, 5996 DTN->getQualifier(), 5997 DTN->getIdentifier(), 5998 TemplateArgs); 5999 6000 // Create source-location information for this type. 6001 TypeLocBuilder Builder; 6002 DependentTemplateSpecializationTypeLoc SpecTL 6003 = Builder.push<DependentTemplateSpecializationTypeLoc>(T); 6004 SpecTL.setLAngleLoc(LAngleLoc); 6005 SpecTL.setRAngleLoc(RAngleLoc); 6006 SpecTL.setKeywordLoc(TypenameLoc); 6007 SpecTL.setNameLoc(TemplateNameLoc); 6008 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 6009 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 6010 6011 // FIXME: Nested-name-specifier source locations. 6012 SpecTL.setQualifierRange(SS.getRange()); 6013 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 6014} 6015 6016 6017/// \brief Build the type that describes a C++ typename specifier, 6018/// e.g., "typename T::type". 6019QualType 6020Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword, 6021 NestedNameSpecifier *NNS, const IdentifierInfo &II, 6022 SourceLocation KeywordLoc, SourceRange NNSRange, 6023 SourceLocation IILoc) { 6024 CXXScopeSpec SS; 6025 SS.MakeTrivial(Context, NNS, NNSRange); 6026 6027 DeclContext *Ctx = computeDeclContext(SS); 6028 if (!Ctx) { 6029 // If the nested-name-specifier is dependent and couldn't be 6030 // resolved to a type, build a typename type. 6031 assert(NNS->isDependent()); 6032 return Context.getDependentNameType(Keyword, NNS, &II); 6033 } 6034 6035 // If the nested-name-specifier refers to the current instantiation, 6036 // the "typename" keyword itself is superfluous. In C++03, the 6037 // program is actually ill-formed. However, DR 382 (in C++0x CD1) 6038 // allows such extraneous "typename" keywords, and we retroactively 6039 // apply this DR to C++03 code with only a warning. In any case we continue. 6040 6041 if (RequireCompleteDeclContext(SS, Ctx)) 6042 return QualType(); 6043 6044 DeclarationName Name(&II); 6045 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName); 6046 LookupQualifiedName(Result, Ctx); 6047 unsigned DiagID = 0; 6048 Decl *Referenced = 0; 6049 switch (Result.getResultKind()) { 6050 case LookupResult::NotFound: 6051 DiagID = diag::err_typename_nested_not_found; 6052 break; 6053 6054 case LookupResult::FoundUnresolvedValue: { 6055 // We found a using declaration that is a value. Most likely, the using 6056 // declaration itself is meant to have the 'typename' keyword. 6057 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(), 6058 IILoc); 6059 Diag(IILoc, diag::err_typename_refers_to_using_value_decl) 6060 << Name << Ctx << FullRange; 6061 if (UnresolvedUsingValueDecl *Using 6062 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){ 6063 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc(); 6064 Diag(Loc, diag::note_using_value_decl_missing_typename) 6065 << FixItHint::CreateInsertion(Loc, "typename "); 6066 } 6067 } 6068 // Fall through to create a dependent typename type, from which we can recover 6069 // better. 6070 6071 case LookupResult::NotFoundInCurrentInstantiation: 6072 // Okay, it's a member of an unknown instantiation. 6073 return Context.getDependentNameType(Keyword, NNS, &II); 6074 6075 case LookupResult::Found: 6076 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) { 6077 // We found a type. Build an ElaboratedType, since the 6078 // typename-specifier was just sugar. 6079 return Context.getElaboratedType(ETK_Typename, NNS, 6080 Context.getTypeDeclType(Type)); 6081 } 6082 6083 DiagID = diag::err_typename_nested_not_type; 6084 Referenced = Result.getFoundDecl(); 6085 break; 6086 6087 6088 llvm_unreachable("unresolved using decl in non-dependent context"); 6089 return QualType(); 6090 6091 case LookupResult::FoundOverloaded: 6092 DiagID = diag::err_typename_nested_not_type; 6093 Referenced = *Result.begin(); 6094 break; 6095 6096 case LookupResult::Ambiguous: 6097 return QualType(); 6098 } 6099 6100 // If we get here, it's because name lookup did not find a 6101 // type. Emit an appropriate diagnostic and return an error. 6102 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : NNSRange.getBegin(), 6103 IILoc); 6104 Diag(IILoc, DiagID) << FullRange << Name << Ctx; 6105 if (Referenced) 6106 Diag(Referenced->getLocation(), diag::note_typename_refers_here) 6107 << Name; 6108 return QualType(); 6109} 6110 6111namespace { 6112 // See Sema::RebuildTypeInCurrentInstantiation 6113 class CurrentInstantiationRebuilder 6114 : public TreeTransform<CurrentInstantiationRebuilder> { 6115 SourceLocation Loc; 6116 DeclarationName Entity; 6117 6118 public: 6119 typedef TreeTransform<CurrentInstantiationRebuilder> inherited; 6120 6121 CurrentInstantiationRebuilder(Sema &SemaRef, 6122 SourceLocation Loc, 6123 DeclarationName Entity) 6124 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef), 6125 Loc(Loc), Entity(Entity) { } 6126 6127 /// \brief Determine whether the given type \p T has already been 6128 /// transformed. 6129 /// 6130 /// For the purposes of type reconstruction, a type has already been 6131 /// transformed if it is NULL or if it is not dependent. 6132 bool AlreadyTransformed(QualType T) { 6133 return T.isNull() || !T->isDependentType(); 6134 } 6135 6136 /// \brief Returns the location of the entity whose type is being 6137 /// rebuilt. 6138 SourceLocation getBaseLocation() { return Loc; } 6139 6140 /// \brief Returns the name of the entity whose type is being rebuilt. 6141 DeclarationName getBaseEntity() { return Entity; } 6142 6143 /// \brief Sets the "base" location and entity when that 6144 /// information is known based on another transformation. 6145 void setBase(SourceLocation Loc, DeclarationName Entity) { 6146 this->Loc = Loc; 6147 this->Entity = Entity; 6148 } 6149 }; 6150} 6151 6152/// \brief Rebuilds a type within the context of the current instantiation. 6153/// 6154/// The type \p T is part of the type of an out-of-line member definition of 6155/// a class template (or class template partial specialization) that was parsed 6156/// and constructed before we entered the scope of the class template (or 6157/// partial specialization thereof). This routine will rebuild that type now 6158/// that we have entered the declarator's scope, which may produce different 6159/// canonical types, e.g., 6160/// 6161/// \code 6162/// template<typename T> 6163/// struct X { 6164/// typedef T* pointer; 6165/// pointer data(); 6166/// }; 6167/// 6168/// template<typename T> 6169/// typename X<T>::pointer X<T>::data() { ... } 6170/// \endcode 6171/// 6172/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType, 6173/// since we do not know that we can look into X<T> when we parsed the type. 6174/// This function will rebuild the type, performing the lookup of "pointer" 6175/// in X<T> and returning an ElaboratedType whose canonical type is the same 6176/// as the canonical type of T*, allowing the return types of the out-of-line 6177/// definition and the declaration to match. 6178TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 6179 SourceLocation Loc, 6180 DeclarationName Name) { 6181 if (!T || !T->getType()->isDependentType()) 6182 return T; 6183 6184 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name); 6185 return Rebuilder.TransformType(T); 6186} 6187 6188ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) { 6189 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(), 6190 DeclarationName()); 6191 return Rebuilder.TransformExpr(E); 6192} 6193 6194bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) { 6195 if (SS.isInvalid()) 6196 return true; 6197 6198 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 6199 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(), 6200 DeclarationName()); 6201 NestedNameSpecifierLoc Rebuilt 6202 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc); 6203 if (!Rebuilt) 6204 return true; 6205 6206 SS.Adopt(Rebuilt); 6207 return false; 6208} 6209 6210/// \brief Produces a formatted string that describes the binding of 6211/// template parameters to template arguments. 6212std::string 6213Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 6214 const TemplateArgumentList &Args) { 6215 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size()); 6216} 6217 6218std::string 6219Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 6220 const TemplateArgument *Args, 6221 unsigned NumArgs) { 6222 llvm::SmallString<128> Str; 6223 llvm::raw_svector_ostream Out(Str); 6224 6225 if (!Params || Params->size() == 0 || NumArgs == 0) 6226 return std::string(); 6227 6228 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 6229 if (I >= NumArgs) 6230 break; 6231 6232 if (I == 0) 6233 Out << "[with "; 6234 else 6235 Out << ", "; 6236 6237 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) { 6238 Out << Id->getName(); 6239 } else { 6240 Out << '$' << I; 6241 } 6242 6243 Out << " = "; 6244 Args[I].print(Context.PrintingPolicy, Out); 6245 } 6246 6247 Out << ']'; 6248 return Out.str(); 6249} 6250