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