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