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