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