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