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