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