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