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