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