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