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