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/Decl.h" 15 #include "clang/AST/DeclFriend.h" 16 #include "clang/AST/DeclTemplate.h" 17 #include "clang/AST/Expr.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/RecursiveASTVisitor.h" 20 #include "clang/AST/TemplateName.h" 21 #include "clang/AST/TypeVisitor.h" 22 #include "clang/Basic/Builtins.h" 23 #include "clang/Basic/DiagnosticSema.h" 24 #include "clang/Basic/LangOptions.h" 25 #include "clang/Basic/PartialDiagnostic.h" 26 #include "clang/Basic/SourceLocation.h" 27 #include "clang/Basic/Stack.h" 28 #include "clang/Basic/TargetInfo.h" 29 #include "clang/Sema/DeclSpec.h" 30 #include "clang/Sema/EnterExpressionEvaluationContext.h" 31 #include "clang/Sema/Initialization.h" 32 #include "clang/Sema/Lookup.h" 33 #include "clang/Sema/Overload.h" 34 #include "clang/Sema/ParsedTemplate.h" 35 #include "clang/Sema/Scope.h" 36 #include "clang/Sema/SemaInternal.h" 37 #include "clang/Sema/Template.h" 38 #include "clang/Sema/TemplateDeduction.h" 39 #include "llvm/ADT/SmallBitVector.h" 40 #include "llvm/ADT/SmallString.h" 41 #include "llvm/ADT/StringExtras.h" 42 43 #include <iterator> 44 #include <optional> 45 using namespace clang; 46 using namespace sema; 47 48 // Exported for use by Parser. 49 SourceRange 50 clang::getTemplateParamsRange(TemplateParameterList const * const *Ps, 51 unsigned N) { 52 if (!N) return SourceRange(); 53 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc()); 54 } 55 56 unsigned Sema::getTemplateDepth(Scope *S) const { 57 unsigned Depth = 0; 58 59 // Each template parameter scope represents one level of template parameter 60 // depth. 61 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope; 62 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) { 63 ++Depth; 64 } 65 66 // Note that there are template parameters with the given depth. 67 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); }; 68 69 // Look for parameters of an enclosing generic lambda. We don't create a 70 // template parameter scope for these. 71 for (FunctionScopeInfo *FSI : getFunctionScopes()) { 72 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) { 73 if (!LSI->TemplateParams.empty()) { 74 ParamsAtDepth(LSI->AutoTemplateParameterDepth); 75 break; 76 } 77 if (LSI->GLTemplateParameterList) { 78 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth()); 79 break; 80 } 81 } 82 } 83 84 // Look for parameters of an enclosing terse function template. We don't 85 // create a template parameter scope for these either. 86 for (const InventedTemplateParameterInfo &Info : 87 getInventedParameterInfos()) { 88 if (!Info.TemplateParams.empty()) { 89 ParamsAtDepth(Info.AutoTemplateParameterDepth); 90 break; 91 } 92 } 93 94 return Depth; 95 } 96 97 /// \brief Determine whether the declaration found is acceptable as the name 98 /// of a template and, if so, return that template declaration. Otherwise, 99 /// returns null. 100 /// 101 /// Note that this may return an UnresolvedUsingValueDecl if AllowDependent 102 /// is true. In all other cases it will return a TemplateDecl (or null). 103 NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D, 104 bool AllowFunctionTemplates, 105 bool AllowDependent) { 106 D = D->getUnderlyingDecl(); 107 108 if (isa<TemplateDecl>(D)) { 109 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D)) 110 return nullptr; 111 112 return D; 113 } 114 115 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) { 116 // C++ [temp.local]p1: 117 // Like normal (non-template) classes, class templates have an 118 // injected-class-name (Clause 9). The injected-class-name 119 // can be used with or without a template-argument-list. When 120 // it is used without a template-argument-list, it is 121 // equivalent to the injected-class-name followed by the 122 // template-parameters of the class template enclosed in 123 // <>. When it is used with a template-argument-list, it 124 // refers to the specified class template specialization, 125 // which could be the current specialization or another 126 // specialization. 127 if (Record->isInjectedClassName()) { 128 Record = cast<CXXRecordDecl>(Record->getDeclContext()); 129 if (Record->getDescribedClassTemplate()) 130 return Record->getDescribedClassTemplate(); 131 132 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record)) 133 return Spec->getSpecializedTemplate(); 134 } 135 136 return nullptr; 137 } 138 139 // 'using Dependent::foo;' can resolve to a template name. 140 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an 141 // injected-class-name). 142 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D)) 143 return D; 144 145 return nullptr; 146 } 147 148 void Sema::FilterAcceptableTemplateNames(LookupResult &R, 149 bool AllowFunctionTemplates, 150 bool AllowDependent) { 151 LookupResult::Filter filter = R.makeFilter(); 152 while (filter.hasNext()) { 153 NamedDecl *Orig = filter.next(); 154 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent)) 155 filter.erase(); 156 } 157 filter.done(); 158 } 159 160 bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R, 161 bool AllowFunctionTemplates, 162 bool AllowDependent, 163 bool AllowNonTemplateFunctions) { 164 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 165 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent)) 166 return true; 167 if (AllowNonTemplateFunctions && 168 isa<FunctionDecl>((*I)->getUnderlyingDecl())) 169 return true; 170 } 171 172 return false; 173 } 174 175 TemplateNameKind Sema::isTemplateName(Scope *S, 176 CXXScopeSpec &SS, 177 bool hasTemplateKeyword, 178 const UnqualifiedId &Name, 179 ParsedType ObjectTypePtr, 180 bool EnteringContext, 181 TemplateTy &TemplateResult, 182 bool &MemberOfUnknownSpecialization, 183 bool Disambiguation) { 184 assert(getLangOpts().CPlusPlus && "No template names in C!"); 185 186 DeclarationName TName; 187 MemberOfUnknownSpecialization = false; 188 189 switch (Name.getKind()) { 190 case UnqualifiedIdKind::IK_Identifier: 191 TName = DeclarationName(Name.Identifier); 192 break; 193 194 case UnqualifiedIdKind::IK_OperatorFunctionId: 195 TName = Context.DeclarationNames.getCXXOperatorName( 196 Name.OperatorFunctionId.Operator); 197 break; 198 199 case UnqualifiedIdKind::IK_LiteralOperatorId: 200 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier); 201 break; 202 203 default: 204 return TNK_Non_template; 205 } 206 207 QualType ObjectType = ObjectTypePtr.get(); 208 209 AssumedTemplateKind AssumedTemplate; 210 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName); 211 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext, 212 MemberOfUnknownSpecialization, SourceLocation(), 213 &AssumedTemplate, 214 /*AllowTypoCorrection=*/!Disambiguation)) 215 return TNK_Non_template; 216 217 if (AssumedTemplate != AssumedTemplateKind::None) { 218 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName)); 219 // Let the parser know whether we found nothing or found functions; if we 220 // found nothing, we want to more carefully check whether this is actually 221 // a function template name versus some other kind of undeclared identifier. 222 return AssumedTemplate == AssumedTemplateKind::FoundNothing 223 ? TNK_Undeclared_template 224 : TNK_Function_template; 225 } 226 227 if (R.empty()) 228 return TNK_Non_template; 229 230 NamedDecl *D = nullptr; 231 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin()); 232 if (R.isAmbiguous()) { 233 // If we got an ambiguity involving a non-function template, treat this 234 // as a template name, and pick an arbitrary template for error recovery. 235 bool AnyFunctionTemplates = false; 236 for (NamedDecl *FoundD : R) { 237 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) { 238 if (isa<FunctionTemplateDecl>(FoundTemplate)) 239 AnyFunctionTemplates = true; 240 else { 241 D = FoundTemplate; 242 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD); 243 break; 244 } 245 } 246 } 247 248 // If we didn't find any templates at all, this isn't a template name. 249 // Leave the ambiguity for a later lookup to diagnose. 250 if (!D && !AnyFunctionTemplates) { 251 R.suppressDiagnostics(); 252 return TNK_Non_template; 253 } 254 255 // If the only templates were function templates, filter out the rest. 256 // We'll diagnose the ambiguity later. 257 if (!D) 258 FilterAcceptableTemplateNames(R); 259 } 260 261 // At this point, we have either picked a single template name declaration D 262 // or we have a non-empty set of results R containing either one template name 263 // declaration or a set of function templates. 264 265 TemplateName Template; 266 TemplateNameKind TemplateKind; 267 268 unsigned ResultCount = R.end() - R.begin(); 269 if (!D && ResultCount > 1) { 270 // We assume that we'll preserve the qualifier from a function 271 // template name in other ways. 272 Template = Context.getOverloadedTemplateName(R.begin(), R.end()); 273 TemplateKind = TNK_Function_template; 274 275 // We'll do this lookup again later. 276 R.suppressDiagnostics(); 277 } else { 278 if (!D) { 279 D = getAsTemplateNameDecl(*R.begin()); 280 assert(D && "unambiguous result is not a template name"); 281 } 282 283 if (isa<UnresolvedUsingValueDecl>(D)) { 284 // We don't yet know whether this is a template-name or not. 285 MemberOfUnknownSpecialization = true; 286 return TNK_Non_template; 287 } 288 289 TemplateDecl *TD = cast<TemplateDecl>(D); 290 Template = 291 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD); 292 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD); 293 if (SS.isSet() && !SS.isInvalid()) { 294 NestedNameSpecifier *Qualifier = SS.getScopeRep(); 295 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword, 296 Template); 297 } 298 299 if (isa<FunctionTemplateDecl>(TD)) { 300 TemplateKind = TNK_Function_template; 301 302 // We'll do this lookup again later. 303 R.suppressDiagnostics(); 304 } else { 305 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || 306 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || 307 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)); 308 TemplateKind = 309 isa<VarTemplateDecl>(TD) ? TNK_Var_template : 310 isa<ConceptDecl>(TD) ? TNK_Concept_template : 311 TNK_Type_template; 312 } 313 } 314 315 TemplateResult = TemplateTy::make(Template); 316 return TemplateKind; 317 } 318 319 bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name, 320 SourceLocation NameLoc, CXXScopeSpec &SS, 321 ParsedTemplateTy *Template /*=nullptr*/) { 322 bool MemberOfUnknownSpecialization = false; 323 324 // We could use redeclaration lookup here, but we don't need to: the 325 // syntactic form of a deduction guide is enough to identify it even 326 // if we can't look up the template name at all. 327 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName); 328 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(), 329 /*EnteringContext*/ false, 330 MemberOfUnknownSpecialization)) 331 return false; 332 333 if (R.empty()) return false; 334 if (R.isAmbiguous()) { 335 // FIXME: Diagnose an ambiguity if we find at least one template. 336 R.suppressDiagnostics(); 337 return false; 338 } 339 340 // We only treat template-names that name type templates as valid deduction 341 // guide names. 342 TemplateDecl *TD = R.getAsSingle<TemplateDecl>(); 343 if (!TD || !getAsTypeTemplateDecl(TD)) 344 return false; 345 346 if (Template) 347 *Template = TemplateTy::make(TemplateName(TD)); 348 return true; 349 } 350 351 bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II, 352 SourceLocation IILoc, 353 Scope *S, 354 const CXXScopeSpec *SS, 355 TemplateTy &SuggestedTemplate, 356 TemplateNameKind &SuggestedKind) { 357 // We can't recover unless there's a dependent scope specifier preceding the 358 // template name. 359 // FIXME: Typo correction? 360 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) || 361 computeDeclContext(*SS)) 362 return false; 363 364 // The code is missing a 'template' keyword prior to the dependent template 365 // name. 366 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep(); 367 Diag(IILoc, diag::err_template_kw_missing) 368 << Qualifier << II.getName() 369 << FixItHint::CreateInsertion(IILoc, "template "); 370 SuggestedTemplate 371 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II)); 372 SuggestedKind = TNK_Dependent_template_name; 373 return true; 374 } 375 376 bool Sema::LookupTemplateName(LookupResult &Found, 377 Scope *S, CXXScopeSpec &SS, 378 QualType ObjectType, 379 bool EnteringContext, 380 bool &MemberOfUnknownSpecialization, 381 RequiredTemplateKind RequiredTemplate, 382 AssumedTemplateKind *ATK, 383 bool AllowTypoCorrection) { 384 if (ATK) 385 *ATK = AssumedTemplateKind::None; 386 387 if (SS.isInvalid()) 388 return true; 389 390 Found.setTemplateNameLookup(true); 391 392 // Determine where to perform name lookup 393 MemberOfUnknownSpecialization = false; 394 DeclContext *LookupCtx = nullptr; 395 bool IsDependent = false; 396 if (!ObjectType.isNull()) { 397 // This nested-name-specifier occurs in a member access expression, e.g., 398 // x->B::f, and we are looking into the type of the object. 399 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist"); 400 LookupCtx = computeDeclContext(ObjectType); 401 IsDependent = !LookupCtx && ObjectType->isDependentType(); 402 assert((IsDependent || !ObjectType->isIncompleteType() || 403 !ObjectType->getAs<TagType>() || 404 ObjectType->castAs<TagType>()->isBeingDefined()) && 405 "Caller should have completed object type"); 406 407 // Template names cannot appear inside an Objective-C class or object type 408 // or a vector type. 409 // 410 // FIXME: This is wrong. For example: 411 // 412 // template<typename T> using Vec = T __attribute__((ext_vector_type(4))); 413 // Vec<int> vi; 414 // vi.Vec<int>::~Vec<int>(); 415 // 416 // ... should be accepted but we will not treat 'Vec' as a template name 417 // here. The right thing to do would be to check if the name is a valid 418 // vector component name, and look up a template name if not. And similarly 419 // for lookups into Objective-C class and object types, where the same 420 // problem can arise. 421 if (ObjectType->isObjCObjectOrInterfaceType() || 422 ObjectType->isVectorType()) { 423 Found.clear(); 424 return false; 425 } 426 } else if (SS.isNotEmpty()) { 427 // This nested-name-specifier occurs after another nested-name-specifier, 428 // so long into the context associated with the prior nested-name-specifier. 429 LookupCtx = computeDeclContext(SS, EnteringContext); 430 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS); 431 432 // The declaration context must be complete. 433 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx)) 434 return true; 435 } 436 437 bool ObjectTypeSearchedInScope = false; 438 bool AllowFunctionTemplatesInLookup = true; 439 if (LookupCtx) { 440 // Perform "qualified" name lookup into the declaration context we 441 // computed, which is either the type of the base of a member access 442 // expression or the declaration context associated with a prior 443 // nested-name-specifier. 444 LookupQualifiedName(Found, LookupCtx); 445 446 // FIXME: The C++ standard does not clearly specify what happens in the 447 // case where the object type is dependent, and implementations vary. In 448 // Clang, we treat a name after a . or -> as a template-name if lookup 449 // finds a non-dependent member or member of the current instantiation that 450 // is a type template, or finds no such members and lookup in the context 451 // of the postfix-expression finds a type template. In the latter case, the 452 // name is nonetheless dependent, and we may resolve it to a member of an 453 // unknown specialization when we come to instantiate the template. 454 IsDependent |= Found.wasNotFoundInCurrentInstantiation(); 455 } 456 457 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) { 458 // C++ [basic.lookup.classref]p1: 459 // In a class member access expression (5.2.5), if the . or -> token is 460 // immediately followed by an identifier followed by a <, the 461 // identifier must be looked up to determine whether the < is the 462 // beginning of a template argument list (14.2) or a less-than operator. 463 // The identifier is first looked up in the class of the object 464 // expression. If the identifier is not found, it is then looked up in 465 // the context of the entire postfix-expression and shall name a class 466 // template. 467 if (S) 468 LookupName(Found, S); 469 470 if (!ObjectType.isNull()) { 471 // FIXME: We should filter out all non-type templates here, particularly 472 // variable templates and concepts. But the exclusion of alias templates 473 // and template template parameters is a wording defect. 474 AllowFunctionTemplatesInLookup = false; 475 ObjectTypeSearchedInScope = true; 476 } 477 478 IsDependent |= Found.wasNotFoundInCurrentInstantiation(); 479 } 480 481 if (Found.isAmbiguous()) 482 return false; 483 484 if (ATK && SS.isEmpty() && ObjectType.isNull() && 485 !RequiredTemplate.hasTemplateKeyword()) { 486 // C++2a [temp.names]p2: 487 // A name is also considered to refer to a template if it is an 488 // unqualified-id followed by a < and name lookup finds either one or more 489 // functions or finds nothing. 490 // 491 // To keep our behavior consistent, we apply the "finds nothing" part in 492 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we 493 // successfully form a call to an undeclared template-id. 494 bool AllFunctions = 495 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) { 496 return isa<FunctionDecl>(ND->getUnderlyingDecl()); 497 }); 498 if (AllFunctions || (Found.empty() && !IsDependent)) { 499 // If lookup found any functions, or if this is a name that can only be 500 // used for a function, then strongly assume this is a function 501 // template-id. 502 *ATK = (Found.empty() && Found.getLookupName().isIdentifier()) 503 ? AssumedTemplateKind::FoundNothing 504 : AssumedTemplateKind::FoundFunctions; 505 Found.clear(); 506 return false; 507 } 508 } 509 510 if (Found.empty() && !IsDependent && AllowTypoCorrection) { 511 // If we did not find any names, and this is not a disambiguation, attempt 512 // to correct any typos. 513 DeclarationName Name = Found.getLookupName(); 514 Found.clear(); 515 // Simple filter callback that, for keywords, only accepts the C++ *_cast 516 DefaultFilterCCC FilterCCC{}; 517 FilterCCC.WantTypeSpecifiers = false; 518 FilterCCC.WantExpressionKeywords = false; 519 FilterCCC.WantRemainingKeywords = false; 520 FilterCCC.WantCXXNamedCasts = true; 521 if (TypoCorrection Corrected = 522 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S, 523 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) { 524 if (auto *ND = Corrected.getFoundDecl()) 525 Found.addDecl(ND); 526 FilterAcceptableTemplateNames(Found); 527 if (Found.isAmbiguous()) { 528 Found.clear(); 529 } else if (!Found.empty()) { 530 Found.setLookupName(Corrected.getCorrection()); 531 if (LookupCtx) { 532 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 533 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 534 Name.getAsString() == CorrectedStr; 535 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest) 536 << Name << LookupCtx << DroppedSpecifier 537 << SS.getRange()); 538 } else { 539 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name); 540 } 541 } 542 } 543 } 544 545 NamedDecl *ExampleLookupResult = 546 Found.empty() ? nullptr : Found.getRepresentativeDecl(); 547 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup); 548 if (Found.empty()) { 549 if (IsDependent) { 550 MemberOfUnknownSpecialization = true; 551 return false; 552 } 553 554 // If a 'template' keyword was used, a lookup that finds only non-template 555 // names is an error. 556 if (ExampleLookupResult && RequiredTemplate) { 557 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template) 558 << Found.getLookupName() << SS.getRange() 559 << RequiredTemplate.hasTemplateKeyword() 560 << RequiredTemplate.getTemplateKeywordLoc(); 561 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(), 562 diag::note_template_kw_refers_to_non_template) 563 << Found.getLookupName(); 564 return true; 565 } 566 567 return false; 568 } 569 570 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope && 571 !getLangOpts().CPlusPlus11) { 572 // C++03 [basic.lookup.classref]p1: 573 // [...] If the lookup in the class of the object expression finds a 574 // template, the name is also looked up in the context of the entire 575 // postfix-expression and [...] 576 // 577 // Note: C++11 does not perform this second lookup. 578 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(), 579 LookupOrdinaryName); 580 FoundOuter.setTemplateNameLookup(true); 581 LookupName(FoundOuter, S); 582 // FIXME: We silently accept an ambiguous lookup here, in violation of 583 // [basic.lookup]/1. 584 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false); 585 586 NamedDecl *OuterTemplate; 587 if (FoundOuter.empty()) { 588 // - if the name is not found, the name found in the class of the 589 // object expression is used, otherwise 590 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() || 591 !(OuterTemplate = 592 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) { 593 // - if the name is found in the context of the entire 594 // postfix-expression and does not name a class template, the name 595 // found in the class of the object expression is used, otherwise 596 FoundOuter.clear(); 597 } else if (!Found.isSuppressingAmbiguousDiagnostics()) { 598 // - if the name found is a class template, it must refer to the same 599 // entity as the one found in the class of the object expression, 600 // otherwise the program is ill-formed. 601 if (!Found.isSingleResult() || 602 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() != 603 OuterTemplate->getCanonicalDecl()) { 604 Diag(Found.getNameLoc(), 605 diag::ext_nested_name_member_ref_lookup_ambiguous) 606 << Found.getLookupName() 607 << ObjectType; 608 Diag(Found.getRepresentativeDecl()->getLocation(), 609 diag::note_ambig_member_ref_object_type) 610 << ObjectType; 611 Diag(FoundOuter.getFoundDecl()->getLocation(), 612 diag::note_ambig_member_ref_scope); 613 614 // Recover by taking the template that we found in the object 615 // expression's type. 616 } 617 } 618 } 619 620 return false; 621 } 622 623 void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, 624 SourceLocation Less, 625 SourceLocation Greater) { 626 if (TemplateName.isInvalid()) 627 return; 628 629 DeclarationNameInfo NameInfo; 630 CXXScopeSpec SS; 631 LookupNameKind LookupKind; 632 633 DeclContext *LookupCtx = nullptr; 634 NamedDecl *Found = nullptr; 635 bool MissingTemplateKeyword = false; 636 637 // Figure out what name we looked up. 638 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) { 639 NameInfo = DRE->getNameInfo(); 640 SS.Adopt(DRE->getQualifierLoc()); 641 LookupKind = LookupOrdinaryName; 642 Found = DRE->getFoundDecl(); 643 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) { 644 NameInfo = ME->getMemberNameInfo(); 645 SS.Adopt(ME->getQualifierLoc()); 646 LookupKind = LookupMemberName; 647 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl(); 648 Found = ME->getMemberDecl(); 649 } else if (auto *DSDRE = 650 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) { 651 NameInfo = DSDRE->getNameInfo(); 652 SS.Adopt(DSDRE->getQualifierLoc()); 653 MissingTemplateKeyword = true; 654 } else if (auto *DSME = 655 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) { 656 NameInfo = DSME->getMemberNameInfo(); 657 SS.Adopt(DSME->getQualifierLoc()); 658 MissingTemplateKeyword = true; 659 } else { 660 llvm_unreachable("unexpected kind of potential template name"); 661 } 662 663 // If this is a dependent-scope lookup, diagnose that the 'template' keyword 664 // was missing. 665 if (MissingTemplateKeyword) { 666 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing) 667 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater); 668 return; 669 } 670 671 // Try to correct the name by looking for templates and C++ named casts. 672 struct TemplateCandidateFilter : CorrectionCandidateCallback { 673 Sema &S; 674 TemplateCandidateFilter(Sema &S) : S(S) { 675 WantTypeSpecifiers = false; 676 WantExpressionKeywords = false; 677 WantRemainingKeywords = false; 678 WantCXXNamedCasts = true; 679 }; 680 bool ValidateCandidate(const TypoCorrection &Candidate) override { 681 if (auto *ND = Candidate.getCorrectionDecl()) 682 return S.getAsTemplateNameDecl(ND); 683 return Candidate.isKeyword(); 684 } 685 686 std::unique_ptr<CorrectionCandidateCallback> clone() override { 687 return std::make_unique<TemplateCandidateFilter>(*this); 688 } 689 }; 690 691 DeclarationName Name = NameInfo.getName(); 692 TemplateCandidateFilter CCC(*this); 693 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC, 694 CTK_ErrorRecovery, LookupCtx)) { 695 auto *ND = Corrected.getFoundDecl(); 696 if (ND) 697 ND = getAsTemplateNameDecl(ND); 698 if (ND || Corrected.isKeyword()) { 699 if (LookupCtx) { 700 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 701 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 702 Name.getAsString() == CorrectedStr; 703 diagnoseTypo(Corrected, 704 PDiag(diag::err_non_template_in_member_template_id_suggest) 705 << Name << LookupCtx << DroppedSpecifier 706 << SS.getRange(), false); 707 } else { 708 diagnoseTypo(Corrected, 709 PDiag(diag::err_non_template_in_template_id_suggest) 710 << Name, false); 711 } 712 if (Found) 713 Diag(Found->getLocation(), 714 diag::note_non_template_in_template_id_found); 715 return; 716 } 717 } 718 719 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id) 720 << Name << SourceRange(Less, Greater); 721 if (Found) 722 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found); 723 } 724 725 /// ActOnDependentIdExpression - Handle a dependent id-expression that 726 /// was just parsed. This is only possible with an explicit scope 727 /// specifier naming a dependent type. 728 ExprResult 729 Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS, 730 SourceLocation TemplateKWLoc, 731 const DeclarationNameInfo &NameInfo, 732 bool isAddressOfOperand, 733 const TemplateArgumentListInfo *TemplateArgs) { 734 DeclContext *DC = getFunctionLevelDeclContext(); 735 736 // C++11 [expr.prim.general]p12: 737 // An id-expression that denotes a non-static data member or non-static 738 // member function of a class can only be used: 739 // (...) 740 // - if that id-expression denotes a non-static data member and it 741 // appears in an unevaluated operand. 742 // 743 // If this might be the case, form a DependentScopeDeclRefExpr instead of a 744 // CXXDependentScopeMemberExpr. The former can instantiate to either 745 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is 746 // always a MemberExpr. 747 bool MightBeCxx11UnevalField = 748 getLangOpts().CPlusPlus11 && isUnevaluatedContext(); 749 750 // Check if the nested name specifier is an enum type. 751 bool IsEnum = false; 752 if (NestedNameSpecifier *NNS = SS.getScopeRep()) 753 IsEnum = isa_and_nonnull<EnumType>(NNS->getAsType()); 754 755 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum && 756 isa<CXXMethodDecl>(DC) && 757 cast<CXXMethodDecl>(DC)->isImplicitObjectMemberFunction()) { 758 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType().getNonReferenceType(); 759 760 // Since the 'this' expression is synthesized, we don't need to 761 // perform the double-lookup check. 762 NamedDecl *FirstQualifierInScope = nullptr; 763 764 return CXXDependentScopeMemberExpr::Create( 765 Context, /*This=*/nullptr, ThisType, 766 /*IsArrow=*/!Context.getLangOpts().HLSL, 767 /*Op=*/SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc, 768 FirstQualifierInScope, NameInfo, TemplateArgs); 769 } 770 771 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs); 772 } 773 774 ExprResult 775 Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 776 SourceLocation TemplateKWLoc, 777 const DeclarationNameInfo &NameInfo, 778 const TemplateArgumentListInfo *TemplateArgs) { 779 // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc 780 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 781 if (!QualifierLoc) 782 return ExprError(); 783 784 return DependentScopeDeclRefExpr::Create( 785 Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs); 786 } 787 788 789 /// Determine whether we would be unable to instantiate this template (because 790 /// it either has no definition, or is in the process of being instantiated). 791 bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, 792 NamedDecl *Instantiation, 793 bool InstantiatedFromMember, 794 const NamedDecl *Pattern, 795 const NamedDecl *PatternDef, 796 TemplateSpecializationKind TSK, 797 bool Complain /*= true*/) { 798 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || 799 isa<VarDecl>(Instantiation)); 800 801 bool IsEntityBeingDefined = false; 802 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef)) 803 IsEntityBeingDefined = TD->isBeingDefined(); 804 805 if (PatternDef && !IsEntityBeingDefined) { 806 NamedDecl *SuggestedDef = nullptr; 807 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef), 808 &SuggestedDef, 809 /*OnlyNeedComplete*/ false)) { 810 // If we're allowed to diagnose this and recover, do so. 811 bool Recover = Complain && !isSFINAEContext(); 812 if (Complain) 813 diagnoseMissingImport(PointOfInstantiation, SuggestedDef, 814 Sema::MissingImportKind::Definition, Recover); 815 return !Recover; 816 } 817 return false; 818 } 819 820 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) 821 return true; 822 823 QualType InstantiationTy; 824 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation)) 825 InstantiationTy = Context.getTypeDeclType(TD); 826 if (PatternDef) { 827 Diag(PointOfInstantiation, 828 diag::err_template_instantiate_within_definition) 829 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation) 830 << InstantiationTy; 831 // Not much point in noting the template declaration here, since 832 // we're lexically inside it. 833 Instantiation->setInvalidDecl(); 834 } else if (InstantiatedFromMember) { 835 if (isa<FunctionDecl>(Instantiation)) { 836 Diag(PointOfInstantiation, 837 diag::err_explicit_instantiation_undefined_member) 838 << /*member function*/ 1 << Instantiation->getDeclName() 839 << Instantiation->getDeclContext(); 840 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here); 841 } else { 842 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!"); 843 Diag(PointOfInstantiation, 844 diag::err_implicit_instantiate_member_undefined) 845 << InstantiationTy; 846 Diag(Pattern->getLocation(), diag::note_member_declared_at); 847 } 848 } else { 849 if (isa<FunctionDecl>(Instantiation)) { 850 Diag(PointOfInstantiation, 851 diag::err_explicit_instantiation_undefined_func_template) 852 << Pattern; 853 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here); 854 } else if (isa<TagDecl>(Instantiation)) { 855 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined) 856 << (TSK != TSK_ImplicitInstantiation) 857 << InstantiationTy; 858 NoteTemplateLocation(*Pattern); 859 } else { 860 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!"); 861 if (isa<VarTemplateSpecializationDecl>(Instantiation)) { 862 Diag(PointOfInstantiation, 863 diag::err_explicit_instantiation_undefined_var_template) 864 << Instantiation; 865 Instantiation->setInvalidDecl(); 866 } else 867 Diag(PointOfInstantiation, 868 diag::err_explicit_instantiation_undefined_member) 869 << /*static data member*/ 2 << Instantiation->getDeclName() 870 << Instantiation->getDeclContext(); 871 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here); 872 } 873 } 874 875 // In general, Instantiation isn't marked invalid to get more than one 876 // error for multiple undefined instantiations. But the code that does 877 // explicit declaration -> explicit definition conversion can't handle 878 // invalid declarations, so mark as invalid in that case. 879 if (TSK == TSK_ExplicitInstantiationDeclaration) 880 Instantiation->setInvalidDecl(); 881 return true; 882 } 883 884 /// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining 885 /// that the template parameter 'PrevDecl' is being shadowed by a new 886 /// declaration at location Loc. Returns true to indicate that this is 887 /// an error, and false otherwise. 888 void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) { 889 assert(PrevDecl->isTemplateParameter() && "Not a template parameter"); 890 891 // C++ [temp.local]p4: 892 // A template-parameter shall not be redeclared within its 893 // scope (including nested scopes). 894 // 895 // Make this a warning when MSVC compatibility is requested. 896 unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow 897 : diag::err_template_param_shadow; 898 const auto *ND = cast<NamedDecl>(PrevDecl); 899 Diag(Loc, DiagId) << ND->getDeclName(); 900 NoteTemplateParameterLocation(*ND); 901 } 902 903 /// AdjustDeclIfTemplate - If the given decl happens to be a template, reset 904 /// the parameter D to reference the templated declaration and return a pointer 905 /// to the template declaration. Otherwise, do nothing to D and return null. 906 TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) { 907 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) { 908 D = Temp->getTemplatedDecl(); 909 return Temp; 910 } 911 return nullptr; 912 } 913 914 ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion( 915 SourceLocation EllipsisLoc) const { 916 assert(Kind == Template && 917 "Only template template arguments can be pack expansions here"); 918 assert(getAsTemplate().get().containsUnexpandedParameterPack() && 919 "Template template argument pack expansion without packs"); 920 ParsedTemplateArgument Result(*this); 921 Result.EllipsisLoc = EllipsisLoc; 922 return Result; 923 } 924 925 static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef, 926 const ParsedTemplateArgument &Arg) { 927 928 switch (Arg.getKind()) { 929 case ParsedTemplateArgument::Type: { 930 TypeSourceInfo *DI; 931 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI); 932 if (!DI) 933 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation()); 934 return TemplateArgumentLoc(TemplateArgument(T), DI); 935 } 936 937 case ParsedTemplateArgument::NonType: { 938 Expr *E = static_cast<Expr *>(Arg.getAsExpr()); 939 return TemplateArgumentLoc(TemplateArgument(E), E); 940 } 941 942 case ParsedTemplateArgument::Template: { 943 TemplateName Template = Arg.getAsTemplate().get(); 944 TemplateArgument TArg; 945 if (Arg.getEllipsisLoc().isValid()) 946 TArg = TemplateArgument(Template, std::optional<unsigned int>()); 947 else 948 TArg = Template; 949 return TemplateArgumentLoc( 950 SemaRef.Context, TArg, 951 Arg.getScopeSpec().getWithLocInContext(SemaRef.Context), 952 Arg.getLocation(), Arg.getEllipsisLoc()); 953 } 954 } 955 956 llvm_unreachable("Unhandled parsed template argument"); 957 } 958 959 /// Translates template arguments as provided by the parser 960 /// into template arguments used by semantic analysis. 961 void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn, 962 TemplateArgumentListInfo &TemplateArgs) { 963 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I) 964 TemplateArgs.addArgument(translateTemplateArgument(*this, 965 TemplateArgsIn[I])); 966 } 967 968 static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S, 969 SourceLocation Loc, 970 IdentifierInfo *Name) { 971 NamedDecl *PrevDecl = SemaRef.LookupSingleName( 972 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 973 if (PrevDecl && PrevDecl->isTemplateParameter()) 974 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl); 975 } 976 977 /// Convert a parsed type into a parsed template argument. This is mostly 978 /// trivial, except that we may have parsed a C++17 deduced class template 979 /// specialization type, in which case we should form a template template 980 /// argument instead of a type template argument. 981 ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) { 982 TypeSourceInfo *TInfo; 983 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo); 984 if (T.isNull()) 985 return ParsedTemplateArgument(); 986 assert(TInfo && "template argument with no location"); 987 988 // If we might have formed a deduced template specialization type, convert 989 // it to a template template argument. 990 if (getLangOpts().CPlusPlus17) { 991 TypeLoc TL = TInfo->getTypeLoc(); 992 SourceLocation EllipsisLoc; 993 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) { 994 EllipsisLoc = PET.getEllipsisLoc(); 995 TL = PET.getPatternLoc(); 996 } 997 998 CXXScopeSpec SS; 999 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) { 1000 SS.Adopt(ET.getQualifierLoc()); 1001 TL = ET.getNamedTypeLoc(); 1002 } 1003 1004 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) { 1005 TemplateName Name = DTST.getTypePtr()->getTemplateName(); 1006 if (SS.isSet()) 1007 Name = Context.getQualifiedTemplateName(SS.getScopeRep(), 1008 /*HasTemplateKeyword=*/false, 1009 Name); 1010 ParsedTemplateArgument Result(SS, TemplateTy::make(Name), 1011 DTST.getTemplateNameLoc()); 1012 if (EllipsisLoc.isValid()) 1013 Result = Result.getTemplatePackExpansion(EllipsisLoc); 1014 return Result; 1015 } 1016 } 1017 1018 // This is a normal type template argument. Note, if the type template 1019 // argument is an injected-class-name for a template, it has a dual nature 1020 // and can be used as either a type or a template. We handle that in 1021 // convertTypeTemplateArgumentToTemplate. 1022 return ParsedTemplateArgument(ParsedTemplateArgument::Type, 1023 ParsedType.get().getAsOpaquePtr(), 1024 TInfo->getTypeLoc().getBeginLoc()); 1025 } 1026 1027 /// ActOnTypeParameter - Called when a C++ template type parameter 1028 /// (e.g., "typename T") has been parsed. Typename specifies whether 1029 /// the keyword "typename" was used to declare the type parameter 1030 /// (otherwise, "class" was used), and KeyLoc is the location of the 1031 /// "class" or "typename" keyword. ParamName is the name of the 1032 /// parameter (NULL indicates an unnamed template parameter) and 1033 /// ParamNameLoc is the location of the parameter name (if any). 1034 /// If the type parameter has a default argument, it will be added 1035 /// later via ActOnTypeParameterDefault. 1036 NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename, 1037 SourceLocation EllipsisLoc, 1038 SourceLocation KeyLoc, 1039 IdentifierInfo *ParamName, 1040 SourceLocation ParamNameLoc, 1041 unsigned Depth, unsigned Position, 1042 SourceLocation EqualLoc, 1043 ParsedType DefaultArg, 1044 bool HasTypeConstraint) { 1045 assert(S->isTemplateParamScope() && 1046 "Template type parameter not in template parameter scope!"); 1047 1048 bool IsParameterPack = EllipsisLoc.isValid(); 1049 TemplateTypeParmDecl *Param 1050 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(), 1051 KeyLoc, ParamNameLoc, Depth, Position, 1052 ParamName, Typename, IsParameterPack, 1053 HasTypeConstraint); 1054 Param->setAccess(AS_public); 1055 1056 if (Param->isParameterPack()) 1057 if (auto *LSI = getEnclosingLambda()) 1058 LSI->LocalPacks.push_back(Param); 1059 1060 if (ParamName) { 1061 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName); 1062 1063 // Add the template parameter into the current scope. 1064 S->AddDecl(Param); 1065 IdResolver.AddDecl(Param); 1066 } 1067 1068 // C++0x [temp.param]p9: 1069 // A default template-argument may be specified for any kind of 1070 // template-parameter that is not a template parameter pack. 1071 if (DefaultArg && IsParameterPack) { 1072 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 1073 DefaultArg = nullptr; 1074 } 1075 1076 // Handle the default argument, if provided. 1077 if (DefaultArg) { 1078 TypeSourceInfo *DefaultTInfo; 1079 GetTypeFromParser(DefaultArg, &DefaultTInfo); 1080 1081 assert(DefaultTInfo && "expected source information for type"); 1082 1083 // Check for unexpanded parameter packs. 1084 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo, 1085 UPPC_DefaultArgument)) 1086 return Param; 1087 1088 // Check the template argument itself. 1089 if (CheckTemplateArgument(DefaultTInfo)) { 1090 Param->setInvalidDecl(); 1091 return Param; 1092 } 1093 1094 Param->setDefaultArgument(DefaultTInfo); 1095 } 1096 1097 return Param; 1098 } 1099 1100 /// Convert the parser's template argument list representation into our form. 1101 static TemplateArgumentListInfo 1102 makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) { 1103 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc, 1104 TemplateId.RAngleLoc); 1105 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(), 1106 TemplateId.NumArgs); 1107 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs); 1108 return TemplateArgs; 1109 } 1110 1111 bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) { 1112 1113 TemplateName TN = TypeConstr->Template.get(); 1114 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl()); 1115 1116 // C++2a [temp.param]p4: 1117 // [...] The concept designated by a type-constraint shall be a type 1118 // concept ([temp.concept]). 1119 if (!CD->isTypeConcept()) { 1120 Diag(TypeConstr->TemplateNameLoc, 1121 diag::err_type_constraint_non_type_concept); 1122 return true; 1123 } 1124 1125 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid(); 1126 1127 if (!WereArgsSpecified && 1128 CD->getTemplateParameters()->getMinRequiredArguments() > 1) { 1129 Diag(TypeConstr->TemplateNameLoc, 1130 diag::err_type_constraint_missing_arguments) 1131 << CD; 1132 return true; 1133 } 1134 return false; 1135 } 1136 1137 bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS, 1138 TemplateIdAnnotation *TypeConstr, 1139 TemplateTypeParmDecl *ConstrainedParameter, 1140 SourceLocation EllipsisLoc) { 1141 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc, 1142 false); 1143 } 1144 1145 bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS, 1146 TemplateIdAnnotation *TypeConstr, 1147 TemplateTypeParmDecl *ConstrainedParameter, 1148 SourceLocation EllipsisLoc, 1149 bool AllowUnexpandedPack) { 1150 1151 if (CheckTypeConstraint(TypeConstr)) 1152 return true; 1153 1154 TemplateName TN = TypeConstr->Template.get(); 1155 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl()); 1156 1157 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name), 1158 TypeConstr->TemplateNameLoc); 1159 1160 TemplateArgumentListInfo TemplateArgs; 1161 if (TypeConstr->LAngleLoc.isValid()) { 1162 TemplateArgs = 1163 makeTemplateArgumentListInfo(*this, *TypeConstr); 1164 1165 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) { 1166 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) { 1167 if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint)) 1168 return true; 1169 } 1170 } 1171 } 1172 return AttachTypeConstraint( 1173 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(), 1174 ConceptName, CD, 1175 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr, 1176 ConstrainedParameter, EllipsisLoc); 1177 } 1178 1179 template<typename ArgumentLocAppender> 1180 static ExprResult formImmediatelyDeclaredConstraint( 1181 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, 1182 ConceptDecl *NamedConcept, SourceLocation LAngleLoc, 1183 SourceLocation RAngleLoc, QualType ConstrainedType, 1184 SourceLocation ParamNameLoc, ArgumentLocAppender Appender, 1185 SourceLocation EllipsisLoc) { 1186 1187 TemplateArgumentListInfo ConstraintArgs; 1188 ConstraintArgs.addArgument( 1189 S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType), 1190 /*NTTPType=*/QualType(), ParamNameLoc)); 1191 1192 ConstraintArgs.setRAngleLoc(RAngleLoc); 1193 ConstraintArgs.setLAngleLoc(LAngleLoc); 1194 Appender(ConstraintArgs); 1195 1196 // C++2a [temp.param]p4: 1197 // [...] This constraint-expression E is called the immediately-declared 1198 // constraint of T. [...] 1199 CXXScopeSpec SS; 1200 SS.Adopt(NS); 1201 ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId( 1202 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo, 1203 /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs); 1204 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid()) 1205 return ImmediatelyDeclaredConstraint; 1206 1207 // C++2a [temp.param]p4: 1208 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...). 1209 // 1210 // We have the following case: 1211 // 1212 // template<typename T> concept C1 = true; 1213 // template<C1... T> struct s1; 1214 // 1215 // The constraint: (C1<T> && ...) 1216 // 1217 // Note that the type of C1<T> is known to be 'bool', so we don't need to do 1218 // any unqualified lookups for 'operator&&' here. 1219 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr, 1220 /*LParenLoc=*/SourceLocation(), 1221 ImmediatelyDeclaredConstraint.get(), BO_LAnd, 1222 EllipsisLoc, /*RHS=*/nullptr, 1223 /*RParenLoc=*/SourceLocation(), 1224 /*NumExpansions=*/std::nullopt); 1225 } 1226 1227 /// Attach a type-constraint to a template parameter. 1228 /// \returns true if an error occurred. This can happen if the 1229 /// immediately-declared constraint could not be formed (e.g. incorrect number 1230 /// of arguments for the named concept). 1231 bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS, 1232 DeclarationNameInfo NameInfo, 1233 ConceptDecl *NamedConcept, 1234 const TemplateArgumentListInfo *TemplateArgs, 1235 TemplateTypeParmDecl *ConstrainedParameter, 1236 SourceLocation EllipsisLoc) { 1237 // C++2a [temp.param]p4: 1238 // [...] If Q is of the form C<A1, ..., An>, then let E' be 1239 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...] 1240 const ASTTemplateArgumentListInfo *ArgsAsWritten = 1241 TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context, 1242 *TemplateArgs) : nullptr; 1243 1244 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0); 1245 1246 ExprResult ImmediatelyDeclaredConstraint = 1247 formImmediatelyDeclaredConstraint( 1248 *this, NS, NameInfo, NamedConcept, 1249 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(), 1250 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(), 1251 ParamAsArgument, ConstrainedParameter->getLocation(), 1252 [&] (TemplateArgumentListInfo &ConstraintArgs) { 1253 if (TemplateArgs) 1254 for (const auto &ArgLoc : TemplateArgs->arguments()) 1255 ConstraintArgs.addArgument(ArgLoc); 1256 }, EllipsisLoc); 1257 if (ImmediatelyDeclaredConstraint.isInvalid()) 1258 return true; 1259 1260 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS, 1261 /*TemplateKWLoc=*/SourceLocation{}, 1262 /*ConceptNameInfo=*/NameInfo, 1263 /*FoundDecl=*/NamedConcept, 1264 /*NamedConcept=*/NamedConcept, 1265 /*ArgsWritten=*/ArgsAsWritten); 1266 ConstrainedParameter->setTypeConstraint(CL, 1267 ImmediatelyDeclaredConstraint.get()); 1268 return false; 1269 } 1270 1271 bool Sema::AttachTypeConstraint(AutoTypeLoc TL, 1272 NonTypeTemplateParmDecl *NewConstrainedParm, 1273 NonTypeTemplateParmDecl *OrigConstrainedParm, 1274 SourceLocation EllipsisLoc) { 1275 if (NewConstrainedParm->getType() != TL.getType() || 1276 TL.getAutoKeyword() != AutoTypeKeyword::Auto) { 1277 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 1278 diag::err_unsupported_placeholder_constraint) 1279 << NewConstrainedParm->getTypeSourceInfo() 1280 ->getTypeLoc() 1281 .getSourceRange(); 1282 return true; 1283 } 1284 // FIXME: Concepts: This should be the type of the placeholder, but this is 1285 // unclear in the wording right now. 1286 DeclRefExpr *Ref = 1287 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(), 1288 VK_PRValue, OrigConstrainedParm->getLocation()); 1289 if (!Ref) 1290 return true; 1291 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint( 1292 *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(), 1293 TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(), 1294 BuildDecltypeType(Ref), OrigConstrainedParm->getLocation(), 1295 [&](TemplateArgumentListInfo &ConstraintArgs) { 1296 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I) 1297 ConstraintArgs.addArgument(TL.getArgLoc(I)); 1298 }, 1299 EllipsisLoc); 1300 if (ImmediatelyDeclaredConstraint.isInvalid() || 1301 !ImmediatelyDeclaredConstraint.isUsable()) 1302 return true; 1303 1304 NewConstrainedParm->setPlaceholderTypeConstraint( 1305 ImmediatelyDeclaredConstraint.get()); 1306 return false; 1307 } 1308 1309 /// Check that the type of a non-type template parameter is 1310 /// well-formed. 1311 /// 1312 /// \returns the (possibly-promoted) parameter type if valid; 1313 /// otherwise, produces a diagnostic and returns a NULL type. 1314 QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, 1315 SourceLocation Loc) { 1316 if (TSI->getType()->isUndeducedType()) { 1317 // C++17 [temp.dep.expr]p3: 1318 // An id-expression is type-dependent if it contains 1319 // - an identifier associated by name lookup with a non-type 1320 // template-parameter declared with a type that contains a 1321 // placeholder type (7.1.7.4), 1322 TSI = SubstAutoTypeSourceInfoDependent(TSI); 1323 } 1324 1325 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc); 1326 } 1327 1328 /// Require the given type to be a structural type, and diagnose if it is not. 1329 /// 1330 /// \return \c true if an error was produced. 1331 bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) { 1332 if (T->isDependentType()) 1333 return false; 1334 1335 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete)) 1336 return true; 1337 1338 if (T->isStructuralType()) 1339 return false; 1340 1341 // Structural types are required to be object types or lvalue references. 1342 if (T->isRValueReferenceType()) { 1343 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T; 1344 return true; 1345 } 1346 1347 // Don't mention structural types in our diagnostic prior to C++20. Also, 1348 // there's not much more we can say about non-scalar non-class types -- 1349 // because we can't see functions or arrays here, those can only be language 1350 // extensions. 1351 if (!getLangOpts().CPlusPlus20 || 1352 (!T->isScalarType() && !T->isRecordType())) { 1353 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T; 1354 return true; 1355 } 1356 1357 // Structural types are required to be literal types. 1358 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal)) 1359 return true; 1360 1361 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T; 1362 1363 // Drill down into the reason why the class is non-structural. 1364 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) { 1365 // All members are required to be public and non-mutable, and can't be of 1366 // rvalue reference type. Check these conditions first to prefer a "local" 1367 // reason over a more distant one. 1368 for (const FieldDecl *FD : RD->fields()) { 1369 if (FD->getAccess() != AS_public) { 1370 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0; 1371 return true; 1372 } 1373 if (FD->isMutable()) { 1374 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T; 1375 return true; 1376 } 1377 if (FD->getType()->isRValueReferenceType()) { 1378 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field) 1379 << T; 1380 return true; 1381 } 1382 } 1383 1384 // All bases are required to be public. 1385 for (const auto &BaseSpec : RD->bases()) { 1386 if (BaseSpec.getAccessSpecifier() != AS_public) { 1387 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public) 1388 << T << 1; 1389 return true; 1390 } 1391 } 1392 1393 // All subobjects are required to be of structural types. 1394 SourceLocation SubLoc; 1395 QualType SubType; 1396 int Kind = -1; 1397 1398 for (const FieldDecl *FD : RD->fields()) { 1399 QualType T = Context.getBaseElementType(FD->getType()); 1400 if (!T->isStructuralType()) { 1401 SubLoc = FD->getLocation(); 1402 SubType = T; 1403 Kind = 0; 1404 break; 1405 } 1406 } 1407 1408 if (Kind == -1) { 1409 for (const auto &BaseSpec : RD->bases()) { 1410 QualType T = BaseSpec.getType(); 1411 if (!T->isStructuralType()) { 1412 SubLoc = BaseSpec.getBaseTypeLoc(); 1413 SubType = T; 1414 Kind = 1; 1415 break; 1416 } 1417 } 1418 } 1419 1420 assert(Kind != -1 && "couldn't find reason why type is not structural"); 1421 Diag(SubLoc, diag::note_not_structural_subobject) 1422 << T << Kind << SubType; 1423 T = SubType; 1424 RD = T->getAsCXXRecordDecl(); 1425 } 1426 1427 return true; 1428 } 1429 1430 QualType Sema::CheckNonTypeTemplateParameterType(QualType T, 1431 SourceLocation Loc) { 1432 // We don't allow variably-modified types as the type of non-type template 1433 // parameters. 1434 if (T->isVariablyModifiedType()) { 1435 Diag(Loc, diag::err_variably_modified_nontype_template_param) 1436 << T; 1437 return QualType(); 1438 } 1439 1440 // C++ [temp.param]p4: 1441 // 1442 // A non-type template-parameter shall have one of the following 1443 // (optionally cv-qualified) types: 1444 // 1445 // -- integral or enumeration type, 1446 if (T->isIntegralOrEnumerationType() || 1447 // -- pointer to object or pointer to function, 1448 T->isPointerType() || 1449 // -- lvalue reference to object or lvalue reference to function, 1450 T->isLValueReferenceType() || 1451 // -- pointer to member, 1452 T->isMemberPointerType() || 1453 // -- std::nullptr_t, or 1454 T->isNullPtrType() || 1455 // -- a type that contains a placeholder type. 1456 T->isUndeducedType()) { 1457 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter 1458 // are ignored when determining its type. 1459 return T.getUnqualifiedType(); 1460 } 1461 1462 // C++ [temp.param]p8: 1463 // 1464 // A non-type template-parameter of type "array of T" or 1465 // "function returning T" is adjusted to be of type "pointer to 1466 // T" or "pointer to function returning T", respectively. 1467 if (T->isArrayType() || T->isFunctionType()) 1468 return Context.getDecayedType(T); 1469 1470 // If T is a dependent type, we can't do the check now, so we 1471 // assume that it is well-formed. Note that stripping off the 1472 // qualifiers here is not really correct if T turns out to be 1473 // an array type, but we'll recompute the type everywhere it's 1474 // used during instantiation, so that should be OK. (Using the 1475 // qualified type is equally wrong.) 1476 if (T->isDependentType()) 1477 return T.getUnqualifiedType(); 1478 1479 // C++20 [temp.param]p6: 1480 // -- a structural type 1481 if (RequireStructuralType(T, Loc)) 1482 return QualType(); 1483 1484 if (!getLangOpts().CPlusPlus20) { 1485 // FIXME: Consider allowing structural types as an extension in C++17. (In 1486 // earlier language modes, the template argument evaluation rules are too 1487 // inflexible.) 1488 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T; 1489 return QualType(); 1490 } 1491 1492 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T; 1493 return T.getUnqualifiedType(); 1494 } 1495 1496 NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 1497 unsigned Depth, 1498 unsigned Position, 1499 SourceLocation EqualLoc, 1500 Expr *Default) { 1501 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 1502 1503 // Check that we have valid decl-specifiers specified. 1504 auto CheckValidDeclSpecifiers = [this, &D] { 1505 // C++ [temp.param] 1506 // p1 1507 // template-parameter: 1508 // ... 1509 // parameter-declaration 1510 // p2 1511 // ... A storage class shall not be specified in a template-parameter 1512 // declaration. 1513 // [dcl.typedef]p1: 1514 // The typedef specifier [...] shall not be used in the decl-specifier-seq 1515 // of a parameter-declaration 1516 const DeclSpec &DS = D.getDeclSpec(); 1517 auto EmitDiag = [this](SourceLocation Loc) { 1518 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm) 1519 << FixItHint::CreateRemoval(Loc); 1520 }; 1521 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) 1522 EmitDiag(DS.getStorageClassSpecLoc()); 1523 1524 if (DS.getThreadStorageClassSpec() != TSCS_unspecified) 1525 EmitDiag(DS.getThreadStorageClassSpecLoc()); 1526 1527 // [dcl.inline]p1: 1528 // The inline specifier can be applied only to the declaration or 1529 // definition of a variable or function. 1530 1531 if (DS.isInlineSpecified()) 1532 EmitDiag(DS.getInlineSpecLoc()); 1533 1534 // [dcl.constexpr]p1: 1535 // The constexpr specifier shall be applied only to the definition of a 1536 // variable or variable template or the declaration of a function or 1537 // function template. 1538 1539 if (DS.hasConstexprSpecifier()) 1540 EmitDiag(DS.getConstexprSpecLoc()); 1541 1542 // [dcl.fct.spec]p1: 1543 // Function-specifiers can be used only in function declarations. 1544 1545 if (DS.isVirtualSpecified()) 1546 EmitDiag(DS.getVirtualSpecLoc()); 1547 1548 if (DS.hasExplicitSpecifier()) 1549 EmitDiag(DS.getExplicitSpecLoc()); 1550 1551 if (DS.isNoreturnSpecified()) 1552 EmitDiag(DS.getNoreturnSpecLoc()); 1553 }; 1554 1555 CheckValidDeclSpecifiers(); 1556 1557 if (const auto *T = TInfo->getType()->getContainedDeducedType()) 1558 if (isa<AutoType>(T)) 1559 Diag(D.getIdentifierLoc(), 1560 diag::warn_cxx14_compat_template_nontype_parm_auto_type) 1561 << QualType(TInfo->getType()->getContainedAutoType(), 0); 1562 1563 assert(S->isTemplateParamScope() && 1564 "Non-type template parameter not in template parameter scope!"); 1565 bool Invalid = false; 1566 1567 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc()); 1568 if (T.isNull()) { 1569 T = Context.IntTy; // Recover with an 'int' type. 1570 Invalid = true; 1571 } 1572 1573 CheckFunctionOrTemplateParamDeclarator(S, D); 1574 1575 IdentifierInfo *ParamName = D.getIdentifier(); 1576 bool IsParameterPack = D.hasEllipsis(); 1577 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create( 1578 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(), 1579 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack, 1580 TInfo); 1581 Param->setAccess(AS_public); 1582 1583 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) 1584 if (TL.isConstrained()) 1585 if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc())) 1586 Invalid = true; 1587 1588 if (Invalid) 1589 Param->setInvalidDecl(); 1590 1591 if (Param->isParameterPack()) 1592 if (auto *LSI = getEnclosingLambda()) 1593 LSI->LocalPacks.push_back(Param); 1594 1595 if (ParamName) { 1596 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(), 1597 ParamName); 1598 1599 // Add the template parameter into the current scope. 1600 S->AddDecl(Param); 1601 IdResolver.AddDecl(Param); 1602 } 1603 1604 // C++0x [temp.param]p9: 1605 // A default template-argument may be specified for any kind of 1606 // template-parameter that is not a template parameter pack. 1607 if (Default && IsParameterPack) { 1608 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 1609 Default = nullptr; 1610 } 1611 1612 // Check the well-formedness of the default template argument, if provided. 1613 if (Default) { 1614 // Check for unexpanded parameter packs. 1615 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument)) 1616 return Param; 1617 1618 Param->setDefaultArgument(Default); 1619 } 1620 1621 return Param; 1622 } 1623 1624 /// ActOnTemplateTemplateParameter - Called when a C++ template template 1625 /// parameter (e.g. T in template <template \<typename> class T> class array) 1626 /// has been parsed. S is the current scope. 1627 NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S, 1628 SourceLocation TmpLoc, 1629 TemplateParameterList *Params, 1630 SourceLocation EllipsisLoc, 1631 IdentifierInfo *Name, 1632 SourceLocation NameLoc, 1633 unsigned Depth, 1634 unsigned Position, 1635 SourceLocation EqualLoc, 1636 ParsedTemplateArgument Default) { 1637 assert(S->isTemplateParamScope() && 1638 "Template template parameter not in template parameter scope!"); 1639 1640 // Construct the parameter object. 1641 bool IsParameterPack = EllipsisLoc.isValid(); 1642 TemplateTemplateParmDecl *Param = 1643 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(), 1644 NameLoc.isInvalid()? TmpLoc : NameLoc, 1645 Depth, Position, IsParameterPack, 1646 Name, Params); 1647 Param->setAccess(AS_public); 1648 1649 if (Param->isParameterPack()) 1650 if (auto *LSI = getEnclosingLambda()) 1651 LSI->LocalPacks.push_back(Param); 1652 1653 // If the template template parameter has a name, then link the identifier 1654 // into the scope and lookup mechanisms. 1655 if (Name) { 1656 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name); 1657 1658 S->AddDecl(Param); 1659 IdResolver.AddDecl(Param); 1660 } 1661 1662 if (Params->size() == 0) { 1663 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms) 1664 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc()); 1665 Param->setInvalidDecl(); 1666 } 1667 1668 // C++0x [temp.param]p9: 1669 // A default template-argument may be specified for any kind of 1670 // template-parameter that is not a template parameter pack. 1671 if (IsParameterPack && !Default.isInvalid()) { 1672 Diag(EqualLoc, diag::err_template_param_pack_default_arg); 1673 Default = ParsedTemplateArgument(); 1674 } 1675 1676 if (!Default.isInvalid()) { 1677 // Check only that we have a template template argument. We don't want to 1678 // try to check well-formedness now, because our template template parameter 1679 // might have dependent types in its template parameters, which we wouldn't 1680 // be able to match now. 1681 // 1682 // If none of the template template parameter's template arguments mention 1683 // other template parameters, we could actually perform more checking here. 1684 // However, it isn't worth doing. 1685 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default); 1686 if (DefaultArg.getArgument().getAsTemplate().isNull()) { 1687 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template) 1688 << DefaultArg.getSourceRange(); 1689 return Param; 1690 } 1691 1692 // Check for unexpanded parameter packs. 1693 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(), 1694 DefaultArg.getArgument().getAsTemplate(), 1695 UPPC_DefaultArgument)) 1696 return Param; 1697 1698 Param->setDefaultArgument(Context, DefaultArg); 1699 } 1700 1701 return Param; 1702 } 1703 1704 namespace { 1705 class ConstraintRefersToContainingTemplateChecker 1706 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> { 1707 bool Result = false; 1708 const FunctionDecl *Friend = nullptr; 1709 unsigned TemplateDepth = 0; 1710 1711 // Check a record-decl that we've seen to see if it is a lexical parent of the 1712 // Friend, likely because it was referred to without its template arguments. 1713 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) { 1714 CheckingRD = CheckingRD->getMostRecentDecl(); 1715 if (!CheckingRD->isTemplated()) 1716 return; 1717 1718 for (const DeclContext *DC = Friend->getLexicalDeclContext(); 1719 DC && !DC->isFileContext(); DC = DC->getParent()) 1720 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC)) 1721 if (CheckingRD == RD->getMostRecentDecl()) 1722 Result = true; 1723 } 1724 1725 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { 1726 assert(D->getDepth() <= TemplateDepth && 1727 "Nothing should reference a value below the actual template depth, " 1728 "depth is likely wrong"); 1729 if (D->getDepth() != TemplateDepth) 1730 Result = true; 1731 1732 // Necessary because the type of the NTTP might be what refers to the parent 1733 // constriant. 1734 TransformType(D->getType()); 1735 } 1736 1737 public: 1738 using inherited = TreeTransform<ConstraintRefersToContainingTemplateChecker>; 1739 1740 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef, 1741 const FunctionDecl *Friend, 1742 unsigned TemplateDepth) 1743 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {} 1744 bool getResult() const { return Result; } 1745 1746 // This should be the only template parm type that we have to deal with. 1747 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and 1748 // FunctionParmPackExpr are all partially substituted, which cannot happen 1749 // with concepts at this point in translation. 1750 using inherited::TransformTemplateTypeParmType; 1751 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB, 1752 TemplateTypeParmTypeLoc TL, bool) { 1753 assert(TL.getDecl()->getDepth() <= TemplateDepth && 1754 "Nothing should reference a value below the actual template depth, " 1755 "depth is likely wrong"); 1756 if (TL.getDecl()->getDepth() != TemplateDepth) 1757 Result = true; 1758 return inherited::TransformTemplateTypeParmType( 1759 TLB, TL, 1760 /*SuppressObjCLifetime=*/false); 1761 } 1762 1763 Decl *TransformDecl(SourceLocation Loc, Decl *D) { 1764 if (!D) 1765 return D; 1766 // FIXME : This is possibly an incomplete list, but it is unclear what other 1767 // Decl kinds could be used to refer to the template parameters. This is a 1768 // best guess so far based on examples currently available, but the 1769 // unreachable should catch future instances/cases. 1770 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) 1771 TransformType(TD->getUnderlyingType()); 1772 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D)) 1773 CheckNonTypeTemplateParmDecl(NTTPD); 1774 else if (auto *VD = dyn_cast<ValueDecl>(D)) 1775 TransformType(VD->getType()); 1776 else if (auto *TD = dyn_cast<TemplateDecl>(D)) 1777 TransformTemplateParameterList(TD->getTemplateParameters()); 1778 else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) 1779 CheckIfContainingRecord(RD); 1780 else if (isa<NamedDecl>(D)) { 1781 // No direct types to visit here I believe. 1782 } else 1783 llvm_unreachable("Don't know how to handle this declaration type yet"); 1784 return D; 1785 } 1786 }; 1787 } // namespace 1788 1789 bool Sema::ConstraintExpressionDependsOnEnclosingTemplate( 1790 const FunctionDecl *Friend, unsigned TemplateDepth, 1791 const Expr *Constraint) { 1792 assert(Friend->getFriendObjectKind() && "Only works on a friend"); 1793 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend, 1794 TemplateDepth); 1795 Checker.TransformExpr(const_cast<Expr *>(Constraint)); 1796 return Checker.getResult(); 1797 } 1798 1799 /// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally 1800 /// constrained by RequiresClause, that contains the template parameters in 1801 /// Params. 1802 TemplateParameterList * 1803 Sema::ActOnTemplateParameterList(unsigned Depth, 1804 SourceLocation ExportLoc, 1805 SourceLocation TemplateLoc, 1806 SourceLocation LAngleLoc, 1807 ArrayRef<NamedDecl *> Params, 1808 SourceLocation RAngleLoc, 1809 Expr *RequiresClause) { 1810 if (ExportLoc.isValid()) 1811 Diag(ExportLoc, diag::warn_template_export_unsupported); 1812 1813 for (NamedDecl *P : Params) 1814 warnOnReservedIdentifier(P); 1815 1816 return TemplateParameterList::Create( 1817 Context, TemplateLoc, LAngleLoc, 1818 llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause); 1819 } 1820 1821 static void SetNestedNameSpecifier(Sema &S, TagDecl *T, 1822 const CXXScopeSpec &SS) { 1823 if (SS.isSet()) 1824 T->setQualifierInfo(SS.getWithLocInContext(S.Context)); 1825 } 1826 1827 DeclResult Sema::CheckClassTemplate( 1828 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 1829 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, 1830 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, 1831 AccessSpecifier AS, SourceLocation ModulePrivateLoc, 1832 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, 1833 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) { 1834 assert(TemplateParams && TemplateParams->size() > 0 && 1835 "No template parameters"); 1836 assert(TUK != TUK_Reference && "Can only declare or define class templates"); 1837 bool Invalid = false; 1838 1839 // Check that we can declare a template here. 1840 if (CheckTemplateDeclScope(S, TemplateParams)) 1841 return true; 1842 1843 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 1844 assert(Kind != TagTypeKind::Enum && 1845 "can't build template of enumerated type"); 1846 1847 // There is no such thing as an unnamed class template. 1848 if (!Name) { 1849 Diag(KWLoc, diag::err_template_unnamed_class); 1850 return true; 1851 } 1852 1853 // Find any previous declaration with this name. For a friend with no 1854 // scope explicitly specified, we only look for tag declarations (per 1855 // C++11 [basic.lookup.elab]p2). 1856 DeclContext *SemanticContext; 1857 LookupResult Previous(*this, Name, NameLoc, 1858 (SS.isEmpty() && TUK == TUK_Friend) 1859 ? LookupTagName : LookupOrdinaryName, 1860 forRedeclarationInCurContext()); 1861 if (SS.isNotEmpty() && !SS.isInvalid()) { 1862 SemanticContext = computeDeclContext(SS, true); 1863 if (!SemanticContext) { 1864 // FIXME: Horrible, horrible hack! We can't currently represent this 1865 // in the AST, and historically we have just ignored such friend 1866 // class templates, so don't complain here. 1867 Diag(NameLoc, TUK == TUK_Friend 1868 ? diag::warn_template_qualified_friend_ignored 1869 : diag::err_template_qualified_declarator_no_match) 1870 << SS.getScopeRep() << SS.getRange(); 1871 return TUK != TUK_Friend; 1872 } 1873 1874 if (RequireCompleteDeclContext(SS, SemanticContext)) 1875 return true; 1876 1877 // If we're adding a template to a dependent context, we may need to 1878 // rebuilding some of the types used within the template parameter list, 1879 // now that we know what the current instantiation is. 1880 if (SemanticContext->isDependentContext()) { 1881 ContextRAII SavedContext(*this, SemanticContext); 1882 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 1883 Invalid = true; 1884 } else if (TUK != TUK_Friend && TUK != TUK_Reference) 1885 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false); 1886 1887 LookupQualifiedName(Previous, SemanticContext); 1888 } else { 1889 SemanticContext = CurContext; 1890 1891 // C++14 [class.mem]p14: 1892 // If T is the name of a class, then each of the following shall have a 1893 // name different from T: 1894 // -- every member template of class T 1895 if (TUK != TUK_Friend && 1896 DiagnoseClassNameShadow(SemanticContext, 1897 DeclarationNameInfo(Name, NameLoc))) 1898 return true; 1899 1900 LookupName(Previous, S); 1901 } 1902 1903 if (Previous.isAmbiguous()) 1904 return true; 1905 1906 NamedDecl *PrevDecl = nullptr; 1907 if (Previous.begin() != Previous.end()) 1908 PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 1909 1910 if (PrevDecl && PrevDecl->isTemplateParameter()) { 1911 // Maybe we will complain about the shadowed template parameter. 1912 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); 1913 // Just pretend that we didn't see the previous declaration. 1914 PrevDecl = nullptr; 1915 } 1916 1917 // If there is a previous declaration with the same name, check 1918 // whether this is a valid redeclaration. 1919 ClassTemplateDecl *PrevClassTemplate = 1920 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl); 1921 1922 // We may have found the injected-class-name of a class template, 1923 // class template partial specialization, or class template specialization. 1924 // In these cases, grab the template that is being defined or specialized. 1925 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) && 1926 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) { 1927 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext()); 1928 PrevClassTemplate 1929 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate(); 1930 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) { 1931 PrevClassTemplate 1932 = cast<ClassTemplateSpecializationDecl>(PrevDecl) 1933 ->getSpecializedTemplate(); 1934 } 1935 } 1936 1937 if (TUK == TUK_Friend) { 1938 // C++ [namespace.memdef]p3: 1939 // [...] When looking for a prior declaration of a class or a function 1940 // declared as a friend, and when the name of the friend class or 1941 // function is neither a qualified name nor a template-id, scopes outside 1942 // the innermost enclosing namespace scope are not considered. 1943 if (!SS.isSet()) { 1944 DeclContext *OutermostContext = CurContext; 1945 while (!OutermostContext->isFileContext()) 1946 OutermostContext = OutermostContext->getLookupParent(); 1947 1948 if (PrevDecl && 1949 (OutermostContext->Equals(PrevDecl->getDeclContext()) || 1950 OutermostContext->Encloses(PrevDecl->getDeclContext()))) { 1951 SemanticContext = PrevDecl->getDeclContext(); 1952 } else { 1953 // Declarations in outer scopes don't matter. However, the outermost 1954 // context we computed is the semantic context for our new 1955 // declaration. 1956 PrevDecl = PrevClassTemplate = nullptr; 1957 SemanticContext = OutermostContext; 1958 1959 // Check that the chosen semantic context doesn't already contain a 1960 // declaration of this name as a non-tag type. 1961 Previous.clear(LookupOrdinaryName); 1962 DeclContext *LookupContext = SemanticContext; 1963 while (LookupContext->isTransparentContext()) 1964 LookupContext = LookupContext->getLookupParent(); 1965 LookupQualifiedName(Previous, LookupContext); 1966 1967 if (Previous.isAmbiguous()) 1968 return true; 1969 1970 if (Previous.begin() != Previous.end()) 1971 PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 1972 } 1973 } 1974 } else if (PrevDecl && 1975 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext, 1976 S, SS.isValid())) 1977 PrevDecl = PrevClassTemplate = nullptr; 1978 1979 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>( 1980 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) { 1981 if (SS.isEmpty() && 1982 !(PrevClassTemplate && 1983 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals( 1984 SemanticContext->getRedeclContext()))) { 1985 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 1986 Diag(Shadow->getTargetDecl()->getLocation(), 1987 diag::note_using_decl_target); 1988 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0; 1989 // Recover by ignoring the old declaration. 1990 PrevDecl = PrevClassTemplate = nullptr; 1991 } 1992 } 1993 1994 if (PrevClassTemplate) { 1995 // Ensure that the template parameter lists are compatible. Skip this check 1996 // for a friend in a dependent context: the template parameter list itself 1997 // could be dependent. 1998 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) && 1999 !TemplateParameterListsAreEqual( 2000 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext 2001 : CurContext, 2002 CurContext, KWLoc), 2003 TemplateParams, PrevClassTemplate, 2004 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true, 2005 TPL_TemplateMatch)) 2006 return true; 2007 2008 // C++ [temp.class]p4: 2009 // In a redeclaration, partial specialization, explicit 2010 // specialization or explicit instantiation of a class template, 2011 // the class-key shall agree in kind with the original class 2012 // template declaration (7.1.5.3). 2013 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl(); 2014 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind, 2015 TUK == TUK_Definition, KWLoc, Name)) { 2016 Diag(KWLoc, diag::err_use_with_wrong_tag) 2017 << Name 2018 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName()); 2019 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use); 2020 Kind = PrevRecordDecl->getTagKind(); 2021 } 2022 2023 // Check for redefinition of this class template. 2024 if (TUK == TUK_Definition) { 2025 if (TagDecl *Def = PrevRecordDecl->getDefinition()) { 2026 // If we have a prior definition that is not visible, treat this as 2027 // simply making that previous definition visible. 2028 NamedDecl *Hidden = nullptr; 2029 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 2030 SkipBody->ShouldSkip = true; 2031 SkipBody->Previous = Def; 2032 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate(); 2033 assert(Tmpl && "original definition of a class template is not a " 2034 "class template?"); 2035 makeMergedDefinitionVisible(Hidden); 2036 makeMergedDefinitionVisible(Tmpl); 2037 } else { 2038 Diag(NameLoc, diag::err_redefinition) << Name; 2039 Diag(Def->getLocation(), diag::note_previous_definition); 2040 // FIXME: Would it make sense to try to "forget" the previous 2041 // definition, as part of error recovery? 2042 return true; 2043 } 2044 } 2045 } 2046 } else if (PrevDecl) { 2047 // C++ [temp]p5: 2048 // A class template shall not have the same name as any other 2049 // template, class, function, object, enumeration, enumerator, 2050 // namespace, or type in the same scope (3.3), except as specified 2051 // in (14.5.4). 2052 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 2053 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2054 return true; 2055 } 2056 2057 // Check the template parameter list of this declaration, possibly 2058 // merging in the template parameter list from the previous class 2059 // template declaration. Skip this check for a friend in a dependent 2060 // context, because the template parameter list might be dependent. 2061 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) && 2062 CheckTemplateParameterList( 2063 TemplateParams, 2064 PrevClassTemplate 2065 ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters() 2066 : nullptr, 2067 (SS.isSet() && SemanticContext && SemanticContext->isRecord() && 2068 SemanticContext->isDependentContext()) 2069 ? TPC_ClassTemplateMember 2070 : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate, 2071 SkipBody)) 2072 Invalid = true; 2073 2074 if (SS.isSet()) { 2075 // If the name of the template was qualified, we must be defining the 2076 // template out-of-line. 2077 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) { 2078 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match 2079 : diag::err_member_decl_does_not_match) 2080 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange(); 2081 Invalid = true; 2082 } 2083 } 2084 2085 // If this is a templated friend in a dependent context we should not put it 2086 // on the redecl chain. In some cases, the templated friend can be the most 2087 // recent declaration tricking the template instantiator to make substitutions 2088 // there. 2089 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious 2090 bool ShouldAddRedecl 2091 = !(TUK == TUK_Friend && CurContext->isDependentContext()); 2092 2093 CXXRecordDecl *NewClass = 2094 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name, 2095 PrevClassTemplate && ShouldAddRedecl ? 2096 PrevClassTemplate->getTemplatedDecl() : nullptr, 2097 /*DelayTypeCreation=*/true); 2098 SetNestedNameSpecifier(*this, NewClass, SS); 2099 if (NumOuterTemplateParamLists > 0) 2100 NewClass->setTemplateParameterListsInfo( 2101 Context, 2102 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists)); 2103 2104 // Add alignment attributes if necessary; these attributes are checked when 2105 // the ASTContext lays out the structure. 2106 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 2107 AddAlignmentAttributesForRecord(NewClass); 2108 AddMsStructLayoutForRecord(NewClass); 2109 } 2110 2111 ClassTemplateDecl *NewTemplate 2112 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc, 2113 DeclarationName(Name), TemplateParams, 2114 NewClass); 2115 2116 if (ShouldAddRedecl) 2117 NewTemplate->setPreviousDecl(PrevClassTemplate); 2118 2119 NewClass->setDescribedClassTemplate(NewTemplate); 2120 2121 if (ModulePrivateLoc.isValid()) 2122 NewTemplate->setModulePrivate(); 2123 2124 // Build the type for the class template declaration now. 2125 QualType T = NewTemplate->getInjectedClassNameSpecialization(); 2126 T = Context.getInjectedClassNameType(NewClass, T); 2127 assert(T->isDependentType() && "Class template type is not dependent?"); 2128 (void)T; 2129 2130 // If we are providing an explicit specialization of a member that is a 2131 // class template, make a note of that. 2132 if (PrevClassTemplate && 2133 PrevClassTemplate->getInstantiatedFromMemberTemplate()) 2134 PrevClassTemplate->setMemberSpecialization(); 2135 2136 // Set the access specifier. 2137 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord()) 2138 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS); 2139 2140 // Set the lexical context of these templates 2141 NewClass->setLexicalDeclContext(CurContext); 2142 NewTemplate->setLexicalDeclContext(CurContext); 2143 2144 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 2145 NewClass->startDefinition(); 2146 2147 ProcessDeclAttributeList(S, NewClass, Attr); 2148 2149 if (PrevClassTemplate) 2150 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl()); 2151 2152 AddPushedVisibilityAttribute(NewClass); 2153 inferGslOwnerPointerAttribute(NewClass); 2154 2155 if (TUK != TUK_Friend) { 2156 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes. 2157 Scope *Outer = S; 2158 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0) 2159 Outer = Outer->getParent(); 2160 PushOnScopeChains(NewTemplate, Outer); 2161 } else { 2162 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) { 2163 NewTemplate->setAccess(PrevClassTemplate->getAccess()); 2164 NewClass->setAccess(PrevClassTemplate->getAccess()); 2165 } 2166 2167 NewTemplate->setObjectOfFriendDecl(); 2168 2169 // Friend templates are visible in fairly strange ways. 2170 if (!CurContext->isDependentContext()) { 2171 DeclContext *DC = SemanticContext->getRedeclContext(); 2172 DC->makeDeclVisibleInContext(NewTemplate); 2173 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 2174 PushOnScopeChains(NewTemplate, EnclosingScope, 2175 /* AddToContext = */ false); 2176 } 2177 2178 FriendDecl *Friend = FriendDecl::Create( 2179 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc); 2180 Friend->setAccess(AS_public); 2181 CurContext->addDecl(Friend); 2182 } 2183 2184 if (PrevClassTemplate) 2185 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate); 2186 2187 if (Invalid) { 2188 NewTemplate->setInvalidDecl(); 2189 NewClass->setInvalidDecl(); 2190 } 2191 2192 ActOnDocumentableDecl(NewTemplate); 2193 2194 if (SkipBody && SkipBody->ShouldSkip) 2195 return SkipBody->Previous; 2196 2197 return NewTemplate; 2198 } 2199 2200 namespace { 2201 /// Tree transform to "extract" a transformed type from a class template's 2202 /// constructor to a deduction guide. 2203 class ExtractTypeForDeductionGuide 2204 : public TreeTransform<ExtractTypeForDeductionGuide> { 2205 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs; 2206 2207 public: 2208 typedef TreeTransform<ExtractTypeForDeductionGuide> Base; 2209 ExtractTypeForDeductionGuide( 2210 Sema &SemaRef, 2211 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) 2212 : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {} 2213 2214 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); } 2215 2216 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) { 2217 ASTContext &Context = SemaRef.getASTContext(); 2218 TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl(); 2219 TypedefNameDecl *Decl = OrigDecl; 2220 // Transform the underlying type of the typedef and clone the Decl only if 2221 // the typedef has a dependent context. 2222 if (OrigDecl->getDeclContext()->isDependentContext()) { 2223 TypeLocBuilder InnerTLB; 2224 QualType Transformed = 2225 TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc()); 2226 TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed); 2227 if (isa<TypeAliasDecl>(OrigDecl)) 2228 Decl = TypeAliasDecl::Create( 2229 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(), 2230 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI); 2231 else { 2232 assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef"); 2233 Decl = TypedefDecl::Create( 2234 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(), 2235 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI); 2236 } 2237 MaterializedTypedefs.push_back(Decl); 2238 } 2239 2240 QualType TDTy = Context.getTypedefType(Decl); 2241 TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy); 2242 TypedefTL.setNameLoc(TL.getNameLoc()); 2243 2244 return TDTy; 2245 } 2246 }; 2247 2248 /// Transform to convert portions of a constructor declaration into the 2249 /// corresponding deduction guide, per C++1z [over.match.class.deduct]p1. 2250 struct ConvertConstructorToDeductionGuideTransform { 2251 ConvertConstructorToDeductionGuideTransform(Sema &S, 2252 ClassTemplateDecl *Template) 2253 : SemaRef(S), Template(Template) { 2254 // If the template is nested, then we need to use the original 2255 // pattern to iterate over the constructors. 2256 ClassTemplateDecl *Pattern = Template; 2257 while (Pattern->getInstantiatedFromMemberTemplate()) { 2258 if (Pattern->isMemberSpecialization()) 2259 break; 2260 Pattern = Pattern->getInstantiatedFromMemberTemplate(); 2261 NestedPattern = Pattern; 2262 } 2263 2264 if (NestedPattern) 2265 OuterInstantiationArgs = SemaRef.getTemplateInstantiationArgs(Template); 2266 } 2267 2268 Sema &SemaRef; 2269 ClassTemplateDecl *Template; 2270 ClassTemplateDecl *NestedPattern = nullptr; 2271 2272 DeclContext *DC = Template->getDeclContext(); 2273 CXXRecordDecl *Primary = Template->getTemplatedDecl(); 2274 DeclarationName DeductionGuideName = 2275 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template); 2276 2277 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary); 2278 2279 // Index adjustment to apply to convert depth-1 template parameters into 2280 // depth-0 template parameters. 2281 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size(); 2282 2283 // Instantiation arguments for the outermost depth-1 templates 2284 // when the template is nested 2285 MultiLevelTemplateArgumentList OuterInstantiationArgs; 2286 2287 /// Transform a constructor declaration into a deduction guide. 2288 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD, 2289 CXXConstructorDecl *CD) { 2290 SmallVector<TemplateArgument, 16> SubstArgs; 2291 2292 LocalInstantiationScope Scope(SemaRef); 2293 2294 // C++ [over.match.class.deduct]p1: 2295 // -- For each constructor of the class template designated by the 2296 // template-name, a function template with the following properties: 2297 2298 // -- The template parameters are the template parameters of the class 2299 // template followed by the template parameters (including default 2300 // template arguments) of the constructor, if any. 2301 TemplateParameterList *TemplateParams = Template->getTemplateParameters(); 2302 if (FTD) { 2303 TemplateParameterList *InnerParams = FTD->getTemplateParameters(); 2304 SmallVector<NamedDecl *, 16> AllParams; 2305 SmallVector<TemplateArgument, 16> Depth1Args; 2306 AllParams.reserve(TemplateParams->size() + InnerParams->size()); 2307 AllParams.insert(AllParams.begin(), 2308 TemplateParams->begin(), TemplateParams->end()); 2309 SubstArgs.reserve(InnerParams->size()); 2310 Depth1Args.reserve(InnerParams->size()); 2311 2312 // Later template parameters could refer to earlier ones, so build up 2313 // a list of substituted template arguments as we go. 2314 for (NamedDecl *Param : *InnerParams) { 2315 MultiLevelTemplateArgumentList Args; 2316 Args.setKind(TemplateSubstitutionKind::Rewrite); 2317 Args.addOuterTemplateArguments(Depth1Args); 2318 Args.addOuterRetainedLevel(); 2319 if (NestedPattern) 2320 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth()); 2321 NamedDecl *NewParam = transformTemplateParameter(Param, Args); 2322 if (!NewParam) 2323 return nullptr; 2324 2325 // Constraints require that we substitute depth-1 arguments 2326 // to match depths when substituted for evaluation later 2327 Depth1Args.push_back(SemaRef.Context.getCanonicalTemplateArgument( 2328 SemaRef.Context.getInjectedTemplateArg(NewParam))); 2329 2330 if (NestedPattern) { 2331 TemplateDeclInstantiator Instantiator(SemaRef, DC, 2332 OuterInstantiationArgs); 2333 Instantiator.setEvaluateConstraints(false); 2334 SemaRef.runWithSufficientStackSpace(NewParam->getLocation(), [&] { 2335 NewParam = cast<NamedDecl>(Instantiator.Visit(NewParam)); 2336 }); 2337 } 2338 2339 assert(NewParam->getTemplateDepth() == 0 && 2340 "Unexpected template parameter depth"); 2341 2342 AllParams.push_back(NewParam); 2343 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument( 2344 SemaRef.Context.getInjectedTemplateArg(NewParam))); 2345 } 2346 2347 // Substitute new template parameters into requires-clause if present. 2348 Expr *RequiresClause = nullptr; 2349 if (Expr *InnerRC = InnerParams->getRequiresClause()) { 2350 MultiLevelTemplateArgumentList Args; 2351 Args.setKind(TemplateSubstitutionKind::Rewrite); 2352 Args.addOuterTemplateArguments(Depth1Args); 2353 Args.addOuterRetainedLevel(); 2354 if (NestedPattern) 2355 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth()); 2356 ExprResult E = SemaRef.SubstExpr(InnerRC, Args); 2357 if (E.isInvalid()) 2358 return nullptr; 2359 RequiresClause = E.getAs<Expr>(); 2360 } 2361 2362 TemplateParams = TemplateParameterList::Create( 2363 SemaRef.Context, InnerParams->getTemplateLoc(), 2364 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(), 2365 RequiresClause); 2366 } 2367 2368 // If we built a new template-parameter-list, track that we need to 2369 // substitute references to the old parameters into references to the 2370 // new ones. 2371 MultiLevelTemplateArgumentList Args; 2372 Args.setKind(TemplateSubstitutionKind::Rewrite); 2373 if (FTD) { 2374 Args.addOuterTemplateArguments(SubstArgs); 2375 Args.addOuterRetainedLevel(); 2376 } 2377 2378 if (NestedPattern) 2379 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth()); 2380 2381 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc() 2382 .getAsAdjusted<FunctionProtoTypeLoc>(); 2383 assert(FPTL && "no prototype for constructor declaration"); 2384 2385 // Transform the type of the function, adjusting the return type and 2386 // replacing references to the old parameters with references to the 2387 // new ones. 2388 TypeLocBuilder TLB; 2389 SmallVector<ParmVarDecl*, 8> Params; 2390 SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs; 2391 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args, 2392 MaterializedTypedefs); 2393 if (NewType.isNull()) 2394 return nullptr; 2395 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType); 2396 2397 return buildDeductionGuide(TemplateParams, CD, CD->getExplicitSpecifier(), 2398 NewTInfo, CD->getBeginLoc(), CD->getLocation(), 2399 CD->getEndLoc(), MaterializedTypedefs); 2400 } 2401 2402 /// Build a deduction guide with the specified parameter types. 2403 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) { 2404 SourceLocation Loc = Template->getLocation(); 2405 2406 // Build the requested type. 2407 FunctionProtoType::ExtProtoInfo EPI; 2408 EPI.HasTrailingReturn = true; 2409 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc, 2410 DeductionGuideName, EPI); 2411 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc); 2412 2413 FunctionProtoTypeLoc FPTL = 2414 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>(); 2415 2416 // Build the parameters, needed during deduction / substitution. 2417 SmallVector<ParmVarDecl*, 4> Params; 2418 for (auto T : ParamTypes) { 2419 ParmVarDecl *NewParam = ParmVarDecl::Create( 2420 SemaRef.Context, DC, Loc, Loc, nullptr, T, 2421 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr); 2422 NewParam->setScopeInfo(0, Params.size()); 2423 FPTL.setParam(Params.size(), NewParam); 2424 Params.push_back(NewParam); 2425 } 2426 2427 return buildDeductionGuide(Template->getTemplateParameters(), nullptr, 2428 ExplicitSpecifier(), TSI, Loc, Loc, Loc); 2429 } 2430 2431 private: 2432 /// Transform a constructor template parameter into a deduction guide template 2433 /// parameter, rebuilding any internal references to earlier parameters and 2434 /// renumbering as we go. 2435 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam, 2436 MultiLevelTemplateArgumentList &Args) { 2437 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) { 2438 // TemplateTypeParmDecl's index cannot be changed after creation, so 2439 // substitute it directly. 2440 auto *NewTTP = TemplateTypeParmDecl::Create( 2441 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(), 2442 TTP->getDepth() - 1, Depth1IndexAdjustment + TTP->getIndex(), 2443 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(), 2444 TTP->isParameterPack(), TTP->hasTypeConstraint(), 2445 TTP->isExpandedParameterPack() 2446 ? std::optional<unsigned>(TTP->getNumExpansionParameters()) 2447 : std::nullopt); 2448 if (const auto *TC = TTP->getTypeConstraint()) 2449 SemaRef.SubstTypeConstraint(NewTTP, TC, Args, 2450 /*EvaluateConstraint*/ true); 2451 if (TTP->hasDefaultArgument()) { 2452 TypeSourceInfo *InstantiatedDefaultArg = 2453 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args, 2454 TTP->getDefaultArgumentLoc(), TTP->getDeclName()); 2455 if (InstantiatedDefaultArg) 2456 NewTTP->setDefaultArgument(InstantiatedDefaultArg); 2457 } 2458 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam, 2459 NewTTP); 2460 return NewTTP; 2461 } 2462 2463 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam)) 2464 return transformTemplateParameterImpl(TTP, Args); 2465 2466 return transformTemplateParameterImpl( 2467 cast<NonTypeTemplateParmDecl>(TemplateParam), Args); 2468 } 2469 template<typename TemplateParmDecl> 2470 TemplateParmDecl * 2471 transformTemplateParameterImpl(TemplateParmDecl *OldParam, 2472 MultiLevelTemplateArgumentList &Args) { 2473 // Ask the template instantiator to do the heavy lifting for us, then adjust 2474 // the index of the parameter once it's done. 2475 auto *NewParam = 2476 cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args)); 2477 assert(NewParam->getDepth() == OldParam->getDepth() - 1 && 2478 "unexpected template param depth"); 2479 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment); 2480 return NewParam; 2481 } 2482 2483 QualType transformFunctionProtoType( 2484 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, 2485 SmallVectorImpl<ParmVarDecl *> &Params, 2486 MultiLevelTemplateArgumentList &Args, 2487 SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) { 2488 SmallVector<QualType, 4> ParamTypes; 2489 const FunctionProtoType *T = TL.getTypePtr(); 2490 2491 // -- The types of the function parameters are those of the constructor. 2492 for (auto *OldParam : TL.getParams()) { 2493 ParmVarDecl *NewParam = 2494 transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs); 2495 if (NestedPattern && NewParam) 2496 NewParam = transformFunctionTypeParam(NewParam, OuterInstantiationArgs, 2497 MaterializedTypedefs); 2498 if (!NewParam) 2499 return QualType(); 2500 ParamTypes.push_back(NewParam->getType()); 2501 Params.push_back(NewParam); 2502 } 2503 2504 // -- The return type is the class template specialization designated by 2505 // the template-name and template arguments corresponding to the 2506 // template parameters obtained from the class template. 2507 // 2508 // We use the injected-class-name type of the primary template instead. 2509 // This has the convenient property that it is different from any type that 2510 // the user can write in a deduction-guide (because they cannot enter the 2511 // context of the template), so implicit deduction guides can never collide 2512 // with explicit ones. 2513 QualType ReturnType = DeducedType; 2514 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation()); 2515 2516 // Resolving a wording defect, we also inherit the variadicness of the 2517 // constructor. 2518 FunctionProtoType::ExtProtoInfo EPI; 2519 EPI.Variadic = T->isVariadic(); 2520 EPI.HasTrailingReturn = true; 2521 2522 QualType Result = SemaRef.BuildFunctionType( 2523 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI); 2524 if (Result.isNull()) 2525 return QualType(); 2526 2527 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result); 2528 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin()); 2529 NewTL.setLParenLoc(TL.getLParenLoc()); 2530 NewTL.setRParenLoc(TL.getRParenLoc()); 2531 NewTL.setExceptionSpecRange(SourceRange()); 2532 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd()); 2533 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I) 2534 NewTL.setParam(I, Params[I]); 2535 2536 return Result; 2537 } 2538 2539 ParmVarDecl *transformFunctionTypeParam( 2540 ParmVarDecl *OldParam, MultiLevelTemplateArgumentList &Args, 2541 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) { 2542 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo(); 2543 TypeSourceInfo *NewDI; 2544 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) { 2545 // Expand out the one and only element in each inner pack. 2546 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0); 2547 NewDI = 2548 SemaRef.SubstType(PackTL.getPatternLoc(), Args, 2549 OldParam->getLocation(), OldParam->getDeclName()); 2550 if (!NewDI) return nullptr; 2551 NewDI = 2552 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(), 2553 PackTL.getTypePtr()->getNumExpansions()); 2554 } else 2555 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(), 2556 OldParam->getDeclName()); 2557 if (!NewDI) 2558 return nullptr; 2559 2560 // Extract the type. This (for instance) replaces references to typedef 2561 // members of the current instantiations with the definitions of those 2562 // typedefs, avoiding triggering instantiation of the deduced type during 2563 // deduction. 2564 NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs) 2565 .transform(NewDI); 2566 2567 // Resolving a wording defect, we also inherit default arguments from the 2568 // constructor. 2569 ExprResult NewDefArg; 2570 if (OldParam->hasDefaultArg()) { 2571 // We don't care what the value is (we won't use it); just create a 2572 // placeholder to indicate there is a default argument. 2573 QualType ParamTy = NewDI->getType(); 2574 NewDefArg = new (SemaRef.Context) 2575 OpaqueValueExpr(OldParam->getDefaultArg()->getBeginLoc(), 2576 ParamTy.getNonLValueExprType(SemaRef.Context), 2577 ParamTy->isLValueReferenceType() ? VK_LValue 2578 : ParamTy->isRValueReferenceType() ? VK_XValue 2579 : VK_PRValue); 2580 } 2581 2582 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC, 2583 OldParam->getInnerLocStart(), 2584 OldParam->getLocation(), 2585 OldParam->getIdentifier(), 2586 NewDI->getType(), 2587 NewDI, 2588 OldParam->getStorageClass(), 2589 NewDefArg.get()); 2590 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(), 2591 OldParam->getFunctionScopeIndex()); 2592 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam); 2593 return NewParam; 2594 } 2595 2596 FunctionTemplateDecl *buildDeductionGuide( 2597 TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor, 2598 ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart, 2599 SourceLocation Loc, SourceLocation LocEnd, 2600 llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) { 2601 DeclarationNameInfo Name(DeductionGuideName, Loc); 2602 ArrayRef<ParmVarDecl *> Params = 2603 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(); 2604 2605 // Build the implicit deduction guide template. 2606 auto *Guide = 2607 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name, 2608 TInfo->getType(), TInfo, LocEnd, Ctor); 2609 Guide->setImplicit(); 2610 Guide->setParams(Params); 2611 2612 for (auto *Param : Params) 2613 Param->setDeclContext(Guide); 2614 for (auto *TD : MaterializedTypedefs) 2615 TD->setDeclContext(Guide); 2616 2617 auto *GuideTemplate = FunctionTemplateDecl::Create( 2618 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide); 2619 GuideTemplate->setImplicit(); 2620 Guide->setDescribedFunctionTemplate(GuideTemplate); 2621 2622 if (isa<CXXRecordDecl>(DC)) { 2623 Guide->setAccess(AS_public); 2624 GuideTemplate->setAccess(AS_public); 2625 } 2626 2627 DC->addDecl(GuideTemplate); 2628 return GuideTemplate; 2629 } 2630 }; 2631 } 2632 2633 FunctionTemplateDecl *Sema::DeclareImplicitDeductionGuideFromInitList( 2634 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes, 2635 SourceLocation Loc) { 2636 if (CXXRecordDecl *DefRecord = 2637 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) { 2638 if (TemplateDecl *DescribedTemplate = 2639 DefRecord->getDescribedClassTemplate()) 2640 Template = DescribedTemplate; 2641 } 2642 2643 DeclContext *DC = Template->getDeclContext(); 2644 if (DC->isDependentContext()) 2645 return nullptr; 2646 2647 ConvertConstructorToDeductionGuideTransform Transform( 2648 *this, cast<ClassTemplateDecl>(Template)); 2649 if (!isCompleteType(Loc, Transform.DeducedType)) 2650 return nullptr; 2651 2652 // In case we were expanding a pack when we attempted to declare deduction 2653 // guides, turn off pack expansion for everything we're about to do. 2654 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, 2655 /*NewSubstitutionIndex=*/-1); 2656 // Create a template instantiation record to track the "instantiation" of 2657 // constructors into deduction guides. 2658 InstantiatingTemplate BuildingDeductionGuides( 2659 *this, Loc, Template, 2660 Sema::InstantiatingTemplate::BuildingDeductionGuidesTag{}); 2661 if (BuildingDeductionGuides.isInvalid()) 2662 return nullptr; 2663 2664 return cast<FunctionTemplateDecl>( 2665 Transform.buildSimpleDeductionGuide(ParamTypes)); 2666 } 2667 2668 void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template, 2669 SourceLocation Loc) { 2670 if (CXXRecordDecl *DefRecord = 2671 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) { 2672 if (TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate()) 2673 Template = DescribedTemplate; 2674 } 2675 2676 DeclContext *DC = Template->getDeclContext(); 2677 if (DC->isDependentContext()) 2678 return; 2679 2680 ConvertConstructorToDeductionGuideTransform Transform( 2681 *this, cast<ClassTemplateDecl>(Template)); 2682 if (!isCompleteType(Loc, Transform.DeducedType)) 2683 return; 2684 2685 // Check whether we've already declared deduction guides for this template. 2686 // FIXME: Consider storing a flag on the template to indicate this. 2687 auto Existing = DC->lookup(Transform.DeductionGuideName); 2688 for (auto *D : Existing) 2689 if (D->isImplicit()) 2690 return; 2691 2692 // In case we were expanding a pack when we attempted to declare deduction 2693 // guides, turn off pack expansion for everything we're about to do. 2694 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1); 2695 // Create a template instantiation record to track the "instantiation" of 2696 // constructors into deduction guides. 2697 InstantiatingTemplate BuildingDeductionGuides( 2698 *this, Loc, Template, 2699 Sema::InstantiatingTemplate::BuildingDeductionGuidesTag{}); 2700 if (BuildingDeductionGuides.isInvalid()) 2701 return; 2702 2703 // Convert declared constructors into deduction guide templates. 2704 // FIXME: Skip constructors for which deduction must necessarily fail (those 2705 // for which some class template parameter without a default argument never 2706 // appears in a deduced context). 2707 ClassTemplateDecl *Pattern = 2708 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template; 2709 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl()); 2710 llvm::SmallPtrSet<NamedDecl *, 8> ProcessedCtors; 2711 bool AddedAny = false; 2712 for (NamedDecl *D : LookupConstructors(Pattern->getTemplatedDecl())) { 2713 D = D->getUnderlyingDecl(); 2714 if (D->isInvalidDecl() || D->isImplicit()) 2715 continue; 2716 2717 D = cast<NamedDecl>(D->getCanonicalDecl()); 2718 2719 // Within C++20 modules, we may have multiple same constructors in 2720 // multiple same RecordDecls. And it doesn't make sense to create 2721 // duplicated deduction guides for the duplicated constructors. 2722 if (ProcessedCtors.count(D)) 2723 continue; 2724 2725 auto *FTD = dyn_cast<FunctionTemplateDecl>(D); 2726 auto *CD = 2727 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D); 2728 // Class-scope explicit specializations (MS extension) do not result in 2729 // deduction guides. 2730 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization())) 2731 continue; 2732 2733 // Cannot make a deduction guide when unparsed arguments are present. 2734 if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) { 2735 return !P || P->hasUnparsedDefaultArg(); 2736 })) 2737 continue; 2738 2739 ProcessedCtors.insert(D); 2740 Transform.transformConstructor(FTD, CD); 2741 AddedAny = true; 2742 } 2743 2744 // C++17 [over.match.class.deduct] 2745 // -- If C is not defined or does not declare any constructors, an 2746 // additional function template derived as above from a hypothetical 2747 // constructor C(). 2748 if (!AddedAny) 2749 Transform.buildSimpleDeductionGuide(std::nullopt); 2750 2751 // -- An additional function template derived as above from a hypothetical 2752 // constructor C(C), called the copy deduction candidate. 2753 cast<CXXDeductionGuideDecl>( 2754 cast<FunctionTemplateDecl>( 2755 Transform.buildSimpleDeductionGuide(Transform.DeducedType)) 2756 ->getTemplatedDecl()) 2757 ->setDeductionCandidateKind(DeductionCandidate::Copy); 2758 2759 SavedContext.pop(); 2760 } 2761 2762 /// Diagnose the presence of a default template argument on a 2763 /// template parameter, which is ill-formed in certain contexts. 2764 /// 2765 /// \returns true if the default template argument should be dropped. 2766 static bool DiagnoseDefaultTemplateArgument(Sema &S, 2767 Sema::TemplateParamListContext TPC, 2768 SourceLocation ParamLoc, 2769 SourceRange DefArgRange) { 2770 switch (TPC) { 2771 case Sema::TPC_ClassTemplate: 2772 case Sema::TPC_VarTemplate: 2773 case Sema::TPC_TypeAliasTemplate: 2774 return false; 2775 2776 case Sema::TPC_FunctionTemplate: 2777 case Sema::TPC_FriendFunctionTemplateDefinition: 2778 // C++ [temp.param]p9: 2779 // A default template-argument shall not be specified in a 2780 // function template declaration or a function template 2781 // definition [...] 2782 // If a friend function template declaration specifies a default 2783 // template-argument, that declaration shall be a definition and shall be 2784 // the only declaration of the function template in the translation unit. 2785 // (C++98/03 doesn't have this wording; see DR226). 2786 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ? 2787 diag::warn_cxx98_compat_template_parameter_default_in_function_template 2788 : diag::ext_template_parameter_default_in_function_template) 2789 << DefArgRange; 2790 return false; 2791 2792 case Sema::TPC_ClassTemplateMember: 2793 // C++0x [temp.param]p9: 2794 // A default template-argument shall not be specified in the 2795 // template-parameter-lists of the definition of a member of a 2796 // class template that appears outside of the member's class. 2797 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member) 2798 << DefArgRange; 2799 return true; 2800 2801 case Sema::TPC_FriendClassTemplate: 2802 case Sema::TPC_FriendFunctionTemplate: 2803 // C++ [temp.param]p9: 2804 // A default template-argument shall not be specified in a 2805 // friend template declaration. 2806 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template) 2807 << DefArgRange; 2808 return true; 2809 2810 // FIXME: C++0x [temp.param]p9 allows default template-arguments 2811 // for friend function templates if there is only a single 2812 // declaration (and it is a definition). Strange! 2813 } 2814 2815 llvm_unreachable("Invalid TemplateParamListContext!"); 2816 } 2817 2818 /// Check for unexpanded parameter packs within the template parameters 2819 /// of a template template parameter, recursively. 2820 static bool DiagnoseUnexpandedParameterPacks(Sema &S, 2821 TemplateTemplateParmDecl *TTP) { 2822 // A template template parameter which is a parameter pack is also a pack 2823 // expansion. 2824 if (TTP->isParameterPack()) 2825 return false; 2826 2827 TemplateParameterList *Params = TTP->getTemplateParameters(); 2828 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 2829 NamedDecl *P = Params->getParam(I); 2830 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) { 2831 if (!TTP->isParameterPack()) 2832 if (const TypeConstraint *TC = TTP->getTypeConstraint()) 2833 if (TC->hasExplicitTemplateArgs()) 2834 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments()) 2835 if (S.DiagnoseUnexpandedParameterPack(ArgLoc, 2836 Sema::UPPC_TypeConstraint)) 2837 return true; 2838 continue; 2839 } 2840 2841 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) { 2842 if (!NTTP->isParameterPack() && 2843 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(), 2844 NTTP->getTypeSourceInfo(), 2845 Sema::UPPC_NonTypeTemplateParameterType)) 2846 return true; 2847 2848 continue; 2849 } 2850 2851 if (TemplateTemplateParmDecl *InnerTTP 2852 = dyn_cast<TemplateTemplateParmDecl>(P)) 2853 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP)) 2854 return true; 2855 } 2856 2857 return false; 2858 } 2859 2860 /// Checks the validity of a template parameter list, possibly 2861 /// considering the template parameter list from a previous 2862 /// declaration. 2863 /// 2864 /// If an "old" template parameter list is provided, it must be 2865 /// equivalent (per TemplateParameterListsAreEqual) to the "new" 2866 /// template parameter list. 2867 /// 2868 /// \param NewParams Template parameter list for a new template 2869 /// declaration. This template parameter list will be updated with any 2870 /// default arguments that are carried through from the previous 2871 /// template parameter list. 2872 /// 2873 /// \param OldParams If provided, template parameter list from a 2874 /// previous declaration of the same template. Default template 2875 /// arguments will be merged from the old template parameter list to 2876 /// the new template parameter list. 2877 /// 2878 /// \param TPC Describes the context in which we are checking the given 2879 /// template parameter list. 2880 /// 2881 /// \param SkipBody If we might have already made a prior merged definition 2882 /// of this template visible, the corresponding body-skipping information. 2883 /// Default argument redefinition is not an error when skipping such a body, 2884 /// because (under the ODR) we can assume the default arguments are the same 2885 /// as the prior merged definition. 2886 /// 2887 /// \returns true if an error occurred, false otherwise. 2888 bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams, 2889 TemplateParameterList *OldParams, 2890 TemplateParamListContext TPC, 2891 SkipBodyInfo *SkipBody) { 2892 bool Invalid = false; 2893 2894 // C++ [temp.param]p10: 2895 // The set of default template-arguments available for use with a 2896 // template declaration or definition is obtained by merging the 2897 // default arguments from the definition (if in scope) and all 2898 // declarations in scope in the same way default function 2899 // arguments are (8.3.6). 2900 bool SawDefaultArgument = false; 2901 SourceLocation PreviousDefaultArgLoc; 2902 2903 // Dummy initialization to avoid warnings. 2904 TemplateParameterList::iterator OldParam = NewParams->end(); 2905 if (OldParams) 2906 OldParam = OldParams->begin(); 2907 2908 bool RemoveDefaultArguments = false; 2909 for (TemplateParameterList::iterator NewParam = NewParams->begin(), 2910 NewParamEnd = NewParams->end(); 2911 NewParam != NewParamEnd; ++NewParam) { 2912 // Whether we've seen a duplicate default argument in the same translation 2913 // unit. 2914 bool RedundantDefaultArg = false; 2915 // Whether we've found inconsis inconsitent default arguments in different 2916 // translation unit. 2917 bool InconsistentDefaultArg = false; 2918 // The name of the module which contains the inconsistent default argument. 2919 std::string PrevModuleName; 2920 2921 SourceLocation OldDefaultLoc; 2922 SourceLocation NewDefaultLoc; 2923 2924 // Variable used to diagnose missing default arguments 2925 bool MissingDefaultArg = false; 2926 2927 // Variable used to diagnose non-final parameter packs 2928 bool SawParameterPack = false; 2929 2930 if (TemplateTypeParmDecl *NewTypeParm 2931 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) { 2932 // Check the presence of a default argument here. 2933 if (NewTypeParm->hasDefaultArgument() && 2934 DiagnoseDefaultTemplateArgument(*this, TPC, 2935 NewTypeParm->getLocation(), 2936 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc() 2937 .getSourceRange())) 2938 NewTypeParm->removeDefaultArgument(); 2939 2940 // Merge default arguments for template type parameters. 2941 TemplateTypeParmDecl *OldTypeParm 2942 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr; 2943 if (NewTypeParm->isParameterPack()) { 2944 assert(!NewTypeParm->hasDefaultArgument() && 2945 "Parameter packs can't have a default argument!"); 2946 SawParameterPack = true; 2947 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) && 2948 NewTypeParm->hasDefaultArgument() && 2949 (!SkipBody || !SkipBody->ShouldSkip)) { 2950 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc(); 2951 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc(); 2952 SawDefaultArgument = true; 2953 2954 if (!OldTypeParm->getOwningModule()) 2955 RedundantDefaultArg = true; 2956 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm, 2957 NewTypeParm)) { 2958 InconsistentDefaultArg = true; 2959 PrevModuleName = 2960 OldTypeParm->getImportedOwningModule()->getFullModuleName(); 2961 } 2962 PreviousDefaultArgLoc = NewDefaultLoc; 2963 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) { 2964 // Merge the default argument from the old declaration to the 2965 // new declaration. 2966 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm); 2967 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc(); 2968 } else if (NewTypeParm->hasDefaultArgument()) { 2969 SawDefaultArgument = true; 2970 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc(); 2971 } else if (SawDefaultArgument) 2972 MissingDefaultArg = true; 2973 } else if (NonTypeTemplateParmDecl *NewNonTypeParm 2974 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) { 2975 // Check for unexpanded parameter packs. 2976 if (!NewNonTypeParm->isParameterPack() && 2977 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(), 2978 NewNonTypeParm->getTypeSourceInfo(), 2979 UPPC_NonTypeTemplateParameterType)) { 2980 Invalid = true; 2981 continue; 2982 } 2983 2984 // Check the presence of a default argument here. 2985 if (NewNonTypeParm->hasDefaultArgument() && 2986 DiagnoseDefaultTemplateArgument(*this, TPC, 2987 NewNonTypeParm->getLocation(), 2988 NewNonTypeParm->getDefaultArgument()->getSourceRange())) { 2989 NewNonTypeParm->removeDefaultArgument(); 2990 } 2991 2992 // Merge default arguments for non-type template parameters 2993 NonTypeTemplateParmDecl *OldNonTypeParm 2994 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr; 2995 if (NewNonTypeParm->isParameterPack()) { 2996 assert(!NewNonTypeParm->hasDefaultArgument() && 2997 "Parameter packs can't have a default argument!"); 2998 if (!NewNonTypeParm->isPackExpansion()) 2999 SawParameterPack = true; 3000 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) && 3001 NewNonTypeParm->hasDefaultArgument() && 3002 (!SkipBody || !SkipBody->ShouldSkip)) { 3003 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc(); 3004 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc(); 3005 SawDefaultArgument = true; 3006 if (!OldNonTypeParm->getOwningModule()) 3007 RedundantDefaultArg = true; 3008 else if (!getASTContext().isSameDefaultTemplateArgument( 3009 OldNonTypeParm, NewNonTypeParm)) { 3010 InconsistentDefaultArg = true; 3011 PrevModuleName = 3012 OldNonTypeParm->getImportedOwningModule()->getFullModuleName(); 3013 } 3014 PreviousDefaultArgLoc = NewDefaultLoc; 3015 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) { 3016 // Merge the default argument from the old declaration to the 3017 // new declaration. 3018 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm); 3019 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc(); 3020 } else if (NewNonTypeParm->hasDefaultArgument()) { 3021 SawDefaultArgument = true; 3022 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc(); 3023 } else if (SawDefaultArgument) 3024 MissingDefaultArg = true; 3025 } else { 3026 TemplateTemplateParmDecl *NewTemplateParm 3027 = cast<TemplateTemplateParmDecl>(*NewParam); 3028 3029 // Check for unexpanded parameter packs, recursively. 3030 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) { 3031 Invalid = true; 3032 continue; 3033 } 3034 3035 // Check the presence of a default argument here. 3036 if (NewTemplateParm->hasDefaultArgument() && 3037 DiagnoseDefaultTemplateArgument(*this, TPC, 3038 NewTemplateParm->getLocation(), 3039 NewTemplateParm->getDefaultArgument().getSourceRange())) 3040 NewTemplateParm->removeDefaultArgument(); 3041 3042 // Merge default arguments for template template parameters 3043 TemplateTemplateParmDecl *OldTemplateParm 3044 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr; 3045 if (NewTemplateParm->isParameterPack()) { 3046 assert(!NewTemplateParm->hasDefaultArgument() && 3047 "Parameter packs can't have a default argument!"); 3048 if (!NewTemplateParm->isPackExpansion()) 3049 SawParameterPack = true; 3050 } else if (OldTemplateParm && 3051 hasVisibleDefaultArgument(OldTemplateParm) && 3052 NewTemplateParm->hasDefaultArgument() && 3053 (!SkipBody || !SkipBody->ShouldSkip)) { 3054 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation(); 3055 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation(); 3056 SawDefaultArgument = true; 3057 if (!OldTemplateParm->getOwningModule()) 3058 RedundantDefaultArg = true; 3059 else if (!getASTContext().isSameDefaultTemplateArgument( 3060 OldTemplateParm, NewTemplateParm)) { 3061 InconsistentDefaultArg = true; 3062 PrevModuleName = 3063 OldTemplateParm->getImportedOwningModule()->getFullModuleName(); 3064 } 3065 PreviousDefaultArgLoc = NewDefaultLoc; 3066 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) { 3067 // Merge the default argument from the old declaration to the 3068 // new declaration. 3069 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm); 3070 PreviousDefaultArgLoc 3071 = OldTemplateParm->getDefaultArgument().getLocation(); 3072 } else if (NewTemplateParm->hasDefaultArgument()) { 3073 SawDefaultArgument = true; 3074 PreviousDefaultArgLoc 3075 = NewTemplateParm->getDefaultArgument().getLocation(); 3076 } else if (SawDefaultArgument) 3077 MissingDefaultArg = true; 3078 } 3079 3080 // C++11 [temp.param]p11: 3081 // If a template parameter of a primary class template or alias template 3082 // is a template parameter pack, it shall be the last template parameter. 3083 if (SawParameterPack && (NewParam + 1) != NewParamEnd && 3084 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate || 3085 TPC == TPC_TypeAliasTemplate)) { 3086 Diag((*NewParam)->getLocation(), 3087 diag::err_template_param_pack_must_be_last_template_parameter); 3088 Invalid = true; 3089 } 3090 3091 // [basic.def.odr]/13: 3092 // There can be more than one definition of a 3093 // ... 3094 // default template argument 3095 // ... 3096 // in a program provided that each definition appears in a different 3097 // translation unit and the definitions satisfy the [same-meaning 3098 // criteria of the ODR]. 3099 // 3100 // Simply, the design of modules allows the definition of template default 3101 // argument to be repeated across translation unit. Note that the ODR is 3102 // checked elsewhere. But it is still not allowed to repeat template default 3103 // argument in the same translation unit. 3104 if (RedundantDefaultArg) { 3105 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition); 3106 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg); 3107 Invalid = true; 3108 } else if (InconsistentDefaultArg) { 3109 // We could only diagnose about the case that the OldParam is imported. 3110 // The case NewParam is imported should be handled in ASTReader. 3111 Diag(NewDefaultLoc, 3112 diag::err_template_param_default_arg_inconsistent_redefinition); 3113 Diag(OldDefaultLoc, 3114 diag::note_template_param_prev_default_arg_in_other_module) 3115 << PrevModuleName; 3116 Invalid = true; 3117 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) { 3118 // C++ [temp.param]p11: 3119 // If a template-parameter of a class template has a default 3120 // template-argument, each subsequent template-parameter shall either 3121 // have a default template-argument supplied or be a template parameter 3122 // pack. 3123 Diag((*NewParam)->getLocation(), 3124 diag::err_template_param_default_arg_missing); 3125 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg); 3126 Invalid = true; 3127 RemoveDefaultArguments = true; 3128 } 3129 3130 // If we have an old template parameter list that we're merging 3131 // in, move on to the next parameter. 3132 if (OldParams) 3133 ++OldParam; 3134 } 3135 3136 // We were missing some default arguments at the end of the list, so remove 3137 // all of the default arguments. 3138 if (RemoveDefaultArguments) { 3139 for (TemplateParameterList::iterator NewParam = NewParams->begin(), 3140 NewParamEnd = NewParams->end(); 3141 NewParam != NewParamEnd; ++NewParam) { 3142 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam)) 3143 TTP->removeDefaultArgument(); 3144 else if (NonTypeTemplateParmDecl *NTTP 3145 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) 3146 NTTP->removeDefaultArgument(); 3147 else 3148 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument(); 3149 } 3150 } 3151 3152 return Invalid; 3153 } 3154 3155 namespace { 3156 3157 /// A class which looks for a use of a certain level of template 3158 /// parameter. 3159 struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> { 3160 typedef RecursiveASTVisitor<DependencyChecker> super; 3161 3162 unsigned Depth; 3163 3164 // Whether we're looking for a use of a template parameter that makes the 3165 // overall construct type-dependent / a dependent type. This is strictly 3166 // best-effort for now; we may fail to match at all for a dependent type 3167 // in some cases if this is set. 3168 bool IgnoreNonTypeDependent; 3169 3170 bool Match; 3171 SourceLocation MatchLoc; 3172 3173 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent) 3174 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent), 3175 Match(false) {} 3176 3177 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent) 3178 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) { 3179 NamedDecl *ND = Params->getParam(0); 3180 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) { 3181 Depth = PD->getDepth(); 3182 } else if (NonTypeTemplateParmDecl *PD = 3183 dyn_cast<NonTypeTemplateParmDecl>(ND)) { 3184 Depth = PD->getDepth(); 3185 } else { 3186 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth(); 3187 } 3188 } 3189 3190 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) { 3191 if (ParmDepth >= Depth) { 3192 Match = true; 3193 MatchLoc = Loc; 3194 return true; 3195 } 3196 return false; 3197 } 3198 3199 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) { 3200 // Prune out non-type-dependent expressions if requested. This can 3201 // sometimes result in us failing to find a template parameter reference 3202 // (if a value-dependent expression creates a dependent type), but this 3203 // mode is best-effort only. 3204 if (auto *E = dyn_cast_or_null<Expr>(S)) 3205 if (IgnoreNonTypeDependent && !E->isTypeDependent()) 3206 return true; 3207 return super::TraverseStmt(S, Q); 3208 } 3209 3210 bool TraverseTypeLoc(TypeLoc TL) { 3211 if (IgnoreNonTypeDependent && !TL.isNull() && 3212 !TL.getType()->isDependentType()) 3213 return true; 3214 return super::TraverseTypeLoc(TL); 3215 } 3216 3217 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) { 3218 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc()); 3219 } 3220 3221 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) { 3222 // For a best-effort search, keep looking until we find a location. 3223 return IgnoreNonTypeDependent || !Matches(T->getDepth()); 3224 } 3225 3226 bool TraverseTemplateName(TemplateName N) { 3227 if (TemplateTemplateParmDecl *PD = 3228 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl())) 3229 if (Matches(PD->getDepth())) 3230 return false; 3231 return super::TraverseTemplateName(N); 3232 } 3233 3234 bool VisitDeclRefExpr(DeclRefExpr *E) { 3235 if (NonTypeTemplateParmDecl *PD = 3236 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl())) 3237 if (Matches(PD->getDepth(), E->getExprLoc())) 3238 return false; 3239 return super::VisitDeclRefExpr(E); 3240 } 3241 3242 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) { 3243 return TraverseType(T->getReplacementType()); 3244 } 3245 3246 bool 3247 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) { 3248 return TraverseTemplateArgument(T->getArgumentPack()); 3249 } 3250 3251 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) { 3252 return TraverseType(T->getInjectedSpecializationType()); 3253 } 3254 }; 3255 } // end anonymous namespace 3256 3257 /// Determines whether a given type depends on the given parameter 3258 /// list. 3259 static bool 3260 DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) { 3261 if (!Params->size()) 3262 return false; 3263 3264 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false); 3265 Checker.TraverseType(T); 3266 return Checker.Match; 3267 } 3268 3269 // Find the source range corresponding to the named type in the given 3270 // nested-name-specifier, if any. 3271 static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context, 3272 QualType T, 3273 const CXXScopeSpec &SS) { 3274 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data()); 3275 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) { 3276 if (const Type *CurType = NNS->getAsType()) { 3277 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0))) 3278 return NNSLoc.getTypeLoc().getSourceRange(); 3279 } else 3280 break; 3281 3282 NNSLoc = NNSLoc.getPrefix(); 3283 } 3284 3285 return SourceRange(); 3286 } 3287 3288 /// Match the given template parameter lists to the given scope 3289 /// specifier, returning the template parameter list that applies to the 3290 /// name. 3291 /// 3292 /// \param DeclStartLoc the start of the declaration that has a scope 3293 /// specifier or a template parameter list. 3294 /// 3295 /// \param DeclLoc The location of the declaration itself. 3296 /// 3297 /// \param SS the scope specifier that will be matched to the given template 3298 /// parameter lists. This scope specifier precedes a qualified name that is 3299 /// being declared. 3300 /// 3301 /// \param TemplateId The template-id following the scope specifier, if there 3302 /// is one. Used to check for a missing 'template<>'. 3303 /// 3304 /// \param ParamLists the template parameter lists, from the outermost to the 3305 /// innermost template parameter lists. 3306 /// 3307 /// \param IsFriend Whether to apply the slightly different rules for 3308 /// matching template parameters to scope specifiers in friend 3309 /// declarations. 3310 /// 3311 /// \param IsMemberSpecialization will be set true if the scope specifier 3312 /// denotes a fully-specialized type, and therefore this is a declaration of 3313 /// a member specialization. 3314 /// 3315 /// \returns the template parameter list, if any, that corresponds to the 3316 /// name that is preceded by the scope specifier @p SS. This template 3317 /// parameter list may have template parameters (if we're declaring a 3318 /// template) or may have no template parameters (if we're declaring a 3319 /// template specialization), or may be NULL (if what we're declaring isn't 3320 /// itself a template). 3321 TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier( 3322 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, 3323 TemplateIdAnnotation *TemplateId, 3324 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, 3325 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) { 3326 IsMemberSpecialization = false; 3327 Invalid = false; 3328 3329 // The sequence of nested types to which we will match up the template 3330 // parameter lists. We first build this list by starting with the type named 3331 // by the nested-name-specifier and walking out until we run out of types. 3332 SmallVector<QualType, 4> NestedTypes; 3333 QualType T; 3334 if (SS.getScopeRep()) { 3335 if (CXXRecordDecl *Record 3336 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true))) 3337 T = Context.getTypeDeclType(Record); 3338 else 3339 T = QualType(SS.getScopeRep()->getAsType(), 0); 3340 } 3341 3342 // If we found an explicit specialization that prevents us from needing 3343 // 'template<>' headers, this will be set to the location of that 3344 // explicit specialization. 3345 SourceLocation ExplicitSpecLoc; 3346 3347 while (!T.isNull()) { 3348 NestedTypes.push_back(T); 3349 3350 // Retrieve the parent of a record type. 3351 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { 3352 // If this type is an explicit specialization, we're done. 3353 if (ClassTemplateSpecializationDecl *Spec 3354 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) { 3355 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) && 3356 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) { 3357 ExplicitSpecLoc = Spec->getLocation(); 3358 break; 3359 } 3360 } else if (Record->getTemplateSpecializationKind() 3361 == TSK_ExplicitSpecialization) { 3362 ExplicitSpecLoc = Record->getLocation(); 3363 break; 3364 } 3365 3366 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent())) 3367 T = Context.getTypeDeclType(Parent); 3368 else 3369 T = QualType(); 3370 continue; 3371 } 3372 3373 if (const TemplateSpecializationType *TST 3374 = T->getAs<TemplateSpecializationType>()) { 3375 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { 3376 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext())) 3377 T = Context.getTypeDeclType(Parent); 3378 else 3379 T = QualType(); 3380 continue; 3381 } 3382 } 3383 3384 // Look one step prior in a dependent template specialization type. 3385 if (const DependentTemplateSpecializationType *DependentTST 3386 = T->getAs<DependentTemplateSpecializationType>()) { 3387 if (NestedNameSpecifier *NNS = DependentTST->getQualifier()) 3388 T = QualType(NNS->getAsType(), 0); 3389 else 3390 T = QualType(); 3391 continue; 3392 } 3393 3394 // Look one step prior in a dependent name type. 3395 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){ 3396 if (NestedNameSpecifier *NNS = DependentName->getQualifier()) 3397 T = QualType(NNS->getAsType(), 0); 3398 else 3399 T = QualType(); 3400 continue; 3401 } 3402 3403 // Retrieve the parent of an enumeration type. 3404 if (const EnumType *EnumT = T->getAs<EnumType>()) { 3405 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization 3406 // check here. 3407 EnumDecl *Enum = EnumT->getDecl(); 3408 3409 // Get to the parent type. 3410 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent())) 3411 T = Context.getTypeDeclType(Parent); 3412 else 3413 T = QualType(); 3414 continue; 3415 } 3416 3417 T = QualType(); 3418 } 3419 // Reverse the nested types list, since we want to traverse from the outermost 3420 // to the innermost while checking template-parameter-lists. 3421 std::reverse(NestedTypes.begin(), NestedTypes.end()); 3422 3423 // C++0x [temp.expl.spec]p17: 3424 // A member or a member template may be nested within many 3425 // enclosing class templates. In an explicit specialization for 3426 // such a member, the member declaration shall be preceded by a 3427 // template<> for each enclosing class template that is 3428 // explicitly specialized. 3429 bool SawNonEmptyTemplateParameterList = false; 3430 3431 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) { 3432 if (SawNonEmptyTemplateParameterList) { 3433 if (!SuppressDiagnostic) 3434 Diag(DeclLoc, diag::err_specialize_member_of_template) 3435 << !Recovery << Range; 3436 Invalid = true; 3437 IsMemberSpecialization = false; 3438 return true; 3439 } 3440 3441 return false; 3442 }; 3443 3444 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) { 3445 // Check that we can have an explicit specialization here. 3446 if (CheckExplicitSpecialization(Range, true)) 3447 return true; 3448 3449 // We don't have a template header, but we should. 3450 SourceLocation ExpectedTemplateLoc; 3451 if (!ParamLists.empty()) 3452 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc(); 3453 else 3454 ExpectedTemplateLoc = DeclStartLoc; 3455 3456 if (!SuppressDiagnostic) 3457 Diag(DeclLoc, diag::err_template_spec_needs_header) 3458 << Range 3459 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> "); 3460 return false; 3461 }; 3462 3463 unsigned ParamIdx = 0; 3464 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes; 3465 ++TypeIdx) { 3466 T = NestedTypes[TypeIdx]; 3467 3468 // Whether we expect a 'template<>' header. 3469 bool NeedEmptyTemplateHeader = false; 3470 3471 // Whether we expect a template header with parameters. 3472 bool NeedNonemptyTemplateHeader = false; 3473 3474 // For a dependent type, the set of template parameters that we 3475 // expect to see. 3476 TemplateParameterList *ExpectedTemplateParams = nullptr; 3477 3478 // C++0x [temp.expl.spec]p15: 3479 // A member or a member template may be nested within many enclosing 3480 // class templates. In an explicit specialization for such a member, the 3481 // member declaration shall be preceded by a template<> for each 3482 // enclosing class template that is explicitly specialized. 3483 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) { 3484 if (ClassTemplatePartialSpecializationDecl *Partial 3485 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) { 3486 ExpectedTemplateParams = Partial->getTemplateParameters(); 3487 NeedNonemptyTemplateHeader = true; 3488 } else if (Record->isDependentType()) { 3489 if (Record->getDescribedClassTemplate()) { 3490 ExpectedTemplateParams = Record->getDescribedClassTemplate() 3491 ->getTemplateParameters(); 3492 NeedNonemptyTemplateHeader = true; 3493 } 3494 } else if (ClassTemplateSpecializationDecl *Spec 3495 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) { 3496 // C++0x [temp.expl.spec]p4: 3497 // Members of an explicitly specialized class template are defined 3498 // in the same manner as members of normal classes, and not using 3499 // the template<> syntax. 3500 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization) 3501 NeedEmptyTemplateHeader = true; 3502 else 3503 continue; 3504 } else if (Record->getTemplateSpecializationKind()) { 3505 if (Record->getTemplateSpecializationKind() 3506 != TSK_ExplicitSpecialization && 3507 TypeIdx == NumTypes - 1) 3508 IsMemberSpecialization = true; 3509 3510 continue; 3511 } 3512 } else if (const TemplateSpecializationType *TST 3513 = T->getAs<TemplateSpecializationType>()) { 3514 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) { 3515 ExpectedTemplateParams = Template->getTemplateParameters(); 3516 NeedNonemptyTemplateHeader = true; 3517 } 3518 } else if (T->getAs<DependentTemplateSpecializationType>()) { 3519 // FIXME: We actually could/should check the template arguments here 3520 // against the corresponding template parameter list. 3521 NeedNonemptyTemplateHeader = false; 3522 } 3523 3524 // C++ [temp.expl.spec]p16: 3525 // In an explicit specialization declaration for a member of a class 3526 // template or a member template that ap- pears in namespace scope, the 3527 // member template and some of its enclosing class templates may remain 3528 // unspecialized, except that the declaration shall not explicitly 3529 // specialize a class member template if its en- closing class templates 3530 // are not explicitly specialized as well. 3531 if (ParamIdx < ParamLists.size()) { 3532 if (ParamLists[ParamIdx]->size() == 0) { 3533 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(), 3534 false)) 3535 return nullptr; 3536 } else 3537 SawNonEmptyTemplateParameterList = true; 3538 } 3539 3540 if (NeedEmptyTemplateHeader) { 3541 // If we're on the last of the types, and we need a 'template<>' header 3542 // here, then it's a member specialization. 3543 if (TypeIdx == NumTypes - 1) 3544 IsMemberSpecialization = true; 3545 3546 if (ParamIdx < ParamLists.size()) { 3547 if (ParamLists[ParamIdx]->size() > 0) { 3548 // The header has template parameters when it shouldn't. Complain. 3549 if (!SuppressDiagnostic) 3550 Diag(ParamLists[ParamIdx]->getTemplateLoc(), 3551 diag::err_template_param_list_matches_nontemplate) 3552 << T 3553 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(), 3554 ParamLists[ParamIdx]->getRAngleLoc()) 3555 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); 3556 Invalid = true; 3557 return nullptr; 3558 } 3559 3560 // Consume this template header. 3561 ++ParamIdx; 3562 continue; 3563 } 3564 3565 if (!IsFriend) 3566 if (DiagnoseMissingExplicitSpecialization( 3567 getRangeOfTypeInNestedNameSpecifier(Context, T, SS))) 3568 return nullptr; 3569 3570 continue; 3571 } 3572 3573 if (NeedNonemptyTemplateHeader) { 3574 // In friend declarations we can have template-ids which don't 3575 // depend on the corresponding template parameter lists. But 3576 // assume that empty parameter lists are supposed to match this 3577 // template-id. 3578 if (IsFriend && T->isDependentType()) { 3579 if (ParamIdx < ParamLists.size() && 3580 DependsOnTemplateParameters(T, ParamLists[ParamIdx])) 3581 ExpectedTemplateParams = nullptr; 3582 else 3583 continue; 3584 } 3585 3586 if (ParamIdx < ParamLists.size()) { 3587 // Check the template parameter list, if we can. 3588 if (ExpectedTemplateParams && 3589 !TemplateParameterListsAreEqual(ParamLists[ParamIdx], 3590 ExpectedTemplateParams, 3591 !SuppressDiagnostic, TPL_TemplateMatch)) 3592 Invalid = true; 3593 3594 if (!Invalid && 3595 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr, 3596 TPC_ClassTemplateMember)) 3597 Invalid = true; 3598 3599 ++ParamIdx; 3600 continue; 3601 } 3602 3603 if (!SuppressDiagnostic) 3604 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters) 3605 << T 3606 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS); 3607 Invalid = true; 3608 continue; 3609 } 3610 } 3611 3612 // If there were at least as many template-ids as there were template 3613 // parameter lists, then there are no template parameter lists remaining for 3614 // the declaration itself. 3615 if (ParamIdx >= ParamLists.size()) { 3616 if (TemplateId && !IsFriend) { 3617 // We don't have a template header for the declaration itself, but we 3618 // should. 3619 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc, 3620 TemplateId->RAngleLoc)); 3621 3622 // Fabricate an empty template parameter list for the invented header. 3623 return TemplateParameterList::Create(Context, SourceLocation(), 3624 SourceLocation(), std::nullopt, 3625 SourceLocation(), nullptr); 3626 } 3627 3628 return nullptr; 3629 } 3630 3631 // If there were too many template parameter lists, complain about that now. 3632 if (ParamIdx < ParamLists.size() - 1) { 3633 bool HasAnyExplicitSpecHeader = false; 3634 bool AllExplicitSpecHeaders = true; 3635 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) { 3636 if (ParamLists[I]->size() == 0) 3637 HasAnyExplicitSpecHeader = true; 3638 else 3639 AllExplicitSpecHeaders = false; 3640 } 3641 3642 if (!SuppressDiagnostic) 3643 Diag(ParamLists[ParamIdx]->getTemplateLoc(), 3644 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers 3645 : diag::err_template_spec_extra_headers) 3646 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(), 3647 ParamLists[ParamLists.size() - 2]->getRAngleLoc()); 3648 3649 // If there was a specialization somewhere, such that 'template<>' is 3650 // not required, and there were any 'template<>' headers, note where the 3651 // specialization occurred. 3652 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader && 3653 !SuppressDiagnostic) 3654 Diag(ExplicitSpecLoc, 3655 diag::note_explicit_template_spec_does_not_need_header) 3656 << NestedTypes.back(); 3657 3658 // We have a template parameter list with no corresponding scope, which 3659 // means that the resulting template declaration can't be instantiated 3660 // properly (we'll end up with dependent nodes when we shouldn't). 3661 if (!AllExplicitSpecHeaders) 3662 Invalid = true; 3663 } 3664 3665 // C++ [temp.expl.spec]p16: 3666 // In an explicit specialization declaration for a member of a class 3667 // template or a member template that ap- pears in namespace scope, the 3668 // member template and some of its enclosing class templates may remain 3669 // unspecialized, except that the declaration shall not explicitly 3670 // specialize a class member template if its en- closing class templates 3671 // are not explicitly specialized as well. 3672 if (ParamLists.back()->size() == 0 && 3673 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(), 3674 false)) 3675 return nullptr; 3676 3677 // Return the last template parameter list, which corresponds to the 3678 // entity being declared. 3679 return ParamLists.back(); 3680 } 3681 3682 void Sema::NoteAllFoundTemplates(TemplateName Name) { 3683 if (TemplateDecl *Template = Name.getAsTemplateDecl()) { 3684 Diag(Template->getLocation(), diag::note_template_declared_here) 3685 << (isa<FunctionTemplateDecl>(Template) 3686 ? 0 3687 : isa<ClassTemplateDecl>(Template) 3688 ? 1 3689 : isa<VarTemplateDecl>(Template) 3690 ? 2 3691 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4) 3692 << Template->getDeclName(); 3693 return; 3694 } 3695 3696 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) { 3697 for (OverloadedTemplateStorage::iterator I = OST->begin(), 3698 IEnd = OST->end(); 3699 I != IEnd; ++I) 3700 Diag((*I)->getLocation(), diag::note_template_declared_here) 3701 << 0 << (*I)->getDeclName(); 3702 3703 return; 3704 } 3705 } 3706 3707 static QualType 3708 checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD, 3709 ArrayRef<TemplateArgument> Converted, 3710 SourceLocation TemplateLoc, 3711 TemplateArgumentListInfo &TemplateArgs) { 3712 ASTContext &Context = SemaRef.getASTContext(); 3713 3714 switch (BTD->getBuiltinTemplateKind()) { 3715 case BTK__make_integer_seq: { 3716 // Specializations of __make_integer_seq<S, T, N> are treated like 3717 // S<T, 0, ..., N-1>. 3718 3719 QualType OrigType = Converted[1].getAsType(); 3720 // C++14 [inteseq.intseq]p1: 3721 // T shall be an integer type. 3722 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) { 3723 SemaRef.Diag(TemplateArgs[1].getLocation(), 3724 diag::err_integer_sequence_integral_element_type); 3725 return QualType(); 3726 } 3727 3728 TemplateArgument NumArgsArg = Converted[2]; 3729 if (NumArgsArg.isDependent()) 3730 return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD), 3731 Converted); 3732 3733 TemplateArgumentListInfo SyntheticTemplateArgs; 3734 // The type argument, wrapped in substitution sugar, gets reused as the 3735 // first template argument in the synthetic template argument list. 3736 SyntheticTemplateArgs.addArgument( 3737 TemplateArgumentLoc(TemplateArgument(OrigType), 3738 SemaRef.Context.getTrivialTypeSourceInfo( 3739 OrigType, TemplateArgs[1].getLocation()))); 3740 3741 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) { 3742 // Expand N into 0 ... N-1. 3743 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned()); 3744 I < NumArgs; ++I) { 3745 TemplateArgument TA(Context, I, OrigType); 3746 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc( 3747 TA, OrigType, TemplateArgs[2].getLocation())); 3748 } 3749 } else { 3750 // C++14 [inteseq.make]p1: 3751 // If N is negative the program is ill-formed. 3752 SemaRef.Diag(TemplateArgs[2].getLocation(), 3753 diag::err_integer_sequence_negative_length); 3754 return QualType(); 3755 } 3756 3757 // The first template argument will be reused as the template decl that 3758 // our synthetic template arguments will be applied to. 3759 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(), 3760 TemplateLoc, SyntheticTemplateArgs); 3761 } 3762 3763 case BTK__type_pack_element: 3764 // Specializations of 3765 // __type_pack_element<Index, T_1, ..., T_N> 3766 // are treated like T_Index. 3767 assert(Converted.size() == 2 && 3768 "__type_pack_element should be given an index and a parameter pack"); 3769 3770 TemplateArgument IndexArg = Converted[0], Ts = Converted[1]; 3771 if (IndexArg.isDependent() || Ts.isDependent()) 3772 return Context.getCanonicalTemplateSpecializationType(TemplateName(BTD), 3773 Converted); 3774 3775 llvm::APSInt Index = IndexArg.getAsIntegral(); 3776 assert(Index >= 0 && "the index used with __type_pack_element should be of " 3777 "type std::size_t, and hence be non-negative"); 3778 // If the Index is out of bounds, the program is ill-formed. 3779 if (Index >= Ts.pack_size()) { 3780 SemaRef.Diag(TemplateArgs[0].getLocation(), 3781 diag::err_type_pack_element_out_of_bounds); 3782 return QualType(); 3783 } 3784 3785 // We simply return the type at index `Index`. 3786 int64_t N = Index.getExtValue(); 3787 return Ts.getPackAsArray()[N].getAsType(); 3788 } 3789 llvm_unreachable("unexpected BuiltinTemplateDecl!"); 3790 } 3791 3792 /// Determine whether this alias template is "enable_if_t". 3793 /// libc++ >=14 uses "__enable_if_t" in C++11 mode. 3794 static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) { 3795 return AliasTemplate->getName().equals("enable_if_t") || 3796 AliasTemplate->getName().equals("__enable_if_t"); 3797 } 3798 3799 /// Collect all of the separable terms in the given condition, which 3800 /// might be a conjunction. 3801 /// 3802 /// FIXME: The right answer is to convert the logical expression into 3803 /// disjunctive normal form, so we can find the first failed term 3804 /// within each possible clause. 3805 static void collectConjunctionTerms(Expr *Clause, 3806 SmallVectorImpl<Expr *> &Terms) { 3807 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) { 3808 if (BinOp->getOpcode() == BO_LAnd) { 3809 collectConjunctionTerms(BinOp->getLHS(), Terms); 3810 collectConjunctionTerms(BinOp->getRHS(), Terms); 3811 return; 3812 } 3813 } 3814 3815 Terms.push_back(Clause); 3816 } 3817 3818 // The ranges-v3 library uses an odd pattern of a top-level "||" with 3819 // a left-hand side that is value-dependent but never true. Identify 3820 // the idiom and ignore that term. 3821 static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) { 3822 // Top-level '||'. 3823 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts()); 3824 if (!BinOp) return Cond; 3825 3826 if (BinOp->getOpcode() != BO_LOr) return Cond; 3827 3828 // With an inner '==' that has a literal on the right-hand side. 3829 Expr *LHS = BinOp->getLHS(); 3830 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts()); 3831 if (!InnerBinOp) return Cond; 3832 3833 if (InnerBinOp->getOpcode() != BO_EQ || 3834 !isa<IntegerLiteral>(InnerBinOp->getRHS())) 3835 return Cond; 3836 3837 // If the inner binary operation came from a macro expansion named 3838 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side 3839 // of the '||', which is the real, user-provided condition. 3840 SourceLocation Loc = InnerBinOp->getExprLoc(); 3841 if (!Loc.isMacroID()) return Cond; 3842 3843 StringRef MacroName = PP.getImmediateMacroName(Loc); 3844 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_") 3845 return BinOp->getRHS(); 3846 3847 return Cond; 3848 } 3849 3850 namespace { 3851 3852 // A PrinterHelper that prints more helpful diagnostics for some sub-expressions 3853 // within failing boolean expression, such as substituting template parameters 3854 // for actual types. 3855 class FailedBooleanConditionPrinterHelper : public PrinterHelper { 3856 public: 3857 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P) 3858 : Policy(P) {} 3859 3860 bool handledStmt(Stmt *E, raw_ostream &OS) override { 3861 const auto *DR = dyn_cast<DeclRefExpr>(E); 3862 if (DR && DR->getQualifier()) { 3863 // If this is a qualified name, expand the template arguments in nested 3864 // qualifiers. 3865 DR->getQualifier()->print(OS, Policy, true); 3866 // Then print the decl itself. 3867 const ValueDecl *VD = DR->getDecl(); 3868 OS << VD->getName(); 3869 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) { 3870 // This is a template variable, print the expanded template arguments. 3871 printTemplateArgumentList( 3872 OS, IV->getTemplateArgs().asArray(), Policy, 3873 IV->getSpecializedTemplate()->getTemplateParameters()); 3874 } 3875 return true; 3876 } 3877 return false; 3878 } 3879 3880 private: 3881 const PrintingPolicy Policy; 3882 }; 3883 3884 } // end anonymous namespace 3885 3886 std::pair<Expr *, std::string> 3887 Sema::findFailedBooleanCondition(Expr *Cond) { 3888 Cond = lookThroughRangesV3Condition(PP, Cond); 3889 3890 // Separate out all of the terms in a conjunction. 3891 SmallVector<Expr *, 4> Terms; 3892 collectConjunctionTerms(Cond, Terms); 3893 3894 // Determine which term failed. 3895 Expr *FailedCond = nullptr; 3896 for (Expr *Term : Terms) { 3897 Expr *TermAsWritten = Term->IgnoreParenImpCasts(); 3898 3899 // Literals are uninteresting. 3900 if (isa<CXXBoolLiteralExpr>(TermAsWritten) || 3901 isa<IntegerLiteral>(TermAsWritten)) 3902 continue; 3903 3904 // The initialization of the parameter from the argument is 3905 // a constant-evaluated context. 3906 EnterExpressionEvaluationContext ConstantEvaluated( 3907 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated); 3908 3909 bool Succeeded; 3910 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) && 3911 !Succeeded) { 3912 FailedCond = TermAsWritten; 3913 break; 3914 } 3915 } 3916 if (!FailedCond) 3917 FailedCond = Cond->IgnoreParenImpCasts(); 3918 3919 std::string Description; 3920 { 3921 llvm::raw_string_ostream Out(Description); 3922 PrintingPolicy Policy = getPrintingPolicy(); 3923 Policy.PrintCanonicalTypes = true; 3924 FailedBooleanConditionPrinterHelper Helper(Policy); 3925 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr); 3926 } 3927 return { FailedCond, Description }; 3928 } 3929 3930 QualType Sema::CheckTemplateIdType(TemplateName Name, 3931 SourceLocation TemplateLoc, 3932 TemplateArgumentListInfo &TemplateArgs) { 3933 DependentTemplateName *DTN 3934 = Name.getUnderlying().getAsDependentTemplateName(); 3935 if (DTN && DTN->isIdentifier()) 3936 // When building a template-id where the template-name is dependent, 3937 // assume the template is a type template. Either our assumption is 3938 // correct, or the code is ill-formed and will be diagnosed when the 3939 // dependent name is substituted. 3940 return Context.getDependentTemplateSpecializationType( 3941 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(), 3942 TemplateArgs.arguments()); 3943 3944 if (Name.getAsAssumedTemplateName() && 3945 resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc)) 3946 return QualType(); 3947 3948 TemplateDecl *Template = Name.getAsTemplateDecl(); 3949 if (!Template || isa<FunctionTemplateDecl>(Template) || 3950 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) { 3951 // We might have a substituted template template parameter pack. If so, 3952 // build a template specialization type for it. 3953 if (Name.getAsSubstTemplateTemplateParmPack()) 3954 return Context.getTemplateSpecializationType(Name, 3955 TemplateArgs.arguments()); 3956 3957 Diag(TemplateLoc, diag::err_template_id_not_a_type) 3958 << Name; 3959 NoteAllFoundTemplates(Name); 3960 return QualType(); 3961 } 3962 3963 // Check that the template argument list is well-formed for this 3964 // template. 3965 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; 3966 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false, 3967 SugaredConverted, CanonicalConverted, 3968 /*UpdateArgsWithConversions=*/true)) 3969 return QualType(); 3970 3971 QualType CanonType; 3972 3973 if (TypeAliasTemplateDecl *AliasTemplate = 3974 dyn_cast<TypeAliasTemplateDecl>(Template)) { 3975 3976 // Find the canonical type for this type alias template specialization. 3977 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl(); 3978 if (Pattern->isInvalidDecl()) 3979 return QualType(); 3980 3981 // Only substitute for the innermost template argument list. 3982 MultiLevelTemplateArgumentList TemplateArgLists; 3983 TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted, 3984 /*Final=*/false); 3985 TemplateArgLists.addOuterRetainedLevels( 3986 AliasTemplate->getTemplateParameters()->getDepth()); 3987 3988 LocalInstantiationScope Scope(*this); 3989 InstantiatingTemplate Inst(*this, TemplateLoc, Template); 3990 if (Inst.isInvalid()) 3991 return QualType(); 3992 3993 CanonType = SubstType(Pattern->getUnderlyingType(), 3994 TemplateArgLists, AliasTemplate->getLocation(), 3995 AliasTemplate->getDeclName()); 3996 if (CanonType.isNull()) { 3997 // If this was enable_if and we failed to find the nested type 3998 // within enable_if in a SFINAE context, dig out the specific 3999 // enable_if condition that failed and present that instead. 4000 if (isEnableIfAliasTemplate(AliasTemplate)) { 4001 if (auto DeductionInfo = isSFINAEContext()) { 4002 if (*DeductionInfo && 4003 (*DeductionInfo)->hasSFINAEDiagnostic() && 4004 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() == 4005 diag::err_typename_nested_not_found_enable_if && 4006 TemplateArgs[0].getArgument().getKind() 4007 == TemplateArgument::Expression) { 4008 Expr *FailedCond; 4009 std::string FailedDescription; 4010 std::tie(FailedCond, FailedDescription) = 4011 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression()); 4012 4013 // Remove the old SFINAE diagnostic. 4014 PartialDiagnosticAt OldDiag = 4015 {SourceLocation(), PartialDiagnostic::NullDiagnostic()}; 4016 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag); 4017 4018 // Add a new SFINAE diagnostic specifying which condition 4019 // failed. 4020 (*DeductionInfo)->addSFINAEDiagnostic( 4021 OldDiag.first, 4022 PDiag(diag::err_typename_nested_not_found_requirement) 4023 << FailedDescription 4024 << FailedCond->getSourceRange()); 4025 } 4026 } 4027 } 4028 4029 return QualType(); 4030 } 4031 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) { 4032 CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted, 4033 TemplateLoc, TemplateArgs); 4034 } else if (Name.isDependent() || 4035 TemplateSpecializationType::anyDependentTemplateArguments( 4036 TemplateArgs, CanonicalConverted)) { 4037 // This class template specialization is a dependent 4038 // type. Therefore, its canonical type is another class template 4039 // specialization type that contains all of the converted 4040 // arguments in canonical form. This ensures that, e.g., A<T> and 4041 // A<T, T> have identical types when A is declared as: 4042 // 4043 // template<typename T, typename U = T> struct A; 4044 CanonType = Context.getCanonicalTemplateSpecializationType( 4045 Name, CanonicalConverted); 4046 4047 // This might work out to be a current instantiation, in which 4048 // case the canonical type needs to be the InjectedClassNameType. 4049 // 4050 // TODO: in theory this could be a simple hashtable lookup; most 4051 // changes to CurContext don't change the set of current 4052 // instantiations. 4053 if (isa<ClassTemplateDecl>(Template)) { 4054 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) { 4055 // If we get out to a namespace, we're done. 4056 if (Ctx->isFileContext()) break; 4057 4058 // If this isn't a record, keep looking. 4059 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx); 4060 if (!Record) continue; 4061 4062 // Look for one of the two cases with InjectedClassNameTypes 4063 // and check whether it's the same template. 4064 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) && 4065 !Record->getDescribedClassTemplate()) 4066 continue; 4067 4068 // Fetch the injected class name type and check whether its 4069 // injected type is equal to the type we just built. 4070 QualType ICNT = Context.getTypeDeclType(Record); 4071 QualType Injected = cast<InjectedClassNameType>(ICNT) 4072 ->getInjectedSpecializationType(); 4073 4074 if (CanonType != Injected->getCanonicalTypeInternal()) 4075 continue; 4076 4077 // If so, the canonical type of this TST is the injected 4078 // class name type of the record we just found. 4079 assert(ICNT.isCanonical()); 4080 CanonType = ICNT; 4081 break; 4082 } 4083 } 4084 } else if (ClassTemplateDecl *ClassTemplate = 4085 dyn_cast<ClassTemplateDecl>(Template)) { 4086 // Find the class template specialization declaration that 4087 // corresponds to these arguments. 4088 void *InsertPos = nullptr; 4089 ClassTemplateSpecializationDecl *Decl = 4090 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos); 4091 if (!Decl) { 4092 // This is the first time we have referenced this class template 4093 // specialization. Create the canonical declaration and add it to 4094 // the set of specializations. 4095 Decl = ClassTemplateSpecializationDecl::Create( 4096 Context, ClassTemplate->getTemplatedDecl()->getTagKind(), 4097 ClassTemplate->getDeclContext(), 4098 ClassTemplate->getTemplatedDecl()->getBeginLoc(), 4099 ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted, 4100 nullptr); 4101 ClassTemplate->AddSpecialization(Decl, InsertPos); 4102 if (ClassTemplate->isOutOfLine()) 4103 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext()); 4104 } 4105 4106 if (Decl->getSpecializationKind() == TSK_Undeclared && 4107 ClassTemplate->getTemplatedDecl()->hasAttrs()) { 4108 InstantiatingTemplate Inst(*this, TemplateLoc, Decl); 4109 if (!Inst.isInvalid()) { 4110 MultiLevelTemplateArgumentList TemplateArgLists(Template, 4111 CanonicalConverted, 4112 /*Final=*/false); 4113 InstantiateAttrsForDecl(TemplateArgLists, 4114 ClassTemplate->getTemplatedDecl(), Decl); 4115 } 4116 } 4117 4118 // Diagnose uses of this specialization. 4119 (void)DiagnoseUseOfDecl(Decl, TemplateLoc); 4120 4121 CanonType = Context.getTypeDeclType(Decl); 4122 assert(isa<RecordType>(CanonType) && 4123 "type of non-dependent specialization is not a RecordType"); 4124 } else { 4125 llvm_unreachable("Unhandled template kind"); 4126 } 4127 4128 // Build the fully-sugared type for this class template 4129 // specialization, which refers back to the class template 4130 // specialization we created or found. 4131 return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(), 4132 CanonType); 4133 } 4134 4135 void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName, 4136 TemplateNameKind &TNK, 4137 SourceLocation NameLoc, 4138 IdentifierInfo *&II) { 4139 assert(TNK == TNK_Undeclared_template && "not an undeclared template name"); 4140 4141 TemplateName Name = ParsedName.get(); 4142 auto *ATN = Name.getAsAssumedTemplateName(); 4143 assert(ATN && "not an assumed template name"); 4144 II = ATN->getDeclName().getAsIdentifierInfo(); 4145 4146 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) { 4147 // Resolved to a type template name. 4148 ParsedName = TemplateTy::make(Name); 4149 TNK = TNK_Type_template; 4150 } 4151 } 4152 4153 bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, 4154 SourceLocation NameLoc, 4155 bool Diagnose) { 4156 // We assumed this undeclared identifier to be an (ADL-only) function 4157 // template name, but it was used in a context where a type was required. 4158 // Try to typo-correct it now. 4159 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName(); 4160 assert(ATN && "not an assumed template name"); 4161 4162 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName); 4163 struct CandidateCallback : CorrectionCandidateCallback { 4164 bool ValidateCandidate(const TypoCorrection &TC) override { 4165 return TC.getCorrectionDecl() && 4166 getAsTypeTemplateDecl(TC.getCorrectionDecl()); 4167 } 4168 std::unique_ptr<CorrectionCandidateCallback> clone() override { 4169 return std::make_unique<CandidateCallback>(*this); 4170 } 4171 } FilterCCC; 4172 4173 TypoCorrection Corrected = 4174 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr, 4175 FilterCCC, CTK_ErrorRecovery); 4176 if (Corrected && Corrected.getFoundDecl()) { 4177 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) 4178 << ATN->getDeclName()); 4179 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()); 4180 return false; 4181 } 4182 4183 if (Diagnose) 4184 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName(); 4185 return true; 4186 } 4187 4188 TypeResult Sema::ActOnTemplateIdType( 4189 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 4190 TemplateTy TemplateD, IdentifierInfo *TemplateII, 4191 SourceLocation TemplateIILoc, SourceLocation LAngleLoc, 4192 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc, 4193 bool IsCtorOrDtorName, bool IsClassName, 4194 ImplicitTypenameContext AllowImplicitTypename) { 4195 if (SS.isInvalid()) 4196 return true; 4197 4198 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) { 4199 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false); 4200 4201 // C++ [temp.res]p3: 4202 // A qualified-id that refers to a type and in which the 4203 // nested-name-specifier depends on a template-parameter (14.6.2) 4204 // shall be prefixed by the keyword typename to indicate that the 4205 // qualified-id denotes a type, forming an 4206 // elaborated-type-specifier (7.1.5.3). 4207 if (!LookupCtx && isDependentScopeSpecifier(SS)) { 4208 // C++2a relaxes some of those restrictions in [temp.res]p5. 4209 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) { 4210 if (getLangOpts().CPlusPlus20) 4211 Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename); 4212 else 4213 Diag(SS.getBeginLoc(), diag::ext_implicit_typename) 4214 << SS.getScopeRep() << TemplateII->getName() 4215 << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename "); 4216 } else 4217 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) 4218 << SS.getScopeRep() << TemplateII->getName(); 4219 4220 // FIXME: This is not quite correct recovery as we don't transform SS 4221 // into the corresponding dependent form (and we don't diagnose missing 4222 // 'template' keywords within SS as a result). 4223 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc, 4224 TemplateD, TemplateII, TemplateIILoc, LAngleLoc, 4225 TemplateArgsIn, RAngleLoc); 4226 } 4227 4228 // Per C++ [class.qual]p2, if the template-id was an injected-class-name, 4229 // it's not actually allowed to be used as a type in most cases. Because 4230 // we annotate it before we know whether it's valid, we have to check for 4231 // this case here. 4232 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 4233 if (LookupRD && LookupRD->getIdentifier() == TemplateII) { 4234 Diag(TemplateIILoc, 4235 TemplateKWLoc.isInvalid() 4236 ? diag::err_out_of_line_qualified_id_type_names_constructor 4237 : diag::ext_out_of_line_qualified_id_type_names_constructor) 4238 << TemplateII << 0 /*injected-class-name used as template name*/ 4239 << 1 /*if any keyword was present, it was 'template'*/; 4240 } 4241 } 4242 4243 TemplateName Template = TemplateD.get(); 4244 if (Template.getAsAssumedTemplateName() && 4245 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc)) 4246 return true; 4247 4248 // Translate the parser's template argument list in our AST format. 4249 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 4250 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 4251 4252 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 4253 assert(SS.getScopeRep() == DTN->getQualifier()); 4254 QualType T = Context.getDependentTemplateSpecializationType( 4255 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(), 4256 TemplateArgs.arguments()); 4257 // Build type-source information. 4258 TypeLocBuilder TLB; 4259 DependentTemplateSpecializationTypeLoc SpecTL 4260 = TLB.push<DependentTemplateSpecializationTypeLoc>(T); 4261 SpecTL.setElaboratedKeywordLoc(SourceLocation()); 4262 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 4263 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 4264 SpecTL.setTemplateNameLoc(TemplateIILoc); 4265 SpecTL.setLAngleLoc(LAngleLoc); 4266 SpecTL.setRAngleLoc(RAngleLoc); 4267 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) 4268 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 4269 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); 4270 } 4271 4272 QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs); 4273 if (SpecTy.isNull()) 4274 return true; 4275 4276 // Build type-source information. 4277 TypeLocBuilder TLB; 4278 TemplateSpecializationTypeLoc SpecTL = 4279 TLB.push<TemplateSpecializationTypeLoc>(SpecTy); 4280 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 4281 SpecTL.setTemplateNameLoc(TemplateIILoc); 4282 SpecTL.setLAngleLoc(LAngleLoc); 4283 SpecTL.setRAngleLoc(RAngleLoc); 4284 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) 4285 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); 4286 4287 // Create an elaborated-type-specifier containing the nested-name-specifier. 4288 QualType ElTy = 4289 getElaboratedType(ElaboratedTypeKeyword::None, 4290 !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy); 4291 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy); 4292 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 4293 if (!ElabTL.isEmpty()) 4294 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 4295 return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy)); 4296 } 4297 4298 TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK, 4299 TypeSpecifierType TagSpec, 4300 SourceLocation TagLoc, 4301 CXXScopeSpec &SS, 4302 SourceLocation TemplateKWLoc, 4303 TemplateTy TemplateD, 4304 SourceLocation TemplateLoc, 4305 SourceLocation LAngleLoc, 4306 ASTTemplateArgsPtr TemplateArgsIn, 4307 SourceLocation RAngleLoc) { 4308 if (SS.isInvalid()) 4309 return TypeResult(true); 4310 4311 TemplateName Template = TemplateD.get(); 4312 4313 // Translate the parser's template argument list in our AST format. 4314 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 4315 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 4316 4317 // Determine the tag kind 4318 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 4319 ElaboratedTypeKeyword Keyword 4320 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind); 4321 4322 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 4323 assert(SS.getScopeRep() == DTN->getQualifier()); 4324 QualType T = Context.getDependentTemplateSpecializationType( 4325 Keyword, DTN->getQualifier(), DTN->getIdentifier(), 4326 TemplateArgs.arguments()); 4327 4328 // Build type-source information. 4329 TypeLocBuilder TLB; 4330 DependentTemplateSpecializationTypeLoc SpecTL 4331 = TLB.push<DependentTemplateSpecializationTypeLoc>(T); 4332 SpecTL.setElaboratedKeywordLoc(TagLoc); 4333 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 4334 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 4335 SpecTL.setTemplateNameLoc(TemplateLoc); 4336 SpecTL.setLAngleLoc(LAngleLoc); 4337 SpecTL.setRAngleLoc(RAngleLoc); 4338 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I) 4339 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 4340 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T)); 4341 } 4342 4343 if (TypeAliasTemplateDecl *TAT = 4344 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) { 4345 // C++0x [dcl.type.elab]p2: 4346 // If the identifier resolves to a typedef-name or the simple-template-id 4347 // resolves to an alias template specialization, the 4348 // elaborated-type-specifier is ill-formed. 4349 Diag(TemplateLoc, diag::err_tag_reference_non_tag) 4350 << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind); 4351 Diag(TAT->getLocation(), diag::note_declared_at); 4352 } 4353 4354 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs); 4355 if (Result.isNull()) 4356 return TypeResult(true); 4357 4358 // Check the tag kind 4359 if (const RecordType *RT = Result->getAs<RecordType>()) { 4360 RecordDecl *D = RT->getDecl(); 4361 4362 IdentifierInfo *Id = D->getIdentifier(); 4363 assert(Id && "templated class must have an identifier"); 4364 4365 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition, 4366 TagLoc, Id)) { 4367 Diag(TagLoc, diag::err_use_with_wrong_tag) 4368 << Result 4369 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName()); 4370 Diag(D->getLocation(), diag::note_previous_use); 4371 } 4372 } 4373 4374 // Provide source-location information for the template specialization. 4375 TypeLocBuilder TLB; 4376 TemplateSpecializationTypeLoc SpecTL 4377 = TLB.push<TemplateSpecializationTypeLoc>(Result); 4378 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 4379 SpecTL.setTemplateNameLoc(TemplateLoc); 4380 SpecTL.setLAngleLoc(LAngleLoc); 4381 SpecTL.setRAngleLoc(RAngleLoc); 4382 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i) 4383 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo()); 4384 4385 // Construct an elaborated type containing the nested-name-specifier (if any) 4386 // and tag keyword. 4387 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result); 4388 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result); 4389 ElabTL.setElaboratedKeywordLoc(TagLoc); 4390 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 4391 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); 4392 } 4393 4394 static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized, 4395 NamedDecl *PrevDecl, 4396 SourceLocation Loc, 4397 bool IsPartialSpecialization); 4398 4399 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D); 4400 4401 static bool isTemplateArgumentTemplateParameter( 4402 const TemplateArgument &Arg, unsigned Depth, unsigned Index) { 4403 switch (Arg.getKind()) { 4404 case TemplateArgument::Null: 4405 case TemplateArgument::NullPtr: 4406 case TemplateArgument::Integral: 4407 case TemplateArgument::Declaration: 4408 case TemplateArgument::Pack: 4409 case TemplateArgument::TemplateExpansion: 4410 return false; 4411 4412 case TemplateArgument::Type: { 4413 QualType Type = Arg.getAsType(); 4414 const TemplateTypeParmType *TPT = 4415 Arg.getAsType()->getAs<TemplateTypeParmType>(); 4416 return TPT && !Type.hasQualifiers() && 4417 TPT->getDepth() == Depth && TPT->getIndex() == Index; 4418 } 4419 4420 case TemplateArgument::Expression: { 4421 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr()); 4422 if (!DRE || !DRE->getDecl()) 4423 return false; 4424 const NonTypeTemplateParmDecl *NTTP = 4425 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl()); 4426 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index; 4427 } 4428 4429 case TemplateArgument::Template: 4430 const TemplateTemplateParmDecl *TTP = 4431 dyn_cast_or_null<TemplateTemplateParmDecl>( 4432 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl()); 4433 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index; 4434 } 4435 llvm_unreachable("unexpected kind of template argument"); 4436 } 4437 4438 static bool isSameAsPrimaryTemplate(TemplateParameterList *Params, 4439 ArrayRef<TemplateArgument> Args) { 4440 if (Params->size() != Args.size()) 4441 return false; 4442 4443 unsigned Depth = Params->getDepth(); 4444 4445 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 4446 TemplateArgument Arg = Args[I]; 4447 4448 // If the parameter is a pack expansion, the argument must be a pack 4449 // whose only element is a pack expansion. 4450 if (Params->getParam(I)->isParameterPack()) { 4451 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 || 4452 !Arg.pack_begin()->isPackExpansion()) 4453 return false; 4454 Arg = Arg.pack_begin()->getPackExpansionPattern(); 4455 } 4456 4457 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I)) 4458 return false; 4459 } 4460 4461 return true; 4462 } 4463 4464 template<typename PartialSpecDecl> 4465 static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) { 4466 if (Partial->getDeclContext()->isDependentContext()) 4467 return; 4468 4469 // FIXME: Get the TDK from deduction in order to provide better diagnostics 4470 // for non-substitution-failure issues? 4471 TemplateDeductionInfo Info(Partial->getLocation()); 4472 if (S.isMoreSpecializedThanPrimary(Partial, Info)) 4473 return; 4474 4475 auto *Template = Partial->getSpecializedTemplate(); 4476 S.Diag(Partial->getLocation(), 4477 diag::ext_partial_spec_not_more_specialized_than_primary) 4478 << isa<VarTemplateDecl>(Template); 4479 4480 if (Info.hasSFINAEDiagnostic()) { 4481 PartialDiagnosticAt Diag = {SourceLocation(), 4482 PartialDiagnostic::NullDiagnostic()}; 4483 Info.takeSFINAEDiagnostic(Diag); 4484 SmallString<128> SFINAEArgString; 4485 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString); 4486 S.Diag(Diag.first, 4487 diag::note_partial_spec_not_more_specialized_than_primary) 4488 << SFINAEArgString; 4489 } 4490 4491 S.NoteTemplateLocation(*Template); 4492 SmallVector<const Expr *, 3> PartialAC, TemplateAC; 4493 Template->getAssociatedConstraints(TemplateAC); 4494 Partial->getAssociatedConstraints(PartialAC); 4495 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template, 4496 TemplateAC); 4497 } 4498 4499 static void 4500 noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams, 4501 const llvm::SmallBitVector &DeducibleParams) { 4502 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) { 4503 if (!DeducibleParams[I]) { 4504 NamedDecl *Param = TemplateParams->getParam(I); 4505 if (Param->getDeclName()) 4506 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter) 4507 << Param->getDeclName(); 4508 else 4509 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter) 4510 << "(anonymous)"; 4511 } 4512 } 4513 } 4514 4515 4516 template<typename PartialSpecDecl> 4517 static void checkTemplatePartialSpecialization(Sema &S, 4518 PartialSpecDecl *Partial) { 4519 // C++1z [temp.class.spec]p8: (DR1495) 4520 // - The specialization shall be more specialized than the primary 4521 // template (14.5.5.2). 4522 checkMoreSpecializedThanPrimary(S, Partial); 4523 4524 // C++ [temp.class.spec]p8: (DR1315) 4525 // - Each template-parameter shall appear at least once in the 4526 // template-id outside a non-deduced context. 4527 // C++1z [temp.class.spec.match]p3 (P0127R2) 4528 // If the template arguments of a partial specialization cannot be 4529 // deduced because of the structure of its template-parameter-list 4530 // and the template-id, the program is ill-formed. 4531 auto *TemplateParams = Partial->getTemplateParameters(); 4532 llvm::SmallBitVector DeducibleParams(TemplateParams->size()); 4533 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true, 4534 TemplateParams->getDepth(), DeducibleParams); 4535 4536 if (!DeducibleParams.all()) { 4537 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count(); 4538 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible) 4539 << isa<VarTemplatePartialSpecializationDecl>(Partial) 4540 << (NumNonDeducible > 1) 4541 << SourceRange(Partial->getLocation(), 4542 Partial->getTemplateArgsAsWritten()->RAngleLoc); 4543 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams); 4544 } 4545 } 4546 4547 void Sema::CheckTemplatePartialSpecialization( 4548 ClassTemplatePartialSpecializationDecl *Partial) { 4549 checkTemplatePartialSpecialization(*this, Partial); 4550 } 4551 4552 void Sema::CheckTemplatePartialSpecialization( 4553 VarTemplatePartialSpecializationDecl *Partial) { 4554 checkTemplatePartialSpecialization(*this, Partial); 4555 } 4556 4557 void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) { 4558 // C++1z [temp.param]p11: 4559 // A template parameter of a deduction guide template that does not have a 4560 // default-argument shall be deducible from the parameter-type-list of the 4561 // deduction guide template. 4562 auto *TemplateParams = TD->getTemplateParameters(); 4563 llvm::SmallBitVector DeducibleParams(TemplateParams->size()); 4564 MarkDeducedTemplateParameters(TD, DeducibleParams); 4565 for (unsigned I = 0; I != TemplateParams->size(); ++I) { 4566 // A parameter pack is deducible (to an empty pack). 4567 auto *Param = TemplateParams->getParam(I); 4568 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param)) 4569 DeducibleParams[I] = true; 4570 } 4571 4572 if (!DeducibleParams.all()) { 4573 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count(); 4574 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible) 4575 << (NumNonDeducible > 1); 4576 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams); 4577 } 4578 } 4579 4580 DeclResult Sema::ActOnVarTemplateSpecialization( 4581 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, 4582 TemplateParameterList *TemplateParams, StorageClass SC, 4583 bool IsPartialSpecialization) { 4584 // D must be variable template id. 4585 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && 4586 "Variable template specialization is declared with a template id."); 4587 4588 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 4589 TemplateArgumentListInfo TemplateArgs = 4590 makeTemplateArgumentListInfo(*this, *TemplateId); 4591 SourceLocation TemplateNameLoc = D.getIdentifierLoc(); 4592 SourceLocation LAngleLoc = TemplateId->LAngleLoc; 4593 SourceLocation RAngleLoc = TemplateId->RAngleLoc; 4594 4595 TemplateName Name = TemplateId->Template.get(); 4596 4597 // The template-id must name a variable template. 4598 VarTemplateDecl *VarTemplate = 4599 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl()); 4600 if (!VarTemplate) { 4601 NamedDecl *FnTemplate; 4602 if (auto *OTS = Name.getAsOverloadedTemplate()) 4603 FnTemplate = *OTS->begin(); 4604 else 4605 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl()); 4606 if (FnTemplate) 4607 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method) 4608 << FnTemplate->getDeclName(); 4609 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template) 4610 << IsPartialSpecialization; 4611 } 4612 4613 // Check for unexpanded parameter packs in any of the template arguments. 4614 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 4615 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I], 4616 IsPartialSpecialization 4617 ? UPPC_PartialSpecialization 4618 : UPPC_ExplicitSpecialization)) 4619 return true; 4620 4621 // Check that the template argument list is well-formed for this 4622 // template. 4623 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; 4624 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs, 4625 false, SugaredConverted, CanonicalConverted, 4626 /*UpdateArgsWithConversions=*/true)) 4627 return true; 4628 4629 // Find the variable template (partial) specialization declaration that 4630 // corresponds to these arguments. 4631 if (IsPartialSpecialization) { 4632 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate, 4633 TemplateArgs.size(), 4634 CanonicalConverted)) 4635 return true; 4636 4637 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we 4638 // also do them during instantiation. 4639 if (!Name.isDependent() && 4640 !TemplateSpecializationType::anyDependentTemplateArguments( 4641 TemplateArgs, CanonicalConverted)) { 4642 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized) 4643 << VarTemplate->getDeclName(); 4644 IsPartialSpecialization = false; 4645 } 4646 4647 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(), 4648 CanonicalConverted) && 4649 (!Context.getLangOpts().CPlusPlus20 || 4650 !TemplateParams->hasAssociatedConstraints())) { 4651 // C++ [temp.class.spec]p9b3: 4652 // 4653 // -- The argument list of the specialization shall not be identical 4654 // to the implicit argument list of the primary template. 4655 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) 4656 << /*variable template*/ 1 4657 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord()) 4658 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc)); 4659 // FIXME: Recover from this by treating the declaration as a redeclaration 4660 // of the primary template. 4661 return true; 4662 } 4663 } 4664 4665 void *InsertPos = nullptr; 4666 VarTemplateSpecializationDecl *PrevDecl = nullptr; 4667 4668 if (IsPartialSpecialization) 4669 PrevDecl = VarTemplate->findPartialSpecialization( 4670 CanonicalConverted, TemplateParams, InsertPos); 4671 else 4672 PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos); 4673 4674 VarTemplateSpecializationDecl *Specialization = nullptr; 4675 4676 // Check whether we can declare a variable template specialization in 4677 // the current scope. 4678 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl, 4679 TemplateNameLoc, 4680 IsPartialSpecialization)) 4681 return true; 4682 4683 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) { 4684 // Since the only prior variable template specialization with these 4685 // arguments was referenced but not declared, reuse that 4686 // declaration node as our own, updating its source location and 4687 // the list of outer template parameters to reflect our new declaration. 4688 Specialization = PrevDecl; 4689 Specialization->setLocation(TemplateNameLoc); 4690 PrevDecl = nullptr; 4691 } else if (IsPartialSpecialization) { 4692 // Create a new class template partial specialization declaration node. 4693 VarTemplatePartialSpecializationDecl *PrevPartial = 4694 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl); 4695 VarTemplatePartialSpecializationDecl *Partial = 4696 VarTemplatePartialSpecializationDecl::Create( 4697 Context, VarTemplate->getDeclContext(), TemplateKWLoc, 4698 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC, 4699 CanonicalConverted, TemplateArgs); 4700 4701 if (!PrevPartial) 4702 VarTemplate->AddPartialSpecialization(Partial, InsertPos); 4703 Specialization = Partial; 4704 4705 // If we are providing an explicit specialization of a member variable 4706 // template specialization, make a note of that. 4707 if (PrevPartial && PrevPartial->getInstantiatedFromMember()) 4708 PrevPartial->setMemberSpecialization(); 4709 4710 CheckTemplatePartialSpecialization(Partial); 4711 } else { 4712 // Create a new class template specialization declaration node for 4713 // this explicit specialization or friend declaration. 4714 Specialization = VarTemplateSpecializationDecl::Create( 4715 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc, 4716 VarTemplate, DI->getType(), DI, SC, CanonicalConverted); 4717 Specialization->setTemplateArgsInfo(TemplateArgs); 4718 4719 if (!PrevDecl) 4720 VarTemplate->AddSpecialization(Specialization, InsertPos); 4721 } 4722 4723 // C++ [temp.expl.spec]p6: 4724 // If a template, a member template or the member of a class template is 4725 // explicitly specialized then that specialization shall be declared 4726 // before the first use of that specialization that would cause an implicit 4727 // instantiation to take place, in every translation unit in which such a 4728 // use occurs; no diagnostic is required. 4729 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { 4730 bool Okay = false; 4731 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { 4732 // Is there any previous explicit specialization declaration? 4733 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { 4734 Okay = true; 4735 break; 4736 } 4737 } 4738 4739 if (!Okay) { 4740 SourceRange Range(TemplateNameLoc, RAngleLoc); 4741 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) 4742 << Name << Range; 4743 4744 Diag(PrevDecl->getPointOfInstantiation(), 4745 diag::note_instantiation_required_here) 4746 << (PrevDecl->getTemplateSpecializationKind() != 4747 TSK_ImplicitInstantiation); 4748 return true; 4749 } 4750 } 4751 4752 Specialization->setTemplateKeywordLoc(TemplateKWLoc); 4753 Specialization->setLexicalDeclContext(CurContext); 4754 4755 // Add the specialization into its lexical context, so that it can 4756 // be seen when iterating through the list of declarations in that 4757 // context. However, specializations are not found by name lookup. 4758 CurContext->addDecl(Specialization); 4759 4760 // Note that this is an explicit specialization. 4761 Specialization->setSpecializationKind(TSK_ExplicitSpecialization); 4762 4763 if (PrevDecl) { 4764 // Check that this isn't a redefinition of this specialization, 4765 // merging with previous declarations. 4766 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName, 4767 forRedeclarationInCurContext()); 4768 PrevSpec.addDecl(PrevDecl); 4769 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec)); 4770 } else if (Specialization->isStaticDataMember() && 4771 Specialization->isOutOfLine()) { 4772 Specialization->setAccess(VarTemplate->getAccess()); 4773 } 4774 4775 return Specialization; 4776 } 4777 4778 namespace { 4779 /// A partial specialization whose template arguments have matched 4780 /// a given template-id. 4781 struct PartialSpecMatchResult { 4782 VarTemplatePartialSpecializationDecl *Partial; 4783 TemplateArgumentList *Args; 4784 }; 4785 } // end anonymous namespace 4786 4787 DeclResult 4788 Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, 4789 SourceLocation TemplateNameLoc, 4790 const TemplateArgumentListInfo &TemplateArgs) { 4791 assert(Template && "A variable template id without template?"); 4792 4793 // Check that the template argument list is well-formed for this template. 4794 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; 4795 if (CheckTemplateArgumentList( 4796 Template, TemplateNameLoc, 4797 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false, 4798 SugaredConverted, CanonicalConverted, 4799 /*UpdateArgsWithConversions=*/true)) 4800 return true; 4801 4802 // Produce a placeholder value if the specialization is dependent. 4803 if (Template->getDeclContext()->isDependentContext() || 4804 TemplateSpecializationType::anyDependentTemplateArguments( 4805 TemplateArgs, CanonicalConverted)) 4806 return DeclResult(); 4807 4808 // Find the variable template specialization declaration that 4809 // corresponds to these arguments. 4810 void *InsertPos = nullptr; 4811 if (VarTemplateSpecializationDecl *Spec = 4812 Template->findSpecialization(CanonicalConverted, InsertPos)) { 4813 checkSpecializationReachability(TemplateNameLoc, Spec); 4814 // If we already have a variable template specialization, return it. 4815 return Spec; 4816 } 4817 4818 // This is the first time we have referenced this variable template 4819 // specialization. Create the canonical declaration and add it to 4820 // the set of specializations, based on the closest partial specialization 4821 // that it represents. That is, 4822 VarDecl *InstantiationPattern = Template->getTemplatedDecl(); 4823 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack, 4824 CanonicalConverted); 4825 TemplateArgumentList *InstantiationArgs = &TemplateArgList; 4826 bool AmbiguousPartialSpec = false; 4827 typedef PartialSpecMatchResult MatchResult; 4828 SmallVector<MatchResult, 4> Matched; 4829 SourceLocation PointOfInstantiation = TemplateNameLoc; 4830 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation, 4831 /*ForTakingAddress=*/false); 4832 4833 // 1. Attempt to find the closest partial specialization that this 4834 // specializes, if any. 4835 // TODO: Unify with InstantiateClassTemplateSpecialization()? 4836 // Perhaps better after unification of DeduceTemplateArguments() and 4837 // getMoreSpecializedPartialSpecialization(). 4838 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs; 4839 Template->getPartialSpecializations(PartialSpecs); 4840 4841 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) { 4842 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I]; 4843 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 4844 4845 if (TemplateDeductionResult Result = 4846 DeduceTemplateArguments(Partial, TemplateArgList, Info)) { 4847 // Store the failed-deduction information for use in diagnostics, later. 4848 // TODO: Actually use the failed-deduction info? 4849 FailedCandidates.addCandidate().set( 4850 DeclAccessPair::make(Template, AS_public), Partial, 4851 MakeDeductionFailureInfo(Context, Result, Info)); 4852 (void)Result; 4853 } else { 4854 Matched.push_back(PartialSpecMatchResult()); 4855 Matched.back().Partial = Partial; 4856 Matched.back().Args = Info.takeCanonical(); 4857 } 4858 } 4859 4860 if (Matched.size() >= 1) { 4861 SmallVector<MatchResult, 4>::iterator Best = Matched.begin(); 4862 if (Matched.size() == 1) { 4863 // -- If exactly one matching specialization is found, the 4864 // instantiation is generated from that specialization. 4865 // We don't need to do anything for this. 4866 } else { 4867 // -- If more than one matching specialization is found, the 4868 // partial order rules (14.5.4.2) are used to determine 4869 // whether one of the specializations is more specialized 4870 // than the others. If none of the specializations is more 4871 // specialized than all of the other matching 4872 // specializations, then the use of the variable template is 4873 // ambiguous and the program is ill-formed. 4874 for (SmallVector<MatchResult, 4>::iterator P = Best + 1, 4875 PEnd = Matched.end(); 4876 P != PEnd; ++P) { 4877 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial, 4878 PointOfInstantiation) == 4879 P->Partial) 4880 Best = P; 4881 } 4882 4883 // Determine if the best partial specialization is more specialized than 4884 // the others. 4885 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(), 4886 PEnd = Matched.end(); 4887 P != PEnd; ++P) { 4888 if (P != Best && getMoreSpecializedPartialSpecialization( 4889 P->Partial, Best->Partial, 4890 PointOfInstantiation) != Best->Partial) { 4891 AmbiguousPartialSpec = true; 4892 break; 4893 } 4894 } 4895 } 4896 4897 // Instantiate using the best variable template partial specialization. 4898 InstantiationPattern = Best->Partial; 4899 InstantiationArgs = Best->Args; 4900 } else { 4901 // -- If no match is found, the instantiation is generated 4902 // from the primary template. 4903 // InstantiationPattern = Template->getTemplatedDecl(); 4904 } 4905 4906 // 2. Create the canonical declaration. 4907 // Note that we do not instantiate a definition until we see an odr-use 4908 // in DoMarkVarDeclReferenced(). 4909 // FIXME: LateAttrs et al.? 4910 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation( 4911 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs, 4912 CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/); 4913 if (!Decl) 4914 return true; 4915 4916 if (AmbiguousPartialSpec) { 4917 // Partial ordering did not produce a clear winner. Complain. 4918 Decl->setInvalidDecl(); 4919 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous) 4920 << Decl; 4921 4922 // Print the matching partial specializations. 4923 for (MatchResult P : Matched) 4924 Diag(P.Partial->getLocation(), diag::note_partial_spec_match) 4925 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(), 4926 *P.Args); 4927 return true; 4928 } 4929 4930 if (VarTemplatePartialSpecializationDecl *D = 4931 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern)) 4932 Decl->setInstantiationOf(D, InstantiationArgs); 4933 4934 checkSpecializationReachability(TemplateNameLoc, Decl); 4935 4936 assert(Decl && "No variable template specialization?"); 4937 return Decl; 4938 } 4939 4940 ExprResult 4941 Sema::CheckVarTemplateId(const CXXScopeSpec &SS, 4942 const DeclarationNameInfo &NameInfo, 4943 VarTemplateDecl *Template, SourceLocation TemplateLoc, 4944 const TemplateArgumentListInfo *TemplateArgs) { 4945 4946 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(), 4947 *TemplateArgs); 4948 if (Decl.isInvalid()) 4949 return ExprError(); 4950 4951 if (!Decl.get()) 4952 return ExprResult(); 4953 4954 VarDecl *Var = cast<VarDecl>(Decl.get()); 4955 if (!Var->getTemplateSpecializationKind()) 4956 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation, 4957 NameInfo.getLoc()); 4958 4959 // Build an ordinary singleton decl ref. 4960 return BuildDeclarationNameExpr(SS, NameInfo, Var, 4961 /*FoundD=*/nullptr, TemplateArgs); 4962 } 4963 4964 void Sema::diagnoseMissingTemplateArguments(TemplateName Name, 4965 SourceLocation Loc) { 4966 Diag(Loc, diag::err_template_missing_args) 4967 << (int)getTemplateNameKindForDiagnostics(Name) << Name; 4968 if (TemplateDecl *TD = Name.getAsTemplateDecl()) { 4969 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange()); 4970 } 4971 } 4972 4973 ExprResult 4974 Sema::CheckConceptTemplateId(const CXXScopeSpec &SS, 4975 SourceLocation TemplateKWLoc, 4976 const DeclarationNameInfo &ConceptNameInfo, 4977 NamedDecl *FoundDecl, 4978 ConceptDecl *NamedConcept, 4979 const TemplateArgumentListInfo *TemplateArgs) { 4980 assert(NamedConcept && "A concept template id without a template?"); 4981 4982 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; 4983 if (CheckTemplateArgumentList( 4984 NamedConcept, ConceptNameInfo.getLoc(), 4985 const_cast<TemplateArgumentListInfo &>(*TemplateArgs), 4986 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted, 4987 /*UpdateArgsWithConversions=*/false)) 4988 return ExprError(); 4989 4990 auto *CSD = ImplicitConceptSpecializationDecl::Create( 4991 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(), 4992 CanonicalConverted); 4993 ConstraintSatisfaction Satisfaction; 4994 bool AreArgsDependent = 4995 TemplateSpecializationType::anyDependentTemplateArguments( 4996 *TemplateArgs, CanonicalConverted); 4997 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted, 4998 /*Final=*/false); 4999 LocalInstantiationScope Scope(*this); 5000 5001 EnterExpressionEvaluationContext EECtx{ 5002 *this, ExpressionEvaluationContext::ConstantEvaluated, CSD}; 5003 5004 if (!AreArgsDependent && 5005 CheckConstraintSatisfaction( 5006 NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL, 5007 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(), 5008 TemplateArgs->getRAngleLoc()), 5009 Satisfaction)) 5010 return ExprError(); 5011 auto *CL = ConceptReference::Create( 5012 Context, 5013 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{}, 5014 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept, 5015 ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs)); 5016 return ConceptSpecializationExpr::Create( 5017 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction); 5018 } 5019 5020 ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS, 5021 SourceLocation TemplateKWLoc, 5022 LookupResult &R, 5023 bool RequiresADL, 5024 const TemplateArgumentListInfo *TemplateArgs) { 5025 // FIXME: Can we do any checking at this point? I guess we could check the 5026 // template arguments that we have against the template name, if the template 5027 // name refers to a single template. That's not a terribly common case, 5028 // though. 5029 // foo<int> could identify a single function unambiguously 5030 // This approach does NOT work, since f<int>(1); 5031 // gets resolved prior to resorting to overload resolution 5032 // i.e., template<class T> void f(double); 5033 // vs template<class T, class U> void f(U); 5034 5035 // These should be filtered out by our callers. 5036 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid"); 5037 5038 // Non-function templates require a template argument list. 5039 if (auto *TD = R.getAsSingle<TemplateDecl>()) { 5040 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) { 5041 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc()); 5042 return ExprError(); 5043 } 5044 } 5045 bool KnownDependent = false; 5046 // In C++1y, check variable template ids. 5047 if (R.getAsSingle<VarTemplateDecl>()) { 5048 ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(), 5049 R.getAsSingle<VarTemplateDecl>(), 5050 TemplateKWLoc, TemplateArgs); 5051 if (Res.isInvalid() || Res.isUsable()) 5052 return Res; 5053 // Result is dependent. Carry on to build an UnresolvedLookupEpxr. 5054 KnownDependent = true; 5055 } 5056 5057 if (R.getAsSingle<ConceptDecl>()) { 5058 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(), 5059 R.getFoundDecl(), 5060 R.getAsSingle<ConceptDecl>(), TemplateArgs); 5061 } 5062 5063 // We don't want lookup warnings at this point. 5064 R.suppressDiagnostics(); 5065 5066 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create( 5067 Context, R.getNamingClass(), SS.getWithLocInContext(Context), 5068 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs, 5069 R.begin(), R.end(), KnownDependent); 5070 5071 return ULE; 5072 } 5073 5074 // We actually only call this from template instantiation. 5075 ExprResult 5076 Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 5077 SourceLocation TemplateKWLoc, 5078 const DeclarationNameInfo &NameInfo, 5079 const TemplateArgumentListInfo *TemplateArgs) { 5080 5081 assert(TemplateArgs || TemplateKWLoc.isValid()); 5082 DeclContext *DC; 5083 if (!(DC = computeDeclContext(SS, false)) || 5084 DC->isDependentContext() || 5085 RequireCompleteDeclContext(SS, DC)) 5086 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs); 5087 5088 bool MemberOfUnknownSpecialization; 5089 LookupResult R(*this, NameInfo, LookupOrdinaryName); 5090 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(), 5091 /*Entering*/false, MemberOfUnknownSpecialization, 5092 TemplateKWLoc)) 5093 return ExprError(); 5094 5095 if (R.isAmbiguous()) 5096 return ExprError(); 5097 5098 if (R.empty()) { 5099 Diag(NameInfo.getLoc(), diag::err_no_member) 5100 << NameInfo.getName() << DC << SS.getRange(); 5101 return ExprError(); 5102 } 5103 5104 auto DiagnoseTypeTemplateDecl = [&](TemplateDecl *Temp, 5105 bool isTypeAliasTemplateDecl) { 5106 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template) 5107 << SS.getScopeRep() << NameInfo.getName().getAsString() << SS.getRange() 5108 << isTypeAliasTemplateDecl; 5109 Diag(Temp->getLocation(), diag::note_referenced_type_template) << 0; 5110 return ExprError(); 5111 }; 5112 5113 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) 5114 return DiagnoseTypeTemplateDecl(Temp, false); 5115 5116 if (TypeAliasTemplateDecl *Temp = R.getAsSingle<TypeAliasTemplateDecl>()) 5117 return DiagnoseTypeTemplateDecl(Temp, true); 5118 5119 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs); 5120 } 5121 5122 /// Form a template name from a name that is syntactically required to name a 5123 /// template, either due to use of the 'template' keyword or because a name in 5124 /// this syntactic context is assumed to name a template (C++ [temp.names]p2-4). 5125 /// 5126 /// This action forms a template name given the name of the template and its 5127 /// optional scope specifier. This is used when the 'template' keyword is used 5128 /// or when the parsing context unambiguously treats a following '<' as 5129 /// introducing a template argument list. Note that this may produce a 5130 /// non-dependent template name if we can perform the lookup now and identify 5131 /// the named template. 5132 /// 5133 /// For example, given "x.MetaFun::template apply", the scope specifier 5134 /// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location 5135 /// of the "template" keyword, and "apply" is the \p Name. 5136 TemplateNameKind Sema::ActOnTemplateName(Scope *S, 5137 CXXScopeSpec &SS, 5138 SourceLocation TemplateKWLoc, 5139 const UnqualifiedId &Name, 5140 ParsedType ObjectType, 5141 bool EnteringContext, 5142 TemplateTy &Result, 5143 bool AllowInjectedClassName) { 5144 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent()) 5145 Diag(TemplateKWLoc, 5146 getLangOpts().CPlusPlus11 ? 5147 diag::warn_cxx98_compat_template_outside_of_template : 5148 diag::ext_template_outside_of_template) 5149 << FixItHint::CreateRemoval(TemplateKWLoc); 5150 5151 if (SS.isInvalid()) 5152 return TNK_Non_template; 5153 5154 // Figure out where isTemplateName is going to look. 5155 DeclContext *LookupCtx = nullptr; 5156 if (SS.isNotEmpty()) 5157 LookupCtx = computeDeclContext(SS, EnteringContext); 5158 else if (ObjectType) 5159 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType)); 5160 5161 // C++0x [temp.names]p5: 5162 // If a name prefixed by the keyword template is not the name of 5163 // a template, the program is ill-formed. [Note: the keyword 5164 // template may not be applied to non-template members of class 5165 // templates. -end note ] [ Note: as is the case with the 5166 // typename prefix, the template prefix is allowed in cases 5167 // where it is not strictly necessary; i.e., when the 5168 // nested-name-specifier or the expression on the left of the -> 5169 // or . is not dependent on a template-parameter, or the use 5170 // does not appear in the scope of a template. -end note] 5171 // 5172 // Note: C++03 was more strict here, because it banned the use of 5173 // the "template" keyword prior to a template-name that was not a 5174 // dependent name. C++ DR468 relaxed this requirement (the 5175 // "template" keyword is now permitted). We follow the C++0x 5176 // rules, even in C++03 mode with a warning, retroactively applying the DR. 5177 bool MemberOfUnknownSpecialization; 5178 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name, 5179 ObjectType, EnteringContext, Result, 5180 MemberOfUnknownSpecialization); 5181 if (TNK != TNK_Non_template) { 5182 // We resolved this to a (non-dependent) template name. Return it. 5183 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 5184 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD && 5185 Name.getKind() == UnqualifiedIdKind::IK_Identifier && 5186 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) { 5187 // C++14 [class.qual]p2: 5188 // In a lookup in which function names are not ignored and the 5189 // nested-name-specifier nominates a class C, if the name specified 5190 // [...] is the injected-class-name of C, [...] the name is instead 5191 // considered to name the constructor 5192 // 5193 // We don't get here if naming the constructor would be valid, so we 5194 // just reject immediately and recover by treating the 5195 // injected-class-name as naming the template. 5196 Diag(Name.getBeginLoc(), 5197 diag::ext_out_of_line_qualified_id_type_names_constructor) 5198 << Name.Identifier 5199 << 0 /*injected-class-name used as template name*/ 5200 << TemplateKWLoc.isValid(); 5201 } 5202 return TNK; 5203 } 5204 5205 if (!MemberOfUnknownSpecialization) { 5206 // Didn't find a template name, and the lookup wasn't dependent. 5207 // Do the lookup again to determine if this is a "nothing found" case or 5208 // a "not a template" case. FIXME: Refactor isTemplateName so we don't 5209 // need to do this. 5210 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name); 5211 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(), 5212 LookupOrdinaryName); 5213 bool MOUS; 5214 // Tell LookupTemplateName that we require a template so that it diagnoses 5215 // cases where it finds a non-template. 5216 RequiredTemplateKind RTK = TemplateKWLoc.isValid() 5217 ? RequiredTemplateKind(TemplateKWLoc) 5218 : TemplateNameIsRequired; 5219 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, MOUS, 5220 RTK, nullptr, /*AllowTypoCorrection=*/false) && 5221 !R.isAmbiguous()) { 5222 if (LookupCtx) 5223 Diag(Name.getBeginLoc(), diag::err_no_member) 5224 << DNI.getName() << LookupCtx << SS.getRange(); 5225 else 5226 Diag(Name.getBeginLoc(), diag::err_undeclared_use) 5227 << DNI.getName() << SS.getRange(); 5228 } 5229 return TNK_Non_template; 5230 } 5231 5232 NestedNameSpecifier *Qualifier = SS.getScopeRep(); 5233 5234 switch (Name.getKind()) { 5235 case UnqualifiedIdKind::IK_Identifier: 5236 Result = TemplateTy::make( 5237 Context.getDependentTemplateName(Qualifier, Name.Identifier)); 5238 return TNK_Dependent_template_name; 5239 5240 case UnqualifiedIdKind::IK_OperatorFunctionId: 5241 Result = TemplateTy::make(Context.getDependentTemplateName( 5242 Qualifier, Name.OperatorFunctionId.Operator)); 5243 return TNK_Function_template; 5244 5245 case UnqualifiedIdKind::IK_LiteralOperatorId: 5246 // This is a kind of template name, but can never occur in a dependent 5247 // scope (literal operators can only be declared at namespace scope). 5248 break; 5249 5250 default: 5251 break; 5252 } 5253 5254 // This name cannot possibly name a dependent template. Diagnose this now 5255 // rather than building a dependent template name that can never be valid. 5256 Diag(Name.getBeginLoc(), 5257 diag::err_template_kw_refers_to_dependent_non_template) 5258 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange() 5259 << TemplateKWLoc.isValid() << TemplateKWLoc; 5260 return TNK_Non_template; 5261 } 5262 5263 bool Sema::CheckTemplateTypeArgument( 5264 TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL, 5265 SmallVectorImpl<TemplateArgument> &SugaredConverted, 5266 SmallVectorImpl<TemplateArgument> &CanonicalConverted) { 5267 const TemplateArgument &Arg = AL.getArgument(); 5268 QualType ArgType; 5269 TypeSourceInfo *TSI = nullptr; 5270 5271 // Check template type parameter. 5272 switch(Arg.getKind()) { 5273 case TemplateArgument::Type: 5274 // C++ [temp.arg.type]p1: 5275 // A template-argument for a template-parameter which is a 5276 // type shall be a type-id. 5277 ArgType = Arg.getAsType(); 5278 TSI = AL.getTypeSourceInfo(); 5279 break; 5280 case TemplateArgument::Template: 5281 case TemplateArgument::TemplateExpansion: { 5282 // We have a template type parameter but the template argument 5283 // is a template without any arguments. 5284 SourceRange SR = AL.getSourceRange(); 5285 TemplateName Name = Arg.getAsTemplateOrTemplatePattern(); 5286 diagnoseMissingTemplateArguments(Name, SR.getEnd()); 5287 return true; 5288 } 5289 case TemplateArgument::Expression: { 5290 // We have a template type parameter but the template argument is an 5291 // expression; see if maybe it is missing the "typename" keyword. 5292 CXXScopeSpec SS; 5293 DeclarationNameInfo NameInfo; 5294 5295 if (DependentScopeDeclRefExpr *ArgExpr = 5296 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) { 5297 SS.Adopt(ArgExpr->getQualifierLoc()); 5298 NameInfo = ArgExpr->getNameInfo(); 5299 } else if (CXXDependentScopeMemberExpr *ArgExpr = 5300 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) { 5301 if (ArgExpr->isImplicitAccess()) { 5302 SS.Adopt(ArgExpr->getQualifierLoc()); 5303 NameInfo = ArgExpr->getMemberNameInfo(); 5304 } 5305 } 5306 5307 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) { 5308 LookupResult Result(*this, NameInfo, LookupOrdinaryName); 5309 LookupParsedName(Result, CurScope, &SS); 5310 5311 if (Result.getAsSingle<TypeDecl>() || 5312 Result.getResultKind() == 5313 LookupResult::NotFoundInCurrentInstantiation) { 5314 assert(SS.getScopeRep() && "dependent scope expr must has a scope!"); 5315 // Suggest that the user add 'typename' before the NNS. 5316 SourceLocation Loc = AL.getSourceRange().getBegin(); 5317 Diag(Loc, getLangOpts().MSVCCompat 5318 ? diag::ext_ms_template_type_arg_missing_typename 5319 : diag::err_template_arg_must_be_type_suggest) 5320 << FixItHint::CreateInsertion(Loc, "typename "); 5321 NoteTemplateParameterLocation(*Param); 5322 5323 // Recover by synthesizing a type using the location information that we 5324 // already have. 5325 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::Typename, 5326 SS.getScopeRep(), II); 5327 TypeLocBuilder TLB; 5328 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType); 5329 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/)); 5330 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 5331 TL.setNameLoc(NameInfo.getLoc()); 5332 TSI = TLB.getTypeSourceInfo(Context, ArgType); 5333 5334 // Overwrite our input TemplateArgumentLoc so that we can recover 5335 // properly. 5336 AL = TemplateArgumentLoc(TemplateArgument(ArgType), 5337 TemplateArgumentLocInfo(TSI)); 5338 5339 break; 5340 } 5341 } 5342 // fallthrough 5343 [[fallthrough]]; 5344 } 5345 default: { 5346 // We have a template type parameter but the template argument 5347 // is not a type. 5348 SourceRange SR = AL.getSourceRange(); 5349 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR; 5350 NoteTemplateParameterLocation(*Param); 5351 5352 return true; 5353 } 5354 } 5355 5356 if (CheckTemplateArgument(TSI)) 5357 return true; 5358 5359 // Objective-C ARC: 5360 // If an explicitly-specified template argument type is a lifetime type 5361 // with no lifetime qualifier, the __strong lifetime qualifier is inferred. 5362 if (getLangOpts().ObjCAutoRefCount && 5363 ArgType->isObjCLifetimeType() && 5364 !ArgType.getObjCLifetime()) { 5365 Qualifiers Qs; 5366 Qs.setObjCLifetime(Qualifiers::OCL_Strong); 5367 ArgType = Context.getQualifiedType(ArgType, Qs); 5368 } 5369 5370 SugaredConverted.push_back(TemplateArgument(ArgType)); 5371 CanonicalConverted.push_back( 5372 TemplateArgument(Context.getCanonicalType(ArgType))); 5373 return false; 5374 } 5375 5376 /// Substitute template arguments into the default template argument for 5377 /// the given template type parameter. 5378 /// 5379 /// \param SemaRef the semantic analysis object for which we are performing 5380 /// the substitution. 5381 /// 5382 /// \param Template the template that we are synthesizing template arguments 5383 /// for. 5384 /// 5385 /// \param TemplateLoc the location of the template name that started the 5386 /// template-id we are checking. 5387 /// 5388 /// \param RAngleLoc the location of the right angle bracket ('>') that 5389 /// terminates the template-id. 5390 /// 5391 /// \param Param the template template parameter whose default we are 5392 /// substituting into. 5393 /// 5394 /// \param Converted the list of template arguments provided for template 5395 /// parameters that precede \p Param in the template parameter list. 5396 /// \returns the substituted template argument, or NULL if an error occurred. 5397 static TypeSourceInfo *SubstDefaultTemplateArgument( 5398 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, 5399 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param, 5400 ArrayRef<TemplateArgument> SugaredConverted, 5401 ArrayRef<TemplateArgument> CanonicalConverted) { 5402 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo(); 5403 5404 // If the argument type is dependent, instantiate it now based 5405 // on the previously-computed template arguments. 5406 if (ArgType->getType()->isInstantiationDependentType()) { 5407 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template, 5408 SugaredConverted, 5409 SourceRange(TemplateLoc, RAngleLoc)); 5410 if (Inst.isInvalid()) 5411 return nullptr; 5412 5413 // Only substitute for the innermost template argument list. 5414 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted, 5415 /*Final=*/true); 5416 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) 5417 TemplateArgLists.addOuterTemplateArguments(std::nullopt); 5418 5419 bool ForLambdaCallOperator = false; 5420 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext())) 5421 ForLambdaCallOperator = Rec->isLambda(); 5422 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(), 5423 !ForLambdaCallOperator); 5424 ArgType = 5425 SemaRef.SubstType(ArgType, TemplateArgLists, 5426 Param->getDefaultArgumentLoc(), Param->getDeclName()); 5427 } 5428 5429 return ArgType; 5430 } 5431 5432 /// Substitute template arguments into the default template argument for 5433 /// the given non-type template parameter. 5434 /// 5435 /// \param SemaRef the semantic analysis object for which we are performing 5436 /// the substitution. 5437 /// 5438 /// \param Template the template that we are synthesizing template arguments 5439 /// for. 5440 /// 5441 /// \param TemplateLoc the location of the template name that started the 5442 /// template-id we are checking. 5443 /// 5444 /// \param RAngleLoc the location of the right angle bracket ('>') that 5445 /// terminates the template-id. 5446 /// 5447 /// \param Param the non-type template parameter whose default we are 5448 /// substituting into. 5449 /// 5450 /// \param Converted the list of template arguments provided for template 5451 /// parameters that precede \p Param in the template parameter list. 5452 /// 5453 /// \returns the substituted template argument, or NULL if an error occurred. 5454 static ExprResult SubstDefaultTemplateArgument( 5455 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, 5456 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param, 5457 ArrayRef<TemplateArgument> SugaredConverted, 5458 ArrayRef<TemplateArgument> CanonicalConverted) { 5459 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template, 5460 SugaredConverted, 5461 SourceRange(TemplateLoc, RAngleLoc)); 5462 if (Inst.isInvalid()) 5463 return ExprError(); 5464 5465 // Only substitute for the innermost template argument list. 5466 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted, 5467 /*Final=*/true); 5468 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) 5469 TemplateArgLists.addOuterTemplateArguments(std::nullopt); 5470 5471 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext()); 5472 EnterExpressionEvaluationContext ConstantEvaluated( 5473 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); 5474 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists); 5475 } 5476 5477 /// Substitute template arguments into the default template argument for 5478 /// the given template template parameter. 5479 /// 5480 /// \param SemaRef the semantic analysis object for which we are performing 5481 /// the substitution. 5482 /// 5483 /// \param Template the template that we are synthesizing template arguments 5484 /// for. 5485 /// 5486 /// \param TemplateLoc the location of the template name that started the 5487 /// template-id we are checking. 5488 /// 5489 /// \param RAngleLoc the location of the right angle bracket ('>') that 5490 /// terminates the template-id. 5491 /// 5492 /// \param Param the template template parameter whose default we are 5493 /// substituting into. 5494 /// 5495 /// \param Converted the list of template arguments provided for template 5496 /// parameters that precede \p Param in the template parameter list. 5497 /// 5498 /// \param QualifierLoc Will be set to the nested-name-specifier (with 5499 /// source-location information) that precedes the template name. 5500 /// 5501 /// \returns the substituted template argument, or NULL if an error occurred. 5502 static TemplateName SubstDefaultTemplateArgument( 5503 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc, 5504 SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param, 5505 ArrayRef<TemplateArgument> SugaredConverted, 5506 ArrayRef<TemplateArgument> CanonicalConverted, 5507 NestedNameSpecifierLoc &QualifierLoc) { 5508 Sema::InstantiatingTemplate Inst( 5509 SemaRef, TemplateLoc, TemplateParameter(Param), Template, 5510 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc)); 5511 if (Inst.isInvalid()) 5512 return TemplateName(); 5513 5514 // Only substitute for the innermost template argument list. 5515 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted, 5516 /*Final=*/true); 5517 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i) 5518 TemplateArgLists.addOuterTemplateArguments(std::nullopt); 5519 5520 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext()); 5521 // Substitute into the nested-name-specifier first, 5522 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc(); 5523 if (QualifierLoc) { 5524 QualifierLoc = 5525 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists); 5526 if (!QualifierLoc) 5527 return TemplateName(); 5528 } 5529 5530 return SemaRef.SubstTemplateName( 5531 QualifierLoc, 5532 Param->getDefaultArgument().getArgument().getAsTemplate(), 5533 Param->getDefaultArgument().getTemplateNameLoc(), 5534 TemplateArgLists); 5535 } 5536 5537 /// If the given template parameter has a default template 5538 /// argument, substitute into that default template argument and 5539 /// return the corresponding template argument. 5540 TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable( 5541 TemplateDecl *Template, SourceLocation TemplateLoc, 5542 SourceLocation RAngleLoc, Decl *Param, 5543 ArrayRef<TemplateArgument> SugaredConverted, 5544 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) { 5545 HasDefaultArg = false; 5546 5547 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) { 5548 if (!hasReachableDefaultArgument(TypeParm)) 5549 return TemplateArgumentLoc(); 5550 5551 HasDefaultArg = true; 5552 TypeSourceInfo *DI = SubstDefaultTemplateArgument( 5553 *this, Template, TemplateLoc, RAngleLoc, TypeParm, SugaredConverted, 5554 CanonicalConverted); 5555 if (DI) 5556 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI); 5557 5558 return TemplateArgumentLoc(); 5559 } 5560 5561 if (NonTypeTemplateParmDecl *NonTypeParm 5562 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 5563 if (!hasReachableDefaultArgument(NonTypeParm)) 5564 return TemplateArgumentLoc(); 5565 5566 HasDefaultArg = true; 5567 ExprResult Arg = SubstDefaultTemplateArgument( 5568 *this, Template, TemplateLoc, RAngleLoc, NonTypeParm, SugaredConverted, 5569 CanonicalConverted); 5570 if (Arg.isInvalid()) 5571 return TemplateArgumentLoc(); 5572 5573 Expr *ArgE = Arg.getAs<Expr>(); 5574 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE); 5575 } 5576 5577 TemplateTemplateParmDecl *TempTempParm 5578 = cast<TemplateTemplateParmDecl>(Param); 5579 if (!hasReachableDefaultArgument(TempTempParm)) 5580 return TemplateArgumentLoc(); 5581 5582 HasDefaultArg = true; 5583 NestedNameSpecifierLoc QualifierLoc; 5584 TemplateName TName = SubstDefaultTemplateArgument( 5585 *this, Template, TemplateLoc, RAngleLoc, TempTempParm, SugaredConverted, 5586 CanonicalConverted, QualifierLoc); 5587 if (TName.isNull()) 5588 return TemplateArgumentLoc(); 5589 5590 return TemplateArgumentLoc( 5591 Context, TemplateArgument(TName), 5592 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(), 5593 TempTempParm->getDefaultArgument().getTemplateNameLoc()); 5594 } 5595 5596 /// Convert a template-argument that we parsed as a type into a template, if 5597 /// possible. C++ permits injected-class-names to perform dual service as 5598 /// template template arguments and as template type arguments. 5599 static TemplateArgumentLoc 5600 convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) { 5601 // Extract and step over any surrounding nested-name-specifier. 5602 NestedNameSpecifierLoc QualLoc; 5603 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) { 5604 if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None) 5605 return TemplateArgumentLoc(); 5606 5607 QualLoc = ETLoc.getQualifierLoc(); 5608 TLoc = ETLoc.getNamedTypeLoc(); 5609 } 5610 // If this type was written as an injected-class-name, it can be used as a 5611 // template template argument. 5612 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>()) 5613 return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(), 5614 QualLoc, InjLoc.getNameLoc()); 5615 5616 // If this type was written as an injected-class-name, it may have been 5617 // converted to a RecordType during instantiation. If the RecordType is 5618 // *not* wrapped in a TemplateSpecializationType and denotes a class 5619 // template specialization, it must have come from an injected-class-name. 5620 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>()) 5621 if (auto *CTSD = 5622 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl())) 5623 return TemplateArgumentLoc(Context, 5624 TemplateName(CTSD->getSpecializedTemplate()), 5625 QualLoc, RecLoc.getNameLoc()); 5626 5627 return TemplateArgumentLoc(); 5628 } 5629 5630 /// Check that the given template argument corresponds to the given 5631 /// template parameter. 5632 /// 5633 /// \param Param The template parameter against which the argument will be 5634 /// checked. 5635 /// 5636 /// \param Arg The template argument, which may be updated due to conversions. 5637 /// 5638 /// \param Template The template in which the template argument resides. 5639 /// 5640 /// \param TemplateLoc The location of the template name for the template 5641 /// whose argument list we're matching. 5642 /// 5643 /// \param RAngleLoc The location of the right angle bracket ('>') that closes 5644 /// the template argument list. 5645 /// 5646 /// \param ArgumentPackIndex The index into the argument pack where this 5647 /// argument will be placed. Only valid if the parameter is a parameter pack. 5648 /// 5649 /// \param Converted The checked, converted argument will be added to the 5650 /// end of this small vector. 5651 /// 5652 /// \param CTAK Describes how we arrived at this particular template argument: 5653 /// explicitly written, deduced, etc. 5654 /// 5655 /// \returns true on error, false otherwise. 5656 bool Sema::CheckTemplateArgument( 5657 NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, 5658 SourceLocation TemplateLoc, SourceLocation RAngleLoc, 5659 unsigned ArgumentPackIndex, 5660 SmallVectorImpl<TemplateArgument> &SugaredConverted, 5661 SmallVectorImpl<TemplateArgument> &CanonicalConverted, 5662 CheckTemplateArgumentKind CTAK) { 5663 // Check template type parameters. 5664 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 5665 return CheckTemplateTypeArgument(TTP, Arg, SugaredConverted, 5666 CanonicalConverted); 5667 5668 // Check non-type template parameters. 5669 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) { 5670 // Do substitution on the type of the non-type template parameter 5671 // with the template arguments we've seen thus far. But if the 5672 // template has a dependent context then we cannot substitute yet. 5673 QualType NTTPType = NTTP->getType(); 5674 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack()) 5675 NTTPType = NTTP->getExpansionType(ArgumentPackIndex); 5676 5677 if (NTTPType->isInstantiationDependentType() && 5678 !isa<TemplateTemplateParmDecl>(Template) && 5679 !Template->getDeclContext()->isDependentContext()) { 5680 // Do substitution on the type of the non-type template parameter. 5681 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP, 5682 SugaredConverted, 5683 SourceRange(TemplateLoc, RAngleLoc)); 5684 if (Inst.isInvalid()) 5685 return true; 5686 5687 MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted, 5688 /*Final=*/true); 5689 // If the parameter is a pack expansion, expand this slice of the pack. 5690 if (auto *PET = NTTPType->getAs<PackExpansionType>()) { 5691 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, 5692 ArgumentPackIndex); 5693 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(), 5694 NTTP->getDeclName()); 5695 } else { 5696 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(), 5697 NTTP->getDeclName()); 5698 } 5699 5700 // If that worked, check the non-type template parameter type 5701 // for validity. 5702 if (!NTTPType.isNull()) 5703 NTTPType = CheckNonTypeTemplateParameterType(NTTPType, 5704 NTTP->getLocation()); 5705 if (NTTPType.isNull()) 5706 return true; 5707 } 5708 5709 switch (Arg.getArgument().getKind()) { 5710 case TemplateArgument::Null: 5711 llvm_unreachable("Should never see a NULL template argument here"); 5712 5713 case TemplateArgument::Expression: { 5714 Expr *E = Arg.getArgument().getAsExpr(); 5715 TemplateArgument SugaredResult, CanonicalResult; 5716 unsigned CurSFINAEErrors = NumSFINAEErrors; 5717 ExprResult Res = CheckTemplateArgument(NTTP, NTTPType, E, SugaredResult, 5718 CanonicalResult, CTAK); 5719 if (Res.isInvalid()) 5720 return true; 5721 // If the current template argument causes an error, give up now. 5722 if (CurSFINAEErrors < NumSFINAEErrors) 5723 return true; 5724 5725 // If the resulting expression is new, then use it in place of the 5726 // old expression in the template argument. 5727 if (Res.get() != E) { 5728 TemplateArgument TA(Res.get()); 5729 Arg = TemplateArgumentLoc(TA, Res.get()); 5730 } 5731 5732 SugaredConverted.push_back(SugaredResult); 5733 CanonicalConverted.push_back(CanonicalResult); 5734 break; 5735 } 5736 5737 case TemplateArgument::Declaration: 5738 case TemplateArgument::Integral: 5739 case TemplateArgument::NullPtr: 5740 // We've already checked this template argument, so just copy 5741 // it to the list of converted arguments. 5742 SugaredConverted.push_back(Arg.getArgument()); 5743 CanonicalConverted.push_back( 5744 Context.getCanonicalTemplateArgument(Arg.getArgument())); 5745 break; 5746 5747 case TemplateArgument::Template: 5748 case TemplateArgument::TemplateExpansion: 5749 // We were given a template template argument. It may not be ill-formed; 5750 // see below. 5751 if (DependentTemplateName *DTN 5752 = Arg.getArgument().getAsTemplateOrTemplatePattern() 5753 .getAsDependentTemplateName()) { 5754 // We have a template argument such as \c T::template X, which we 5755 // parsed as a template template argument. However, since we now 5756 // know that we need a non-type template argument, convert this 5757 // template name into an expression. 5758 5759 DeclarationNameInfo NameInfo(DTN->getIdentifier(), 5760 Arg.getTemplateNameLoc()); 5761 5762 CXXScopeSpec SS; 5763 SS.Adopt(Arg.getTemplateQualifierLoc()); 5764 // FIXME: the template-template arg was a DependentTemplateName, 5765 // so it was provided with a template keyword. However, its source 5766 // location is not stored in the template argument structure. 5767 SourceLocation TemplateKWLoc; 5768 ExprResult E = DependentScopeDeclRefExpr::Create( 5769 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo, 5770 nullptr); 5771 5772 // If we parsed the template argument as a pack expansion, create a 5773 // pack expansion expression. 5774 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){ 5775 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc()); 5776 if (E.isInvalid()) 5777 return true; 5778 } 5779 5780 TemplateArgument SugaredResult, CanonicalResult; 5781 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), SugaredResult, 5782 CanonicalResult, CTAK_Specified); 5783 if (E.isInvalid()) 5784 return true; 5785 5786 SugaredConverted.push_back(SugaredResult); 5787 CanonicalConverted.push_back(CanonicalResult); 5788 break; 5789 } 5790 5791 // We have a template argument that actually does refer to a class 5792 // template, alias template, or template template parameter, and 5793 // therefore cannot be a non-type template argument. 5794 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr) 5795 << Arg.getSourceRange(); 5796 NoteTemplateParameterLocation(*Param); 5797 5798 return true; 5799 5800 case TemplateArgument::Type: { 5801 // We have a non-type template parameter but the template 5802 // argument is a type. 5803 5804 // C++ [temp.arg]p2: 5805 // In a template-argument, an ambiguity between a type-id and 5806 // an expression is resolved to a type-id, regardless of the 5807 // form of the corresponding template-parameter. 5808 // 5809 // We warn specifically about this case, since it can be rather 5810 // confusing for users. 5811 QualType T = Arg.getArgument().getAsType(); 5812 SourceRange SR = Arg.getSourceRange(); 5813 if (T->isFunctionType()) 5814 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T; 5815 else 5816 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR; 5817 NoteTemplateParameterLocation(*Param); 5818 return true; 5819 } 5820 5821 case TemplateArgument::Pack: 5822 llvm_unreachable("Caller must expand template argument packs"); 5823 } 5824 5825 return false; 5826 } 5827 5828 5829 // Check template template parameters. 5830 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param); 5831 5832 TemplateParameterList *Params = TempParm->getTemplateParameters(); 5833 if (TempParm->isExpandedParameterPack()) 5834 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex); 5835 5836 // Substitute into the template parameter list of the template 5837 // template parameter, since previously-supplied template arguments 5838 // may appear within the template template parameter. 5839 // 5840 // FIXME: Skip this if the parameters aren't instantiation-dependent. 5841 { 5842 // Set up a template instantiation context. 5843 LocalInstantiationScope Scope(*this); 5844 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm, 5845 SugaredConverted, 5846 SourceRange(TemplateLoc, RAngleLoc)); 5847 if (Inst.isInvalid()) 5848 return true; 5849 5850 Params = 5851 SubstTemplateParams(Params, CurContext, 5852 MultiLevelTemplateArgumentList( 5853 Template, SugaredConverted, /*Final=*/true), 5854 /*EvaluateConstraints=*/false); 5855 if (!Params) 5856 return true; 5857 } 5858 5859 // C++1z [temp.local]p1: (DR1004) 5860 // When [the injected-class-name] is used [...] as a template-argument for 5861 // a template template-parameter [...] it refers to the class template 5862 // itself. 5863 if (Arg.getArgument().getKind() == TemplateArgument::Type) { 5864 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate( 5865 Context, Arg.getTypeSourceInfo()->getTypeLoc()); 5866 if (!ConvertedArg.getArgument().isNull()) 5867 Arg = ConvertedArg; 5868 } 5869 5870 switch (Arg.getArgument().getKind()) { 5871 case TemplateArgument::Null: 5872 llvm_unreachable("Should never see a NULL template argument here"); 5873 5874 case TemplateArgument::Template: 5875 case TemplateArgument::TemplateExpansion: 5876 if (CheckTemplateTemplateArgument(TempParm, Params, Arg)) 5877 return true; 5878 5879 SugaredConverted.push_back(Arg.getArgument()); 5880 CanonicalConverted.push_back( 5881 Context.getCanonicalTemplateArgument(Arg.getArgument())); 5882 break; 5883 5884 case TemplateArgument::Expression: 5885 case TemplateArgument::Type: 5886 // We have a template template parameter but the template 5887 // argument does not refer to a template. 5888 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template) 5889 << getLangOpts().CPlusPlus11; 5890 return true; 5891 5892 case TemplateArgument::Declaration: 5893 llvm_unreachable("Declaration argument with template template parameter"); 5894 case TemplateArgument::Integral: 5895 llvm_unreachable("Integral argument with template template parameter"); 5896 case TemplateArgument::NullPtr: 5897 llvm_unreachable("Null pointer argument with template template parameter"); 5898 5899 case TemplateArgument::Pack: 5900 llvm_unreachable("Caller must expand template argument packs"); 5901 } 5902 5903 return false; 5904 } 5905 5906 /// Diagnose a missing template argument. 5907 template<typename TemplateParmDecl> 5908 static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc, 5909 TemplateDecl *TD, 5910 const TemplateParmDecl *D, 5911 TemplateArgumentListInfo &Args) { 5912 // Dig out the most recent declaration of the template parameter; there may be 5913 // declarations of the template that are more recent than TD. 5914 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl()) 5915 ->getTemplateParameters() 5916 ->getParam(D->getIndex())); 5917 5918 // If there's a default argument that's not reachable, diagnose that we're 5919 // missing a module import. 5920 llvm::SmallVector<Module*, 8> Modules; 5921 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) { 5922 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD), 5923 D->getDefaultArgumentLoc(), Modules, 5924 Sema::MissingImportKind::DefaultArgument, 5925 /*Recover*/true); 5926 return true; 5927 } 5928 5929 // FIXME: If there's a more recent default argument that *is* visible, 5930 // diagnose that it was declared too late. 5931 5932 TemplateParameterList *Params = TD->getTemplateParameters(); 5933 5934 S.Diag(Loc, diag::err_template_arg_list_different_arity) 5935 << /*not enough args*/0 5936 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD)) 5937 << TD; 5938 S.NoteTemplateLocation(*TD, Params->getSourceRange()); 5939 return true; 5940 } 5941 5942 /// Check that the given template argument list is well-formed 5943 /// for specializing the given template. 5944 bool Sema::CheckTemplateArgumentList( 5945 TemplateDecl *Template, SourceLocation TemplateLoc, 5946 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, 5947 SmallVectorImpl<TemplateArgument> &SugaredConverted, 5948 SmallVectorImpl<TemplateArgument> &CanonicalConverted, 5949 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) { 5950 5951 if (ConstraintsNotSatisfied) 5952 *ConstraintsNotSatisfied = false; 5953 5954 // Make a copy of the template arguments for processing. Only make the 5955 // changes at the end when successful in matching the arguments to the 5956 // template. 5957 TemplateArgumentListInfo NewArgs = TemplateArgs; 5958 5959 // Make sure we get the template parameter list from the most 5960 // recent declaration, since that is the only one that is guaranteed to 5961 // have all the default template argument information. 5962 TemplateParameterList *Params = 5963 cast<TemplateDecl>(Template->getMostRecentDecl()) 5964 ->getTemplateParameters(); 5965 5966 SourceLocation RAngleLoc = NewArgs.getRAngleLoc(); 5967 5968 // C++ [temp.arg]p1: 5969 // [...] The type and form of each template-argument specified in 5970 // a template-id shall match the type and form specified for the 5971 // corresponding parameter declared by the template in its 5972 // template-parameter-list. 5973 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template); 5974 SmallVector<TemplateArgument, 2> SugaredArgumentPack; 5975 SmallVector<TemplateArgument, 2> CanonicalArgumentPack; 5976 unsigned ArgIdx = 0, NumArgs = NewArgs.size(); 5977 LocalInstantiationScope InstScope(*this, true); 5978 for (TemplateParameterList::iterator Param = Params->begin(), 5979 ParamEnd = Params->end(); 5980 Param != ParamEnd; /* increment in loop */) { 5981 // If we have an expanded parameter pack, make sure we don't have too 5982 // many arguments. 5983 if (std::optional<unsigned> Expansions = getExpandedPackSize(*Param)) { 5984 if (*Expansions == SugaredArgumentPack.size()) { 5985 // We're done with this parameter pack. Pack up its arguments and add 5986 // them to the list. 5987 SugaredConverted.push_back( 5988 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack)); 5989 SugaredArgumentPack.clear(); 5990 5991 CanonicalConverted.push_back( 5992 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack)); 5993 CanonicalArgumentPack.clear(); 5994 5995 // This argument is assigned to the next parameter. 5996 ++Param; 5997 continue; 5998 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) { 5999 // Not enough arguments for this parameter pack. 6000 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 6001 << /*not enough args*/0 6002 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template)) 6003 << Template; 6004 NoteTemplateLocation(*Template, Params->getSourceRange()); 6005 return true; 6006 } 6007 } 6008 6009 if (ArgIdx < NumArgs) { 6010 // Check the template argument we were given. 6011 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc, 6012 RAngleLoc, SugaredArgumentPack.size(), 6013 SugaredConverted, CanonicalConverted, 6014 CTAK_Specified)) 6015 return true; 6016 6017 CanonicalConverted.back().setIsDefaulted( 6018 clang::isSubstitutedDefaultArgument( 6019 Context, NewArgs[ArgIdx].getArgument(), *Param, 6020 CanonicalConverted, Params->getDepth())); 6021 6022 bool PackExpansionIntoNonPack = 6023 NewArgs[ArgIdx].getArgument().isPackExpansion() && 6024 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param)); 6025 if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Template) || 6026 isa<ConceptDecl>(Template))) { 6027 // Core issue 1430: we have a pack expansion as an argument to an 6028 // alias template, and it's not part of a parameter pack. This 6029 // can't be canonicalized, so reject it now. 6030 // As for concepts - we cannot normalize constraints where this 6031 // situation exists. 6032 Diag(NewArgs[ArgIdx].getLocation(), 6033 diag::err_template_expansion_into_fixed_list) 6034 << (isa<ConceptDecl>(Template) ? 1 : 0) 6035 << NewArgs[ArgIdx].getSourceRange(); 6036 NoteTemplateParameterLocation(**Param); 6037 return true; 6038 } 6039 6040 // We're now done with this argument. 6041 ++ArgIdx; 6042 6043 if ((*Param)->isTemplateParameterPack()) { 6044 // The template parameter was a template parameter pack, so take the 6045 // deduced argument and place it on the argument pack. Note that we 6046 // stay on the same template parameter so that we can deduce more 6047 // arguments. 6048 SugaredArgumentPack.push_back(SugaredConverted.pop_back_val()); 6049 CanonicalArgumentPack.push_back(CanonicalConverted.pop_back_val()); 6050 } else { 6051 // Move to the next template parameter. 6052 ++Param; 6053 } 6054 6055 // If we just saw a pack expansion into a non-pack, then directly convert 6056 // the remaining arguments, because we don't know what parameters they'll 6057 // match up with. 6058 if (PackExpansionIntoNonPack) { 6059 if (!SugaredArgumentPack.empty()) { 6060 // If we were part way through filling in an expanded parameter pack, 6061 // fall back to just producing individual arguments. 6062 SugaredConverted.insert(SugaredConverted.end(), 6063 SugaredArgumentPack.begin(), 6064 SugaredArgumentPack.end()); 6065 SugaredArgumentPack.clear(); 6066 6067 CanonicalConverted.insert(CanonicalConverted.end(), 6068 CanonicalArgumentPack.begin(), 6069 CanonicalArgumentPack.end()); 6070 CanonicalArgumentPack.clear(); 6071 } 6072 6073 while (ArgIdx < NumArgs) { 6074 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument(); 6075 SugaredConverted.push_back(Arg); 6076 CanonicalConverted.push_back( 6077 Context.getCanonicalTemplateArgument(Arg)); 6078 ++ArgIdx; 6079 } 6080 6081 return false; 6082 } 6083 6084 continue; 6085 } 6086 6087 // If we're checking a partial template argument list, we're done. 6088 if (PartialTemplateArgs) { 6089 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) { 6090 SugaredConverted.push_back( 6091 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack)); 6092 CanonicalConverted.push_back( 6093 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack)); 6094 } 6095 return false; 6096 } 6097 6098 // If we have a template parameter pack with no more corresponding 6099 // arguments, just break out now and we'll fill in the argument pack below. 6100 if ((*Param)->isTemplateParameterPack()) { 6101 assert(!getExpandedPackSize(*Param) && 6102 "Should have dealt with this already"); 6103 6104 // A non-expanded parameter pack before the end of the parameter list 6105 // only occurs for an ill-formed template parameter list, unless we've 6106 // got a partial argument list for a function template, so just bail out. 6107 if (Param + 1 != ParamEnd) { 6108 assert( 6109 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) && 6110 "Concept templates must have parameter packs at the end."); 6111 return true; 6112 } 6113 6114 SugaredConverted.push_back( 6115 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack)); 6116 SugaredArgumentPack.clear(); 6117 6118 CanonicalConverted.push_back( 6119 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack)); 6120 CanonicalArgumentPack.clear(); 6121 6122 ++Param; 6123 continue; 6124 } 6125 6126 // Check whether we have a default argument. 6127 TemplateArgumentLoc Arg; 6128 6129 // Retrieve the default template argument from the template 6130 // parameter. For each kind of template parameter, we substitute the 6131 // template arguments provided thus far and any "outer" template arguments 6132 // (when the template parameter was part of a nested template) into 6133 // the default argument. 6134 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) { 6135 if (!hasReachableDefaultArgument(TTP)) 6136 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP, 6137 NewArgs); 6138 6139 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument( 6140 *this, Template, TemplateLoc, RAngleLoc, TTP, SugaredConverted, 6141 CanonicalConverted); 6142 if (!ArgType) 6143 return true; 6144 6145 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()), 6146 ArgType); 6147 } else if (NonTypeTemplateParmDecl *NTTP 6148 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) { 6149 if (!hasReachableDefaultArgument(NTTP)) 6150 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP, 6151 NewArgs); 6152 6153 ExprResult E = SubstDefaultTemplateArgument( 6154 *this, Template, TemplateLoc, RAngleLoc, NTTP, SugaredConverted, 6155 CanonicalConverted); 6156 if (E.isInvalid()) 6157 return true; 6158 6159 Expr *Ex = E.getAs<Expr>(); 6160 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex); 6161 } else { 6162 TemplateTemplateParmDecl *TempParm 6163 = cast<TemplateTemplateParmDecl>(*Param); 6164 6165 if (!hasReachableDefaultArgument(TempParm)) 6166 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm, 6167 NewArgs); 6168 6169 NestedNameSpecifierLoc QualifierLoc; 6170 TemplateName Name = SubstDefaultTemplateArgument( 6171 *this, Template, TemplateLoc, RAngleLoc, TempParm, SugaredConverted, 6172 CanonicalConverted, QualifierLoc); 6173 if (Name.isNull()) 6174 return true; 6175 6176 Arg = TemplateArgumentLoc( 6177 Context, TemplateArgument(Name), QualifierLoc, 6178 TempParm->getDefaultArgument().getTemplateNameLoc()); 6179 } 6180 6181 // Introduce an instantiation record that describes where we are using 6182 // the default template argument. We're not actually instantiating a 6183 // template here, we just create this object to put a note into the 6184 // context stack. 6185 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, 6186 SugaredConverted, 6187 SourceRange(TemplateLoc, RAngleLoc)); 6188 if (Inst.isInvalid()) 6189 return true; 6190 6191 // Check the default template argument. 6192 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0, 6193 SugaredConverted, CanonicalConverted, 6194 CTAK_Specified)) 6195 return true; 6196 6197 CanonicalConverted.back().setIsDefaulted(true); 6198 6199 // Core issue 150 (assumed resolution): if this is a template template 6200 // parameter, keep track of the default template arguments from the 6201 // template definition. 6202 if (isTemplateTemplateParameter) 6203 NewArgs.addArgument(Arg); 6204 6205 // Move to the next template parameter and argument. 6206 ++Param; 6207 ++ArgIdx; 6208 } 6209 6210 // If we're performing a partial argument substitution, allow any trailing 6211 // pack expansions; they might be empty. This can happen even if 6212 // PartialTemplateArgs is false (the list of arguments is complete but 6213 // still dependent). 6214 if (ArgIdx < NumArgs && CurrentInstantiationScope && 6215 CurrentInstantiationScope->getPartiallySubstitutedPack()) { 6216 while (ArgIdx < NumArgs && 6217 NewArgs[ArgIdx].getArgument().isPackExpansion()) { 6218 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument(); 6219 SugaredConverted.push_back(Arg); 6220 CanonicalConverted.push_back(Context.getCanonicalTemplateArgument(Arg)); 6221 } 6222 } 6223 6224 // If we have any leftover arguments, then there were too many arguments. 6225 // Complain and fail. 6226 if (ArgIdx < NumArgs) { 6227 Diag(TemplateLoc, diag::err_template_arg_list_different_arity) 6228 << /*too many args*/1 6229 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template)) 6230 << Template 6231 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc()); 6232 NoteTemplateLocation(*Template, Params->getSourceRange()); 6233 return true; 6234 } 6235 6236 // No problems found with the new argument list, propagate changes back 6237 // to caller. 6238 if (UpdateArgsWithConversions) 6239 TemplateArgs = std::move(NewArgs); 6240 6241 if (!PartialTemplateArgs) { 6242 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack, 6243 CanonicalConverted); 6244 // Setup the context/ThisScope for the case where we are needing to 6245 // re-instantiate constraints outside of normal instantiation. 6246 DeclContext *NewContext = Template->getDeclContext(); 6247 6248 // If this template is in a template, make sure we extract the templated 6249 // decl. 6250 if (auto *TD = dyn_cast<TemplateDecl>(NewContext)) 6251 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl()); 6252 auto *RD = dyn_cast<CXXRecordDecl>(NewContext); 6253 6254 Qualifiers ThisQuals; 6255 if (const auto *Method = 6256 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl())) 6257 ThisQuals = Method->getMethodQualifiers(); 6258 6259 ContextRAII Context(*this, NewContext); 6260 CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr); 6261 6262 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs( 6263 Template, NewContext, /*Final=*/false, &StackTemplateArgs, 6264 /*RelativeToPrimary=*/true, 6265 /*Pattern=*/nullptr, 6266 /*ForConceptInstantiation=*/true); 6267 if (EnsureTemplateArgumentListConstraints( 6268 Template, MLTAL, 6269 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) { 6270 if (ConstraintsNotSatisfied) 6271 *ConstraintsNotSatisfied = true; 6272 return true; 6273 } 6274 } 6275 6276 return false; 6277 } 6278 6279 namespace { 6280 class UnnamedLocalNoLinkageFinder 6281 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool> 6282 { 6283 Sema &S; 6284 SourceRange SR; 6285 6286 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited; 6287 6288 public: 6289 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { } 6290 6291 bool Visit(QualType T) { 6292 return T.isNull() ? false : inherited::Visit(T.getTypePtr()); 6293 } 6294 6295 #define TYPE(Class, Parent) \ 6296 bool Visit##Class##Type(const Class##Type *); 6297 #define ABSTRACT_TYPE(Class, Parent) \ 6298 bool Visit##Class##Type(const Class##Type *) { return false; } 6299 #define NON_CANONICAL_TYPE(Class, Parent) \ 6300 bool Visit##Class##Type(const Class##Type *) { return false; } 6301 #include "clang/AST/TypeNodes.inc" 6302 6303 bool VisitTagDecl(const TagDecl *Tag); 6304 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS); 6305 }; 6306 } // end anonymous namespace 6307 6308 bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) { 6309 return false; 6310 } 6311 6312 bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) { 6313 return Visit(T->getElementType()); 6314 } 6315 6316 bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) { 6317 return Visit(T->getPointeeType()); 6318 } 6319 6320 bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType( 6321 const BlockPointerType* T) { 6322 return Visit(T->getPointeeType()); 6323 } 6324 6325 bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType( 6326 const LValueReferenceType* T) { 6327 return Visit(T->getPointeeType()); 6328 } 6329 6330 bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType( 6331 const RValueReferenceType* T) { 6332 return Visit(T->getPointeeType()); 6333 } 6334 6335 bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType( 6336 const MemberPointerType* T) { 6337 return Visit(T->getPointeeType()) || Visit(QualType(T->getClass(), 0)); 6338 } 6339 6340 bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType( 6341 const ConstantArrayType* T) { 6342 return Visit(T->getElementType()); 6343 } 6344 6345 bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType( 6346 const IncompleteArrayType* T) { 6347 return Visit(T->getElementType()); 6348 } 6349 6350 bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType( 6351 const VariableArrayType* T) { 6352 return Visit(T->getElementType()); 6353 } 6354 6355 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType( 6356 const DependentSizedArrayType* T) { 6357 return Visit(T->getElementType()); 6358 } 6359 6360 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType( 6361 const DependentSizedExtVectorType* T) { 6362 return Visit(T->getElementType()); 6363 } 6364 6365 bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType( 6366 const DependentSizedMatrixType *T) { 6367 return Visit(T->getElementType()); 6368 } 6369 6370 bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType( 6371 const DependentAddressSpaceType *T) { 6372 return Visit(T->getPointeeType()); 6373 } 6374 6375 bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) { 6376 return Visit(T->getElementType()); 6377 } 6378 6379 bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType( 6380 const DependentVectorType *T) { 6381 return Visit(T->getElementType()); 6382 } 6383 6384 bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) { 6385 return Visit(T->getElementType()); 6386 } 6387 6388 bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType( 6389 const ConstantMatrixType *T) { 6390 return Visit(T->getElementType()); 6391 } 6392 6393 bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType( 6394 const FunctionProtoType* T) { 6395 for (const auto &A : T->param_types()) { 6396 if (Visit(A)) 6397 return true; 6398 } 6399 6400 return Visit(T->getReturnType()); 6401 } 6402 6403 bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType( 6404 const FunctionNoProtoType* T) { 6405 return Visit(T->getReturnType()); 6406 } 6407 6408 bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType( 6409 const UnresolvedUsingType*) { 6410 return false; 6411 } 6412 6413 bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) { 6414 return false; 6415 } 6416 6417 bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) { 6418 return Visit(T->getUnmodifiedType()); 6419 } 6420 6421 bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) { 6422 return false; 6423 } 6424 6425 bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType( 6426 const UnaryTransformType*) { 6427 return false; 6428 } 6429 6430 bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) { 6431 return Visit(T->getDeducedType()); 6432 } 6433 6434 bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType( 6435 const DeducedTemplateSpecializationType *T) { 6436 return Visit(T->getDeducedType()); 6437 } 6438 6439 bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) { 6440 return VisitTagDecl(T->getDecl()); 6441 } 6442 6443 bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) { 6444 return VisitTagDecl(T->getDecl()); 6445 } 6446 6447 bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType( 6448 const TemplateTypeParmType*) { 6449 return false; 6450 } 6451 6452 bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType( 6453 const SubstTemplateTypeParmPackType *) { 6454 return false; 6455 } 6456 6457 bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType( 6458 const TemplateSpecializationType*) { 6459 return false; 6460 } 6461 6462 bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType( 6463 const InjectedClassNameType* T) { 6464 return VisitTagDecl(T->getDecl()); 6465 } 6466 6467 bool UnnamedLocalNoLinkageFinder::VisitDependentNameType( 6468 const DependentNameType* T) { 6469 return VisitNestedNameSpecifier(T->getQualifier()); 6470 } 6471 6472 bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType( 6473 const DependentTemplateSpecializationType* T) { 6474 if (auto *Q = T->getQualifier()) 6475 return VisitNestedNameSpecifier(Q); 6476 return false; 6477 } 6478 6479 bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType( 6480 const PackExpansionType* T) { 6481 return Visit(T->getPattern()); 6482 } 6483 6484 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) { 6485 return false; 6486 } 6487 6488 bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType( 6489 const ObjCInterfaceType *) { 6490 return false; 6491 } 6492 6493 bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType( 6494 const ObjCObjectPointerType *) { 6495 return false; 6496 } 6497 6498 bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) { 6499 return Visit(T->getValueType()); 6500 } 6501 6502 bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) { 6503 return false; 6504 } 6505 6506 bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) { 6507 return false; 6508 } 6509 6510 bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType( 6511 const DependentBitIntType *T) { 6512 return false; 6513 } 6514 6515 bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) { 6516 if (Tag->getDeclContext()->isFunctionOrMethod()) { 6517 S.Diag(SR.getBegin(), 6518 S.getLangOpts().CPlusPlus11 ? 6519 diag::warn_cxx98_compat_template_arg_local_type : 6520 diag::ext_template_arg_local_type) 6521 << S.Context.getTypeDeclType(Tag) << SR; 6522 return true; 6523 } 6524 6525 if (!Tag->hasNameForLinkage()) { 6526 S.Diag(SR.getBegin(), 6527 S.getLangOpts().CPlusPlus11 ? 6528 diag::warn_cxx98_compat_template_arg_unnamed_type : 6529 diag::ext_template_arg_unnamed_type) << SR; 6530 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here); 6531 return true; 6532 } 6533 6534 return false; 6535 } 6536 6537 bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier( 6538 NestedNameSpecifier *NNS) { 6539 assert(NNS); 6540 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS->getPrefix())) 6541 return true; 6542 6543 switch (NNS->getKind()) { 6544 case NestedNameSpecifier::Identifier: 6545 case NestedNameSpecifier::Namespace: 6546 case NestedNameSpecifier::NamespaceAlias: 6547 case NestedNameSpecifier::Global: 6548 case NestedNameSpecifier::Super: 6549 return false; 6550 6551 case NestedNameSpecifier::TypeSpec: 6552 case NestedNameSpecifier::TypeSpecWithTemplate: 6553 return Visit(QualType(NNS->getAsType(), 0)); 6554 } 6555 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 6556 } 6557 6558 /// Check a template argument against its corresponding 6559 /// template type parameter. 6560 /// 6561 /// This routine implements the semantics of C++ [temp.arg.type]. It 6562 /// returns true if an error occurred, and false otherwise. 6563 bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) { 6564 assert(ArgInfo && "invalid TypeSourceInfo"); 6565 QualType Arg = ArgInfo->getType(); 6566 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange(); 6567 QualType CanonArg = Context.getCanonicalType(Arg); 6568 6569 if (CanonArg->isVariablyModifiedType()) { 6570 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg; 6571 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) { 6572 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR; 6573 } 6574 6575 // C++03 [temp.arg.type]p2: 6576 // A local type, a type with no linkage, an unnamed type or a type 6577 // compounded from any of these types shall not be used as a 6578 // template-argument for a template type-parameter. 6579 // 6580 // C++11 allows these, and even in C++03 we allow them as an extension with 6581 // a warning. 6582 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) { 6583 UnnamedLocalNoLinkageFinder Finder(*this, SR); 6584 (void)Finder.Visit(CanonArg); 6585 } 6586 6587 return false; 6588 } 6589 6590 enum NullPointerValueKind { 6591 NPV_NotNullPointer, 6592 NPV_NullPointer, 6593 NPV_Error 6594 }; 6595 6596 /// Determine whether the given template argument is a null pointer 6597 /// value of the appropriate type. 6598 static NullPointerValueKind 6599 isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param, 6600 QualType ParamType, Expr *Arg, 6601 Decl *Entity = nullptr) { 6602 if (Arg->isValueDependent() || Arg->isTypeDependent()) 6603 return NPV_NotNullPointer; 6604 6605 // dllimport'd entities aren't constant but are available inside of template 6606 // arguments. 6607 if (Entity && Entity->hasAttr<DLLImportAttr>()) 6608 return NPV_NotNullPointer; 6609 6610 if (!S.isCompleteType(Arg->getExprLoc(), ParamType)) 6611 llvm_unreachable( 6612 "Incomplete parameter type in isNullPointerValueTemplateArgument!"); 6613 6614 if (!S.getLangOpts().CPlusPlus11) 6615 return NPV_NotNullPointer; 6616 6617 // Determine whether we have a constant expression. 6618 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg); 6619 if (ArgRV.isInvalid()) 6620 return NPV_Error; 6621 Arg = ArgRV.get(); 6622 6623 Expr::EvalResult EvalResult; 6624 SmallVector<PartialDiagnosticAt, 8> Notes; 6625 EvalResult.Diag = &Notes; 6626 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) || 6627 EvalResult.HasSideEffects) { 6628 SourceLocation DiagLoc = Arg->getExprLoc(); 6629 6630 // If our only note is the usual "invalid subexpression" note, just point 6631 // the caret at its location rather than producing an essentially 6632 // redundant note. 6633 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 6634 diag::note_invalid_subexpr_in_const_expr) { 6635 DiagLoc = Notes[0].first; 6636 Notes.clear(); 6637 } 6638 6639 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant) 6640 << Arg->getType() << Arg->getSourceRange(); 6641 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 6642 S.Diag(Notes[I].first, Notes[I].second); 6643 6644 S.NoteTemplateParameterLocation(*Param); 6645 return NPV_Error; 6646 } 6647 6648 // C++11 [temp.arg.nontype]p1: 6649 // - an address constant expression of type std::nullptr_t 6650 if (Arg->getType()->isNullPtrType()) 6651 return NPV_NullPointer; 6652 6653 // - a constant expression that evaluates to a null pointer value (4.10); or 6654 // - a constant expression that evaluates to a null member pointer value 6655 // (4.11); or 6656 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) || 6657 (EvalResult.Val.isMemberPointer() && 6658 !EvalResult.Val.getMemberPointerDecl())) { 6659 // If our expression has an appropriate type, we've succeeded. 6660 bool ObjCLifetimeConversion; 6661 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) || 6662 S.IsQualificationConversion(Arg->getType(), ParamType, false, 6663 ObjCLifetimeConversion)) 6664 return NPV_NullPointer; 6665 6666 // The types didn't match, but we know we got a null pointer; complain, 6667 // then recover as if the types were correct. 6668 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant) 6669 << Arg->getType() << ParamType << Arg->getSourceRange(); 6670 S.NoteTemplateParameterLocation(*Param); 6671 return NPV_NullPointer; 6672 } 6673 6674 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) { 6675 // We found a pointer that isn't null, but doesn't refer to an object. 6676 // We could just return NPV_NotNullPointer, but we can print a better 6677 // message with the information we have here. 6678 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid) 6679 << EvalResult.Val.getAsString(S.Context, ParamType); 6680 S.NoteTemplateParameterLocation(*Param); 6681 return NPV_Error; 6682 } 6683 6684 // If we don't have a null pointer value, but we do have a NULL pointer 6685 // constant, suggest a cast to the appropriate type. 6686 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) { 6687 std::string Code = "static_cast<" + ParamType.getAsString() + ">("; 6688 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant) 6689 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code) 6690 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()), 6691 ")"); 6692 S.NoteTemplateParameterLocation(*Param); 6693 return NPV_NullPointer; 6694 } 6695 6696 // FIXME: If we ever want to support general, address-constant expressions 6697 // as non-type template arguments, we should return the ExprResult here to 6698 // be interpreted by the caller. 6699 return NPV_NotNullPointer; 6700 } 6701 6702 /// Checks whether the given template argument is compatible with its 6703 /// template parameter. 6704 static bool CheckTemplateArgumentIsCompatibleWithParameter( 6705 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, 6706 Expr *Arg, QualType ArgType) { 6707 bool ObjCLifetimeConversion; 6708 if (ParamType->isPointerType() && 6709 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() && 6710 S.IsQualificationConversion(ArgType, ParamType, false, 6711 ObjCLifetimeConversion)) { 6712 // For pointer-to-object types, qualification conversions are 6713 // permitted. 6714 } else { 6715 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) { 6716 if (!ParamRef->getPointeeType()->isFunctionType()) { 6717 // C++ [temp.arg.nontype]p5b3: 6718 // For a non-type template-parameter of type reference to 6719 // object, no conversions apply. The type referred to by the 6720 // reference may be more cv-qualified than the (otherwise 6721 // identical) type of the template- argument. The 6722 // template-parameter is bound directly to the 6723 // template-argument, which shall be an lvalue. 6724 6725 // FIXME: Other qualifiers? 6726 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers(); 6727 unsigned ArgQuals = ArgType.getCVRQualifiers(); 6728 6729 if ((ParamQuals | ArgQuals) != ParamQuals) { 6730 S.Diag(Arg->getBeginLoc(), 6731 diag::err_template_arg_ref_bind_ignores_quals) 6732 << ParamType << Arg->getType() << Arg->getSourceRange(); 6733 S.NoteTemplateParameterLocation(*Param); 6734 return true; 6735 } 6736 } 6737 } 6738 6739 // At this point, the template argument refers to an object or 6740 // function with external linkage. We now need to check whether the 6741 // argument and parameter types are compatible. 6742 if (!S.Context.hasSameUnqualifiedType(ArgType, 6743 ParamType.getNonReferenceType())) { 6744 // We can't perform this conversion or binding. 6745 if (ParamType->isReferenceType()) 6746 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind) 6747 << ParamType << ArgIn->getType() << Arg->getSourceRange(); 6748 else 6749 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible) 6750 << ArgIn->getType() << ParamType << Arg->getSourceRange(); 6751 S.NoteTemplateParameterLocation(*Param); 6752 return true; 6753 } 6754 } 6755 6756 return false; 6757 } 6758 6759 /// Checks whether the given template argument is the address 6760 /// of an object or function according to C++ [temp.arg.nontype]p1. 6761 static bool CheckTemplateArgumentAddressOfObjectOrFunction( 6762 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn, 6763 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) { 6764 bool Invalid = false; 6765 Expr *Arg = ArgIn; 6766 QualType ArgType = Arg->getType(); 6767 6768 bool AddressTaken = false; 6769 SourceLocation AddrOpLoc; 6770 if (S.getLangOpts().MicrosoftExt) { 6771 // Microsoft Visual C++ strips all casts, allows an arbitrary number of 6772 // dereference and address-of operators. 6773 Arg = Arg->IgnoreParenCasts(); 6774 6775 bool ExtWarnMSTemplateArg = false; 6776 UnaryOperatorKind FirstOpKind; 6777 SourceLocation FirstOpLoc; 6778 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 6779 UnaryOperatorKind UnOpKind = UnOp->getOpcode(); 6780 if (UnOpKind == UO_Deref) 6781 ExtWarnMSTemplateArg = true; 6782 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) { 6783 Arg = UnOp->getSubExpr()->IgnoreParenCasts(); 6784 if (!AddrOpLoc.isValid()) { 6785 FirstOpKind = UnOpKind; 6786 FirstOpLoc = UnOp->getOperatorLoc(); 6787 } 6788 } else 6789 break; 6790 } 6791 if (FirstOpLoc.isValid()) { 6792 if (ExtWarnMSTemplateArg) 6793 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument) 6794 << ArgIn->getSourceRange(); 6795 6796 if (FirstOpKind == UO_AddrOf) 6797 AddressTaken = true; 6798 else if (Arg->getType()->isPointerType()) { 6799 // We cannot let pointers get dereferenced here, that is obviously not a 6800 // constant expression. 6801 assert(FirstOpKind == UO_Deref); 6802 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref) 6803 << Arg->getSourceRange(); 6804 } 6805 } 6806 } else { 6807 // See through any implicit casts we added to fix the type. 6808 Arg = Arg->IgnoreImpCasts(); 6809 6810 // C++ [temp.arg.nontype]p1: 6811 // 6812 // A template-argument for a non-type, non-template 6813 // template-parameter shall be one of: [...] 6814 // 6815 // -- the address of an object or function with external 6816 // linkage, including function templates and function 6817 // template-ids but excluding non-static class members, 6818 // expressed as & id-expression where the & is optional if 6819 // the name refers to a function or array, or if the 6820 // corresponding template-parameter is a reference; or 6821 6822 // In C++98/03 mode, give an extension warning on any extra parentheses. 6823 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 6824 bool ExtraParens = false; 6825 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 6826 if (!Invalid && !ExtraParens) { 6827 S.Diag(Arg->getBeginLoc(), 6828 S.getLangOpts().CPlusPlus11 6829 ? diag::warn_cxx98_compat_template_arg_extra_parens 6830 : diag::ext_template_arg_extra_parens) 6831 << Arg->getSourceRange(); 6832 ExtraParens = true; 6833 } 6834 6835 Arg = Parens->getSubExpr(); 6836 } 6837 6838 while (SubstNonTypeTemplateParmExpr *subst = 6839 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg)) 6840 Arg = subst->getReplacement()->IgnoreImpCasts(); 6841 6842 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 6843 if (UnOp->getOpcode() == UO_AddrOf) { 6844 Arg = UnOp->getSubExpr(); 6845 AddressTaken = true; 6846 AddrOpLoc = UnOp->getOperatorLoc(); 6847 } 6848 } 6849 6850 while (SubstNonTypeTemplateParmExpr *subst = 6851 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg)) 6852 Arg = subst->getReplacement()->IgnoreImpCasts(); 6853 } 6854 6855 ValueDecl *Entity = nullptr; 6856 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg)) 6857 Entity = DRE->getDecl(); 6858 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg)) 6859 Entity = CUE->getGuidDecl(); 6860 6861 // If our parameter has pointer type, check for a null template value. 6862 if (ParamType->isPointerType() || ParamType->isNullPtrType()) { 6863 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn, 6864 Entity)) { 6865 case NPV_NullPointer: 6866 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); 6867 SugaredConverted = TemplateArgument(ParamType, 6868 /*isNullPtr=*/true); 6869 CanonicalConverted = 6870 TemplateArgument(S.Context.getCanonicalType(ParamType), 6871 /*isNullPtr=*/true); 6872 return false; 6873 6874 case NPV_Error: 6875 return true; 6876 6877 case NPV_NotNullPointer: 6878 break; 6879 } 6880 } 6881 6882 // Stop checking the precise nature of the argument if it is value dependent, 6883 // it should be checked when instantiated. 6884 if (Arg->isValueDependent()) { 6885 SugaredConverted = TemplateArgument(ArgIn); 6886 CanonicalConverted = 6887 S.Context.getCanonicalTemplateArgument(SugaredConverted); 6888 return false; 6889 } 6890 6891 if (!Entity) { 6892 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref) 6893 << Arg->getSourceRange(); 6894 S.NoteTemplateParameterLocation(*Param); 6895 return true; 6896 } 6897 6898 // Cannot refer to non-static data members 6899 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) { 6900 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field) 6901 << Entity << Arg->getSourceRange(); 6902 S.NoteTemplateParameterLocation(*Param); 6903 return true; 6904 } 6905 6906 // Cannot refer to non-static member functions 6907 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) { 6908 if (!Method->isStatic()) { 6909 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method) 6910 << Method << Arg->getSourceRange(); 6911 S.NoteTemplateParameterLocation(*Param); 6912 return true; 6913 } 6914 } 6915 6916 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity); 6917 VarDecl *Var = dyn_cast<VarDecl>(Entity); 6918 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity); 6919 6920 // A non-type template argument must refer to an object or function. 6921 if (!Func && !Var && !Guid) { 6922 // We found something, but we don't know specifically what it is. 6923 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func) 6924 << Arg->getSourceRange(); 6925 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here); 6926 return true; 6927 } 6928 6929 // Address / reference template args must have external linkage in C++98. 6930 if (Entity->getFormalLinkage() == Linkage::Internal) { 6931 S.Diag(Arg->getBeginLoc(), 6932 S.getLangOpts().CPlusPlus11 6933 ? diag::warn_cxx98_compat_template_arg_object_internal 6934 : diag::ext_template_arg_object_internal) 6935 << !Func << Entity << Arg->getSourceRange(); 6936 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object) 6937 << !Func; 6938 } else if (!Entity->hasLinkage()) { 6939 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage) 6940 << !Func << Entity << Arg->getSourceRange(); 6941 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object) 6942 << !Func; 6943 return true; 6944 } 6945 6946 if (Var) { 6947 // A value of reference type is not an object. 6948 if (Var->getType()->isReferenceType()) { 6949 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var) 6950 << Var->getType() << Arg->getSourceRange(); 6951 S.NoteTemplateParameterLocation(*Param); 6952 return true; 6953 } 6954 6955 // A template argument must have static storage duration. 6956 if (Var->getTLSKind()) { 6957 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local) 6958 << Arg->getSourceRange(); 6959 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here); 6960 return true; 6961 } 6962 } 6963 6964 if (AddressTaken && ParamType->isReferenceType()) { 6965 // If we originally had an address-of operator, but the 6966 // parameter has reference type, complain and (if things look 6967 // like they will work) drop the address-of operator. 6968 if (!S.Context.hasSameUnqualifiedType(Entity->getType(), 6969 ParamType.getNonReferenceType())) { 6970 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 6971 << ParamType; 6972 S.NoteTemplateParameterLocation(*Param); 6973 return true; 6974 } 6975 6976 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer) 6977 << ParamType 6978 << FixItHint::CreateRemoval(AddrOpLoc); 6979 S.NoteTemplateParameterLocation(*Param); 6980 6981 ArgType = Entity->getType(); 6982 } 6983 6984 // If the template parameter has pointer type, either we must have taken the 6985 // address or the argument must decay to a pointer. 6986 if (!AddressTaken && ParamType->isPointerType()) { 6987 if (Func) { 6988 // Function-to-pointer decay. 6989 ArgType = S.Context.getPointerType(Func->getType()); 6990 } else if (Entity->getType()->isArrayType()) { 6991 // Array-to-pointer decay. 6992 ArgType = S.Context.getArrayDecayedType(Entity->getType()); 6993 } else { 6994 // If the template parameter has pointer type but the address of 6995 // this object was not taken, complain and (possibly) recover by 6996 // taking the address of the entity. 6997 ArgType = S.Context.getPointerType(Entity->getType()); 6998 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) { 6999 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of) 7000 << ParamType; 7001 S.NoteTemplateParameterLocation(*Param); 7002 return true; 7003 } 7004 7005 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of) 7006 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&"); 7007 7008 S.NoteTemplateParameterLocation(*Param); 7009 } 7010 } 7011 7012 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn, 7013 Arg, ArgType)) 7014 return true; 7015 7016 // Create the template argument. 7017 SugaredConverted = TemplateArgument(Entity, ParamType); 7018 CanonicalConverted = 7019 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()), 7020 S.Context.getCanonicalType(ParamType)); 7021 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false); 7022 return false; 7023 } 7024 7025 /// Checks whether the given template argument is a pointer to 7026 /// member constant according to C++ [temp.arg.nontype]p1. 7027 static bool 7028 CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param, 7029 QualType ParamType, Expr *&ResultArg, 7030 TemplateArgument &SugaredConverted, 7031 TemplateArgument &CanonicalConverted) { 7032 bool Invalid = false; 7033 7034 Expr *Arg = ResultArg; 7035 bool ObjCLifetimeConversion; 7036 7037 // C++ [temp.arg.nontype]p1: 7038 // 7039 // A template-argument for a non-type, non-template 7040 // template-parameter shall be one of: [...] 7041 // 7042 // -- a pointer to member expressed as described in 5.3.1. 7043 DeclRefExpr *DRE = nullptr; 7044 7045 // In C++98/03 mode, give an extension warning on any extra parentheses. 7046 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773 7047 bool ExtraParens = false; 7048 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) { 7049 if (!Invalid && !ExtraParens) { 7050 S.Diag(Arg->getBeginLoc(), 7051 S.getLangOpts().CPlusPlus11 7052 ? diag::warn_cxx98_compat_template_arg_extra_parens 7053 : diag::ext_template_arg_extra_parens) 7054 << Arg->getSourceRange(); 7055 ExtraParens = true; 7056 } 7057 7058 Arg = Parens->getSubExpr(); 7059 } 7060 7061 while (SubstNonTypeTemplateParmExpr *subst = 7062 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg)) 7063 Arg = subst->getReplacement()->IgnoreImpCasts(); 7064 7065 // A pointer-to-member constant written &Class::member. 7066 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) { 7067 if (UnOp->getOpcode() == UO_AddrOf) { 7068 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr()); 7069 if (DRE && !DRE->getQualifier()) 7070 DRE = nullptr; 7071 } 7072 } 7073 // A constant of pointer-to-member type. 7074 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) { 7075 ValueDecl *VD = DRE->getDecl(); 7076 if (VD->getType()->isMemberPointerType()) { 7077 if (isa<NonTypeTemplateParmDecl>(VD)) { 7078 if (Arg->isTypeDependent() || Arg->isValueDependent()) { 7079 SugaredConverted = TemplateArgument(Arg); 7080 CanonicalConverted = 7081 S.Context.getCanonicalTemplateArgument(SugaredConverted); 7082 } else { 7083 SugaredConverted = TemplateArgument(VD, ParamType); 7084 CanonicalConverted = 7085 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()), 7086 S.Context.getCanonicalType(ParamType)); 7087 } 7088 return Invalid; 7089 } 7090 } 7091 7092 DRE = nullptr; 7093 } 7094 7095 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr; 7096 7097 // Check for a null pointer value. 7098 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg, 7099 Entity)) { 7100 case NPV_Error: 7101 return true; 7102 case NPV_NullPointer: 7103 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); 7104 SugaredConverted = TemplateArgument(ParamType, 7105 /*isNullPtr*/ true); 7106 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType), 7107 /*isNullPtr*/ true); 7108 return false; 7109 case NPV_NotNullPointer: 7110 break; 7111 } 7112 7113 if (S.IsQualificationConversion(ResultArg->getType(), 7114 ParamType.getNonReferenceType(), false, 7115 ObjCLifetimeConversion)) { 7116 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp, 7117 ResultArg->getValueKind()) 7118 .get(); 7119 } else if (!S.Context.hasSameUnqualifiedType( 7120 ResultArg->getType(), ParamType.getNonReferenceType())) { 7121 // We can't perform this conversion. 7122 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible) 7123 << ResultArg->getType() << ParamType << ResultArg->getSourceRange(); 7124 S.NoteTemplateParameterLocation(*Param); 7125 return true; 7126 } 7127 7128 if (!DRE) 7129 return S.Diag(Arg->getBeginLoc(), 7130 diag::err_template_arg_not_pointer_to_member_form) 7131 << Arg->getSourceRange(); 7132 7133 if (isa<FieldDecl>(DRE->getDecl()) || 7134 isa<IndirectFieldDecl>(DRE->getDecl()) || 7135 isa<CXXMethodDecl>(DRE->getDecl())) { 7136 assert((isa<FieldDecl>(DRE->getDecl()) || 7137 isa<IndirectFieldDecl>(DRE->getDecl()) || 7138 cast<CXXMethodDecl>(DRE->getDecl()) 7139 ->isImplicitObjectMemberFunction()) && 7140 "Only non-static member pointers can make it here"); 7141 7142 // Okay: this is the address of a non-static member, and therefore 7143 // a member pointer constant. 7144 if (Arg->isTypeDependent() || Arg->isValueDependent()) { 7145 SugaredConverted = TemplateArgument(Arg); 7146 CanonicalConverted = 7147 S.Context.getCanonicalTemplateArgument(SugaredConverted); 7148 } else { 7149 ValueDecl *D = DRE->getDecl(); 7150 SugaredConverted = TemplateArgument(D, ParamType); 7151 CanonicalConverted = 7152 TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()), 7153 S.Context.getCanonicalType(ParamType)); 7154 } 7155 return Invalid; 7156 } 7157 7158 // We found something else, but we don't know specifically what it is. 7159 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form) 7160 << Arg->getSourceRange(); 7161 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here); 7162 return true; 7163 } 7164 7165 /// Check a template argument against its corresponding 7166 /// non-type template parameter. 7167 /// 7168 /// This routine implements the semantics of C++ [temp.arg.nontype]. 7169 /// If an error occurred, it returns ExprError(); otherwise, it 7170 /// returns the converted template argument. \p ParamType is the 7171 /// type of the non-type template parameter after it has been instantiated. 7172 ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 7173 QualType ParamType, Expr *Arg, 7174 TemplateArgument &SugaredConverted, 7175 TemplateArgument &CanonicalConverted, 7176 CheckTemplateArgumentKind CTAK) { 7177 SourceLocation StartLoc = Arg->getBeginLoc(); 7178 7179 // If the parameter type somehow involves auto, deduce the type now. 7180 DeducedType *DeducedT = ParamType->getContainedDeducedType(); 7181 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) { 7182 // During template argument deduction, we allow 'decltype(auto)' to 7183 // match an arbitrary dependent argument. 7184 // FIXME: The language rules don't say what happens in this case. 7185 // FIXME: We get an opaque dependent type out of decltype(auto) if the 7186 // expression is merely instantiation-dependent; is this enough? 7187 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) { 7188 auto *AT = dyn_cast<AutoType>(DeducedT); 7189 if (AT && AT->isDecltypeAuto()) { 7190 SugaredConverted = TemplateArgument(Arg); 7191 CanonicalConverted = TemplateArgument( 7192 Context.getCanonicalTemplateArgument(SugaredConverted)); 7193 return Arg; 7194 } 7195 } 7196 7197 // When checking a deduced template argument, deduce from its type even if 7198 // the type is dependent, in order to check the types of non-type template 7199 // arguments line up properly in partial ordering. 7200 Expr *DeductionArg = Arg; 7201 if (auto *PE = dyn_cast<PackExpansionExpr>(DeductionArg)) 7202 DeductionArg = PE->getPattern(); 7203 TypeSourceInfo *TSI = 7204 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation()); 7205 if (isa<DeducedTemplateSpecializationType>(DeducedT)) { 7206 InitializedEntity Entity = 7207 InitializedEntity::InitializeTemplateParameter(ParamType, Param); 7208 InitializationKind Kind = InitializationKind::CreateForInit( 7209 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg); 7210 Expr *Inits[1] = {DeductionArg}; 7211 ParamType = 7212 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits); 7213 if (ParamType.isNull()) 7214 return ExprError(); 7215 } else { 7216 TemplateDeductionInfo Info(DeductionArg->getExprLoc(), 7217 Param->getDepth() + 1); 7218 ParamType = QualType(); 7219 TemplateDeductionResult Result = 7220 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info, 7221 /*DependentDeduction=*/true, 7222 // We do not check constraints right now because the 7223 // immediately-declared constraint of the auto type is 7224 // also an associated constraint, and will be checked 7225 // along with the other associated constraints after 7226 // checking the template argument list. 7227 /*IgnoreConstraints=*/true); 7228 if (Result == TDK_AlreadyDiagnosed) { 7229 if (ParamType.isNull()) 7230 return ExprError(); 7231 } else if (Result != TDK_Success) { 7232 Diag(Arg->getExprLoc(), 7233 diag::err_non_type_template_parm_type_deduction_failure) 7234 << Param->getDeclName() << Param->getType() << Arg->getType() 7235 << Arg->getSourceRange(); 7236 NoteTemplateParameterLocation(*Param); 7237 return ExprError(); 7238 } 7239 } 7240 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's 7241 // an error. The error message normally references the parameter 7242 // declaration, but here we'll pass the argument location because that's 7243 // where the parameter type is deduced. 7244 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc()); 7245 if (ParamType.isNull()) { 7246 NoteTemplateParameterLocation(*Param); 7247 return ExprError(); 7248 } 7249 } 7250 7251 // We should have already dropped all cv-qualifiers by now. 7252 assert(!ParamType.hasQualifiers() && 7253 "non-type template parameter type cannot be qualified"); 7254 7255 // FIXME: When Param is a reference, should we check that Arg is an lvalue? 7256 if (CTAK == CTAK_Deduced && 7257 (ParamType->isReferenceType() 7258 ? !Context.hasSameType(ParamType.getNonReferenceType(), 7259 Arg->getType()) 7260 : !Context.hasSameUnqualifiedType(ParamType, Arg->getType()))) { 7261 // FIXME: If either type is dependent, we skip the check. This isn't 7262 // correct, since during deduction we're supposed to have replaced each 7263 // template parameter with some unique (non-dependent) placeholder. 7264 // FIXME: If the argument type contains 'auto', we carry on and fail the 7265 // type check in order to force specific types to be more specialized than 7266 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to 7267 // work. Similarly for CTAD, when comparing 'A<x>' against 'A'. 7268 if ((ParamType->isDependentType() || Arg->isTypeDependent()) && 7269 !Arg->getType()->getContainedDeducedType()) { 7270 SugaredConverted = TemplateArgument(Arg); 7271 CanonicalConverted = TemplateArgument( 7272 Context.getCanonicalTemplateArgument(SugaredConverted)); 7273 return Arg; 7274 } 7275 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770, 7276 // we should actually be checking the type of the template argument in P, 7277 // not the type of the template argument deduced from A, against the 7278 // template parameter type. 7279 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch) 7280 << Arg->getType() 7281 << ParamType.getUnqualifiedType(); 7282 NoteTemplateParameterLocation(*Param); 7283 return ExprError(); 7284 } 7285 7286 // If either the parameter has a dependent type or the argument is 7287 // type-dependent, there's nothing we can check now. 7288 if (ParamType->isDependentType() || Arg->isTypeDependent()) { 7289 // Force the argument to the type of the parameter to maintain invariants. 7290 auto *PE = dyn_cast<PackExpansionExpr>(Arg); 7291 if (PE) 7292 Arg = PE->getPattern(); 7293 ExprResult E = ImpCastExprToType( 7294 Arg, ParamType.getNonLValueExprType(Context), CK_Dependent, 7295 ParamType->isLValueReferenceType() ? VK_LValue 7296 : ParamType->isRValueReferenceType() ? VK_XValue 7297 : VK_PRValue); 7298 if (E.isInvalid()) 7299 return ExprError(); 7300 if (PE) { 7301 // Recreate a pack expansion if we unwrapped one. 7302 E = new (Context) 7303 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(), 7304 PE->getNumExpansions()); 7305 } 7306 SugaredConverted = TemplateArgument(E.get()); 7307 CanonicalConverted = TemplateArgument( 7308 Context.getCanonicalTemplateArgument(SugaredConverted)); 7309 return E; 7310 } 7311 7312 QualType CanonParamType = Context.getCanonicalType(ParamType); 7313 // Avoid making a copy when initializing a template parameter of class type 7314 // from a template parameter object of the same type. This is going beyond 7315 // the standard, but is required for soundness: in 7316 // template<A a> struct X { X *p; X<a> *q; }; 7317 // ... we need p and q to have the same type. 7318 // 7319 // Similarly, don't inject a call to a copy constructor when initializing 7320 // from a template parameter of the same type. 7321 Expr *InnerArg = Arg->IgnoreParenImpCasts(); 7322 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) && 7323 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) { 7324 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl(); 7325 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) { 7326 7327 SugaredConverted = TemplateArgument(TPO, ParamType); 7328 CanonicalConverted = 7329 TemplateArgument(TPO->getCanonicalDecl(), CanonParamType); 7330 return Arg; 7331 } 7332 if (isa<NonTypeTemplateParmDecl>(ND)) { 7333 SugaredConverted = TemplateArgument(Arg); 7334 CanonicalConverted = 7335 Context.getCanonicalTemplateArgument(SugaredConverted); 7336 return Arg; 7337 } 7338 } 7339 7340 // The initialization of the parameter from the argument is 7341 // a constant-evaluated context. 7342 EnterExpressionEvaluationContext ConstantEvaluated( 7343 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated); 7344 7345 bool IsConvertedConstantExpression = true; 7346 if (isa<InitListExpr>(Arg) || ParamType->isRecordType()) { 7347 InitializationKind Kind = InitializationKind::CreateForInit( 7348 Arg->getBeginLoc(), /*DirectInit=*/false, Arg); 7349 Expr *Inits[1] = {Arg}; 7350 InitializedEntity Entity = 7351 InitializedEntity::InitializeTemplateParameter(ParamType, Param); 7352 InitializationSequence InitSeq(*this, Entity, Kind, Inits); 7353 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits); 7354 if (Result.isInvalid() || !Result.get()) 7355 return ExprError(); 7356 Result = ActOnConstantExpression(Result.get()); 7357 if (Result.isInvalid() || !Result.get()) 7358 return ExprError(); 7359 Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(), 7360 /*DiscardedValue=*/false, 7361 /*IsConstexpr=*/true, /*IsTemplateArgument=*/true) 7362 .get(); 7363 IsConvertedConstantExpression = false; 7364 } 7365 7366 if (getLangOpts().CPlusPlus17) { 7367 // C++17 [temp.arg.nontype]p1: 7368 // A template-argument for a non-type template parameter shall be 7369 // a converted constant expression of the type of the template-parameter. 7370 APValue Value; 7371 ExprResult ArgResult; 7372 if (IsConvertedConstantExpression) { 7373 ArgResult = BuildConvertedConstantExpression(Arg, ParamType, 7374 CCEK_TemplateArg, Param); 7375 if (ArgResult.isInvalid()) 7376 return ExprError(); 7377 } else { 7378 ArgResult = Arg; 7379 } 7380 7381 // For a value-dependent argument, CheckConvertedConstantExpression is 7382 // permitted (and expected) to be unable to determine a value. 7383 if (ArgResult.get()->isValueDependent()) { 7384 SugaredConverted = TemplateArgument(ArgResult.get()); 7385 CanonicalConverted = 7386 Context.getCanonicalTemplateArgument(SugaredConverted); 7387 return ArgResult; 7388 } 7389 7390 APValue PreNarrowingValue; 7391 ArgResult = EvaluateConvertedConstantExpression( 7392 ArgResult.get(), ParamType, Value, CCEK_TemplateArg, /*RequireInt=*/ 7393 false, PreNarrowingValue); 7394 if (ArgResult.isInvalid()) 7395 return ExprError(); 7396 7397 // Convert the APValue to a TemplateArgument. 7398 switch (Value.getKind()) { 7399 case APValue::None: 7400 assert(ParamType->isNullPtrType()); 7401 SugaredConverted = TemplateArgument(ParamType, /*isNullPtr=*/true); 7402 CanonicalConverted = TemplateArgument(CanonParamType, /*isNullPtr=*/true); 7403 break; 7404 case APValue::Indeterminate: 7405 llvm_unreachable("result of constant evaluation should be initialized"); 7406 break; 7407 case APValue::Int: 7408 assert(ParamType->isIntegralOrEnumerationType()); 7409 SugaredConverted = TemplateArgument(Context, Value.getInt(), ParamType); 7410 CanonicalConverted = 7411 TemplateArgument(Context, Value.getInt(), CanonParamType); 7412 break; 7413 case APValue::MemberPointer: { 7414 assert(ParamType->isMemberPointerType()); 7415 7416 // FIXME: We need TemplateArgument representation and mangling for these. 7417 if (!Value.getMemberPointerPath().empty()) { 7418 Diag(Arg->getBeginLoc(), 7419 diag::err_template_arg_member_ptr_base_derived_not_supported) 7420 << Value.getMemberPointerDecl() << ParamType 7421 << Arg->getSourceRange(); 7422 return ExprError(); 7423 } 7424 7425 auto *VD = const_cast<ValueDecl*>(Value.getMemberPointerDecl()); 7426 SugaredConverted = VD ? TemplateArgument(VD, ParamType) 7427 : TemplateArgument(ParamType, /*isNullPtr=*/true); 7428 CanonicalConverted = 7429 VD ? TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()), 7430 CanonParamType) 7431 : TemplateArgument(CanonParamType, /*isNullPtr=*/true); 7432 break; 7433 } 7434 case APValue::LValue: { 7435 // For a non-type template-parameter of pointer or reference type, 7436 // the value of the constant expression shall not refer to 7437 assert(ParamType->isPointerType() || ParamType->isReferenceType() || 7438 ParamType->isNullPtrType()); 7439 // -- a temporary object 7440 // -- a string literal 7441 // -- the result of a typeid expression, or 7442 // -- a predefined __func__ variable 7443 APValue::LValueBase Base = Value.getLValueBase(); 7444 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>()); 7445 if (Base && 7446 (!VD || 7447 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) { 7448 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref) 7449 << Arg->getSourceRange(); 7450 return ExprError(); 7451 } 7452 // -- a subobject 7453 // FIXME: Until C++20 7454 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && 7455 VD && VD->getType()->isArrayType() && 7456 Value.getLValuePath()[0].getAsArrayIndex() == 0 && 7457 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) { 7458 // Per defect report (no number yet): 7459 // ... other than a pointer to the first element of a complete array 7460 // object. 7461 } else if (!Value.hasLValuePath() || Value.getLValuePath().size() || 7462 Value.isLValueOnePastTheEnd()) { 7463 Diag(StartLoc, diag::err_non_type_template_arg_subobject) 7464 << Value.getAsString(Context, ParamType); 7465 return ExprError(); 7466 } 7467 assert((VD || !ParamType->isReferenceType()) && 7468 "null reference should not be a constant expression"); 7469 assert((!VD || !ParamType->isNullPtrType()) && 7470 "non-null value of type nullptr_t?"); 7471 7472 SugaredConverted = VD ? TemplateArgument(VD, ParamType) 7473 : TemplateArgument(ParamType, /*isNullPtr=*/true); 7474 CanonicalConverted = 7475 VD ? TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()), 7476 CanonParamType) 7477 : TemplateArgument(CanonParamType, /*isNullPtr=*/true); 7478 break; 7479 } 7480 case APValue::Struct: 7481 case APValue::Union: { 7482 // Get or create the corresponding template parameter object. 7483 TemplateParamObjectDecl *D = 7484 Context.getTemplateParamObjectDecl(ParamType, Value); 7485 SugaredConverted = TemplateArgument(D, ParamType); 7486 CanonicalConverted = 7487 TemplateArgument(D->getCanonicalDecl(), CanonParamType); 7488 break; 7489 } 7490 case APValue::AddrLabelDiff: 7491 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff); 7492 case APValue::FixedPoint: 7493 case APValue::Float: 7494 case APValue::ComplexInt: 7495 case APValue::ComplexFloat: 7496 case APValue::Vector: 7497 case APValue::Array: 7498 return Diag(StartLoc, diag::err_non_type_template_arg_unsupported) 7499 << ParamType; 7500 } 7501 7502 return ArgResult.get(); 7503 } 7504 7505 // C++ [temp.arg.nontype]p5: 7506 // The following conversions are performed on each expression used 7507 // as a non-type template-argument. If a non-type 7508 // template-argument cannot be converted to the type of the 7509 // corresponding template-parameter then the program is 7510 // ill-formed. 7511 if (ParamType->isIntegralOrEnumerationType()) { 7512 // C++11: 7513 // -- for a non-type template-parameter of integral or 7514 // enumeration type, conversions permitted in a converted 7515 // constant expression are applied. 7516 // 7517 // C++98: 7518 // -- for a non-type template-parameter of integral or 7519 // enumeration type, integral promotions (4.5) and integral 7520 // conversions (4.7) are applied. 7521 7522 if (getLangOpts().CPlusPlus11) { 7523 // C++ [temp.arg.nontype]p1: 7524 // A template-argument for a non-type, non-template template-parameter 7525 // shall be one of: 7526 // 7527 // -- for a non-type template-parameter of integral or enumeration 7528 // type, a converted constant expression of the type of the 7529 // template-parameter; or 7530 llvm::APSInt Value; 7531 ExprResult ArgResult = 7532 CheckConvertedConstantExpression(Arg, ParamType, Value, 7533 CCEK_TemplateArg); 7534 if (ArgResult.isInvalid()) 7535 return ExprError(); 7536 7537 // We can't check arbitrary value-dependent arguments. 7538 if (ArgResult.get()->isValueDependent()) { 7539 SugaredConverted = TemplateArgument(ArgResult.get()); 7540 CanonicalConverted = 7541 Context.getCanonicalTemplateArgument(SugaredConverted); 7542 return ArgResult; 7543 } 7544 7545 // Widen the argument value to sizeof(parameter type). This is almost 7546 // always a no-op, except when the parameter type is bool. In 7547 // that case, this may extend the argument from 1 bit to 8 bits. 7548 QualType IntegerType = ParamType; 7549 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) 7550 IntegerType = Enum->getDecl()->getIntegerType(); 7551 Value = Value.extOrTrunc(IntegerType->isBitIntType() 7552 ? Context.getIntWidth(IntegerType) 7553 : Context.getTypeSize(IntegerType)); 7554 7555 SugaredConverted = TemplateArgument(Context, Value, ParamType); 7556 CanonicalConverted = 7557 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType)); 7558 return ArgResult; 7559 } 7560 7561 ExprResult ArgResult = DefaultLvalueConversion(Arg); 7562 if (ArgResult.isInvalid()) 7563 return ExprError(); 7564 Arg = ArgResult.get(); 7565 7566 QualType ArgType = Arg->getType(); 7567 7568 // C++ [temp.arg.nontype]p1: 7569 // A template-argument for a non-type, non-template 7570 // template-parameter shall be one of: 7571 // 7572 // -- an integral constant-expression of integral or enumeration 7573 // type; or 7574 // -- the name of a non-type template-parameter; or 7575 llvm::APSInt Value; 7576 if (!ArgType->isIntegralOrEnumerationType()) { 7577 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral) 7578 << ArgType << Arg->getSourceRange(); 7579 NoteTemplateParameterLocation(*Param); 7580 return ExprError(); 7581 } else if (!Arg->isValueDependent()) { 7582 class TmplArgICEDiagnoser : public VerifyICEDiagnoser { 7583 QualType T; 7584 7585 public: 7586 TmplArgICEDiagnoser(QualType T) : T(T) { } 7587 7588 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 7589 SourceLocation Loc) override { 7590 return S.Diag(Loc, diag::err_template_arg_not_ice) << T; 7591 } 7592 } Diagnoser(ArgType); 7593 7594 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get(); 7595 if (!Arg) 7596 return ExprError(); 7597 } 7598 7599 // From here on out, all we care about is the unqualified form 7600 // of the argument type. 7601 ArgType = ArgType.getUnqualifiedType(); 7602 7603 // Try to convert the argument to the parameter's type. 7604 if (Context.hasSameType(ParamType, ArgType)) { 7605 // Okay: no conversion necessary 7606 } else if (ParamType->isBooleanType()) { 7607 // This is an integral-to-boolean conversion. 7608 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get(); 7609 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) || 7610 !ParamType->isEnumeralType()) { 7611 // This is an integral promotion or conversion. 7612 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get(); 7613 } else { 7614 // We can't perform this conversion. 7615 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible) 7616 << Arg->getType() << ParamType << Arg->getSourceRange(); 7617 NoteTemplateParameterLocation(*Param); 7618 return ExprError(); 7619 } 7620 7621 // Add the value of this argument to the list of converted 7622 // arguments. We use the bitwidth and signedness of the template 7623 // parameter. 7624 if (Arg->isValueDependent()) { 7625 // The argument is value-dependent. Create a new 7626 // TemplateArgument with the converted expression. 7627 SugaredConverted = TemplateArgument(Arg); 7628 CanonicalConverted = 7629 Context.getCanonicalTemplateArgument(SugaredConverted); 7630 return Arg; 7631 } 7632 7633 QualType IntegerType = ParamType; 7634 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) { 7635 IntegerType = Enum->getDecl()->getIntegerType(); 7636 } 7637 7638 if (ParamType->isBooleanType()) { 7639 // Value must be zero or one. 7640 Value = Value != 0; 7641 unsigned AllowedBits = Context.getTypeSize(IntegerType); 7642 if (Value.getBitWidth() != AllowedBits) 7643 Value = Value.extOrTrunc(AllowedBits); 7644 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType()); 7645 } else { 7646 llvm::APSInt OldValue = Value; 7647 7648 // Coerce the template argument's value to the value it will have 7649 // based on the template parameter's type. 7650 unsigned AllowedBits = IntegerType->isBitIntType() 7651 ? Context.getIntWidth(IntegerType) 7652 : Context.getTypeSize(IntegerType); 7653 if (Value.getBitWidth() != AllowedBits) 7654 Value = Value.extOrTrunc(AllowedBits); 7655 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType()); 7656 7657 // Complain if an unsigned parameter received a negative value. 7658 if (IntegerType->isUnsignedIntegerOrEnumerationType() && 7659 (OldValue.isSigned() && OldValue.isNegative())) { 7660 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative) 7661 << toString(OldValue, 10) << toString(Value, 10) << Param->getType() 7662 << Arg->getSourceRange(); 7663 NoteTemplateParameterLocation(*Param); 7664 } 7665 7666 // Complain if we overflowed the template parameter's type. 7667 unsigned RequiredBits; 7668 if (IntegerType->isUnsignedIntegerOrEnumerationType()) 7669 RequiredBits = OldValue.getActiveBits(); 7670 else if (OldValue.isUnsigned()) 7671 RequiredBits = OldValue.getActiveBits() + 1; 7672 else 7673 RequiredBits = OldValue.getSignificantBits(); 7674 if (RequiredBits > AllowedBits) { 7675 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large) 7676 << toString(OldValue, 10) << toString(Value, 10) << Param->getType() 7677 << Arg->getSourceRange(); 7678 NoteTemplateParameterLocation(*Param); 7679 } 7680 } 7681 7682 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType; 7683 SugaredConverted = TemplateArgument(Context, Value, T); 7684 CanonicalConverted = 7685 TemplateArgument(Context, Value, Context.getCanonicalType(T)); 7686 return Arg; 7687 } 7688 7689 QualType ArgType = Arg->getType(); 7690 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction 7691 7692 // Handle pointer-to-function, reference-to-function, and 7693 // pointer-to-member-function all in (roughly) the same way. 7694 if (// -- For a non-type template-parameter of type pointer to 7695 // function, only the function-to-pointer conversion (4.3) is 7696 // applied. If the template-argument represents a set of 7697 // overloaded functions (or a pointer to such), the matching 7698 // function is selected from the set (13.4). 7699 (ParamType->isPointerType() && 7700 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) || 7701 // -- For a non-type template-parameter of type reference to 7702 // function, no conversions apply. If the template-argument 7703 // represents a set of overloaded functions, the matching 7704 // function is selected from the set (13.4). 7705 (ParamType->isReferenceType() && 7706 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) || 7707 // -- For a non-type template-parameter of type pointer to 7708 // member function, no conversions apply. If the 7709 // template-argument represents a set of overloaded member 7710 // functions, the matching member function is selected from 7711 // the set (13.4). 7712 (ParamType->isMemberPointerType() && 7713 ParamType->castAs<MemberPointerType>()->getPointeeType() 7714 ->isFunctionType())) { 7715 7716 if (Arg->getType() == Context.OverloadTy) { 7717 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType, 7718 true, 7719 FoundResult)) { 7720 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc())) 7721 return ExprError(); 7722 7723 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn); 7724 if (Res.isInvalid()) 7725 return ExprError(); 7726 Arg = Res.get(); 7727 ArgType = Arg->getType(); 7728 } else 7729 return ExprError(); 7730 } 7731 7732 if (!ParamType->isMemberPointerType()) { 7733 if (CheckTemplateArgumentAddressOfObjectOrFunction( 7734 *this, Param, ParamType, Arg, SugaredConverted, 7735 CanonicalConverted)) 7736 return ExprError(); 7737 return Arg; 7738 } 7739 7740 if (CheckTemplateArgumentPointerToMember( 7741 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted)) 7742 return ExprError(); 7743 return Arg; 7744 } 7745 7746 if (ParamType->isPointerType()) { 7747 // -- for a non-type template-parameter of type pointer to 7748 // object, qualification conversions (4.4) and the 7749 // array-to-pointer conversion (4.2) are applied. 7750 // C++0x also allows a value of std::nullptr_t. 7751 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() && 7752 "Only object pointers allowed here"); 7753 7754 if (CheckTemplateArgumentAddressOfObjectOrFunction( 7755 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted)) 7756 return ExprError(); 7757 return Arg; 7758 } 7759 7760 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) { 7761 // -- For a non-type template-parameter of type reference to 7762 // object, no conversions apply. The type referred to by the 7763 // reference may be more cv-qualified than the (otherwise 7764 // identical) type of the template-argument. The 7765 // template-parameter is bound directly to the 7766 // template-argument, which must be an lvalue. 7767 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() && 7768 "Only object references allowed here"); 7769 7770 if (Arg->getType() == Context.OverloadTy) { 7771 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, 7772 ParamRefType->getPointeeType(), 7773 true, 7774 FoundResult)) { 7775 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc())) 7776 return ExprError(); 7777 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn); 7778 if (Res.isInvalid()) 7779 return ExprError(); 7780 Arg = Res.get(); 7781 ArgType = Arg->getType(); 7782 } else 7783 return ExprError(); 7784 } 7785 7786 if (CheckTemplateArgumentAddressOfObjectOrFunction( 7787 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted)) 7788 return ExprError(); 7789 return Arg; 7790 } 7791 7792 // Deal with parameters of type std::nullptr_t. 7793 if (ParamType->isNullPtrType()) { 7794 if (Arg->isTypeDependent() || Arg->isValueDependent()) { 7795 SugaredConverted = TemplateArgument(Arg); 7796 CanonicalConverted = 7797 Context.getCanonicalTemplateArgument(SugaredConverted); 7798 return Arg; 7799 } 7800 7801 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) { 7802 case NPV_NotNullPointer: 7803 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible) 7804 << Arg->getType() << ParamType; 7805 NoteTemplateParameterLocation(*Param); 7806 return ExprError(); 7807 7808 case NPV_Error: 7809 return ExprError(); 7810 7811 case NPV_NullPointer: 7812 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null); 7813 SugaredConverted = TemplateArgument(ParamType, 7814 /*isNullPtr=*/true); 7815 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType), 7816 /*isNullPtr=*/true); 7817 return Arg; 7818 } 7819 } 7820 7821 // -- For a non-type template-parameter of type pointer to data 7822 // member, qualification conversions (4.4) are applied. 7823 assert(ParamType->isMemberPointerType() && "Only pointers to members remain"); 7824 7825 if (CheckTemplateArgumentPointerToMember( 7826 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted)) 7827 return ExprError(); 7828 return Arg; 7829 } 7830 7831 static void DiagnoseTemplateParameterListArityMismatch( 7832 Sema &S, TemplateParameterList *New, TemplateParameterList *Old, 7833 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc); 7834 7835 /// Check a template argument against its corresponding 7836 /// template template parameter. 7837 /// 7838 /// This routine implements the semantics of C++ [temp.arg.template]. 7839 /// It returns true if an error occurred, and false otherwise. 7840 bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, 7841 TemplateParameterList *Params, 7842 TemplateArgumentLoc &Arg) { 7843 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern(); 7844 TemplateDecl *Template = Name.getAsTemplateDecl(); 7845 if (!Template) { 7846 // Any dependent template name is fine. 7847 assert(Name.isDependent() && "Non-dependent template isn't a declaration?"); 7848 return false; 7849 } 7850 7851 if (Template->isInvalidDecl()) 7852 return true; 7853 7854 // C++0x [temp.arg.template]p1: 7855 // A template-argument for a template template-parameter shall be 7856 // the name of a class template or an alias template, expressed as an 7857 // id-expression. When the template-argument names a class template, only 7858 // primary class templates are considered when matching the 7859 // template template argument with the corresponding parameter; 7860 // partial specializations are not considered even if their 7861 // parameter lists match that of the template template parameter. 7862 // 7863 // Note that we also allow template template parameters here, which 7864 // will happen when we are dealing with, e.g., class template 7865 // partial specializations. 7866 if (!isa<ClassTemplateDecl>(Template) && 7867 !isa<TemplateTemplateParmDecl>(Template) && 7868 !isa<TypeAliasTemplateDecl>(Template) && 7869 !isa<BuiltinTemplateDecl>(Template)) { 7870 assert(isa<FunctionTemplateDecl>(Template) && 7871 "Only function templates are possible here"); 7872 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template); 7873 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func) 7874 << Template; 7875 } 7876 7877 // C++1z [temp.arg.template]p3: (DR 150) 7878 // A template-argument matches a template template-parameter P when P 7879 // is at least as specialized as the template-argument A. 7880 // FIXME: We should enable RelaxedTemplateTemplateArgs by default as it is a 7881 // defect report resolution from C++17 and shouldn't be introduced by 7882 // concepts. 7883 if (getLangOpts().RelaxedTemplateTemplateArgs) { 7884 // Quick check for the common case: 7885 // If P contains a parameter pack, then A [...] matches P if each of A's 7886 // template parameters matches the corresponding template parameter in 7887 // the template-parameter-list of P. 7888 if (TemplateParameterListsAreEqual( 7889 Template->getTemplateParameters(), Params, false, 7890 TPL_TemplateTemplateArgumentMatch, Arg.getLocation()) && 7891 // If the argument has no associated constraints, then the parameter is 7892 // definitely at least as specialized as the argument. 7893 // Otherwise - we need a more thorough check. 7894 !Template->hasAssociatedConstraints()) 7895 return false; 7896 7897 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(Params, Template, 7898 Arg.getLocation())) { 7899 // P2113 7900 // C++20[temp.func.order]p2 7901 // [...] If both deductions succeed, the partial ordering selects the 7902 // more constrained template (if one exists) as determined below. 7903 SmallVector<const Expr *, 3> ParamsAC, TemplateAC; 7904 Params->getAssociatedConstraints(ParamsAC); 7905 // C++2a[temp.arg.template]p3 7906 // [...] In this comparison, if P is unconstrained, the constraints on A 7907 // are not considered. 7908 if (ParamsAC.empty()) 7909 return false; 7910 7911 Template->getAssociatedConstraints(TemplateAC); 7912 7913 bool IsParamAtLeastAsConstrained; 7914 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC, 7915 IsParamAtLeastAsConstrained)) 7916 return true; 7917 if (!IsParamAtLeastAsConstrained) { 7918 Diag(Arg.getLocation(), 7919 diag::err_template_template_parameter_not_at_least_as_constrained) 7920 << Template << Param << Arg.getSourceRange(); 7921 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param; 7922 Diag(Template->getLocation(), diag::note_entity_declared_at) 7923 << Template; 7924 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template, 7925 TemplateAC); 7926 return true; 7927 } 7928 return false; 7929 } 7930 // FIXME: Produce better diagnostics for deduction failures. 7931 } 7932 7933 return !TemplateParameterListsAreEqual(Template->getTemplateParameters(), 7934 Params, 7935 true, 7936 TPL_TemplateTemplateArgumentMatch, 7937 Arg.getLocation()); 7938 } 7939 7940 static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl, 7941 unsigned HereDiagID, 7942 unsigned ExternalDiagID) { 7943 if (Decl.getLocation().isValid()) 7944 return S.Diag(Decl.getLocation(), HereDiagID); 7945 7946 SmallString<128> Str; 7947 llvm::raw_svector_ostream Out(Str); 7948 PrintingPolicy PP = S.getPrintingPolicy(); 7949 PP.TerseOutput = 1; 7950 Decl.print(Out, PP); 7951 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str(); 7952 } 7953 7954 void Sema::NoteTemplateLocation(const NamedDecl &Decl, 7955 std::optional<SourceRange> ParamRange) { 7956 SemaDiagnosticBuilder DB = 7957 noteLocation(*this, Decl, diag::note_template_decl_here, 7958 diag::note_template_decl_external); 7959 if (ParamRange && ParamRange->isValid()) { 7960 assert(Decl.getLocation().isValid() && 7961 "Parameter range has location when Decl does not"); 7962 DB << *ParamRange; 7963 } 7964 } 7965 7966 void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) { 7967 noteLocation(*this, Decl, diag::note_template_param_here, 7968 diag::note_template_param_external); 7969 } 7970 7971 /// Given a non-type template argument that refers to a 7972 /// declaration and the type of its corresponding non-type template 7973 /// parameter, produce an expression that properly refers to that 7974 /// declaration. 7975 ExprResult 7976 Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 7977 QualType ParamType, 7978 SourceLocation Loc) { 7979 // C++ [temp.param]p8: 7980 // 7981 // A non-type template-parameter of type "array of T" or 7982 // "function returning T" is adjusted to be of type "pointer to 7983 // T" or "pointer to function returning T", respectively. 7984 if (ParamType->isArrayType()) 7985 ParamType = Context.getArrayDecayedType(ParamType); 7986 else if (ParamType->isFunctionType()) 7987 ParamType = Context.getPointerType(ParamType); 7988 7989 // For a NULL non-type template argument, return nullptr casted to the 7990 // parameter's type. 7991 if (Arg.getKind() == TemplateArgument::NullPtr) { 7992 return ImpCastExprToType( 7993 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc), 7994 ParamType, 7995 ParamType->getAs<MemberPointerType>() 7996 ? CK_NullToMemberPointer 7997 : CK_NullToPointer); 7998 } 7999 assert(Arg.getKind() == TemplateArgument::Declaration && 8000 "Only declaration template arguments permitted here"); 8001 8002 ValueDecl *VD = Arg.getAsDecl(); 8003 8004 CXXScopeSpec SS; 8005 if (ParamType->isMemberPointerType()) { 8006 // If this is a pointer to member, we need to use a qualified name to 8007 // form a suitable pointer-to-member constant. 8008 assert(VD->getDeclContext()->isRecord() && 8009 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) || 8010 isa<IndirectFieldDecl>(VD))); 8011 QualType ClassType 8012 = Context.getTypeDeclType(cast<RecordDecl>(VD->getDeclContext())); 8013 NestedNameSpecifier *Qualifier 8014 = NestedNameSpecifier::Create(Context, nullptr, false, 8015 ClassType.getTypePtr()); 8016 SS.MakeTrivial(Context, Qualifier, Loc); 8017 } 8018 8019 ExprResult RefExpr = BuildDeclarationNameExpr( 8020 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD); 8021 if (RefExpr.isInvalid()) 8022 return ExprError(); 8023 8024 // For a pointer, the argument declaration is the pointee. Take its address. 8025 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0); 8026 if (ParamType->isPointerType() && !ElemT.isNull() && 8027 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) { 8028 // Decay an array argument if we want a pointer to its first element. 8029 RefExpr = DefaultFunctionArrayConversion(RefExpr.get()); 8030 if (RefExpr.isInvalid()) 8031 return ExprError(); 8032 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) { 8033 // For any other pointer, take the address (or form a pointer-to-member). 8034 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get()); 8035 if (RefExpr.isInvalid()) 8036 return ExprError(); 8037 } else if (ParamType->isRecordType()) { 8038 assert(isa<TemplateParamObjectDecl>(VD) && 8039 "arg for class template param not a template parameter object"); 8040 // No conversions apply in this case. 8041 return RefExpr; 8042 } else { 8043 assert(ParamType->isReferenceType() && 8044 "unexpected type for decl template argument"); 8045 } 8046 8047 // At this point we should have the right value category. 8048 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() && 8049 "value kind mismatch for non-type template argument"); 8050 8051 // The type of the template parameter can differ from the type of the 8052 // argument in various ways; convert it now if necessary. 8053 QualType DestExprType = ParamType.getNonLValueExprType(Context); 8054 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) { 8055 CastKind CK; 8056 QualType Ignored; 8057 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) || 8058 IsFunctionConversion(RefExpr.get()->getType(), DestExprType, Ignored)) { 8059 CK = CK_NoOp; 8060 } else if (ParamType->isVoidPointerType() && 8061 RefExpr.get()->getType()->isPointerType()) { 8062 CK = CK_BitCast; 8063 } else { 8064 // FIXME: Pointers to members can need conversion derived-to-base or 8065 // base-to-derived conversions. We currently don't retain enough 8066 // information to convert properly (we need to track a cast path or 8067 // subobject number in the template argument). 8068 llvm_unreachable( 8069 "unexpected conversion required for non-type template argument"); 8070 } 8071 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK, 8072 RefExpr.get()->getValueKind()); 8073 } 8074 8075 return RefExpr; 8076 } 8077 8078 /// Construct a new expression that refers to the given 8079 /// integral template argument with the given source-location 8080 /// information. 8081 /// 8082 /// This routine takes care of the mapping from an integral template 8083 /// argument (which may have any integral type) to the appropriate 8084 /// literal value. 8085 ExprResult 8086 Sema::BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 8087 SourceLocation Loc) { 8088 assert(Arg.getKind() == TemplateArgument::Integral && 8089 "Operation is only valid for integral template arguments"); 8090 QualType OrigT = Arg.getIntegralType(); 8091 8092 // If this is an enum type that we're instantiating, we need to use an integer 8093 // type the same size as the enumerator. We don't want to build an 8094 // IntegerLiteral with enum type. The integer type of an enum type can be of 8095 // any integral type with C++11 enum classes, make sure we create the right 8096 // type of literal for it. 8097 QualType T = OrigT; 8098 if (const EnumType *ET = OrigT->getAs<EnumType>()) 8099 T = ET->getDecl()->getIntegerType(); 8100 8101 Expr *E; 8102 if (T->isAnyCharacterType()) { 8103 CharacterLiteralKind Kind; 8104 if (T->isWideCharType()) 8105 Kind = CharacterLiteralKind::Wide; 8106 else if (T->isChar8Type() && getLangOpts().Char8) 8107 Kind = CharacterLiteralKind::UTF8; 8108 else if (T->isChar16Type()) 8109 Kind = CharacterLiteralKind::UTF16; 8110 else if (T->isChar32Type()) 8111 Kind = CharacterLiteralKind::UTF32; 8112 else 8113 Kind = CharacterLiteralKind::Ascii; 8114 8115 E = new (Context) CharacterLiteral(Arg.getAsIntegral().getZExtValue(), 8116 Kind, T, Loc); 8117 } else if (T->isBooleanType()) { 8118 E = CXXBoolLiteralExpr::Create(Context, Arg.getAsIntegral().getBoolValue(), 8119 T, Loc); 8120 } else if (T->isNullPtrType()) { 8121 E = new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); 8122 } else { 8123 E = IntegerLiteral::Create(Context, Arg.getAsIntegral(), T, Loc); 8124 } 8125 8126 if (OrigT->isEnumeralType()) { 8127 // FIXME: This is a hack. We need a better way to handle substituted 8128 // non-type template parameters. 8129 E = CStyleCastExpr::Create(Context, OrigT, VK_PRValue, CK_IntegralCast, E, 8130 nullptr, CurFPFeatureOverrides(), 8131 Context.getTrivialTypeSourceInfo(OrigT, Loc), 8132 Loc, Loc); 8133 } 8134 8135 return E; 8136 } 8137 8138 /// Match two template parameters within template parameter lists. 8139 static bool MatchTemplateParameterKind( 8140 Sema &S, NamedDecl *New, 8141 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old, 8142 const NamedDecl *OldInstFrom, bool Complain, 8143 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) { 8144 // Check the actual kind (type, non-type, template). 8145 if (Old->getKind() != New->getKind()) { 8146 if (Complain) { 8147 unsigned NextDiag = diag::err_template_param_different_kind; 8148 if (TemplateArgLoc.isValid()) { 8149 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 8150 NextDiag = diag::note_template_param_different_kind; 8151 } 8152 S.Diag(New->getLocation(), NextDiag) 8153 << (Kind != Sema::TPL_TemplateMatch); 8154 S.Diag(Old->getLocation(), diag::note_template_prev_declaration) 8155 << (Kind != Sema::TPL_TemplateMatch); 8156 } 8157 8158 return false; 8159 } 8160 8161 // Check that both are parameter packs or neither are parameter packs. 8162 // However, if we are matching a template template argument to a 8163 // template template parameter, the template template parameter can have 8164 // a parameter pack where the template template argument does not. 8165 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() && 8166 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch && 8167 Old->isTemplateParameterPack())) { 8168 if (Complain) { 8169 unsigned NextDiag = diag::err_template_parameter_pack_non_pack; 8170 if (TemplateArgLoc.isValid()) { 8171 S.Diag(TemplateArgLoc, 8172 diag::err_template_arg_template_params_mismatch); 8173 NextDiag = diag::note_template_parameter_pack_non_pack; 8174 } 8175 8176 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 0 8177 : isa<NonTypeTemplateParmDecl>(New)? 1 8178 : 2; 8179 S.Diag(New->getLocation(), NextDiag) 8180 << ParamKind << New->isParameterPack(); 8181 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here) 8182 << ParamKind << Old->isParameterPack(); 8183 } 8184 8185 return false; 8186 } 8187 8188 // For non-type template parameters, check the type of the parameter. 8189 if (NonTypeTemplateParmDecl *OldNTTP 8190 = dyn_cast<NonTypeTemplateParmDecl>(Old)) { 8191 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New); 8192 8193 // If we are matching a template template argument to a template 8194 // template parameter and one of the non-type template parameter types 8195 // is dependent, then we must wait until template instantiation time 8196 // to actually compare the arguments. 8197 if (Kind != Sema::TPL_TemplateTemplateArgumentMatch || 8198 (!OldNTTP->getType()->isDependentType() && 8199 !NewNTTP->getType()->isDependentType())) { 8200 // C++20 [temp.over.link]p6: 8201 // Two [non-type] template-parameters are equivalent [if] they have 8202 // equivalent types ignoring the use of type-constraints for 8203 // placeholder types 8204 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType()); 8205 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType()); 8206 if (!S.Context.hasSameType(OldType, NewType)) { 8207 if (Complain) { 8208 unsigned NextDiag = diag::err_template_nontype_parm_different_type; 8209 if (TemplateArgLoc.isValid()) { 8210 S.Diag(TemplateArgLoc, 8211 diag::err_template_arg_template_params_mismatch); 8212 NextDiag = diag::note_template_nontype_parm_different_type; 8213 } 8214 S.Diag(NewNTTP->getLocation(), NextDiag) 8215 << NewNTTP->getType() 8216 << (Kind != Sema::TPL_TemplateMatch); 8217 S.Diag(OldNTTP->getLocation(), 8218 diag::note_template_nontype_parm_prev_declaration) 8219 << OldNTTP->getType(); 8220 } 8221 8222 return false; 8223 } 8224 } 8225 } 8226 // For template template parameters, check the template parameter types. 8227 // The template parameter lists of template template 8228 // parameters must agree. 8229 else if (TemplateTemplateParmDecl *OldTTP = 8230 dyn_cast<TemplateTemplateParmDecl>(Old)) { 8231 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New); 8232 if (!S.TemplateParameterListsAreEqual( 8233 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom, 8234 OldTTP->getTemplateParameters(), Complain, 8235 (Kind == Sema::TPL_TemplateMatch 8236 ? Sema::TPL_TemplateTemplateParmMatch 8237 : Kind), 8238 TemplateArgLoc)) 8239 return false; 8240 } 8241 8242 if (Kind != Sema::TPL_TemplateParamsEquivalent && 8243 Kind != Sema::TPL_TemplateTemplateArgumentMatch && 8244 !isa<TemplateTemplateParmDecl>(Old)) { 8245 const Expr *NewC = nullptr, *OldC = nullptr; 8246 8247 if (isa<TemplateTypeParmDecl>(New)) { 8248 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint()) 8249 NewC = TC->getImmediatelyDeclaredConstraint(); 8250 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint()) 8251 OldC = TC->getImmediatelyDeclaredConstraint(); 8252 } else if (isa<NonTypeTemplateParmDecl>(New)) { 8253 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New) 8254 ->getPlaceholderTypeConstraint()) 8255 NewC = E; 8256 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old) 8257 ->getPlaceholderTypeConstraint()) 8258 OldC = E; 8259 } else 8260 llvm_unreachable("unexpected template parameter type"); 8261 8262 auto Diagnose = [&] { 8263 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(), 8264 diag::err_template_different_type_constraint); 8265 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(), 8266 diag::note_template_prev_declaration) << /*declaration*/0; 8267 }; 8268 8269 if (!NewC != !OldC) { 8270 if (Complain) 8271 Diagnose(); 8272 return false; 8273 } 8274 8275 if (NewC) { 8276 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom, 8277 NewC)) { 8278 if (Complain) 8279 Diagnose(); 8280 return false; 8281 } 8282 } 8283 } 8284 8285 return true; 8286 } 8287 8288 /// Diagnose a known arity mismatch when comparing template argument 8289 /// lists. 8290 static 8291 void DiagnoseTemplateParameterListArityMismatch(Sema &S, 8292 TemplateParameterList *New, 8293 TemplateParameterList *Old, 8294 Sema::TemplateParameterListEqualKind Kind, 8295 SourceLocation TemplateArgLoc) { 8296 unsigned NextDiag = diag::err_template_param_list_different_arity; 8297 if (TemplateArgLoc.isValid()) { 8298 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch); 8299 NextDiag = diag::note_template_param_list_different_arity; 8300 } 8301 S.Diag(New->getTemplateLoc(), NextDiag) 8302 << (New->size() > Old->size()) 8303 << (Kind != Sema::TPL_TemplateMatch) 8304 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc()); 8305 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration) 8306 << (Kind != Sema::TPL_TemplateMatch) 8307 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc()); 8308 } 8309 8310 /// Determine whether the given template parameter lists are 8311 /// equivalent. 8312 /// 8313 /// \param New The new template parameter list, typically written in the 8314 /// source code as part of a new template declaration. 8315 /// 8316 /// \param Old The old template parameter list, typically found via 8317 /// name lookup of the template declared with this template parameter 8318 /// list. 8319 /// 8320 /// \param Complain If true, this routine will produce a diagnostic if 8321 /// the template parameter lists are not equivalent. 8322 /// 8323 /// \param Kind describes how we are to match the template parameter lists. 8324 /// 8325 /// \param TemplateArgLoc If this source location is valid, then we 8326 /// are actually checking the template parameter list of a template 8327 /// argument (New) against the template parameter list of its 8328 /// corresponding template template parameter (Old). We produce 8329 /// slightly different diagnostics in this scenario. 8330 /// 8331 /// \returns True if the template parameter lists are equal, false 8332 /// otherwise. 8333 bool Sema::TemplateParameterListsAreEqual( 8334 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, 8335 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, 8336 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) { 8337 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) { 8338 if (Complain) 8339 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 8340 TemplateArgLoc); 8341 8342 return false; 8343 } 8344 8345 // C++0x [temp.arg.template]p3: 8346 // A template-argument matches a template template-parameter (call it P) 8347 // when each of the template parameters in the template-parameter-list of 8348 // the template-argument's corresponding class template or alias template 8349 // (call it A) matches the corresponding template parameter in the 8350 // template-parameter-list of P. [...] 8351 TemplateParameterList::iterator NewParm = New->begin(); 8352 TemplateParameterList::iterator NewParmEnd = New->end(); 8353 for (TemplateParameterList::iterator OldParm = Old->begin(), 8354 OldParmEnd = Old->end(); 8355 OldParm != OldParmEnd; ++OldParm) { 8356 if (Kind != TPL_TemplateTemplateArgumentMatch || 8357 !(*OldParm)->isTemplateParameterPack()) { 8358 if (NewParm == NewParmEnd) { 8359 if (Complain) 8360 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 8361 TemplateArgLoc); 8362 8363 return false; 8364 } 8365 8366 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm, 8367 OldInstFrom, Complain, Kind, 8368 TemplateArgLoc)) 8369 return false; 8370 8371 ++NewParm; 8372 continue; 8373 } 8374 8375 // C++0x [temp.arg.template]p3: 8376 // [...] When P's template- parameter-list contains a template parameter 8377 // pack (14.5.3), the template parameter pack will match zero or more 8378 // template parameters or template parameter packs in the 8379 // template-parameter-list of A with the same type and form as the 8380 // template parameter pack in P (ignoring whether those template 8381 // parameters are template parameter packs). 8382 for (; NewParm != NewParmEnd; ++NewParm) { 8383 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm, 8384 OldInstFrom, Complain, Kind, 8385 TemplateArgLoc)) 8386 return false; 8387 } 8388 } 8389 8390 // Make sure we exhausted all of the arguments. 8391 if (NewParm != NewParmEnd) { 8392 if (Complain) 8393 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind, 8394 TemplateArgLoc); 8395 8396 return false; 8397 } 8398 8399 if (Kind != TPL_TemplateTemplateArgumentMatch && 8400 Kind != TPL_TemplateParamsEquivalent) { 8401 const Expr *NewRC = New->getRequiresClause(); 8402 const Expr *OldRC = Old->getRequiresClause(); 8403 8404 auto Diagnose = [&] { 8405 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(), 8406 diag::err_template_different_requires_clause); 8407 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(), 8408 diag::note_template_prev_declaration) << /*declaration*/0; 8409 }; 8410 8411 if (!NewRC != !OldRC) { 8412 if (Complain) 8413 Diagnose(); 8414 return false; 8415 } 8416 8417 if (NewRC) { 8418 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom, 8419 NewRC)) { 8420 if (Complain) 8421 Diagnose(); 8422 return false; 8423 } 8424 } 8425 } 8426 8427 return true; 8428 } 8429 8430 /// Check whether a template can be declared within this scope. 8431 /// 8432 /// If the template declaration is valid in this scope, returns 8433 /// false. Otherwise, issues a diagnostic and returns true. 8434 bool 8435 Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) { 8436 if (!S) 8437 return false; 8438 8439 // Find the nearest enclosing declaration scope. 8440 while ((S->getFlags() & Scope::DeclScope) == 0 || 8441 (S->getFlags() & Scope::TemplateParamScope) != 0) 8442 S = S->getParent(); 8443 8444 // C++ [temp.pre]p6: [P2096] 8445 // A template, explicit specialization, or partial specialization shall not 8446 // have C linkage. 8447 DeclContext *Ctx = S->getEntity(); 8448 if (Ctx && Ctx->isExternCContext()) { 8449 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage) 8450 << TemplateParams->getSourceRange(); 8451 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext()) 8452 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here); 8453 return true; 8454 } 8455 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr; 8456 8457 // C++ [temp]p2: 8458 // A template-declaration can appear only as a namespace scope or 8459 // class scope declaration. 8460 // C++ [temp.expl.spec]p3: 8461 // An explicit specialization may be declared in any scope in which the 8462 // corresponding primary template may be defined. 8463 // C++ [temp.class.spec]p6: [P2096] 8464 // A partial specialization may be declared in any scope in which the 8465 // corresponding primary template may be defined. 8466 if (Ctx) { 8467 if (Ctx->isFileContext()) 8468 return false; 8469 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) { 8470 // C++ [temp.mem]p2: 8471 // A local class shall not have member templates. 8472 if (RD->isLocalClass()) 8473 return Diag(TemplateParams->getTemplateLoc(), 8474 diag::err_template_inside_local_class) 8475 << TemplateParams->getSourceRange(); 8476 else 8477 return false; 8478 } 8479 } 8480 8481 return Diag(TemplateParams->getTemplateLoc(), 8482 diag::err_template_outside_namespace_or_class_scope) 8483 << TemplateParams->getSourceRange(); 8484 } 8485 8486 /// Determine what kind of template specialization the given declaration 8487 /// is. 8488 static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) { 8489 if (!D) 8490 return TSK_Undeclared; 8491 8492 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) 8493 return Record->getTemplateSpecializationKind(); 8494 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) 8495 return Function->getTemplateSpecializationKind(); 8496 if (VarDecl *Var = dyn_cast<VarDecl>(D)) 8497 return Var->getTemplateSpecializationKind(); 8498 8499 return TSK_Undeclared; 8500 } 8501 8502 /// Check whether a specialization is well-formed in the current 8503 /// context. 8504 /// 8505 /// This routine determines whether a template specialization can be declared 8506 /// in the current context (C++ [temp.expl.spec]p2). 8507 /// 8508 /// \param S the semantic analysis object for which this check is being 8509 /// performed. 8510 /// 8511 /// \param Specialized the entity being specialized or instantiated, which 8512 /// may be a kind of template (class template, function template, etc.) or 8513 /// a member of a class template (member function, static data member, 8514 /// member class). 8515 /// 8516 /// \param PrevDecl the previous declaration of this entity, if any. 8517 /// 8518 /// \param Loc the location of the explicit specialization or instantiation of 8519 /// this entity. 8520 /// 8521 /// \param IsPartialSpecialization whether this is a partial specialization of 8522 /// a class template. 8523 /// 8524 /// \returns true if there was an error that we cannot recover from, false 8525 /// otherwise. 8526 static bool CheckTemplateSpecializationScope(Sema &S, 8527 NamedDecl *Specialized, 8528 NamedDecl *PrevDecl, 8529 SourceLocation Loc, 8530 bool IsPartialSpecialization) { 8531 // Keep these "kind" numbers in sync with the %select statements in the 8532 // various diagnostics emitted by this routine. 8533 int EntityKind = 0; 8534 if (isa<ClassTemplateDecl>(Specialized)) 8535 EntityKind = IsPartialSpecialization? 1 : 0; 8536 else if (isa<VarTemplateDecl>(Specialized)) 8537 EntityKind = IsPartialSpecialization ? 3 : 2; 8538 else if (isa<FunctionTemplateDecl>(Specialized)) 8539 EntityKind = 4; 8540 else if (isa<CXXMethodDecl>(Specialized)) 8541 EntityKind = 5; 8542 else if (isa<VarDecl>(Specialized)) 8543 EntityKind = 6; 8544 else if (isa<RecordDecl>(Specialized)) 8545 EntityKind = 7; 8546 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11) 8547 EntityKind = 8; 8548 else { 8549 S.Diag(Loc, diag::err_template_spec_unknown_kind) 8550 << S.getLangOpts().CPlusPlus11; 8551 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 8552 return true; 8553 } 8554 8555 // C++ [temp.expl.spec]p2: 8556 // An explicit specialization may be declared in any scope in which 8557 // the corresponding primary template may be defined. 8558 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8559 S.Diag(Loc, diag::err_template_spec_decl_function_scope) 8560 << Specialized; 8561 return true; 8562 } 8563 8564 // C++ [temp.class.spec]p6: 8565 // A class template partial specialization may be declared in any 8566 // scope in which the primary template may be defined. 8567 DeclContext *SpecializedContext = 8568 Specialized->getDeclContext()->getRedeclContext(); 8569 DeclContext *DC = S.CurContext->getRedeclContext(); 8570 8571 // Make sure that this redeclaration (or definition) occurs in the same 8572 // scope or an enclosing namespace. 8573 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext) 8574 : DC->Equals(SpecializedContext))) { 8575 if (isa<TranslationUnitDecl>(SpecializedContext)) 8576 S.Diag(Loc, diag::err_template_spec_redecl_global_scope) 8577 << EntityKind << Specialized; 8578 else { 8579 auto *ND = cast<NamedDecl>(SpecializedContext); 8580 int Diag = diag::err_template_spec_redecl_out_of_scope; 8581 if (S.getLangOpts().MicrosoftExt && !DC->isRecord()) 8582 Diag = diag::ext_ms_template_spec_redecl_out_of_scope; 8583 S.Diag(Loc, Diag) << EntityKind << Specialized 8584 << ND << isa<CXXRecordDecl>(ND); 8585 } 8586 8587 S.Diag(Specialized->getLocation(), diag::note_specialized_entity); 8588 8589 // Don't allow specializing in the wrong class during error recovery. 8590 // Otherwise, things can go horribly wrong. 8591 if (DC->isRecord()) 8592 return true; 8593 } 8594 8595 return false; 8596 } 8597 8598 static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) { 8599 if (!E->isTypeDependent()) 8600 return SourceLocation(); 8601 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true); 8602 Checker.TraverseStmt(E); 8603 if (Checker.MatchLoc.isInvalid()) 8604 return E->getSourceRange(); 8605 return Checker.MatchLoc; 8606 } 8607 8608 static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) { 8609 if (!TL.getType()->isDependentType()) 8610 return SourceLocation(); 8611 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true); 8612 Checker.TraverseTypeLoc(TL); 8613 if (Checker.MatchLoc.isInvalid()) 8614 return TL.getSourceRange(); 8615 return Checker.MatchLoc; 8616 } 8617 8618 /// Subroutine of Sema::CheckTemplatePartialSpecializationArgs 8619 /// that checks non-type template partial specialization arguments. 8620 static bool CheckNonTypeTemplatePartialSpecializationArgs( 8621 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param, 8622 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) { 8623 for (unsigned I = 0; I != NumArgs; ++I) { 8624 if (Args[I].getKind() == TemplateArgument::Pack) { 8625 if (CheckNonTypeTemplatePartialSpecializationArgs( 8626 S, TemplateNameLoc, Param, Args[I].pack_begin(), 8627 Args[I].pack_size(), IsDefaultArgument)) 8628 return true; 8629 8630 continue; 8631 } 8632 8633 if (Args[I].getKind() != TemplateArgument::Expression) 8634 continue; 8635 8636 Expr *ArgExpr = Args[I].getAsExpr(); 8637 8638 // We can have a pack expansion of any of the bullets below. 8639 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr)) 8640 ArgExpr = Expansion->getPattern(); 8641 8642 // Strip off any implicit casts we added as part of type checking. 8643 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 8644 ArgExpr = ICE->getSubExpr(); 8645 8646 // C++ [temp.class.spec]p8: 8647 // A non-type argument is non-specialized if it is the name of a 8648 // non-type parameter. All other non-type arguments are 8649 // specialized. 8650 // 8651 // Below, we check the two conditions that only apply to 8652 // specialized non-type arguments, so skip any non-specialized 8653 // arguments. 8654 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr)) 8655 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl())) 8656 continue; 8657 8658 // C++ [temp.class.spec]p9: 8659 // Within the argument list of a class template partial 8660 // specialization, the following restrictions apply: 8661 // -- A partially specialized non-type argument expression 8662 // shall not involve a template parameter of the partial 8663 // specialization except when the argument expression is a 8664 // simple identifier. 8665 // -- The type of a template parameter corresponding to a 8666 // specialized non-type argument shall not be dependent on a 8667 // parameter of the specialization. 8668 // DR1315 removes the first bullet, leaving an incoherent set of rules. 8669 // We implement a compromise between the original rules and DR1315: 8670 // -- A specialized non-type template argument shall not be 8671 // type-dependent and the corresponding template parameter 8672 // shall have a non-dependent type. 8673 SourceRange ParamUseRange = 8674 findTemplateParameterInType(Param->getDepth(), ArgExpr); 8675 if (ParamUseRange.isValid()) { 8676 if (IsDefaultArgument) { 8677 S.Diag(TemplateNameLoc, 8678 diag::err_dependent_non_type_arg_in_partial_spec); 8679 S.Diag(ParamUseRange.getBegin(), 8680 diag::note_dependent_non_type_default_arg_in_partial_spec) 8681 << ParamUseRange; 8682 } else { 8683 S.Diag(ParamUseRange.getBegin(), 8684 diag::err_dependent_non_type_arg_in_partial_spec) 8685 << ParamUseRange; 8686 } 8687 return true; 8688 } 8689 8690 ParamUseRange = findTemplateParameter( 8691 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc()); 8692 if (ParamUseRange.isValid()) { 8693 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(), 8694 diag::err_dependent_typed_non_type_arg_in_partial_spec) 8695 << Param->getType(); 8696 S.NoteTemplateParameterLocation(*Param); 8697 return true; 8698 } 8699 } 8700 8701 return false; 8702 } 8703 8704 /// Check the non-type template arguments of a class template 8705 /// partial specialization according to C++ [temp.class.spec]p9. 8706 /// 8707 /// \param TemplateNameLoc the location of the template name. 8708 /// \param PrimaryTemplate the template parameters of the primary class 8709 /// template. 8710 /// \param NumExplicit the number of explicitly-specified template arguments. 8711 /// \param TemplateArgs the template arguments of the class template 8712 /// partial specialization. 8713 /// 8714 /// \returns \c true if there was an error, \c false otherwise. 8715 bool Sema::CheckTemplatePartialSpecializationArgs( 8716 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate, 8717 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) { 8718 // We have to be conservative when checking a template in a dependent 8719 // context. 8720 if (PrimaryTemplate->getDeclContext()->isDependentContext()) 8721 return false; 8722 8723 TemplateParameterList *TemplateParams = 8724 PrimaryTemplate->getTemplateParameters(); 8725 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 8726 NonTypeTemplateParmDecl *Param 8727 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I)); 8728 if (!Param) 8729 continue; 8730 8731 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc, 8732 Param, &TemplateArgs[I], 8733 1, I >= NumExplicit)) 8734 return true; 8735 } 8736 8737 return false; 8738 } 8739 8740 DeclResult Sema::ActOnClassTemplateSpecialization( 8741 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, 8742 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, 8743 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, 8744 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) { 8745 assert(TUK != TUK_Reference && "References are not specializations"); 8746 8747 // NOTE: KWLoc is the location of the tag keyword. This will instead 8748 // store the location of the outermost template keyword in the declaration. 8749 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0 8750 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc; 8751 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc; 8752 SourceLocation LAngleLoc = TemplateId.LAngleLoc; 8753 SourceLocation RAngleLoc = TemplateId.RAngleLoc; 8754 8755 // Find the class template we're specializing 8756 TemplateName Name = TemplateId.Template.get(); 8757 ClassTemplateDecl *ClassTemplate 8758 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl()); 8759 8760 if (!ClassTemplate) { 8761 Diag(TemplateNameLoc, diag::err_not_class_template_specialization) 8762 << (Name.getAsTemplateDecl() && 8763 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())); 8764 return true; 8765 } 8766 8767 bool isMemberSpecialization = false; 8768 bool isPartialSpecialization = false; 8769 8770 // Check the validity of the template headers that introduce this 8771 // template. 8772 // FIXME: We probably shouldn't complain about these headers for 8773 // friend declarations. 8774 bool Invalid = false; 8775 TemplateParameterList *TemplateParams = 8776 MatchTemplateParametersToScopeSpecifier( 8777 KWLoc, TemplateNameLoc, SS, &TemplateId, 8778 TemplateParameterLists, TUK == TUK_Friend, isMemberSpecialization, 8779 Invalid); 8780 if (Invalid) 8781 return true; 8782 8783 // Check that we can declare a template specialization here. 8784 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams)) 8785 return true; 8786 8787 if (TemplateParams && TemplateParams->size() > 0) { 8788 isPartialSpecialization = true; 8789 8790 if (TUK == TUK_Friend) { 8791 Diag(KWLoc, diag::err_partial_specialization_friend) 8792 << SourceRange(LAngleLoc, RAngleLoc); 8793 return true; 8794 } 8795 8796 // C++ [temp.class.spec]p10: 8797 // The template parameter list of a specialization shall not 8798 // contain default template argument values. 8799 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) { 8800 Decl *Param = TemplateParams->getParam(I); 8801 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) { 8802 if (TTP->hasDefaultArgument()) { 8803 Diag(TTP->getDefaultArgumentLoc(), 8804 diag::err_default_arg_in_partial_spec); 8805 TTP->removeDefaultArgument(); 8806 } 8807 } else if (NonTypeTemplateParmDecl *NTTP 8808 = dyn_cast<NonTypeTemplateParmDecl>(Param)) { 8809 if (Expr *DefArg = NTTP->getDefaultArgument()) { 8810 Diag(NTTP->getDefaultArgumentLoc(), 8811 diag::err_default_arg_in_partial_spec) 8812 << DefArg->getSourceRange(); 8813 NTTP->removeDefaultArgument(); 8814 } 8815 } else { 8816 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param); 8817 if (TTP->hasDefaultArgument()) { 8818 Diag(TTP->getDefaultArgument().getLocation(), 8819 diag::err_default_arg_in_partial_spec) 8820 << TTP->getDefaultArgument().getSourceRange(); 8821 TTP->removeDefaultArgument(); 8822 } 8823 } 8824 } 8825 } else if (TemplateParams) { 8826 if (TUK == TUK_Friend) 8827 Diag(KWLoc, diag::err_template_spec_friend) 8828 << FixItHint::CreateRemoval( 8829 SourceRange(TemplateParams->getTemplateLoc(), 8830 TemplateParams->getRAngleLoc())) 8831 << SourceRange(LAngleLoc, RAngleLoc); 8832 } else { 8833 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl"); 8834 } 8835 8836 // Check that the specialization uses the same tag kind as the 8837 // original template. 8838 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 8839 assert(Kind != TagTypeKind::Enum && 8840 "Invalid enum tag in class template spec!"); 8841 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 8842 Kind, TUK == TUK_Definition, KWLoc, 8843 ClassTemplate->getIdentifier())) { 8844 Diag(KWLoc, diag::err_use_with_wrong_tag) 8845 << ClassTemplate 8846 << FixItHint::CreateReplacement(KWLoc, 8847 ClassTemplate->getTemplatedDecl()->getKindName()); 8848 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 8849 diag::note_previous_use); 8850 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 8851 } 8852 8853 // Translate the parser's template argument list in our AST format. 8854 TemplateArgumentListInfo TemplateArgs = 8855 makeTemplateArgumentListInfo(*this, TemplateId); 8856 8857 // Check for unexpanded parameter packs in any of the template arguments. 8858 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 8859 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I], 8860 isPartialSpecialization 8861 ? UPPC_PartialSpecialization 8862 : UPPC_ExplicitSpecialization)) 8863 return true; 8864 8865 // Check that the template argument list is well-formed for this 8866 // template. 8867 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; 8868 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs, 8869 false, SugaredConverted, CanonicalConverted, 8870 /*UpdateArgsWithConversions=*/true)) 8871 return true; 8872 8873 // Find the class template (partial) specialization declaration that 8874 // corresponds to these arguments. 8875 if (isPartialSpecialization) { 8876 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate, 8877 TemplateArgs.size(), 8878 CanonicalConverted)) 8879 return true; 8880 8881 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we 8882 // also do it during instantiation. 8883 if (!Name.isDependent() && 8884 !TemplateSpecializationType::anyDependentTemplateArguments( 8885 TemplateArgs, CanonicalConverted)) { 8886 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized) 8887 << ClassTemplate->getDeclName(); 8888 isPartialSpecialization = false; 8889 } 8890 } 8891 8892 void *InsertPos = nullptr; 8893 ClassTemplateSpecializationDecl *PrevDecl = nullptr; 8894 8895 if (isPartialSpecialization) 8896 PrevDecl = ClassTemplate->findPartialSpecialization( 8897 CanonicalConverted, TemplateParams, InsertPos); 8898 else 8899 PrevDecl = ClassTemplate->findSpecialization(CanonicalConverted, InsertPos); 8900 8901 ClassTemplateSpecializationDecl *Specialization = nullptr; 8902 8903 // Check whether we can declare a class template specialization in 8904 // the current scope. 8905 if (TUK != TUK_Friend && 8906 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl, 8907 TemplateNameLoc, 8908 isPartialSpecialization)) 8909 return true; 8910 8911 // The canonical type 8912 QualType CanonType; 8913 if (isPartialSpecialization) { 8914 // Build the canonical type that describes the converted template 8915 // arguments of the class template partial specialization. 8916 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); 8917 CanonType = Context.getTemplateSpecializationType(CanonTemplate, 8918 CanonicalConverted); 8919 8920 if (Context.hasSameType(CanonType, 8921 ClassTemplate->getInjectedClassNameSpecialization()) && 8922 (!Context.getLangOpts().CPlusPlus20 || 8923 !TemplateParams->hasAssociatedConstraints())) { 8924 // C++ [temp.class.spec]p9b3: 8925 // 8926 // -- The argument list of the specialization shall not be identical 8927 // to the implicit argument list of the primary template. 8928 // 8929 // This rule has since been removed, because it's redundant given DR1495, 8930 // but we keep it because it produces better diagnostics and recovery. 8931 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template) 8932 << /*class template*/0 << (TUK == TUK_Definition) 8933 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc)); 8934 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS, 8935 ClassTemplate->getIdentifier(), 8936 TemplateNameLoc, 8937 Attr, 8938 TemplateParams, 8939 AS_none, /*ModulePrivateLoc=*/SourceLocation(), 8940 /*FriendLoc*/SourceLocation(), 8941 TemplateParameterLists.size() - 1, 8942 TemplateParameterLists.data()); 8943 } 8944 8945 // Create a new class template partial specialization declaration node. 8946 ClassTemplatePartialSpecializationDecl *PrevPartial 8947 = cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl); 8948 ClassTemplatePartialSpecializationDecl *Partial = 8949 ClassTemplatePartialSpecializationDecl::Create( 8950 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, 8951 TemplateNameLoc, TemplateParams, ClassTemplate, CanonicalConverted, 8952 TemplateArgs, CanonType, PrevPartial); 8953 SetNestedNameSpecifier(*this, Partial, SS); 8954 if (TemplateParameterLists.size() > 1 && SS.isSet()) { 8955 Partial->setTemplateParameterListsInfo( 8956 Context, TemplateParameterLists.drop_back(1)); 8957 } 8958 8959 if (!PrevPartial) 8960 ClassTemplate->AddPartialSpecialization(Partial, InsertPos); 8961 Specialization = Partial; 8962 8963 // If we are providing an explicit specialization of a member class 8964 // template specialization, make a note of that. 8965 if (PrevPartial && PrevPartial->getInstantiatedFromMember()) 8966 PrevPartial->setMemberSpecialization(); 8967 8968 CheckTemplatePartialSpecialization(Partial); 8969 } else { 8970 // Create a new class template specialization declaration node for 8971 // this explicit specialization or friend declaration. 8972 Specialization = ClassTemplateSpecializationDecl::Create( 8973 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc, 8974 ClassTemplate, CanonicalConverted, PrevDecl); 8975 SetNestedNameSpecifier(*this, Specialization, SS); 8976 if (TemplateParameterLists.size() > 0) { 8977 Specialization->setTemplateParameterListsInfo(Context, 8978 TemplateParameterLists); 8979 } 8980 8981 if (!PrevDecl) 8982 ClassTemplate->AddSpecialization(Specialization, InsertPos); 8983 8984 if (CurContext->isDependentContext()) { 8985 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name); 8986 CanonType = Context.getTemplateSpecializationType(CanonTemplate, 8987 CanonicalConverted); 8988 } else { 8989 CanonType = Context.getTypeDeclType(Specialization); 8990 } 8991 } 8992 8993 // C++ [temp.expl.spec]p6: 8994 // If a template, a member template or the member of a class template is 8995 // explicitly specialized then that specialization shall be declared 8996 // before the first use of that specialization that would cause an implicit 8997 // instantiation to take place, in every translation unit in which such a 8998 // use occurs; no diagnostic is required. 8999 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) { 9000 bool Okay = false; 9001 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { 9002 // Is there any previous explicit specialization declaration? 9003 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { 9004 Okay = true; 9005 break; 9006 } 9007 } 9008 9009 if (!Okay) { 9010 SourceRange Range(TemplateNameLoc, RAngleLoc); 9011 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation) 9012 << Context.getTypeDeclType(Specialization) << Range; 9013 9014 Diag(PrevDecl->getPointOfInstantiation(), 9015 diag::note_instantiation_required_here) 9016 << (PrevDecl->getTemplateSpecializationKind() 9017 != TSK_ImplicitInstantiation); 9018 return true; 9019 } 9020 } 9021 9022 // If this is not a friend, note that this is an explicit specialization. 9023 if (TUK != TUK_Friend) 9024 Specialization->setSpecializationKind(TSK_ExplicitSpecialization); 9025 9026 // Check that this isn't a redefinition of this specialization. 9027 if (TUK == TUK_Definition) { 9028 RecordDecl *Def = Specialization->getDefinition(); 9029 NamedDecl *Hidden = nullptr; 9030 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 9031 SkipBody->ShouldSkip = true; 9032 SkipBody->Previous = Def; 9033 makeMergedDefinitionVisible(Hidden); 9034 } else if (Def) { 9035 SourceRange Range(TemplateNameLoc, RAngleLoc); 9036 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range; 9037 Diag(Def->getLocation(), diag::note_previous_definition); 9038 Specialization->setInvalidDecl(); 9039 return true; 9040 } 9041 } 9042 9043 ProcessDeclAttributeList(S, Specialization, Attr); 9044 9045 // Add alignment attributes if necessary; these attributes are checked when 9046 // the ASTContext lays out the structure. 9047 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 9048 AddAlignmentAttributesForRecord(Specialization); 9049 AddMsStructLayoutForRecord(Specialization); 9050 } 9051 9052 if (ModulePrivateLoc.isValid()) 9053 Diag(Specialization->getLocation(), diag::err_module_private_specialization) 9054 << (isPartialSpecialization? 1 : 0) 9055 << FixItHint::CreateRemoval(ModulePrivateLoc); 9056 9057 // Build the fully-sugared type for this class template 9058 // specialization as the user wrote in the specialization 9059 // itself. This means that we'll pretty-print the type retrieved 9060 // from the specialization's declaration the way that the user 9061 // actually wrote the specialization, rather than formatting the 9062 // name based on the "canonical" representation used to store the 9063 // template arguments in the specialization. 9064 TypeSourceInfo *WrittenTy 9065 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc, 9066 TemplateArgs, CanonType); 9067 if (TUK != TUK_Friend) { 9068 Specialization->setTypeAsWritten(WrittenTy); 9069 Specialization->setTemplateKeywordLoc(TemplateKWLoc); 9070 } 9071 9072 // C++ [temp.expl.spec]p9: 9073 // A template explicit specialization is in the scope of the 9074 // namespace in which the template was defined. 9075 // 9076 // We actually implement this paragraph where we set the semantic 9077 // context (in the creation of the ClassTemplateSpecializationDecl), 9078 // but we also maintain the lexical context where the actual 9079 // definition occurs. 9080 Specialization->setLexicalDeclContext(CurContext); 9081 9082 // We may be starting the definition of this specialization. 9083 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 9084 Specialization->startDefinition(); 9085 9086 if (TUK == TUK_Friend) { 9087 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, 9088 TemplateNameLoc, 9089 WrittenTy, 9090 /*FIXME:*/KWLoc); 9091 Friend->setAccess(AS_public); 9092 CurContext->addDecl(Friend); 9093 } else { 9094 // Add the specialization into its lexical context, so that it can 9095 // be seen when iterating through the list of declarations in that 9096 // context. However, specializations are not found by name lookup. 9097 CurContext->addDecl(Specialization); 9098 } 9099 9100 if (SkipBody && SkipBody->ShouldSkip) 9101 return SkipBody->Previous; 9102 9103 return Specialization; 9104 } 9105 9106 Decl *Sema::ActOnTemplateDeclarator(Scope *S, 9107 MultiTemplateParamsArg TemplateParameterLists, 9108 Declarator &D) { 9109 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists); 9110 ActOnDocumentableDecl(NewDecl); 9111 return NewDecl; 9112 } 9113 9114 Decl *Sema::ActOnConceptDefinition(Scope *S, 9115 MultiTemplateParamsArg TemplateParameterLists, 9116 IdentifierInfo *Name, SourceLocation NameLoc, 9117 Expr *ConstraintExpr) { 9118 DeclContext *DC = CurContext; 9119 9120 if (!DC->getRedeclContext()->isFileContext()) { 9121 Diag(NameLoc, 9122 diag::err_concept_decls_may_only_appear_in_global_namespace_scope); 9123 return nullptr; 9124 } 9125 9126 if (TemplateParameterLists.size() > 1) { 9127 Diag(NameLoc, diag::err_concept_extra_headers); 9128 return nullptr; 9129 } 9130 9131 TemplateParameterList *Params = TemplateParameterLists.front(); 9132 9133 if (Params->size() == 0) { 9134 Diag(NameLoc, diag::err_concept_no_parameters); 9135 return nullptr; 9136 } 9137 9138 // Ensure that the parameter pack, if present, is the last parameter in the 9139 // template. 9140 for (TemplateParameterList::const_iterator ParamIt = Params->begin(), 9141 ParamEnd = Params->end(); 9142 ParamIt != ParamEnd; ++ParamIt) { 9143 Decl const *Param = *ParamIt; 9144 if (Param->isParameterPack()) { 9145 if (++ParamIt == ParamEnd) 9146 break; 9147 Diag(Param->getLocation(), 9148 diag::err_template_param_pack_must_be_last_template_parameter); 9149 return nullptr; 9150 } 9151 } 9152 9153 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) 9154 return nullptr; 9155 9156 ConceptDecl *NewDecl = 9157 ConceptDecl::Create(Context, DC, NameLoc, Name, Params, ConstraintExpr); 9158 9159 if (NewDecl->hasAssociatedConstraints()) { 9160 // C++2a [temp.concept]p4: 9161 // A concept shall not have associated constraints. 9162 Diag(NameLoc, diag::err_concept_no_associated_constraints); 9163 NewDecl->setInvalidDecl(); 9164 } 9165 9166 // Check for conflicting previous declaration. 9167 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc); 9168 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 9169 forRedeclarationInCurContext()); 9170 LookupName(Previous, S); 9171 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage=*/false, 9172 /*AllowInlineNamespace*/false); 9173 bool AddToScope = true; 9174 CheckConceptRedefinition(NewDecl, Previous, AddToScope); 9175 9176 ActOnDocumentableDecl(NewDecl); 9177 if (AddToScope) 9178 PushOnScopeChains(NewDecl, S); 9179 return NewDecl; 9180 } 9181 9182 void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl, 9183 LookupResult &Previous, bool &AddToScope) { 9184 AddToScope = true; 9185 9186 if (Previous.empty()) 9187 return; 9188 9189 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl()); 9190 if (!OldConcept) { 9191 auto *Old = Previous.getRepresentativeDecl(); 9192 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind) 9193 << NewDecl->getDeclName(); 9194 notePreviousDefinition(Old, NewDecl->getLocation()); 9195 AddToScope = false; 9196 return; 9197 } 9198 // Check if we can merge with a concept declaration. 9199 bool IsSame = Context.isSameEntity(NewDecl, OldConcept); 9200 if (!IsSame) { 9201 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept) 9202 << NewDecl->getDeclName(); 9203 notePreviousDefinition(OldConcept, NewDecl->getLocation()); 9204 AddToScope = false; 9205 return; 9206 } 9207 if (hasReachableDefinition(OldConcept) && 9208 IsRedefinitionInModule(NewDecl, OldConcept)) { 9209 Diag(NewDecl->getLocation(), diag::err_redefinition) 9210 << NewDecl->getDeclName(); 9211 notePreviousDefinition(OldConcept, NewDecl->getLocation()); 9212 AddToScope = false; 9213 return; 9214 } 9215 if (!Previous.isSingleResult()) { 9216 // FIXME: we should produce an error in case of ambig and failed lookups. 9217 // Other decls (e.g. namespaces) also have this shortcoming. 9218 return; 9219 } 9220 // We unwrap canonical decl late to check for module visibility. 9221 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl()); 9222 } 9223 9224 /// \brief Strips various properties off an implicit instantiation 9225 /// that has just been explicitly specialized. 9226 static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) { 9227 if (MinGW || (isa<FunctionDecl>(D) && 9228 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())) { 9229 D->dropAttr<DLLImportAttr>(); 9230 D->dropAttr<DLLExportAttr>(); 9231 } 9232 9233 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 9234 FD->setInlineSpecified(false); 9235 } 9236 9237 /// Compute the diagnostic location for an explicit instantiation 9238 // declaration or definition. 9239 static SourceLocation DiagLocForExplicitInstantiation( 9240 NamedDecl* D, SourceLocation PointOfInstantiation) { 9241 // Explicit instantiations following a specialization have no effect and 9242 // hence no PointOfInstantiation. In that case, walk decl backwards 9243 // until a valid name loc is found. 9244 SourceLocation PrevDiagLoc = PointOfInstantiation; 9245 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid(); 9246 Prev = Prev->getPreviousDecl()) { 9247 PrevDiagLoc = Prev->getLocation(); 9248 } 9249 assert(PrevDiagLoc.isValid() && 9250 "Explicit instantiation without point of instantiation?"); 9251 return PrevDiagLoc; 9252 } 9253 9254 /// Diagnose cases where we have an explicit template specialization 9255 /// before/after an explicit template instantiation, producing diagnostics 9256 /// for those cases where they are required and determining whether the 9257 /// new specialization/instantiation will have any effect. 9258 /// 9259 /// \param NewLoc the location of the new explicit specialization or 9260 /// instantiation. 9261 /// 9262 /// \param NewTSK the kind of the new explicit specialization or instantiation. 9263 /// 9264 /// \param PrevDecl the previous declaration of the entity. 9265 /// 9266 /// \param PrevTSK the kind of the old explicit specialization or instantiatin. 9267 /// 9268 /// \param PrevPointOfInstantiation if valid, indicates where the previous 9269 /// declaration was instantiated (either implicitly or explicitly). 9270 /// 9271 /// \param HasNoEffect will be set to true to indicate that the new 9272 /// specialization or instantiation has no effect and should be ignored. 9273 /// 9274 /// \returns true if there was an error that should prevent the introduction of 9275 /// the new declaration into the AST, false otherwise. 9276 bool 9277 Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 9278 TemplateSpecializationKind NewTSK, 9279 NamedDecl *PrevDecl, 9280 TemplateSpecializationKind PrevTSK, 9281 SourceLocation PrevPointOfInstantiation, 9282 bool &HasNoEffect) { 9283 HasNoEffect = false; 9284 9285 switch (NewTSK) { 9286 case TSK_Undeclared: 9287 case TSK_ImplicitInstantiation: 9288 assert( 9289 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) && 9290 "previous declaration must be implicit!"); 9291 return false; 9292 9293 case TSK_ExplicitSpecialization: 9294 switch (PrevTSK) { 9295 case TSK_Undeclared: 9296 case TSK_ExplicitSpecialization: 9297 // Okay, we're just specializing something that is either already 9298 // explicitly specialized or has merely been mentioned without any 9299 // instantiation. 9300 return false; 9301 9302 case TSK_ImplicitInstantiation: 9303 if (PrevPointOfInstantiation.isInvalid()) { 9304 // The declaration itself has not actually been instantiated, so it is 9305 // still okay to specialize it. 9306 StripImplicitInstantiation( 9307 PrevDecl, 9308 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()); 9309 return false; 9310 } 9311 // Fall through 9312 [[fallthrough]]; 9313 9314 case TSK_ExplicitInstantiationDeclaration: 9315 case TSK_ExplicitInstantiationDefinition: 9316 assert((PrevTSK == TSK_ImplicitInstantiation || 9317 PrevPointOfInstantiation.isValid()) && 9318 "Explicit instantiation without point of instantiation?"); 9319 9320 // C++ [temp.expl.spec]p6: 9321 // If a template, a member template or the member of a class template 9322 // is explicitly specialized then that specialization shall be declared 9323 // before the first use of that specialization that would cause an 9324 // implicit instantiation to take place, in every translation unit in 9325 // which such a use occurs; no diagnostic is required. 9326 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { 9327 // Is there any previous explicit specialization declaration? 9328 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) 9329 return false; 9330 } 9331 9332 Diag(NewLoc, diag::err_specialization_after_instantiation) 9333 << PrevDecl; 9334 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here) 9335 << (PrevTSK != TSK_ImplicitInstantiation); 9336 9337 return true; 9338 } 9339 llvm_unreachable("The switch over PrevTSK must be exhaustive."); 9340 9341 case TSK_ExplicitInstantiationDeclaration: 9342 switch (PrevTSK) { 9343 case TSK_ExplicitInstantiationDeclaration: 9344 // This explicit instantiation declaration is redundant (that's okay). 9345 HasNoEffect = true; 9346 return false; 9347 9348 case TSK_Undeclared: 9349 case TSK_ImplicitInstantiation: 9350 // We're explicitly instantiating something that may have already been 9351 // implicitly instantiated; that's fine. 9352 return false; 9353 9354 case TSK_ExplicitSpecialization: 9355 // C++0x [temp.explicit]p4: 9356 // For a given set of template parameters, if an explicit instantiation 9357 // of a template appears after a declaration of an explicit 9358 // specialization for that template, the explicit instantiation has no 9359 // effect. 9360 HasNoEffect = true; 9361 return false; 9362 9363 case TSK_ExplicitInstantiationDefinition: 9364 // C++0x [temp.explicit]p10: 9365 // If an entity is the subject of both an explicit instantiation 9366 // declaration and an explicit instantiation definition in the same 9367 // translation unit, the definition shall follow the declaration. 9368 Diag(NewLoc, 9369 diag::err_explicit_instantiation_declaration_after_definition); 9370 9371 // Explicit instantiations following a specialization have no effect and 9372 // hence no PrevPointOfInstantiation. In that case, walk decl backwards 9373 // until a valid name loc is found. 9374 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation), 9375 diag::note_explicit_instantiation_definition_here); 9376 HasNoEffect = true; 9377 return false; 9378 } 9379 llvm_unreachable("Unexpected TemplateSpecializationKind!"); 9380 9381 case TSK_ExplicitInstantiationDefinition: 9382 switch (PrevTSK) { 9383 case TSK_Undeclared: 9384 case TSK_ImplicitInstantiation: 9385 // We're explicitly instantiating something that may have already been 9386 // implicitly instantiated; that's fine. 9387 return false; 9388 9389 case TSK_ExplicitSpecialization: 9390 // C++ DR 259, C++0x [temp.explicit]p4: 9391 // For a given set of template parameters, if an explicit 9392 // instantiation of a template appears after a declaration of 9393 // an explicit specialization for that template, the explicit 9394 // instantiation has no effect. 9395 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization) 9396 << PrevDecl; 9397 Diag(PrevDecl->getLocation(), 9398 diag::note_previous_template_specialization); 9399 HasNoEffect = true; 9400 return false; 9401 9402 case TSK_ExplicitInstantiationDeclaration: 9403 // We're explicitly instantiating a definition for something for which we 9404 // were previously asked to suppress instantiations. That's fine. 9405 9406 // C++0x [temp.explicit]p4: 9407 // For a given set of template parameters, if an explicit instantiation 9408 // of a template appears after a declaration of an explicit 9409 // specialization for that template, the explicit instantiation has no 9410 // effect. 9411 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) { 9412 // Is there any previous explicit specialization declaration? 9413 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) { 9414 HasNoEffect = true; 9415 break; 9416 } 9417 } 9418 9419 return false; 9420 9421 case TSK_ExplicitInstantiationDefinition: 9422 // C++0x [temp.spec]p5: 9423 // For a given template and a given set of template-arguments, 9424 // - an explicit instantiation definition shall appear at most once 9425 // in a program, 9426 9427 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations. 9428 Diag(NewLoc, (getLangOpts().MSVCCompat) 9429 ? diag::ext_explicit_instantiation_duplicate 9430 : diag::err_explicit_instantiation_duplicate) 9431 << PrevDecl; 9432 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation), 9433 diag::note_previous_explicit_instantiation); 9434 HasNoEffect = true; 9435 return false; 9436 } 9437 } 9438 9439 llvm_unreachable("Missing specialization/instantiation case?"); 9440 } 9441 9442 /// Perform semantic analysis for the given dependent function 9443 /// template specialization. 9444 /// 9445 /// The only possible way to get a dependent function template specialization 9446 /// is with a friend declaration, like so: 9447 /// 9448 /// \code 9449 /// template \<class T> void foo(T); 9450 /// template \<class T> class A { 9451 /// friend void foo<>(T); 9452 /// }; 9453 /// \endcode 9454 /// 9455 /// There really isn't any useful analysis we can do here, so we 9456 /// just store the information. 9457 bool Sema::CheckDependentFunctionTemplateSpecialization( 9458 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs, 9459 LookupResult &Previous) { 9460 // Remove anything from Previous that isn't a function template in 9461 // the correct context. 9462 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext(); 9463 LookupResult::Filter F = Previous.makeFilter(); 9464 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing }; 9465 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates; 9466 while (F.hasNext()) { 9467 NamedDecl *D = F.next()->getUnderlyingDecl(); 9468 if (!isa<FunctionTemplateDecl>(D)) { 9469 F.erase(); 9470 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D)); 9471 continue; 9472 } 9473 9474 if (!FDLookupContext->InEnclosingNamespaceSetOf( 9475 D->getDeclContext()->getRedeclContext())) { 9476 F.erase(); 9477 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D)); 9478 continue; 9479 } 9480 } 9481 F.done(); 9482 9483 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None; 9484 if (Previous.empty()) { 9485 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match) 9486 << IsFriend; 9487 for (auto &P : DiscardedCandidates) 9488 Diag(P.second->getLocation(), 9489 diag::note_dependent_function_template_spec_discard_reason) 9490 << P.first << IsFriend; 9491 return true; 9492 } 9493 9494 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(), 9495 ExplicitTemplateArgs); 9496 return false; 9497 } 9498 9499 /// Perform semantic analysis for the given function template 9500 /// specialization. 9501 /// 9502 /// This routine performs all of the semantic analysis required for an 9503 /// explicit function template specialization. On successful completion, 9504 /// the function declaration \p FD will become a function template 9505 /// specialization. 9506 /// 9507 /// \param FD the function declaration, which will be updated to become a 9508 /// function template specialization. 9509 /// 9510 /// \param ExplicitTemplateArgs the explicitly-provided template arguments, 9511 /// if any. Note that this may be valid info even when 0 arguments are 9512 /// explicitly provided as in, e.g., \c void sort<>(char*, char*); 9513 /// as it anyway contains info on the angle brackets locations. 9514 /// 9515 /// \param Previous the set of declarations that may be specialized by 9516 /// this function specialization. 9517 /// 9518 /// \param QualifiedFriend whether this is a lookup for a qualified friend 9519 /// declaration with no explicit template argument list that might be 9520 /// befriending a function template specialization. 9521 bool Sema::CheckFunctionTemplateSpecialization( 9522 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, 9523 LookupResult &Previous, bool QualifiedFriend) { 9524 // The set of function template specializations that could match this 9525 // explicit function template specialization. 9526 UnresolvedSet<8> Candidates; 9527 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(), 9528 /*ForTakingAddress=*/false); 9529 9530 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8> 9531 ConvertedTemplateArgs; 9532 9533 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext(); 9534 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9535 I != E; ++I) { 9536 NamedDecl *Ovl = (*I)->getUnderlyingDecl(); 9537 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) { 9538 // Only consider templates found within the same semantic lookup scope as 9539 // FD. 9540 if (!FDLookupContext->InEnclosingNamespaceSetOf( 9541 Ovl->getDeclContext()->getRedeclContext())) 9542 continue; 9543 9544 // When matching a constexpr member function template specialization 9545 // against the primary template, we don't yet know whether the 9546 // specialization has an implicit 'const' (because we don't know whether 9547 // it will be a static member function until we know which template it 9548 // specializes), so adjust it now assuming it specializes this template. 9549 QualType FT = FD->getType(); 9550 if (FD->isConstexpr()) { 9551 CXXMethodDecl *OldMD = 9552 dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl()); 9553 if (OldMD && OldMD->isConst()) { 9554 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>(); 9555 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9556 EPI.TypeQuals.addConst(); 9557 FT = Context.getFunctionType(FPT->getReturnType(), 9558 FPT->getParamTypes(), EPI); 9559 } 9560 } 9561 9562 TemplateArgumentListInfo Args; 9563 if (ExplicitTemplateArgs) 9564 Args = *ExplicitTemplateArgs; 9565 9566 // C++ [temp.expl.spec]p11: 9567 // A trailing template-argument can be left unspecified in the 9568 // template-id naming an explicit function template specialization 9569 // provided it can be deduced from the function argument type. 9570 // Perform template argument deduction to determine whether we may be 9571 // specializing this template. 9572 // FIXME: It is somewhat wasteful to build 9573 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9574 FunctionDecl *Specialization = nullptr; 9575 if (TemplateDeductionResult TDK = DeduceTemplateArguments( 9576 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()), 9577 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, 9578 Info)) { 9579 // Template argument deduction failed; record why it failed, so 9580 // that we can provide nifty diagnostics. 9581 FailedCandidates.addCandidate().set( 9582 I.getPair(), FunTmpl->getTemplatedDecl(), 9583 MakeDeductionFailureInfo(Context, TDK, Info)); 9584 (void)TDK; 9585 continue; 9586 } 9587 9588 // Target attributes are part of the cuda function signature, so 9589 // the deduced template's cuda target must match that of the 9590 // specialization. Given that C++ template deduction does not 9591 // take target attributes into account, we reject candidates 9592 // here that have a different target. 9593 if (LangOpts.CUDA && 9594 IdentifyCUDATarget(Specialization, 9595 /* IgnoreImplicitHDAttr = */ true) != 9596 IdentifyCUDATarget(FD, /* IgnoreImplicitHDAttr = */ true)) { 9597 FailedCandidates.addCandidate().set( 9598 I.getPair(), FunTmpl->getTemplatedDecl(), 9599 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info)); 9600 continue; 9601 } 9602 9603 // Record this candidate. 9604 if (ExplicitTemplateArgs) 9605 ConvertedTemplateArgs[Specialization] = std::move(Args); 9606 Candidates.addDecl(Specialization, I.getAccess()); 9607 } 9608 } 9609 9610 // For a qualified friend declaration (with no explicit marker to indicate 9611 // that a template specialization was intended), note all (template and 9612 // non-template) candidates. 9613 if (QualifiedFriend && Candidates.empty()) { 9614 Diag(FD->getLocation(), diag::err_qualified_friend_no_match) 9615 << FD->getDeclName() << FDLookupContext; 9616 // FIXME: We should form a single candidate list and diagnose all 9617 // candidates at once, to get proper sorting and limiting. 9618 for (auto *OldND : Previous) { 9619 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl())) 9620 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false); 9621 } 9622 FailedCandidates.NoteCandidates(*this, FD->getLocation()); 9623 return true; 9624 } 9625 9626 // Find the most specialized function template. 9627 UnresolvedSetIterator Result = getMostSpecialized( 9628 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(), 9629 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(), 9630 PDiag(diag::err_function_template_spec_ambiguous) 9631 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr), 9632 PDiag(diag::note_function_template_spec_matched)); 9633 9634 if (Result == Candidates.end()) 9635 return true; 9636 9637 // Ignore access information; it doesn't figure into redeclaration checking. 9638 FunctionDecl *Specialization = cast<FunctionDecl>(*Result); 9639 9640 FunctionTemplateSpecializationInfo *SpecInfo 9641 = Specialization->getTemplateSpecializationInfo(); 9642 assert(SpecInfo && "Function template specialization info missing?"); 9643 9644 // Note: do not overwrite location info if previous template 9645 // specialization kind was explicit. 9646 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind(); 9647 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) { 9648 Specialization->setLocation(FD->getLocation()); 9649 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext()); 9650 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr 9651 // function can differ from the template declaration with respect to 9652 // the constexpr specifier. 9653 // FIXME: We need an update record for this AST mutation. 9654 // FIXME: What if there are multiple such prior declarations (for instance, 9655 // from different modules)? 9656 Specialization->setConstexprKind(FD->getConstexprKind()); 9657 } 9658 9659 // FIXME: Check if the prior specialization has a point of instantiation. 9660 // If so, we have run afoul of . 9661 9662 // If this is a friend declaration, then we're not really declaring 9663 // an explicit specialization. 9664 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None); 9665 9666 // Check the scope of this explicit specialization. 9667 if (!isFriend && 9668 CheckTemplateSpecializationScope(*this, 9669 Specialization->getPrimaryTemplate(), 9670 Specialization, FD->getLocation(), 9671 false)) 9672 return true; 9673 9674 // C++ [temp.expl.spec]p6: 9675 // If a template, a member template or the member of a class template is 9676 // explicitly specialized then that specialization shall be declared 9677 // before the first use of that specialization that would cause an implicit 9678 // instantiation to take place, in every translation unit in which such a 9679 // use occurs; no diagnostic is required. 9680 bool HasNoEffect = false; 9681 if (!isFriend && 9682 CheckSpecializationInstantiationRedecl(FD->getLocation(), 9683 TSK_ExplicitSpecialization, 9684 Specialization, 9685 SpecInfo->getTemplateSpecializationKind(), 9686 SpecInfo->getPointOfInstantiation(), 9687 HasNoEffect)) 9688 return true; 9689 9690 // Mark the prior declaration as an explicit specialization, so that later 9691 // clients know that this is an explicit specialization. 9692 if (!isFriend) { 9693 // Since explicit specializations do not inherit '=delete' from their 9694 // primary function template - check if the 'specialization' that was 9695 // implicitly generated (during template argument deduction for partial 9696 // ordering) from the most specialized of all the function templates that 9697 // 'FD' could have been specializing, has a 'deleted' definition. If so, 9698 // first check that it was implicitly generated during template argument 9699 // deduction by making sure it wasn't referenced, and then reset the deleted 9700 // flag to not-deleted, so that we can inherit that information from 'FD'. 9701 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() && 9702 !Specialization->getCanonicalDecl()->isReferenced()) { 9703 // FIXME: This assert will not hold in the presence of modules. 9704 assert( 9705 Specialization->getCanonicalDecl() == Specialization && 9706 "This must be the only existing declaration of this specialization"); 9707 // FIXME: We need an update record for this AST mutation. 9708 Specialization->setDeletedAsWritten(false); 9709 } 9710 // FIXME: We need an update record for this AST mutation. 9711 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization); 9712 MarkUnusedFileScopedDecl(Specialization); 9713 } 9714 9715 // Turn the given function declaration into a function template 9716 // specialization, with the template arguments from the previous 9717 // specialization. 9718 // Take copies of (semantic and syntactic) template argument lists. 9719 const TemplateArgumentList* TemplArgs = new (Context) 9720 TemplateArgumentList(Specialization->getTemplateSpecializationArgs()); 9721 FD->setFunctionTemplateSpecialization( 9722 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr, 9723 SpecInfo->getTemplateSpecializationKind(), 9724 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr); 9725 9726 // A function template specialization inherits the target attributes 9727 // of its template. (We require the attributes explicitly in the 9728 // code to match, but a template may have implicit attributes by 9729 // virtue e.g. of being constexpr, and it passes these implicit 9730 // attributes on to its specializations.) 9731 if (LangOpts.CUDA) 9732 inheritCUDATargetAttrs(FD, *Specialization->getPrimaryTemplate()); 9733 9734 // The "previous declaration" for this function template specialization is 9735 // the prior function template specialization. 9736 Previous.clear(); 9737 Previous.addDecl(Specialization); 9738 return false; 9739 } 9740 9741 /// Perform semantic analysis for the given non-template member 9742 /// specialization. 9743 /// 9744 /// This routine performs all of the semantic analysis required for an 9745 /// explicit member function specialization. On successful completion, 9746 /// the function declaration \p FD will become a member function 9747 /// specialization. 9748 /// 9749 /// \param Member the member declaration, which will be updated to become a 9750 /// specialization. 9751 /// 9752 /// \param Previous the set of declarations, one of which may be specialized 9753 /// by this function specialization; the set will be modified to contain the 9754 /// redeclared member. 9755 bool 9756 Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) { 9757 assert(!isa<TemplateDecl>(Member) && "Only for non-template members"); 9758 9759 // Try to find the member we are instantiating. 9760 NamedDecl *FoundInstantiation = nullptr; 9761 NamedDecl *Instantiation = nullptr; 9762 NamedDecl *InstantiatedFrom = nullptr; 9763 MemberSpecializationInfo *MSInfo = nullptr; 9764 9765 if (Previous.empty()) { 9766 // Nowhere to look anyway. 9767 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) { 9768 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 9769 I != E; ++I) { 9770 NamedDecl *D = (*I)->getUnderlyingDecl(); 9771 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { 9772 QualType Adjusted = Function->getType(); 9773 if (!hasExplicitCallingConv(Adjusted)) 9774 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType()); 9775 // This doesn't handle deduced return types, but both function 9776 // declarations should be undeduced at this point. 9777 if (Context.hasSameType(Adjusted, Method->getType())) { 9778 FoundInstantiation = *I; 9779 Instantiation = Method; 9780 InstantiatedFrom = Method->getInstantiatedFromMemberFunction(); 9781 MSInfo = Method->getMemberSpecializationInfo(); 9782 break; 9783 } 9784 } 9785 } 9786 } else if (isa<VarDecl>(Member)) { 9787 VarDecl *PrevVar; 9788 if (Previous.isSingleResult() && 9789 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl()))) 9790 if (PrevVar->isStaticDataMember()) { 9791 FoundInstantiation = Previous.getRepresentativeDecl(); 9792 Instantiation = PrevVar; 9793 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember(); 9794 MSInfo = PrevVar->getMemberSpecializationInfo(); 9795 } 9796 } else if (isa<RecordDecl>(Member)) { 9797 CXXRecordDecl *PrevRecord; 9798 if (Previous.isSingleResult() && 9799 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) { 9800 FoundInstantiation = Previous.getRepresentativeDecl(); 9801 Instantiation = PrevRecord; 9802 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass(); 9803 MSInfo = PrevRecord->getMemberSpecializationInfo(); 9804 } 9805 } else if (isa<EnumDecl>(Member)) { 9806 EnumDecl *PrevEnum; 9807 if (Previous.isSingleResult() && 9808 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) { 9809 FoundInstantiation = Previous.getRepresentativeDecl(); 9810 Instantiation = PrevEnum; 9811 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum(); 9812 MSInfo = PrevEnum->getMemberSpecializationInfo(); 9813 } 9814 } 9815 9816 if (!Instantiation) { 9817 // There is no previous declaration that matches. Since member 9818 // specializations are always out-of-line, the caller will complain about 9819 // this mismatch later. 9820 return false; 9821 } 9822 9823 // A member specialization in a friend declaration isn't really declaring 9824 // an explicit specialization, just identifying a specific (possibly implicit) 9825 // specialization. Don't change the template specialization kind. 9826 // 9827 // FIXME: Is this really valid? Other compilers reject. 9828 if (Member->getFriendObjectKind() != Decl::FOK_None) { 9829 // Preserve instantiation information. 9830 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) { 9831 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction( 9832 cast<CXXMethodDecl>(InstantiatedFrom), 9833 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind()); 9834 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) { 9835 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass( 9836 cast<CXXRecordDecl>(InstantiatedFrom), 9837 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind()); 9838 } 9839 9840 Previous.clear(); 9841 Previous.addDecl(FoundInstantiation); 9842 return false; 9843 } 9844 9845 // Make sure that this is a specialization of a member. 9846 if (!InstantiatedFrom) { 9847 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated) 9848 << Member; 9849 Diag(Instantiation->getLocation(), diag::note_specialized_decl); 9850 return true; 9851 } 9852 9853 // C++ [temp.expl.spec]p6: 9854 // If a template, a member template or the member of a class template is 9855 // explicitly specialized then that specialization shall be declared 9856 // before the first use of that specialization that would cause an implicit 9857 // instantiation to take place, in every translation unit in which such a 9858 // use occurs; no diagnostic is required. 9859 assert(MSInfo && "Member specialization info missing?"); 9860 9861 bool HasNoEffect = false; 9862 if (CheckSpecializationInstantiationRedecl(Member->getLocation(), 9863 TSK_ExplicitSpecialization, 9864 Instantiation, 9865 MSInfo->getTemplateSpecializationKind(), 9866 MSInfo->getPointOfInstantiation(), 9867 HasNoEffect)) 9868 return true; 9869 9870 // Check the scope of this explicit specialization. 9871 if (CheckTemplateSpecializationScope(*this, 9872 InstantiatedFrom, 9873 Instantiation, Member->getLocation(), 9874 false)) 9875 return true; 9876 9877 // Note that this member specialization is an "instantiation of" the 9878 // corresponding member of the original template. 9879 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) { 9880 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation); 9881 if (InstantiationFunction->getTemplateSpecializationKind() == 9882 TSK_ImplicitInstantiation) { 9883 // Explicit specializations of member functions of class templates do not 9884 // inherit '=delete' from the member function they are specializing. 9885 if (InstantiationFunction->isDeleted()) { 9886 // FIXME: This assert will not hold in the presence of modules. 9887 assert(InstantiationFunction->getCanonicalDecl() == 9888 InstantiationFunction); 9889 // FIXME: We need an update record for this AST mutation. 9890 InstantiationFunction->setDeletedAsWritten(false); 9891 } 9892 } 9893 9894 MemberFunction->setInstantiationOfMemberFunction( 9895 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); 9896 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) { 9897 MemberVar->setInstantiationOfStaticDataMember( 9898 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); 9899 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) { 9900 MemberClass->setInstantiationOfMemberClass( 9901 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); 9902 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) { 9903 MemberEnum->setInstantiationOfMemberEnum( 9904 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization); 9905 } else { 9906 llvm_unreachable("unknown member specialization kind"); 9907 } 9908 9909 // Save the caller the trouble of having to figure out which declaration 9910 // this specialization matches. 9911 Previous.clear(); 9912 Previous.addDecl(FoundInstantiation); 9913 return false; 9914 } 9915 9916 /// Complete the explicit specialization of a member of a class template by 9917 /// updating the instantiated member to be marked as an explicit specialization. 9918 /// 9919 /// \param OrigD The member declaration instantiated from the template. 9920 /// \param Loc The location of the explicit specialization of the member. 9921 template<typename DeclT> 9922 static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD, 9923 SourceLocation Loc) { 9924 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation) 9925 return; 9926 9927 // FIXME: Inform AST mutation listeners of this AST mutation. 9928 // FIXME: If there are multiple in-class declarations of the member (from 9929 // multiple modules, or a declaration and later definition of a member type), 9930 // should we update all of them? 9931 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization); 9932 OrigD->setLocation(Loc); 9933 } 9934 9935 void Sema::CompleteMemberSpecialization(NamedDecl *Member, 9936 LookupResult &Previous) { 9937 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl()); 9938 if (Instantiation == Member) 9939 return; 9940 9941 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation)) 9942 completeMemberSpecializationImpl(*this, Function, Member->getLocation()); 9943 else if (auto *Var = dyn_cast<VarDecl>(Instantiation)) 9944 completeMemberSpecializationImpl(*this, Var, Member->getLocation()); 9945 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation)) 9946 completeMemberSpecializationImpl(*this, Record, Member->getLocation()); 9947 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation)) 9948 completeMemberSpecializationImpl(*this, Enum, Member->getLocation()); 9949 else 9950 llvm_unreachable("unknown member specialization kind"); 9951 } 9952 9953 /// Check the scope of an explicit instantiation. 9954 /// 9955 /// \returns true if a serious error occurs, false otherwise. 9956 static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D, 9957 SourceLocation InstLoc, 9958 bool WasQualifiedName) { 9959 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext(); 9960 DeclContext *CurContext = S.CurContext->getRedeclContext(); 9961 9962 if (CurContext->isRecord()) { 9963 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class) 9964 << D; 9965 return true; 9966 } 9967 9968 // C++11 [temp.explicit]p3: 9969 // An explicit instantiation shall appear in an enclosing namespace of its 9970 // template. If the name declared in the explicit instantiation is an 9971 // unqualified name, the explicit instantiation shall appear in the 9972 // namespace where its template is declared or, if that namespace is inline 9973 // (7.3.1), any namespace from its enclosing namespace set. 9974 // 9975 // This is DR275, which we do not retroactively apply to C++98/03. 9976 if (WasQualifiedName) { 9977 if (CurContext->Encloses(OrigContext)) 9978 return false; 9979 } else { 9980 if (CurContext->InEnclosingNamespaceSetOf(OrigContext)) 9981 return false; 9982 } 9983 9984 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) { 9985 if (WasQualifiedName) 9986 S.Diag(InstLoc, 9987 S.getLangOpts().CPlusPlus11? 9988 diag::err_explicit_instantiation_out_of_scope : 9989 diag::warn_explicit_instantiation_out_of_scope_0x) 9990 << D << NS; 9991 else 9992 S.Diag(InstLoc, 9993 S.getLangOpts().CPlusPlus11? 9994 diag::err_explicit_instantiation_unqualified_wrong_namespace : 9995 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x) 9996 << D << NS; 9997 } else 9998 S.Diag(InstLoc, 9999 S.getLangOpts().CPlusPlus11? 10000 diag::err_explicit_instantiation_must_be_global : 10001 diag::warn_explicit_instantiation_must_be_global_0x) 10002 << D; 10003 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here); 10004 return false; 10005 } 10006 10007 /// Common checks for whether an explicit instantiation of \p D is valid. 10008 static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D, 10009 SourceLocation InstLoc, 10010 bool WasQualifiedName, 10011 TemplateSpecializationKind TSK) { 10012 // C++ [temp.explicit]p13: 10013 // An explicit instantiation declaration shall not name a specialization of 10014 // a template with internal linkage. 10015 if (TSK == TSK_ExplicitInstantiationDeclaration && 10016 D->getFormalLinkage() == Linkage::Internal) { 10017 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D; 10018 return true; 10019 } 10020 10021 // C++11 [temp.explicit]p3: [DR 275] 10022 // An explicit instantiation shall appear in an enclosing namespace of its 10023 // template. 10024 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName)) 10025 return true; 10026 10027 return false; 10028 } 10029 10030 /// Determine whether the given scope specifier has a template-id in it. 10031 static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) { 10032 if (!SS.isSet()) 10033 return false; 10034 10035 // C++11 [temp.explicit]p3: 10036 // If the explicit instantiation is for a member function, a member class 10037 // or a static data member of a class template specialization, the name of 10038 // the class template specialization in the qualified-id for the member 10039 // name shall be a simple-template-id. 10040 // 10041 // C++98 has the same restriction, just worded differently. 10042 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS; 10043 NNS = NNS->getPrefix()) 10044 if (const Type *T = NNS->getAsType()) 10045 if (isa<TemplateSpecializationType>(T)) 10046 return true; 10047 10048 return false; 10049 } 10050 10051 /// Make a dllexport or dllimport attr on a class template specialization take 10052 /// effect. 10053 static void dllExportImportClassTemplateSpecialization( 10054 Sema &S, ClassTemplateSpecializationDecl *Def) { 10055 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def)); 10056 assert(A && "dllExportImportClassTemplateSpecialization called " 10057 "on Def without dllexport or dllimport"); 10058 10059 // We reject explicit instantiations in class scope, so there should 10060 // never be any delayed exported classes to worry about. 10061 assert(S.DelayedDllExportClasses.empty() && 10062 "delayed exports present at explicit instantiation"); 10063 S.checkClassLevelDLLAttribute(Def); 10064 10065 // Propagate attribute to base class templates. 10066 for (auto &B : Def->bases()) { 10067 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>( 10068 B.getType()->getAsCXXRecordDecl())) 10069 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc()); 10070 } 10071 10072 S.referenceDLLExportedClassMethods(); 10073 } 10074 10075 // Explicit instantiation of a class template specialization 10076 DeclResult Sema::ActOnExplicitInstantiation( 10077 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, 10078 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, 10079 TemplateTy TemplateD, SourceLocation TemplateNameLoc, 10080 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, 10081 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) { 10082 // Find the class template we're specializing 10083 TemplateName Name = TemplateD.get(); 10084 TemplateDecl *TD = Name.getAsTemplateDecl(); 10085 // Check that the specialization uses the same tag kind as the 10086 // original template. 10087 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10088 assert(Kind != TagTypeKind::Enum && 10089 "Invalid enum tag in class template explicit instantiation!"); 10090 10091 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD); 10092 10093 if (!ClassTemplate) { 10094 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind); 10095 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) 10096 << TD << NTK << llvm::to_underlying(Kind); 10097 Diag(TD->getLocation(), diag::note_previous_use); 10098 return true; 10099 } 10100 10101 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), 10102 Kind, /*isDefinition*/false, KWLoc, 10103 ClassTemplate->getIdentifier())) { 10104 Diag(KWLoc, diag::err_use_with_wrong_tag) 10105 << ClassTemplate 10106 << FixItHint::CreateReplacement(KWLoc, 10107 ClassTemplate->getTemplatedDecl()->getKindName()); 10108 Diag(ClassTemplate->getTemplatedDecl()->getLocation(), 10109 diag::note_previous_use); 10110 Kind = ClassTemplate->getTemplatedDecl()->getTagKind(); 10111 } 10112 10113 // C++0x [temp.explicit]p2: 10114 // There are two forms of explicit instantiation: an explicit instantiation 10115 // definition and an explicit instantiation declaration. An explicit 10116 // instantiation declaration begins with the extern keyword. [...] 10117 TemplateSpecializationKind TSK = ExternLoc.isInvalid() 10118 ? TSK_ExplicitInstantiationDefinition 10119 : TSK_ExplicitInstantiationDeclaration; 10120 10121 if (TSK == TSK_ExplicitInstantiationDeclaration && 10122 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 10123 // Check for dllexport class template instantiation declarations, 10124 // except for MinGW mode. 10125 for (const ParsedAttr &AL : Attr) { 10126 if (AL.getKind() == ParsedAttr::AT_DLLExport) { 10127 Diag(ExternLoc, 10128 diag::warn_attribute_dllexport_explicit_instantiation_decl); 10129 Diag(AL.getLoc(), diag::note_attribute); 10130 break; 10131 } 10132 } 10133 10134 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) { 10135 Diag(ExternLoc, 10136 diag::warn_attribute_dllexport_explicit_instantiation_decl); 10137 Diag(A->getLocation(), diag::note_attribute); 10138 } 10139 } 10140 10141 // In MSVC mode, dllimported explicit instantiation definitions are treated as 10142 // instantiation declarations for most purposes. 10143 bool DLLImportExplicitInstantiationDef = false; 10144 if (TSK == TSK_ExplicitInstantiationDefinition && 10145 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 10146 // Check for dllimport class template instantiation definitions. 10147 bool DLLImport = 10148 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>(); 10149 for (const ParsedAttr &AL : Attr) { 10150 if (AL.getKind() == ParsedAttr::AT_DLLImport) 10151 DLLImport = true; 10152 if (AL.getKind() == ParsedAttr::AT_DLLExport) { 10153 // dllexport trumps dllimport here. 10154 DLLImport = false; 10155 break; 10156 } 10157 } 10158 if (DLLImport) { 10159 TSK = TSK_ExplicitInstantiationDeclaration; 10160 DLLImportExplicitInstantiationDef = true; 10161 } 10162 } 10163 10164 // Translate the parser's template argument list in our AST format. 10165 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 10166 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 10167 10168 // Check that the template argument list is well-formed for this 10169 // template. 10170 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; 10171 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs, 10172 false, SugaredConverted, CanonicalConverted, 10173 /*UpdateArgsWithConversions=*/true)) 10174 return true; 10175 10176 // Find the class template specialization declaration that 10177 // corresponds to these arguments. 10178 void *InsertPos = nullptr; 10179 ClassTemplateSpecializationDecl *PrevDecl = 10180 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos); 10181 10182 TemplateSpecializationKind PrevDecl_TSK 10183 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared; 10184 10185 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr && 10186 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) { 10187 // Check for dllexport class template instantiation definitions in MinGW 10188 // mode, if a previous declaration of the instantiation was seen. 10189 for (const ParsedAttr &AL : Attr) { 10190 if (AL.getKind() == ParsedAttr::AT_DLLExport) { 10191 Diag(AL.getLoc(), 10192 diag::warn_attribute_dllexport_explicit_instantiation_def); 10193 break; 10194 } 10195 } 10196 } 10197 10198 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc, 10199 SS.isSet(), TSK)) 10200 return true; 10201 10202 ClassTemplateSpecializationDecl *Specialization = nullptr; 10203 10204 bool HasNoEffect = false; 10205 if (PrevDecl) { 10206 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK, 10207 PrevDecl, PrevDecl_TSK, 10208 PrevDecl->getPointOfInstantiation(), 10209 HasNoEffect)) 10210 return PrevDecl; 10211 10212 // Even though HasNoEffect == true means that this explicit instantiation 10213 // has no effect on semantics, we go on to put its syntax in the AST. 10214 10215 if (PrevDecl_TSK == TSK_ImplicitInstantiation || 10216 PrevDecl_TSK == TSK_Undeclared) { 10217 // Since the only prior class template specialization with these 10218 // arguments was referenced but not declared, reuse that 10219 // declaration node as our own, updating the source location 10220 // for the template name to reflect our new declaration. 10221 // (Other source locations will be updated later.) 10222 Specialization = PrevDecl; 10223 Specialization->setLocation(TemplateNameLoc); 10224 PrevDecl = nullptr; 10225 } 10226 10227 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration && 10228 DLLImportExplicitInstantiationDef) { 10229 // The new specialization might add a dllimport attribute. 10230 HasNoEffect = false; 10231 } 10232 } 10233 10234 if (!Specialization) { 10235 // Create a new class template specialization declaration node for 10236 // this explicit specialization. 10237 Specialization = ClassTemplateSpecializationDecl::Create( 10238 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc, 10239 ClassTemplate, CanonicalConverted, PrevDecl); 10240 SetNestedNameSpecifier(*this, Specialization, SS); 10241 10242 // A MSInheritanceAttr attached to the previous declaration must be 10243 // propagated to the new node prior to instantiation. 10244 if (PrevDecl) { 10245 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) { 10246 auto *Clone = A->clone(getASTContext()); 10247 Clone->setInherited(true); 10248 Specialization->addAttr(Clone); 10249 Consumer.AssignInheritanceModel(Specialization); 10250 } 10251 } 10252 10253 if (!HasNoEffect && !PrevDecl) { 10254 // Insert the new specialization. 10255 ClassTemplate->AddSpecialization(Specialization, InsertPos); 10256 } 10257 } 10258 10259 // Build the fully-sugared type for this explicit instantiation as 10260 // the user wrote in the explicit instantiation itself. This means 10261 // that we'll pretty-print the type retrieved from the 10262 // specialization's declaration the way that the user actually wrote 10263 // the explicit instantiation, rather than formatting the name based 10264 // on the "canonical" representation used to store the template 10265 // arguments in the specialization. 10266 TypeSourceInfo *WrittenTy 10267 = Context.getTemplateSpecializationTypeInfo(Name, TemplateNameLoc, 10268 TemplateArgs, 10269 Context.getTypeDeclType(Specialization)); 10270 Specialization->setTypeAsWritten(WrittenTy); 10271 10272 // Set source locations for keywords. 10273 Specialization->setExternLoc(ExternLoc); 10274 Specialization->setTemplateKeywordLoc(TemplateLoc); 10275 Specialization->setBraceRange(SourceRange()); 10276 10277 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>(); 10278 ProcessDeclAttributeList(S, Specialization, Attr); 10279 10280 // Add the explicit instantiation into its lexical context. However, 10281 // since explicit instantiations are never found by name lookup, we 10282 // just put it into the declaration context directly. 10283 Specialization->setLexicalDeclContext(CurContext); 10284 CurContext->addDecl(Specialization); 10285 10286 // Syntax is now OK, so return if it has no other effect on semantics. 10287 if (HasNoEffect) { 10288 // Set the template specialization kind. 10289 Specialization->setTemplateSpecializationKind(TSK); 10290 return Specialization; 10291 } 10292 10293 // C++ [temp.explicit]p3: 10294 // A definition of a class template or class member template 10295 // shall be in scope at the point of the explicit instantiation of 10296 // the class template or class member template. 10297 // 10298 // This check comes when we actually try to perform the 10299 // instantiation. 10300 ClassTemplateSpecializationDecl *Def 10301 = cast_or_null<ClassTemplateSpecializationDecl>( 10302 Specialization->getDefinition()); 10303 if (!Def) 10304 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK); 10305 else if (TSK == TSK_ExplicitInstantiationDefinition) { 10306 MarkVTableUsed(TemplateNameLoc, Specialization, true); 10307 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation()); 10308 } 10309 10310 // Instantiate the members of this class template specialization. 10311 Def = cast_or_null<ClassTemplateSpecializationDecl>( 10312 Specialization->getDefinition()); 10313 if (Def) { 10314 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind(); 10315 // Fix a TSK_ExplicitInstantiationDeclaration followed by a 10316 // TSK_ExplicitInstantiationDefinition 10317 if (Old_TSK == TSK_ExplicitInstantiationDeclaration && 10318 (TSK == TSK_ExplicitInstantiationDefinition || 10319 DLLImportExplicitInstantiationDef)) { 10320 // FIXME: Need to notify the ASTMutationListener that we did this. 10321 Def->setTemplateSpecializationKind(TSK); 10322 10323 if (!getDLLAttr(Def) && getDLLAttr(Specialization) && 10324 (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 10325 !Context.getTargetInfo().getTriple().isPS())) { 10326 // An explicit instantiation definition can add a dll attribute to a 10327 // template with a previous instantiation declaration. MinGW doesn't 10328 // allow this. 10329 auto *A = cast<InheritableAttr>( 10330 getDLLAttr(Specialization)->clone(getASTContext())); 10331 A->setInherited(true); 10332 Def->addAttr(A); 10333 dllExportImportClassTemplateSpecialization(*this, Def); 10334 } 10335 } 10336 10337 // Fix a TSK_ImplicitInstantiation followed by a 10338 // TSK_ExplicitInstantiationDefinition 10339 bool NewlyDLLExported = 10340 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>(); 10341 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported && 10342 (Context.getTargetInfo().shouldDLLImportComdatSymbols() && 10343 !Context.getTargetInfo().getTriple().isPS())) { 10344 // An explicit instantiation definition can add a dll attribute to a 10345 // template with a previous implicit instantiation. MinGW doesn't allow 10346 // this. We limit clang to only adding dllexport, to avoid potentially 10347 // strange codegen behavior. For example, if we extend this conditional 10348 // to dllimport, and we have a source file calling a method on an 10349 // implicitly instantiated template class instance and then declaring a 10350 // dllimport explicit instantiation definition for the same template 10351 // class, the codegen for the method call will not respect the dllimport, 10352 // while it will with cl. The Def will already have the DLL attribute, 10353 // since the Def and Specialization will be the same in the case of 10354 // Old_TSK == TSK_ImplicitInstantiation, and we already added the 10355 // attribute to the Specialization; we just need to make it take effect. 10356 assert(Def == Specialization && 10357 "Def and Specialization should match for implicit instantiation"); 10358 dllExportImportClassTemplateSpecialization(*this, Def); 10359 } 10360 10361 // In MinGW mode, export the template instantiation if the declaration 10362 // was marked dllexport. 10363 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration && 10364 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() && 10365 PrevDecl->hasAttr<DLLExportAttr>()) { 10366 dllExportImportClassTemplateSpecialization(*this, Def); 10367 } 10368 10369 // Set the template specialization kind. Make sure it is set before 10370 // instantiating the members which will trigger ASTConsumer callbacks. 10371 Specialization->setTemplateSpecializationKind(TSK); 10372 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK); 10373 } else { 10374 10375 // Set the template specialization kind. 10376 Specialization->setTemplateSpecializationKind(TSK); 10377 } 10378 10379 return Specialization; 10380 } 10381 10382 // Explicit instantiation of a member class of a class template. 10383 DeclResult 10384 Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, 10385 SourceLocation TemplateLoc, unsigned TagSpec, 10386 SourceLocation KWLoc, CXXScopeSpec &SS, 10387 IdentifierInfo *Name, SourceLocation NameLoc, 10388 const ParsedAttributesView &Attr) { 10389 10390 bool Owned = false; 10391 bool IsDependent = false; 10392 Decl *TagD = ActOnTag(S, TagSpec, Sema::TUK_Reference, KWLoc, SS, Name, 10393 NameLoc, Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(), 10394 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(), 10395 false, TypeResult(), /*IsTypeSpecifier*/ false, 10396 /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside).get(); 10397 assert(!IsDependent && "explicit instantiation of dependent name not yet handled"); 10398 10399 if (!TagD) 10400 return true; 10401 10402 TagDecl *Tag = cast<TagDecl>(TagD); 10403 assert(!Tag->isEnum() && "shouldn't see enumerations here"); 10404 10405 if (Tag->isInvalidDecl()) 10406 return true; 10407 10408 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag); 10409 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); 10410 if (!Pattern) { 10411 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type) 10412 << Context.getTypeDeclType(Record); 10413 Diag(Record->getLocation(), diag::note_nontemplate_decl_here); 10414 return true; 10415 } 10416 10417 // C++0x [temp.explicit]p2: 10418 // If the explicit instantiation is for a class or member class, the 10419 // elaborated-type-specifier in the declaration shall include a 10420 // simple-template-id. 10421 // 10422 // C++98 has the same restriction, just worded differently. 10423 if (!ScopeSpecifierHasTemplateId(SS)) 10424 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id) 10425 << Record << SS.getRange(); 10426 10427 // C++0x [temp.explicit]p2: 10428 // There are two forms of explicit instantiation: an explicit instantiation 10429 // definition and an explicit instantiation declaration. An explicit 10430 // instantiation declaration begins with the extern keyword. [...] 10431 TemplateSpecializationKind TSK 10432 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 10433 : TSK_ExplicitInstantiationDeclaration; 10434 10435 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK); 10436 10437 // Verify that it is okay to explicitly instantiate here. 10438 CXXRecordDecl *PrevDecl 10439 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl()); 10440 if (!PrevDecl && Record->getDefinition()) 10441 PrevDecl = Record; 10442 if (PrevDecl) { 10443 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo(); 10444 bool HasNoEffect = false; 10445 assert(MSInfo && "No member specialization information?"); 10446 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK, 10447 PrevDecl, 10448 MSInfo->getTemplateSpecializationKind(), 10449 MSInfo->getPointOfInstantiation(), 10450 HasNoEffect)) 10451 return true; 10452 if (HasNoEffect) 10453 return TagD; 10454 } 10455 10456 CXXRecordDecl *RecordDef 10457 = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 10458 if (!RecordDef) { 10459 // C++ [temp.explicit]p3: 10460 // A definition of a member class of a class template shall be in scope 10461 // at the point of an explicit instantiation of the member class. 10462 CXXRecordDecl *Def 10463 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition()); 10464 if (!Def) { 10465 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member) 10466 << 0 << Record->getDeclName() << Record->getDeclContext(); 10467 Diag(Pattern->getLocation(), diag::note_forward_declaration) 10468 << Pattern; 10469 return true; 10470 } else { 10471 if (InstantiateClass(NameLoc, Record, Def, 10472 getTemplateInstantiationArgs(Record), 10473 TSK)) 10474 return true; 10475 10476 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition()); 10477 if (!RecordDef) 10478 return true; 10479 } 10480 } 10481 10482 // Instantiate all of the members of the class. 10483 InstantiateClassMembers(NameLoc, RecordDef, 10484 getTemplateInstantiationArgs(Record), TSK); 10485 10486 if (TSK == TSK_ExplicitInstantiationDefinition) 10487 MarkVTableUsed(NameLoc, RecordDef, true); 10488 10489 // FIXME: We don't have any representation for explicit instantiations of 10490 // member classes. Such a representation is not needed for compilation, but it 10491 // should be available for clients that want to see all of the declarations in 10492 // the source code. 10493 return TagD; 10494 } 10495 10496 DeclResult Sema::ActOnExplicitInstantiation(Scope *S, 10497 SourceLocation ExternLoc, 10498 SourceLocation TemplateLoc, 10499 Declarator &D) { 10500 // Explicit instantiations always require a name. 10501 // TODO: check if/when DNInfo should replace Name. 10502 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 10503 DeclarationName Name = NameInfo.getName(); 10504 if (!Name) { 10505 if (!D.isInvalidType()) 10506 Diag(D.getDeclSpec().getBeginLoc(), 10507 diag::err_explicit_instantiation_requires_name) 10508 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 10509 10510 return true; 10511 } 10512 10513 // The scope passed in may not be a decl scope. Zip up the scope tree until 10514 // we find one that is. 10515 while ((S->getFlags() & Scope::DeclScope) == 0 || 10516 (S->getFlags() & Scope::TemplateParamScope) != 0) 10517 S = S->getParent(); 10518 10519 // Determine the type of the declaration. 10520 TypeSourceInfo *T = GetTypeForDeclarator(D, S); 10521 QualType R = T->getType(); 10522 if (R.isNull()) 10523 return true; 10524 10525 // C++ [dcl.stc]p1: 10526 // A storage-class-specifier shall not be specified in [...] an explicit 10527 // instantiation (14.7.2) directive. 10528 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 10529 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef) 10530 << Name; 10531 return true; 10532 } else if (D.getDeclSpec().getStorageClassSpec() 10533 != DeclSpec::SCS_unspecified) { 10534 // Complain about then remove the storage class specifier. 10535 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class) 10536 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 10537 10538 D.getMutableDeclSpec().ClearStorageClassSpecs(); 10539 } 10540 10541 // C++0x [temp.explicit]p1: 10542 // [...] An explicit instantiation of a function template shall not use the 10543 // inline or constexpr specifiers. 10544 // Presumably, this also applies to member functions of class templates as 10545 // well. 10546 if (D.getDeclSpec().isInlineSpecified()) 10547 Diag(D.getDeclSpec().getInlineSpecLoc(), 10548 getLangOpts().CPlusPlus11 ? 10549 diag::err_explicit_instantiation_inline : 10550 diag::warn_explicit_instantiation_inline_0x) 10551 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 10552 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType()) 10553 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is 10554 // not already specified. 10555 Diag(D.getDeclSpec().getConstexprSpecLoc(), 10556 diag::err_explicit_instantiation_constexpr); 10557 10558 // A deduction guide is not on the list of entities that can be explicitly 10559 // instantiated. 10560 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 10561 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized) 10562 << /*explicit instantiation*/ 0; 10563 return true; 10564 } 10565 10566 // C++0x [temp.explicit]p2: 10567 // There are two forms of explicit instantiation: an explicit instantiation 10568 // definition and an explicit instantiation declaration. An explicit 10569 // instantiation declaration begins with the extern keyword. [...] 10570 TemplateSpecializationKind TSK 10571 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition 10572 : TSK_ExplicitInstantiationDeclaration; 10573 10574 LookupResult Previous(*this, NameInfo, LookupOrdinaryName); 10575 LookupParsedName(Previous, S, &D.getCXXScopeSpec()); 10576 10577 if (!R->isFunctionType()) { 10578 // C++ [temp.explicit]p1: 10579 // A [...] static data member of a class template can be explicitly 10580 // instantiated from the member definition associated with its class 10581 // template. 10582 // C++1y [temp.explicit]p1: 10583 // A [...] variable [...] template specialization can be explicitly 10584 // instantiated from its template. 10585 if (Previous.isAmbiguous()) 10586 return true; 10587 10588 VarDecl *Prev = Previous.getAsSingle<VarDecl>(); 10589 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>(); 10590 10591 if (!PrevTemplate) { 10592 if (!Prev || !Prev->isStaticDataMember()) { 10593 // We expect to see a static data member here. 10594 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known) 10595 << Name; 10596 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 10597 P != PEnd; ++P) 10598 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here); 10599 return true; 10600 } 10601 10602 if (!Prev->getInstantiatedFromStaticDataMember()) { 10603 // FIXME: Check for explicit specialization? 10604 Diag(D.getIdentifierLoc(), 10605 diag::err_explicit_instantiation_data_member_not_instantiated) 10606 << Prev; 10607 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here); 10608 // FIXME: Can we provide a note showing where this was declared? 10609 return true; 10610 } 10611 } else { 10612 // Explicitly instantiate a variable template. 10613 10614 // C++1y [dcl.spec.auto]p6: 10615 // ... A program that uses auto or decltype(auto) in a context not 10616 // explicitly allowed in this section is ill-formed. 10617 // 10618 // This includes auto-typed variable template instantiations. 10619 if (R->isUndeducedType()) { 10620 Diag(T->getTypeLoc().getBeginLoc(), 10621 diag::err_auto_not_allowed_var_inst); 10622 return true; 10623 } 10624 10625 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 10626 // C++1y [temp.explicit]p3: 10627 // If the explicit instantiation is for a variable, the unqualified-id 10628 // in the declaration shall be a template-id. 10629 Diag(D.getIdentifierLoc(), 10630 diag::err_explicit_instantiation_without_template_id) 10631 << PrevTemplate; 10632 Diag(PrevTemplate->getLocation(), 10633 diag::note_explicit_instantiation_here); 10634 return true; 10635 } 10636 10637 // Translate the parser's template argument list into our AST format. 10638 TemplateArgumentListInfo TemplateArgs = 10639 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId); 10640 10641 DeclResult Res = CheckVarTemplateId(PrevTemplate, TemplateLoc, 10642 D.getIdentifierLoc(), TemplateArgs); 10643 if (Res.isInvalid()) 10644 return true; 10645 10646 if (!Res.isUsable()) { 10647 // We somehow specified dependent template arguments in an explicit 10648 // instantiation. This should probably only happen during error 10649 // recovery. 10650 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent); 10651 return true; 10652 } 10653 10654 // Ignore access control bits, we don't need them for redeclaration 10655 // checking. 10656 Prev = cast<VarDecl>(Res.get()); 10657 } 10658 10659 // C++0x [temp.explicit]p2: 10660 // If the explicit instantiation is for a member function, a member class 10661 // or a static data member of a class template specialization, the name of 10662 // the class template specialization in the qualified-id for the member 10663 // name shall be a simple-template-id. 10664 // 10665 // C++98 has the same restriction, just worded differently. 10666 // 10667 // This does not apply to variable template specializations, where the 10668 // template-id is in the unqualified-id instead. 10669 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate) 10670 Diag(D.getIdentifierLoc(), 10671 diag::ext_explicit_instantiation_without_qualified_id) 10672 << Prev << D.getCXXScopeSpec().getRange(); 10673 10674 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK); 10675 10676 // Verify that it is okay to explicitly instantiate here. 10677 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind(); 10678 SourceLocation POI = Prev->getPointOfInstantiation(); 10679 bool HasNoEffect = false; 10680 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev, 10681 PrevTSK, POI, HasNoEffect)) 10682 return true; 10683 10684 if (!HasNoEffect) { 10685 // Instantiate static data member or variable template. 10686 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 10687 // Merge attributes. 10688 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes()); 10689 if (TSK == TSK_ExplicitInstantiationDefinition) 10690 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev); 10691 } 10692 10693 // Check the new variable specialization against the parsed input. 10694 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) { 10695 Diag(T->getTypeLoc().getBeginLoc(), 10696 diag::err_invalid_var_template_spec_type) 10697 << 0 << PrevTemplate << R << Prev->getType(); 10698 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here) 10699 << 2 << PrevTemplate->getDeclName(); 10700 return true; 10701 } 10702 10703 // FIXME: Create an ExplicitInstantiation node? 10704 return (Decl*) nullptr; 10705 } 10706 10707 // If the declarator is a template-id, translate the parser's template 10708 // argument list into our AST format. 10709 bool HasExplicitTemplateArgs = false; 10710 TemplateArgumentListInfo TemplateArgs; 10711 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 10712 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId); 10713 HasExplicitTemplateArgs = true; 10714 } 10715 10716 // C++ [temp.explicit]p1: 10717 // A [...] function [...] can be explicitly instantiated from its template. 10718 // A member function [...] of a class template can be explicitly 10719 // instantiated from the member definition associated with its class 10720 // template. 10721 UnresolvedSet<8> TemplateMatches; 10722 FunctionDecl *NonTemplateMatch = nullptr; 10723 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc()); 10724 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end(); 10725 P != PEnd; ++P) { 10726 NamedDecl *Prev = *P; 10727 if (!HasExplicitTemplateArgs) { 10728 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) { 10729 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(), 10730 /*AdjustExceptionSpec*/true); 10731 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) { 10732 if (Method->getPrimaryTemplate()) { 10733 TemplateMatches.addDecl(Method, P.getAccess()); 10734 } else { 10735 // FIXME: Can this assert ever happen? Needs a test. 10736 assert(!NonTemplateMatch && "Multiple NonTemplateMatches"); 10737 NonTemplateMatch = Method; 10738 } 10739 } 10740 } 10741 } 10742 10743 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev); 10744 if (!FunTmpl) 10745 continue; 10746 10747 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10748 FunctionDecl *Specialization = nullptr; 10749 if (TemplateDeductionResult TDK 10750 = DeduceTemplateArguments(FunTmpl, 10751 (HasExplicitTemplateArgs ? &TemplateArgs 10752 : nullptr), 10753 R, Specialization, Info)) { 10754 // Keep track of almost-matches. 10755 FailedCandidates.addCandidate() 10756 .set(P.getPair(), FunTmpl->getTemplatedDecl(), 10757 MakeDeductionFailureInfo(Context, TDK, Info)); 10758 (void)TDK; 10759 continue; 10760 } 10761 10762 // Target attributes are part of the cuda function signature, so 10763 // the cuda target of the instantiated function must match that of its 10764 // template. Given that C++ template deduction does not take 10765 // target attributes into account, we reject candidates here that 10766 // have a different target. 10767 if (LangOpts.CUDA && 10768 IdentifyCUDATarget(Specialization, 10769 /* IgnoreImplicitHDAttr = */ true) != 10770 IdentifyCUDATarget(D.getDeclSpec().getAttributes())) { 10771 FailedCandidates.addCandidate().set( 10772 P.getPair(), FunTmpl->getTemplatedDecl(), 10773 MakeDeductionFailureInfo(Context, TDK_CUDATargetMismatch, Info)); 10774 continue; 10775 } 10776 10777 TemplateMatches.addDecl(Specialization, P.getAccess()); 10778 } 10779 10780 FunctionDecl *Specialization = NonTemplateMatch; 10781 if (!Specialization) { 10782 // Find the most specialized function template specialization. 10783 UnresolvedSetIterator Result = getMostSpecialized( 10784 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates, 10785 D.getIdentifierLoc(), 10786 PDiag(diag::err_explicit_instantiation_not_known) << Name, 10787 PDiag(diag::err_explicit_instantiation_ambiguous) << Name, 10788 PDiag(diag::note_explicit_instantiation_candidate)); 10789 10790 if (Result == TemplateMatches.end()) 10791 return true; 10792 10793 // Ignore access control bits, we don't need them for redeclaration checking. 10794 Specialization = cast<FunctionDecl>(*Result); 10795 } 10796 10797 // C++11 [except.spec]p4 10798 // In an explicit instantiation an exception-specification may be specified, 10799 // but is not required. 10800 // If an exception-specification is specified in an explicit instantiation 10801 // directive, it shall be compatible with the exception-specifications of 10802 // other declarations of that function. 10803 if (auto *FPT = R->getAs<FunctionProtoType>()) 10804 if (FPT->hasExceptionSpec()) { 10805 unsigned DiagID = 10806 diag::err_mismatched_exception_spec_explicit_instantiation; 10807 if (getLangOpts().MicrosoftExt) 10808 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation; 10809 bool Result = CheckEquivalentExceptionSpec( 10810 PDiag(DiagID) << Specialization->getType(), 10811 PDiag(diag::note_explicit_instantiation_here), 10812 Specialization->getType()->getAs<FunctionProtoType>(), 10813 Specialization->getLocation(), FPT, D.getBeginLoc()); 10814 // In Microsoft mode, mismatching exception specifications just cause a 10815 // warning. 10816 if (!getLangOpts().MicrosoftExt && Result) 10817 return true; 10818 } 10819 10820 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) { 10821 Diag(D.getIdentifierLoc(), 10822 diag::err_explicit_instantiation_member_function_not_instantiated) 10823 << Specialization 10824 << (Specialization->getTemplateSpecializationKind() == 10825 TSK_ExplicitSpecialization); 10826 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here); 10827 return true; 10828 } 10829 10830 FunctionDecl *PrevDecl = Specialization->getPreviousDecl(); 10831 if (!PrevDecl && Specialization->isThisDeclarationADefinition()) 10832 PrevDecl = Specialization; 10833 10834 if (PrevDecl) { 10835 bool HasNoEffect = false; 10836 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, 10837 PrevDecl, 10838 PrevDecl->getTemplateSpecializationKind(), 10839 PrevDecl->getPointOfInstantiation(), 10840 HasNoEffect)) 10841 return true; 10842 10843 // FIXME: We may still want to build some representation of this 10844 // explicit specialization. 10845 if (HasNoEffect) 10846 return (Decl*) nullptr; 10847 } 10848 10849 // HACK: libc++ has a bug where it attempts to explicitly instantiate the 10850 // functions 10851 // valarray<size_t>::valarray(size_t) and 10852 // valarray<size_t>::~valarray() 10853 // that it declared to have internal linkage with the internal_linkage 10854 // attribute. Ignore the explicit instantiation declaration in this case. 10855 if (Specialization->hasAttr<InternalLinkageAttr>() && 10856 TSK == TSK_ExplicitInstantiationDeclaration) { 10857 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext())) 10858 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") && 10859 RD->isInStdNamespace()) 10860 return (Decl*) nullptr; 10861 } 10862 10863 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes()); 10864 10865 // In MSVC mode, dllimported explicit instantiation definitions are treated as 10866 // instantiation declarations. 10867 if (TSK == TSK_ExplicitInstantiationDefinition && 10868 Specialization->hasAttr<DLLImportAttr>() && 10869 Context.getTargetInfo().getCXXABI().isMicrosoft()) 10870 TSK = TSK_ExplicitInstantiationDeclaration; 10871 10872 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc()); 10873 10874 if (Specialization->isDefined()) { 10875 // Let the ASTConsumer know that this function has been explicitly 10876 // instantiated now, and its linkage might have changed. 10877 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization)); 10878 } else if (TSK == TSK_ExplicitInstantiationDefinition) 10879 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization); 10880 10881 // C++0x [temp.explicit]p2: 10882 // If the explicit instantiation is for a member function, a member class 10883 // or a static data member of a class template specialization, the name of 10884 // the class template specialization in the qualified-id for the member 10885 // name shall be a simple-template-id. 10886 // 10887 // C++98 has the same restriction, just worded differently. 10888 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate(); 10889 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl && 10890 D.getCXXScopeSpec().isSet() && 10891 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec())) 10892 Diag(D.getIdentifierLoc(), 10893 diag::ext_explicit_instantiation_without_qualified_id) 10894 << Specialization << D.getCXXScopeSpec().getRange(); 10895 10896 CheckExplicitInstantiation( 10897 *this, 10898 FunTmpl ? (NamedDecl *)FunTmpl 10899 : Specialization->getInstantiatedFromMemberFunction(), 10900 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK); 10901 10902 // FIXME: Create some kind of ExplicitInstantiationDecl here. 10903 return (Decl*) nullptr; 10904 } 10905 10906 TypeResult 10907 Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 10908 const CXXScopeSpec &SS, IdentifierInfo *Name, 10909 SourceLocation TagLoc, SourceLocation NameLoc) { 10910 // This has to hold, because SS is expected to be defined. 10911 assert(Name && "Expected a name in a dependent tag"); 10912 10913 NestedNameSpecifier *NNS = SS.getScopeRep(); 10914 if (!NNS) 10915 return true; 10916 10917 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 10918 10919 if (TUK == TUK_Declaration || TUK == TUK_Definition) { 10920 Diag(NameLoc, diag::err_dependent_tag_decl) 10921 << (TUK == TUK_Definition) << llvm::to_underlying(Kind) 10922 << SS.getRange(); 10923 return true; 10924 } 10925 10926 // Create the resulting type. 10927 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind); 10928 QualType Result = Context.getDependentNameType(Kwd, NNS, Name); 10929 10930 // Create type-source location information for this type. 10931 TypeLocBuilder TLB; 10932 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result); 10933 TL.setElaboratedKeywordLoc(TagLoc); 10934 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 10935 TL.setNameLoc(NameLoc); 10936 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result)); 10937 } 10938 10939 TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 10940 const CXXScopeSpec &SS, 10941 const IdentifierInfo &II, 10942 SourceLocation IdLoc, 10943 ImplicitTypenameContext IsImplicitTypename) { 10944 if (SS.isInvalid()) 10945 return true; 10946 10947 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent()) 10948 Diag(TypenameLoc, 10949 getLangOpts().CPlusPlus11 ? 10950 diag::warn_cxx98_compat_typename_outside_of_template : 10951 diag::ext_typename_outside_of_template) 10952 << FixItHint::CreateRemoval(TypenameLoc); 10953 10954 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 10955 TypeSourceInfo *TSI = nullptr; 10956 QualType T = 10957 CheckTypenameType((TypenameLoc.isValid() || 10958 IsImplicitTypename == ImplicitTypenameContext::Yes) 10959 ? ElaboratedTypeKeyword::Typename 10960 : ElaboratedTypeKeyword::None, 10961 TypenameLoc, QualifierLoc, II, IdLoc, &TSI, 10962 /*DeducedTSTContext=*/true); 10963 if (T.isNull()) 10964 return true; 10965 return CreateParsedType(T, TSI); 10966 } 10967 10968 TypeResult 10969 Sema::ActOnTypenameType(Scope *S, 10970 SourceLocation TypenameLoc, 10971 const CXXScopeSpec &SS, 10972 SourceLocation TemplateKWLoc, 10973 TemplateTy TemplateIn, 10974 IdentifierInfo *TemplateII, 10975 SourceLocation TemplateIILoc, 10976 SourceLocation LAngleLoc, 10977 ASTTemplateArgsPtr TemplateArgsIn, 10978 SourceLocation RAngleLoc) { 10979 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent()) 10980 Diag(TypenameLoc, 10981 getLangOpts().CPlusPlus11 ? 10982 diag::warn_cxx98_compat_typename_outside_of_template : 10983 diag::ext_typename_outside_of_template) 10984 << FixItHint::CreateRemoval(TypenameLoc); 10985 10986 // Strangely, non-type results are not ignored by this lookup, so the 10987 // program is ill-formed if it finds an injected-class-name. 10988 if (TypenameLoc.isValid()) { 10989 auto *LookupRD = 10990 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false)); 10991 if (LookupRD && LookupRD->getIdentifier() == TemplateII) { 10992 Diag(TemplateIILoc, 10993 diag::ext_out_of_line_qualified_id_type_names_constructor) 10994 << TemplateII << 0 /*injected-class-name used as template name*/ 10995 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/); 10996 } 10997 } 10998 10999 // Translate the parser's template argument list in our AST format. 11000 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc); 11001 translateTemplateArguments(TemplateArgsIn, TemplateArgs); 11002 11003 TemplateName Template = TemplateIn.get(); 11004 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) { 11005 // Construct a dependent template specialization type. 11006 assert(DTN && "dependent template has non-dependent name?"); 11007 assert(DTN->getQualifier() == SS.getScopeRep()); 11008 QualType T = Context.getDependentTemplateSpecializationType( 11009 ElaboratedTypeKeyword::Typename, DTN->getQualifier(), 11010 DTN->getIdentifier(), TemplateArgs.arguments()); 11011 11012 // Create source-location information for this type. 11013 TypeLocBuilder Builder; 11014 DependentTemplateSpecializationTypeLoc SpecTL 11015 = Builder.push<DependentTemplateSpecializationTypeLoc>(T); 11016 SpecTL.setElaboratedKeywordLoc(TypenameLoc); 11017 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context)); 11018 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 11019 SpecTL.setTemplateNameLoc(TemplateIILoc); 11020 SpecTL.setLAngleLoc(LAngleLoc); 11021 SpecTL.setRAngleLoc(RAngleLoc); 11022 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 11023 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 11024 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 11025 } 11026 11027 QualType T = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs); 11028 if (T.isNull()) 11029 return true; 11030 11031 // Provide source-location information for the template specialization type. 11032 TypeLocBuilder Builder; 11033 TemplateSpecializationTypeLoc SpecTL 11034 = Builder.push<TemplateSpecializationTypeLoc>(T); 11035 SpecTL.setTemplateKeywordLoc(TemplateKWLoc); 11036 SpecTL.setTemplateNameLoc(TemplateIILoc); 11037 SpecTL.setLAngleLoc(LAngleLoc); 11038 SpecTL.setRAngleLoc(RAngleLoc); 11039 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) 11040 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo()); 11041 11042 T = Context.getElaboratedType(ElaboratedTypeKeyword::Typename, 11043 SS.getScopeRep(), T); 11044 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T); 11045 TL.setElaboratedKeywordLoc(TypenameLoc); 11046 TL.setQualifierLoc(SS.getWithLocInContext(Context)); 11047 11048 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T); 11049 return CreateParsedType(T, TSI); 11050 } 11051 11052 11053 /// Determine whether this failed name lookup should be treated as being 11054 /// disabled by a usage of std::enable_if. 11055 static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II, 11056 SourceRange &CondRange, Expr *&Cond) { 11057 // We must be looking for a ::type... 11058 if (!II.isStr("type")) 11059 return false; 11060 11061 // ... within an explicitly-written template specialization... 11062 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType()) 11063 return false; 11064 TypeLoc EnableIfTy = NNS.getTypeLoc(); 11065 TemplateSpecializationTypeLoc EnableIfTSTLoc = 11066 EnableIfTy.getAs<TemplateSpecializationTypeLoc>(); 11067 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0) 11068 return false; 11069 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr(); 11070 11071 // ... which names a complete class template declaration... 11072 const TemplateDecl *EnableIfDecl = 11073 EnableIfTST->getTemplateName().getAsTemplateDecl(); 11074 if (!EnableIfDecl || EnableIfTST->isIncompleteType()) 11075 return false; 11076 11077 // ... called "enable_if". 11078 const IdentifierInfo *EnableIfII = 11079 EnableIfDecl->getDeclName().getAsIdentifierInfo(); 11080 if (!EnableIfII || !EnableIfII->isStr("enable_if")) 11081 return false; 11082 11083 // Assume the first template argument is the condition. 11084 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange(); 11085 11086 // Dig out the condition. 11087 Cond = nullptr; 11088 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind() 11089 != TemplateArgument::Expression) 11090 return true; 11091 11092 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression(); 11093 11094 // Ignore Boolean literals; they add no value. 11095 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts())) 11096 Cond = nullptr; 11097 11098 return true; 11099 } 11100 11101 QualType 11102 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword, 11103 SourceLocation KeywordLoc, 11104 NestedNameSpecifierLoc QualifierLoc, 11105 const IdentifierInfo &II, 11106 SourceLocation IILoc, 11107 TypeSourceInfo **TSI, 11108 bool DeducedTSTContext) { 11109 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc, 11110 DeducedTSTContext); 11111 if (T.isNull()) 11112 return QualType(); 11113 11114 *TSI = Context.CreateTypeSourceInfo(T); 11115 if (isa<DependentNameType>(T)) { 11116 DependentNameTypeLoc TL = 11117 (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>(); 11118 TL.setElaboratedKeywordLoc(KeywordLoc); 11119 TL.setQualifierLoc(QualifierLoc); 11120 TL.setNameLoc(IILoc); 11121 } else { 11122 ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>(); 11123 TL.setElaboratedKeywordLoc(KeywordLoc); 11124 TL.setQualifierLoc(QualifierLoc); 11125 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc); 11126 } 11127 return T; 11128 } 11129 11130 /// Build the type that describes a C++ typename specifier, 11131 /// e.g., "typename T::type". 11132 QualType 11133 Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword, 11134 SourceLocation KeywordLoc, 11135 NestedNameSpecifierLoc QualifierLoc, 11136 const IdentifierInfo &II, 11137 SourceLocation IILoc, bool DeducedTSTContext) { 11138 CXXScopeSpec SS; 11139 SS.Adopt(QualifierLoc); 11140 11141 DeclContext *Ctx = nullptr; 11142 if (QualifierLoc) { 11143 Ctx = computeDeclContext(SS); 11144 if (!Ctx) { 11145 // If the nested-name-specifier is dependent and couldn't be 11146 // resolved to a type, build a typename type. 11147 assert(QualifierLoc.getNestedNameSpecifier()->isDependent()); 11148 return Context.getDependentNameType(Keyword, 11149 QualifierLoc.getNestedNameSpecifier(), 11150 &II); 11151 } 11152 11153 // If the nested-name-specifier refers to the current instantiation, 11154 // the "typename" keyword itself is superfluous. In C++03, the 11155 // program is actually ill-formed. However, DR 382 (in C++0x CD1) 11156 // allows such extraneous "typename" keywords, and we retroactively 11157 // apply this DR to C++03 code with only a warning. In any case we continue. 11158 11159 if (RequireCompleteDeclContext(SS, Ctx)) 11160 return QualType(); 11161 } 11162 11163 DeclarationName Name(&II); 11164 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName); 11165 if (Ctx) 11166 LookupQualifiedName(Result, Ctx, SS); 11167 else 11168 LookupName(Result, CurScope); 11169 unsigned DiagID = 0; 11170 Decl *Referenced = nullptr; 11171 switch (Result.getResultKind()) { 11172 case LookupResult::NotFound: { 11173 // If we're looking up 'type' within a template named 'enable_if', produce 11174 // a more specific diagnostic. 11175 SourceRange CondRange; 11176 Expr *Cond = nullptr; 11177 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) { 11178 // If we have a condition, narrow it down to the specific failed 11179 // condition. 11180 if (Cond) { 11181 Expr *FailedCond; 11182 std::string FailedDescription; 11183 std::tie(FailedCond, FailedDescription) = 11184 findFailedBooleanCondition(Cond); 11185 11186 Diag(FailedCond->getExprLoc(), 11187 diag::err_typename_nested_not_found_requirement) 11188 << FailedDescription 11189 << FailedCond->getSourceRange(); 11190 return QualType(); 11191 } 11192 11193 Diag(CondRange.getBegin(), 11194 diag::err_typename_nested_not_found_enable_if) 11195 << Ctx << CondRange; 11196 return QualType(); 11197 } 11198 11199 DiagID = Ctx ? diag::err_typename_nested_not_found 11200 : diag::err_unknown_typename; 11201 break; 11202 } 11203 11204 case LookupResult::FoundUnresolvedValue: { 11205 // We found a using declaration that is a value. Most likely, the using 11206 // declaration itself is meant to have the 'typename' keyword. 11207 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(), 11208 IILoc); 11209 Diag(IILoc, diag::err_typename_refers_to_using_value_decl) 11210 << Name << Ctx << FullRange; 11211 if (UnresolvedUsingValueDecl *Using 11212 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){ 11213 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc(); 11214 Diag(Loc, diag::note_using_value_decl_missing_typename) 11215 << FixItHint::CreateInsertion(Loc, "typename "); 11216 } 11217 } 11218 // Fall through to create a dependent typename type, from which we can recover 11219 // better. 11220 [[fallthrough]]; 11221 11222 case LookupResult::NotFoundInCurrentInstantiation: 11223 // Okay, it's a member of an unknown instantiation. 11224 return Context.getDependentNameType(Keyword, 11225 QualifierLoc.getNestedNameSpecifier(), 11226 &II); 11227 11228 case LookupResult::Found: 11229 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) { 11230 // C++ [class.qual]p2: 11231 // In a lookup in which function names are not ignored and the 11232 // nested-name-specifier nominates a class C, if the name specified 11233 // after the nested-name-specifier, when looked up in C, is the 11234 // injected-class-name of C [...] then the name is instead considered 11235 // to name the constructor of class C. 11236 // 11237 // Unlike in an elaborated-type-specifier, function names are not ignored 11238 // in typename-specifier lookup. However, they are ignored in all the 11239 // contexts where we form a typename type with no keyword (that is, in 11240 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers). 11241 // 11242 // FIXME: That's not strictly true: mem-initializer-id lookup does not 11243 // ignore functions, but that appears to be an oversight. 11244 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Ctx); 11245 auto *FoundRD = dyn_cast<CXXRecordDecl>(Type); 11246 if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD && 11247 FoundRD->isInjectedClassName() && 11248 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 11249 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor) 11250 << &II << 1 << 0 /*'typename' keyword used*/; 11251 11252 // We found a type. Build an ElaboratedType, since the 11253 // typename-specifier was just sugar. 11254 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 11255 return Context.getElaboratedType(Keyword, 11256 QualifierLoc.getNestedNameSpecifier(), 11257 Context.getTypeDeclType(Type)); 11258 } 11259 11260 // C++ [dcl.type.simple]p2: 11261 // A type-specifier of the form 11262 // typename[opt] nested-name-specifier[opt] template-name 11263 // is a placeholder for a deduced class type [...]. 11264 if (getLangOpts().CPlusPlus17) { 11265 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) { 11266 if (!DeducedTSTContext) { 11267 QualType T(QualifierLoc 11268 ? QualifierLoc.getNestedNameSpecifier()->getAsType() 11269 : nullptr, 0); 11270 if (!T.isNull()) 11271 Diag(IILoc, diag::err_dependent_deduced_tst) 11272 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << T; 11273 else 11274 Diag(IILoc, diag::err_deduced_tst) 11275 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)); 11276 NoteTemplateLocation(*TD); 11277 return QualType(); 11278 } 11279 return Context.getElaboratedType( 11280 Keyword, QualifierLoc.getNestedNameSpecifier(), 11281 Context.getDeducedTemplateSpecializationType(TemplateName(TD), 11282 QualType(), false)); 11283 } 11284 } 11285 11286 DiagID = Ctx ? diag::err_typename_nested_not_type 11287 : diag::err_typename_not_type; 11288 Referenced = Result.getFoundDecl(); 11289 break; 11290 11291 case LookupResult::FoundOverloaded: 11292 DiagID = Ctx ? diag::err_typename_nested_not_type 11293 : diag::err_typename_not_type; 11294 Referenced = *Result.begin(); 11295 break; 11296 11297 case LookupResult::Ambiguous: 11298 return QualType(); 11299 } 11300 11301 // If we get here, it's because name lookup did not find a 11302 // type. Emit an appropriate diagnostic and return an error. 11303 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(), 11304 IILoc); 11305 if (Ctx) 11306 Diag(IILoc, DiagID) << FullRange << Name << Ctx; 11307 else 11308 Diag(IILoc, DiagID) << FullRange << Name; 11309 if (Referenced) 11310 Diag(Referenced->getLocation(), 11311 Ctx ? diag::note_typename_member_refers_here 11312 : diag::note_typename_refers_here) 11313 << Name; 11314 return QualType(); 11315 } 11316 11317 namespace { 11318 // See Sema::RebuildTypeInCurrentInstantiation 11319 class CurrentInstantiationRebuilder 11320 : public TreeTransform<CurrentInstantiationRebuilder> { 11321 SourceLocation Loc; 11322 DeclarationName Entity; 11323 11324 public: 11325 typedef TreeTransform<CurrentInstantiationRebuilder> inherited; 11326 11327 CurrentInstantiationRebuilder(Sema &SemaRef, 11328 SourceLocation Loc, 11329 DeclarationName Entity) 11330 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef), 11331 Loc(Loc), Entity(Entity) { } 11332 11333 /// Determine whether the given type \p T has already been 11334 /// transformed. 11335 /// 11336 /// For the purposes of type reconstruction, a type has already been 11337 /// transformed if it is NULL or if it is not dependent. 11338 bool AlreadyTransformed(QualType T) { 11339 return T.isNull() || !T->isInstantiationDependentType(); 11340 } 11341 11342 /// Returns the location of the entity whose type is being 11343 /// rebuilt. 11344 SourceLocation getBaseLocation() { return Loc; } 11345 11346 /// Returns the name of the entity whose type is being rebuilt. 11347 DeclarationName getBaseEntity() { return Entity; } 11348 11349 /// Sets the "base" location and entity when that 11350 /// information is known based on another transformation. 11351 void setBase(SourceLocation Loc, DeclarationName Entity) { 11352 this->Loc = Loc; 11353 this->Entity = Entity; 11354 } 11355 11356 ExprResult TransformLambdaExpr(LambdaExpr *E) { 11357 // Lambdas never need to be transformed. 11358 return E; 11359 } 11360 }; 11361 } // end anonymous namespace 11362 11363 /// Rebuilds a type within the context of the current instantiation. 11364 /// 11365 /// The type \p T is part of the type of an out-of-line member definition of 11366 /// a class template (or class template partial specialization) that was parsed 11367 /// and constructed before we entered the scope of the class template (or 11368 /// partial specialization thereof). This routine will rebuild that type now 11369 /// that we have entered the declarator's scope, which may produce different 11370 /// canonical types, e.g., 11371 /// 11372 /// \code 11373 /// template<typename T> 11374 /// struct X { 11375 /// typedef T* pointer; 11376 /// pointer data(); 11377 /// }; 11378 /// 11379 /// template<typename T> 11380 /// typename X<T>::pointer X<T>::data() { ... } 11381 /// \endcode 11382 /// 11383 /// Here, the type "typename X<T>::pointer" will be created as a DependentNameType, 11384 /// since we do not know that we can look into X<T> when we parsed the type. 11385 /// This function will rebuild the type, performing the lookup of "pointer" 11386 /// in X<T> and returning an ElaboratedType whose canonical type is the same 11387 /// as the canonical type of T*, allowing the return types of the out-of-line 11388 /// definition and the declaration to match. 11389 TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 11390 SourceLocation Loc, 11391 DeclarationName Name) { 11392 if (!T || !T->getType()->isInstantiationDependentType()) 11393 return T; 11394 11395 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name); 11396 return Rebuilder.TransformType(T); 11397 } 11398 11399 ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) { 11400 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(), 11401 DeclarationName()); 11402 return Rebuilder.TransformExpr(E); 11403 } 11404 11405 bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) { 11406 if (SS.isInvalid()) 11407 return true; 11408 11409 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context); 11410 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(), 11411 DeclarationName()); 11412 NestedNameSpecifierLoc Rebuilt 11413 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc); 11414 if (!Rebuilt) 11415 return true; 11416 11417 SS.Adopt(Rebuilt); 11418 return false; 11419 } 11420 11421 /// Rebuild the template parameters now that we know we're in a current 11422 /// instantiation. 11423 bool Sema::RebuildTemplateParamsInCurrentInstantiation( 11424 TemplateParameterList *Params) { 11425 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 11426 Decl *Param = Params->getParam(I); 11427 11428 // There is nothing to rebuild in a type parameter. 11429 if (isa<TemplateTypeParmDecl>(Param)) 11430 continue; 11431 11432 // Rebuild the template parameter list of a template template parameter. 11433 if (TemplateTemplateParmDecl *TTP 11434 = dyn_cast<TemplateTemplateParmDecl>(Param)) { 11435 if (RebuildTemplateParamsInCurrentInstantiation( 11436 TTP->getTemplateParameters())) 11437 return true; 11438 11439 continue; 11440 } 11441 11442 // Rebuild the type of a non-type template parameter. 11443 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param); 11444 TypeSourceInfo *NewTSI 11445 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(), 11446 NTTP->getLocation(), 11447 NTTP->getDeclName()); 11448 if (!NewTSI) 11449 return true; 11450 11451 if (NewTSI->getType()->isUndeducedType()) { 11452 // C++17 [temp.dep.expr]p3: 11453 // An id-expression is type-dependent if it contains 11454 // - an identifier associated by name lookup with a non-type 11455 // template-parameter declared with a type that contains a 11456 // placeholder type (7.1.7.4), 11457 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI); 11458 } 11459 11460 if (NewTSI != NTTP->getTypeSourceInfo()) { 11461 NTTP->setTypeSourceInfo(NewTSI); 11462 NTTP->setType(NewTSI->getType()); 11463 } 11464 } 11465 11466 return false; 11467 } 11468 11469 /// Produces a formatted string that describes the binding of 11470 /// template parameters to template arguments. 11471 std::string 11472 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 11473 const TemplateArgumentList &Args) { 11474 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size()); 11475 } 11476 11477 std::string 11478 Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params, 11479 const TemplateArgument *Args, 11480 unsigned NumArgs) { 11481 SmallString<128> Str; 11482 llvm::raw_svector_ostream Out(Str); 11483 11484 if (!Params || Params->size() == 0 || NumArgs == 0) 11485 return std::string(); 11486 11487 for (unsigned I = 0, N = Params->size(); I != N; ++I) { 11488 if (I >= NumArgs) 11489 break; 11490 11491 if (I == 0) 11492 Out << "[with "; 11493 else 11494 Out << ", "; 11495 11496 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) { 11497 Out << Id->getName(); 11498 } else { 11499 Out << '$' << I; 11500 } 11501 11502 Out << " = "; 11503 Args[I].print(getPrintingPolicy(), Out, 11504 TemplateParameterList::shouldIncludeTypeForArgument( 11505 getPrintingPolicy(), Params, I)); 11506 } 11507 11508 Out << ']'; 11509 return std::string(Out.str()); 11510 } 11511 11512 void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, 11513 CachedTokens &Toks) { 11514 if (!FD) 11515 return; 11516 11517 auto LPT = std::make_unique<LateParsedTemplate>(); 11518 11519 // Take tokens to avoid allocations 11520 LPT->Toks.swap(Toks); 11521 LPT->D = FnD; 11522 LPT->FPO = getCurFPFeatures(); 11523 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT))); 11524 11525 FD->setLateTemplateParsed(true); 11526 } 11527 11528 void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) { 11529 if (!FD) 11530 return; 11531 FD->setLateTemplateParsed(false); 11532 } 11533 11534 bool Sema::IsInsideALocalClassWithinATemplateFunction() { 11535 DeclContext *DC = CurContext; 11536 11537 while (DC) { 11538 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) { 11539 const FunctionDecl *FD = RD->isLocalClass(); 11540 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate); 11541 } else if (DC->isTranslationUnit() || DC->isNamespace()) 11542 return false; 11543 11544 DC = DC->getParent(); 11545 } 11546 return false; 11547 } 11548 11549 namespace { 11550 /// Walk the path from which a declaration was instantiated, and check 11551 /// that every explicit specialization along that path is visible. This enforces 11552 /// C++ [temp.expl.spec]/6: 11553 /// 11554 /// If a template, a member template or a member of a class template is 11555 /// explicitly specialized then that specialization shall be declared before 11556 /// the first use of that specialization that would cause an implicit 11557 /// instantiation to take place, in every translation unit in which such a 11558 /// use occurs; no diagnostic is required. 11559 /// 11560 /// and also C++ [temp.class.spec]/1: 11561 /// 11562 /// A partial specialization shall be declared before the first use of a 11563 /// class template specialization that would make use of the partial 11564 /// specialization as the result of an implicit or explicit instantiation 11565 /// in every translation unit in which such a use occurs; no diagnostic is 11566 /// required. 11567 class ExplicitSpecializationVisibilityChecker { 11568 Sema &S; 11569 SourceLocation Loc; 11570 llvm::SmallVector<Module *, 8> Modules; 11571 Sema::AcceptableKind Kind; 11572 11573 public: 11574 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc, 11575 Sema::AcceptableKind Kind) 11576 : S(S), Loc(Loc), Kind(Kind) {} 11577 11578 void check(NamedDecl *ND) { 11579 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 11580 return checkImpl(FD); 11581 if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) 11582 return checkImpl(RD); 11583 if (auto *VD = dyn_cast<VarDecl>(ND)) 11584 return checkImpl(VD); 11585 if (auto *ED = dyn_cast<EnumDecl>(ND)) 11586 return checkImpl(ED); 11587 } 11588 11589 private: 11590 void diagnose(NamedDecl *D, bool IsPartialSpec) { 11591 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization 11592 : Sema::MissingImportKind::ExplicitSpecialization; 11593 const bool Recover = true; 11594 11595 // If we got a custom set of modules (because only a subset of the 11596 // declarations are interesting), use them, otherwise let 11597 // diagnoseMissingImport intelligently pick some. 11598 if (Modules.empty()) 11599 S.diagnoseMissingImport(Loc, D, Kind, Recover); 11600 else 11601 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover); 11602 } 11603 11604 bool CheckMemberSpecialization(const NamedDecl *D) { 11605 return Kind == Sema::AcceptableKind::Visible 11606 ? S.hasVisibleMemberSpecialization(D) 11607 : S.hasReachableMemberSpecialization(D); 11608 } 11609 11610 bool CheckExplicitSpecialization(const NamedDecl *D) { 11611 return Kind == Sema::AcceptableKind::Visible 11612 ? S.hasVisibleExplicitSpecialization(D) 11613 : S.hasReachableExplicitSpecialization(D); 11614 } 11615 11616 bool CheckDeclaration(const NamedDecl *D) { 11617 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D) 11618 : S.hasReachableDeclaration(D); 11619 } 11620 11621 // Check a specific declaration. There are three problematic cases: 11622 // 11623 // 1) The declaration is an explicit specialization of a template 11624 // specialization. 11625 // 2) The declaration is an explicit specialization of a member of an 11626 // templated class. 11627 // 3) The declaration is an instantiation of a template, and that template 11628 // is an explicit specialization of a member of a templated class. 11629 // 11630 // We don't need to go any deeper than that, as the instantiation of the 11631 // surrounding class / etc is not triggered by whatever triggered this 11632 // instantiation, and thus should be checked elsewhere. 11633 template<typename SpecDecl> 11634 void checkImpl(SpecDecl *Spec) { 11635 bool IsHiddenExplicitSpecialization = false; 11636 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) { 11637 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo() 11638 ? !CheckMemberSpecialization(Spec) 11639 : !CheckExplicitSpecialization(Spec); 11640 } else { 11641 checkInstantiated(Spec); 11642 } 11643 11644 if (IsHiddenExplicitSpecialization) 11645 diagnose(Spec->getMostRecentDecl(), false); 11646 } 11647 11648 void checkInstantiated(FunctionDecl *FD) { 11649 if (auto *TD = FD->getPrimaryTemplate()) 11650 checkTemplate(TD); 11651 } 11652 11653 void checkInstantiated(CXXRecordDecl *RD) { 11654 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD); 11655 if (!SD) 11656 return; 11657 11658 auto From = SD->getSpecializedTemplateOrPartial(); 11659 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>()) 11660 checkTemplate(TD); 11661 else if (auto *TD = 11662 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) { 11663 if (!CheckDeclaration(TD)) 11664 diagnose(TD, true); 11665 checkTemplate(TD); 11666 } 11667 } 11668 11669 void checkInstantiated(VarDecl *RD) { 11670 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD); 11671 if (!SD) 11672 return; 11673 11674 auto From = SD->getSpecializedTemplateOrPartial(); 11675 if (auto *TD = From.dyn_cast<VarTemplateDecl *>()) 11676 checkTemplate(TD); 11677 else if (auto *TD = 11678 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) { 11679 if (!CheckDeclaration(TD)) 11680 diagnose(TD, true); 11681 checkTemplate(TD); 11682 } 11683 } 11684 11685 void checkInstantiated(EnumDecl *FD) {} 11686 11687 template<typename TemplDecl> 11688 void checkTemplate(TemplDecl *TD) { 11689 if (TD->isMemberSpecialization()) { 11690 if (!CheckMemberSpecialization(TD)) 11691 diagnose(TD->getMostRecentDecl(), false); 11692 } 11693 } 11694 }; 11695 } // end anonymous namespace 11696 11697 void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) { 11698 if (!getLangOpts().Modules) 11699 return; 11700 11701 ExplicitSpecializationVisibilityChecker(*this, Loc, 11702 Sema::AcceptableKind::Visible) 11703 .check(Spec); 11704 } 11705 11706 void Sema::checkSpecializationReachability(SourceLocation Loc, 11707 NamedDecl *Spec) { 11708 if (!getLangOpts().CPlusPlusModules) 11709 return checkSpecializationVisibility(Loc, Spec); 11710 11711 ExplicitSpecializationVisibilityChecker(*this, Loc, 11712 Sema::AcceptableKind::Reachable) 11713 .check(Spec); 11714 } 11715 11716 /// Returns the top most location responsible for the definition of \p N. 11717 /// If \p N is a a template specialization, this is the location 11718 /// of the top of the instantiation stack. 11719 /// Otherwise, the location of \p N is returned. 11720 SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const { 11721 if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty()) 11722 return N->getLocation(); 11723 if (const auto *FD = dyn_cast<FunctionDecl>(N)) { 11724 if (!FD->isFunctionTemplateSpecialization()) 11725 return FD->getLocation(); 11726 } else if (!isa<ClassTemplateSpecializationDecl, 11727 VarTemplateSpecializationDecl>(N)) { 11728 return N->getLocation(); 11729 } 11730 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) { 11731 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid()) 11732 continue; 11733 return CSC.PointOfInstantiation; 11734 } 11735 return N->getLocation(); 11736 } 11737