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