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