12137 lines · cpp
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-exception6//===----------------------------------------------------------------------===//7//8// This file implements semantic analysis for C++ templates.9//===----------------------------------------------------------------------===//10 11#include "TreeTransform.h"12#include "clang/AST/ASTConcept.h"13#include "clang/AST/ASTConsumer.h"14#include "clang/AST/ASTContext.h"15#include "clang/AST/Decl.h"16#include "clang/AST/DeclFriend.h"17#include "clang/AST/DeclTemplate.h"18#include "clang/AST/DynamicRecursiveASTVisitor.h"19#include "clang/AST/Expr.h"20#include "clang/AST/ExprCXX.h"21#include "clang/AST/TemplateName.h"22#include "clang/AST/Type.h"23#include "clang/AST/TypeOrdering.h"24#include "clang/AST/TypeVisitor.h"25#include "clang/Basic/Builtins.h"26#include "clang/Basic/DiagnosticSema.h"27#include "clang/Basic/LangOptions.h"28#include "clang/Basic/PartialDiagnostic.h"29#include "clang/Basic/SourceLocation.h"30#include "clang/Basic/TargetInfo.h"31#include "clang/Sema/DeclSpec.h"32#include "clang/Sema/EnterExpressionEvaluationContext.h"33#include "clang/Sema/Initialization.h"34#include "clang/Sema/Lookup.h"35#include "clang/Sema/Overload.h"36#include "clang/Sema/ParsedTemplate.h"37#include "clang/Sema/Scope.h"38#include "clang/Sema/SemaCUDA.h"39#include "clang/Sema/SemaInternal.h"40#include "clang/Sema/Template.h"41#include "clang/Sema/TemplateDeduction.h"42#include "llvm/ADT/SmallBitVector.h"43#include "llvm/ADT/StringExtras.h"44#include "llvm/Support/Casting.h"45#include "llvm/Support/SaveAndRestore.h"46 47#include <optional>48using namespace clang;49using namespace sema;50 51// Exported for use by Parser.52SourceRange53clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,54 unsigned N) {55 if (!N) return SourceRange();56 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());57}58 59unsigned Sema::getTemplateDepth(Scope *S) const {60 unsigned Depth = 0;61 62 // Each template parameter scope represents one level of template parameter63 // depth.64 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;65 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {66 ++Depth;67 }68 69 // Note that there are template parameters with the given depth.70 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };71 72 // Look for parameters of an enclosing generic lambda. We don't create a73 // template parameter scope for these.74 for (FunctionScopeInfo *FSI : getFunctionScopes()) {75 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {76 if (!LSI->TemplateParams.empty()) {77 ParamsAtDepth(LSI->AutoTemplateParameterDepth);78 break;79 }80 if (LSI->GLTemplateParameterList) {81 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());82 break;83 }84 }85 }86 87 // Look for parameters of an enclosing terse function template. We don't88 // create a template parameter scope for these either.89 for (const InventedTemplateParameterInfo &Info :90 getInventedParameterInfos()) {91 if (!Info.TemplateParams.empty()) {92 ParamsAtDepth(Info.AutoTemplateParameterDepth);93 break;94 }95 }96 97 return Depth;98}99 100/// \brief Determine whether the declaration found is acceptable as the name101/// of a template and, if so, return that template declaration. Otherwise,102/// returns null.103///104/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent105/// is true. In all other cases it will return a TemplateDecl (or null).106NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,107 bool AllowFunctionTemplates,108 bool AllowDependent) {109 D = D->getUnderlyingDecl();110 111 if (isa<TemplateDecl>(D)) {112 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))113 return nullptr;114 115 return D;116 }117 118 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {119 // C++ [temp.local]p1:120 // Like normal (non-template) classes, class templates have an121 // injected-class-name (Clause 9). The injected-class-name122 // can be used with or without a template-argument-list. When123 // it is used without a template-argument-list, it is124 // equivalent to the injected-class-name followed by the125 // template-parameters of the class template enclosed in126 // <>. When it is used with a template-argument-list, it127 // refers to the specified class template specialization,128 // which could be the current specialization or another129 // specialization.130 if (Record->isInjectedClassName()) {131 Record = cast<CXXRecordDecl>(Record->getDeclContext());132 if (Record->getDescribedClassTemplate())133 return Record->getDescribedClassTemplate();134 135 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))136 return Spec->getSpecializedTemplate();137 }138 139 return nullptr;140 }141 142 // 'using Dependent::foo;' can resolve to a template name.143 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an144 // injected-class-name).145 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))146 return D;147 148 return nullptr;149}150 151void Sema::FilterAcceptableTemplateNames(LookupResult &R,152 bool AllowFunctionTemplates,153 bool AllowDependent) {154 LookupResult::Filter filter = R.makeFilter();155 while (filter.hasNext()) {156 NamedDecl *Orig = filter.next();157 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))158 filter.erase();159 }160 filter.done();161}162 163bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,164 bool AllowFunctionTemplates,165 bool AllowDependent,166 bool AllowNonTemplateFunctions) {167 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {168 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))169 return true;170 if (AllowNonTemplateFunctions &&171 isa<FunctionDecl>((*I)->getUnderlyingDecl()))172 return true;173 }174 175 return false;176}177 178TemplateNameKind Sema::isTemplateName(Scope *S,179 CXXScopeSpec &SS,180 bool hasTemplateKeyword,181 const UnqualifiedId &Name,182 ParsedType ObjectTypePtr,183 bool EnteringContext,184 TemplateTy &TemplateResult,185 bool &MemberOfUnknownSpecialization,186 bool Disambiguation) {187 assert(getLangOpts().CPlusPlus && "No template names in C!");188 189 DeclarationName TName;190 MemberOfUnknownSpecialization = false;191 192 switch (Name.getKind()) {193 case UnqualifiedIdKind::IK_Identifier:194 TName = DeclarationName(Name.Identifier);195 break;196 197 case UnqualifiedIdKind::IK_OperatorFunctionId:198 TName = Context.DeclarationNames.getCXXOperatorName(199 Name.OperatorFunctionId.Operator);200 break;201 202 case UnqualifiedIdKind::IK_LiteralOperatorId:203 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);204 break;205 206 default:207 return TNK_Non_template;208 }209 210 QualType ObjectType = ObjectTypePtr.get();211 212 AssumedTemplateKind AssumedTemplate;213 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);214 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,215 /*RequiredTemplate=*/SourceLocation(),216 &AssumedTemplate,217 /*AllowTypoCorrection=*/!Disambiguation))218 return TNK_Non_template;219 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();220 221 if (AssumedTemplate != AssumedTemplateKind::None) {222 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));223 // Let the parser know whether we found nothing or found functions; if we224 // found nothing, we want to more carefully check whether this is actually225 // a function template name versus some other kind of undeclared identifier.226 return AssumedTemplate == AssumedTemplateKind::FoundNothing227 ? TNK_Undeclared_template228 : TNK_Function_template;229 }230 231 if (R.empty())232 return TNK_Non_template;233 234 NamedDecl *D = nullptr;235 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());236 if (R.isAmbiguous()) {237 // If we got an ambiguity involving a non-function template, treat this238 // as a template name, and pick an arbitrary template for error recovery.239 bool AnyFunctionTemplates = false;240 for (NamedDecl *FoundD : R) {241 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {242 if (isa<FunctionTemplateDecl>(FoundTemplate))243 AnyFunctionTemplates = true;244 else {245 D = FoundTemplate;246 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);247 break;248 }249 }250 }251 252 // If we didn't find any templates at all, this isn't a template name.253 // Leave the ambiguity for a later lookup to diagnose.254 if (!D && !AnyFunctionTemplates) {255 R.suppressDiagnostics();256 return TNK_Non_template;257 }258 259 // If the only templates were function templates, filter out the rest.260 // We'll diagnose the ambiguity later.261 if (!D)262 FilterAcceptableTemplateNames(R);263 }264 265 // At this point, we have either picked a single template name declaration D266 // or we have a non-empty set of results R containing either one template name267 // declaration or a set of function templates.268 269 TemplateName Template;270 TemplateNameKind TemplateKind;271 272 unsigned ResultCount = R.end() - R.begin();273 if (!D && ResultCount > 1) {274 // We assume that we'll preserve the qualifier from a function275 // template name in other ways.276 Template = Context.getOverloadedTemplateName(R.begin(), R.end());277 TemplateKind = TNK_Function_template;278 279 // We'll do this lookup again later.280 R.suppressDiagnostics();281 } else {282 if (!D) {283 D = getAsTemplateNameDecl(*R.begin());284 assert(D && "unambiguous result is not a template name");285 }286 287 if (isa<UnresolvedUsingValueDecl>(D)) {288 // We don't yet know whether this is a template-name or not.289 MemberOfUnknownSpecialization = true;290 return TNK_Non_template;291 }292 293 TemplateDecl *TD = cast<TemplateDecl>(D);294 Template =295 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);296 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);297 if (!SS.isInvalid()) {298 NestedNameSpecifier Qualifier = SS.getScopeRep();299 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,300 Template);301 }302 303 if (isa<FunctionTemplateDecl>(TD)) {304 TemplateKind = TNK_Function_template;305 306 // We'll do this lookup again later.307 R.suppressDiagnostics();308 } else {309 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||310 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||311 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));312 TemplateKind =313 isa<TemplateTemplateParmDecl>(TD)314 ? dyn_cast<TemplateTemplateParmDecl>(TD)->templateParameterKind()315 : isa<VarTemplateDecl>(TD) ? TNK_Var_template316 : isa<ConceptDecl>(TD) ? TNK_Concept_template317 : TNK_Type_template;318 }319 }320 321 if (isPackProducingBuiltinTemplateName(Template) && S &&322 S->getTemplateParamParent() == nullptr)323 Diag(Name.getBeginLoc(), diag::err_builtin_pack_outside_template) << TName;324 // Recover by returning the template, even though we would never be able to325 // substitute it.326 327 TemplateResult = TemplateTy::make(Template);328 return TemplateKind;329}330 331bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,332 SourceLocation NameLoc, CXXScopeSpec &SS,333 ParsedTemplateTy *Template /*=nullptr*/) {334 // We could use redeclaration lookup here, but we don't need to: the335 // syntactic form of a deduction guide is enough to identify it even336 // if we can't look up the template name at all.337 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);338 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),339 /*EnteringContext*/ false))340 return false;341 342 if (R.empty()) return false;343 if (R.isAmbiguous()) {344 // FIXME: Diagnose an ambiguity if we find at least one template.345 R.suppressDiagnostics();346 return false;347 }348 349 // We only treat template-names that name type templates as valid deduction350 // guide names.351 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();352 if (!TD || !getAsTypeTemplateDecl(TD))353 return false;354 355 if (Template) {356 TemplateName Name = Context.getQualifiedTemplateName(357 SS.getScopeRep(), /*TemplateKeyword=*/false, TemplateName(TD));358 *Template = TemplateTy::make(Name);359 }360 return true;361}362 363bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,364 SourceLocation IILoc,365 Scope *S,366 const CXXScopeSpec *SS,367 TemplateTy &SuggestedTemplate,368 TemplateNameKind &SuggestedKind) {369 // We can't recover unless there's a dependent scope specifier preceding the370 // template name.371 // FIXME: Typo correction?372 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||373 computeDeclContext(*SS))374 return false;375 376 // The code is missing a 'template' keyword prior to the dependent template377 // name.378 SuggestedTemplate = TemplateTy::make(Context.getDependentTemplateName(379 {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));380 Diag(IILoc, diag::err_template_kw_missing)381 << SuggestedTemplate.get()382 << FixItHint::CreateInsertion(IILoc, "template ");383 SuggestedKind = TNK_Dependent_template_name;384 return true;385}386 387bool Sema::LookupTemplateName(LookupResult &Found, Scope *S, CXXScopeSpec &SS,388 QualType ObjectType, bool EnteringContext,389 RequiredTemplateKind RequiredTemplate,390 AssumedTemplateKind *ATK,391 bool AllowTypoCorrection) {392 if (ATK)393 *ATK = AssumedTemplateKind::None;394 395 if (SS.isInvalid())396 return true;397 398 Found.setTemplateNameLookup(true);399 400 // Determine where to perform name lookup401 DeclContext *LookupCtx = nullptr;402 bool IsDependent = false;403 if (!ObjectType.isNull()) {404 // This nested-name-specifier occurs in a member access expression, e.g.,405 // x->B::f, and we are looking into the type of the object.406 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");407 LookupCtx = computeDeclContext(ObjectType);408 IsDependent = !LookupCtx && ObjectType->isDependentType();409 assert((IsDependent || !ObjectType->isIncompleteType() ||410 !ObjectType->getAs<TagType>() ||411 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&412 "Caller should have completed object type");413 414 // Template names cannot appear inside an Objective-C class or object type415 // or a vector type.416 //417 // FIXME: This is wrong. For example:418 //419 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));420 // Vec<int> vi;421 // vi.Vec<int>::~Vec<int>();422 //423 // ... should be accepted but we will not treat 'Vec' as a template name424 // here. The right thing to do would be to check if the name is a valid425 // vector component name, and look up a template name if not. And similarly426 // for lookups into Objective-C class and object types, where the same427 // problem can arise.428 if (ObjectType->isObjCObjectOrInterfaceType() ||429 ObjectType->isVectorType()) {430 Found.clear();431 return false;432 }433 } else if (SS.isNotEmpty()) {434 // This nested-name-specifier occurs after another nested-name-specifier,435 // so long into the context associated with the prior nested-name-specifier.436 LookupCtx = computeDeclContext(SS, EnteringContext);437 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);438 439 // The declaration context must be complete.440 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))441 return true;442 }443 444 bool ObjectTypeSearchedInScope = false;445 bool AllowFunctionTemplatesInLookup = true;446 if (LookupCtx) {447 // Perform "qualified" name lookup into the declaration context we448 // computed, which is either the type of the base of a member access449 // expression or the declaration context associated with a prior450 // nested-name-specifier.451 LookupQualifiedName(Found, LookupCtx);452 453 // FIXME: The C++ standard does not clearly specify what happens in the454 // case where the object type is dependent, and implementations vary. In455 // Clang, we treat a name after a . or -> as a template-name if lookup456 // finds a non-dependent member or member of the current instantiation that457 // is a type template, or finds no such members and lookup in the context458 // of the postfix-expression finds a type template. In the latter case, the459 // name is nonetheless dependent, and we may resolve it to a member of an460 // unknown specialization when we come to instantiate the template.461 IsDependent |= Found.wasNotFoundInCurrentInstantiation();462 }463 464 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {465 // C++ [basic.lookup.classref]p1:466 // In a class member access expression (5.2.5), if the . or -> token is467 // immediately followed by an identifier followed by a <, the468 // identifier must be looked up to determine whether the < is the469 // beginning of a template argument list (14.2) or a less-than operator.470 // The identifier is first looked up in the class of the object471 // expression. If the identifier is not found, it is then looked up in472 // the context of the entire postfix-expression and shall name a class473 // template.474 if (S)475 LookupName(Found, S);476 477 if (!ObjectType.isNull()) {478 // FIXME: We should filter out all non-type templates here, particularly479 // variable templates and concepts. But the exclusion of alias templates480 // and template template parameters is a wording defect.481 AllowFunctionTemplatesInLookup = false;482 ObjectTypeSearchedInScope = true;483 }484 485 IsDependent |= Found.wasNotFoundInCurrentInstantiation();486 }487 488 if (Found.isAmbiguous())489 return false;490 491 if (ATK && SS.isEmpty() && ObjectType.isNull() &&492 !RequiredTemplate.hasTemplateKeyword()) {493 // C++2a [temp.names]p2:494 // A name is also considered to refer to a template if it is an495 // unqualified-id followed by a < and name lookup finds either one or more496 // functions or finds nothing.497 //498 // To keep our behavior consistent, we apply the "finds nothing" part in499 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we500 // successfully form a call to an undeclared template-id.501 bool AllFunctions =502 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {503 return isa<FunctionDecl>(ND->getUnderlyingDecl());504 });505 if (AllFunctions || (Found.empty() && !IsDependent)) {506 // If lookup found any functions, or if this is a name that can only be507 // used for a function, then strongly assume this is a function508 // template-id.509 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())510 ? AssumedTemplateKind::FoundNothing511 : AssumedTemplateKind::FoundFunctions;512 Found.clear();513 return false;514 }515 }516 517 if (Found.empty() && !IsDependent && AllowTypoCorrection) {518 // If we did not find any names, and this is not a disambiguation, attempt519 // to correct any typos.520 DeclarationName Name = Found.getLookupName();521 Found.clear();522 // Simple filter callback that, for keywords, only accepts the C++ *_cast523 DefaultFilterCCC FilterCCC{};524 FilterCCC.WantTypeSpecifiers = false;525 FilterCCC.WantExpressionKeywords = false;526 FilterCCC.WantRemainingKeywords = false;527 FilterCCC.WantCXXNamedCasts = true;528 if (TypoCorrection Corrected = CorrectTypo(529 Found.getLookupNameInfo(), Found.getLookupKind(), S, &SS, FilterCCC,530 CorrectTypoKind::ErrorRecovery, LookupCtx)) {531 if (auto *ND = Corrected.getFoundDecl())532 Found.addDecl(ND);533 FilterAcceptableTemplateNames(Found);534 if (Found.isAmbiguous()) {535 Found.clear();536 } else if (!Found.empty()) {537 // Do not erase the typo-corrected result to avoid duplicated538 // diagnostics.539 AllowFunctionTemplatesInLookup = true;540 Found.setLookupName(Corrected.getCorrection());541 if (LookupCtx) {542 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));543 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&544 Name.getAsString() == CorrectedStr;545 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)546 << Name << LookupCtx << DroppedSpecifier547 << SS.getRange());548 } else {549 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);550 }551 }552 }553 }554 555 NamedDecl *ExampleLookupResult =556 Found.empty() ? nullptr : Found.getRepresentativeDecl();557 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);558 if (Found.empty()) {559 if (IsDependent) {560 Found.setNotFoundInCurrentInstantiation();561 return false;562 }563 564 // If a 'template' keyword was used, a lookup that finds only non-template565 // names is an error.566 if (ExampleLookupResult && RequiredTemplate) {567 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)568 << Found.getLookupName() << SS.getRange()569 << RequiredTemplate.hasTemplateKeyword()570 << RequiredTemplate.getTemplateKeywordLoc();571 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),572 diag::note_template_kw_refers_to_non_template)573 << Found.getLookupName();574 return true;575 }576 577 return false;578 }579 580 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&581 !getLangOpts().CPlusPlus11) {582 // C++03 [basic.lookup.classref]p1:583 // [...] If the lookup in the class of the object expression finds a584 // template, the name is also looked up in the context of the entire585 // postfix-expression and [...]586 //587 // Note: C++11 does not perform this second lookup.588 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),589 LookupOrdinaryName);590 FoundOuter.setTemplateNameLookup(true);591 LookupName(FoundOuter, S);592 // FIXME: We silently accept an ambiguous lookup here, in violation of593 // [basic.lookup]/1.594 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);595 596 NamedDecl *OuterTemplate;597 if (FoundOuter.empty()) {598 // - if the name is not found, the name found in the class of the599 // object expression is used, otherwise600 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||601 !(OuterTemplate =602 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {603 // - if the name is found in the context of the entire604 // postfix-expression and does not name a class template, the name605 // found in the class of the object expression is used, otherwise606 FoundOuter.clear();607 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {608 // - if the name found is a class template, it must refer to the same609 // entity as the one found in the class of the object expression,610 // otherwise the program is ill-formed.611 if (!Found.isSingleResult() ||612 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=613 OuterTemplate->getCanonicalDecl()) {614 Diag(Found.getNameLoc(),615 diag::ext_nested_name_member_ref_lookup_ambiguous)616 << Found.getLookupName()617 << ObjectType;618 Diag(Found.getRepresentativeDecl()->getLocation(),619 diag::note_ambig_member_ref_object_type)620 << ObjectType;621 Diag(FoundOuter.getFoundDecl()->getLocation(),622 diag::note_ambig_member_ref_scope);623 624 // Recover by taking the template that we found in the object625 // expression's type.626 }627 }628 }629 630 return false;631}632 633void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,634 SourceLocation Less,635 SourceLocation Greater) {636 if (TemplateName.isInvalid())637 return;638 639 DeclarationNameInfo NameInfo;640 CXXScopeSpec SS;641 LookupNameKind LookupKind;642 643 DeclContext *LookupCtx = nullptr;644 NamedDecl *Found = nullptr;645 bool MissingTemplateKeyword = false;646 647 // Figure out what name we looked up.648 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {649 NameInfo = DRE->getNameInfo();650 SS.Adopt(DRE->getQualifierLoc());651 LookupKind = LookupOrdinaryName;652 Found = DRE->getFoundDecl();653 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {654 NameInfo = ME->getMemberNameInfo();655 SS.Adopt(ME->getQualifierLoc());656 LookupKind = LookupMemberName;657 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();658 Found = ME->getMemberDecl();659 } else if (auto *DSDRE =660 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {661 NameInfo = DSDRE->getNameInfo();662 SS.Adopt(DSDRE->getQualifierLoc());663 MissingTemplateKeyword = true;664 } else if (auto *DSME =665 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {666 NameInfo = DSME->getMemberNameInfo();667 SS.Adopt(DSME->getQualifierLoc());668 MissingTemplateKeyword = true;669 } else {670 llvm_unreachable("unexpected kind of potential template name");671 }672 673 // If this is a dependent-scope lookup, diagnose that the 'template' keyword674 // was missing.675 if (MissingTemplateKeyword) {676 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)677 << NameInfo.getName() << SourceRange(Less, Greater);678 return;679 }680 681 // Try to correct the name by looking for templates and C++ named casts.682 struct TemplateCandidateFilter : CorrectionCandidateCallback {683 Sema &S;684 TemplateCandidateFilter(Sema &S) : S(S) {685 WantTypeSpecifiers = false;686 WantExpressionKeywords = false;687 WantRemainingKeywords = false;688 WantCXXNamedCasts = true;689 };690 bool ValidateCandidate(const TypoCorrection &Candidate) override {691 if (auto *ND = Candidate.getCorrectionDecl())692 return S.getAsTemplateNameDecl(ND);693 return Candidate.isKeyword();694 }695 696 std::unique_ptr<CorrectionCandidateCallback> clone() override {697 return std::make_unique<TemplateCandidateFilter>(*this);698 }699 };700 701 DeclarationName Name = NameInfo.getName();702 TemplateCandidateFilter CCC(*this);703 if (TypoCorrection Corrected =704 CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,705 CorrectTypoKind::ErrorRecovery, LookupCtx)) {706 auto *ND = Corrected.getFoundDecl();707 if (ND)708 ND = getAsTemplateNameDecl(ND);709 if (ND || Corrected.isKeyword()) {710 if (LookupCtx) {711 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));712 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&713 Name.getAsString() == CorrectedStr;714 diagnoseTypo(Corrected,715 PDiag(diag::err_non_template_in_member_template_id_suggest)716 << Name << LookupCtx << DroppedSpecifier717 << SS.getRange(), false);718 } else {719 diagnoseTypo(Corrected,720 PDiag(diag::err_non_template_in_template_id_suggest)721 << Name, false);722 }723 if (Found)724 Diag(Found->getLocation(),725 diag::note_non_template_in_template_id_found);726 return;727 }728 }729 730 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)731 << Name << SourceRange(Less, Greater);732 if (Found)733 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);734}735 736ExprResult737Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,738 SourceLocation TemplateKWLoc,739 const DeclarationNameInfo &NameInfo,740 bool isAddressOfOperand,741 const TemplateArgumentListInfo *TemplateArgs) {742 if (SS.isEmpty()) {743 // FIXME: This codepath is only used by dependent unqualified names744 // (e.g. a dependent conversion-function-id, or operator= once we support745 // it). It doesn't quite do the right thing, and it will silently fail if746 // getCurrentThisType() returns null.747 QualType ThisType = getCurrentThisType();748 if (ThisType.isNull())749 return ExprError();750 751 return CXXDependentScopeMemberExpr::Create(752 Context, /*Base=*/nullptr, ThisType,753 /*IsArrow=*/!Context.getLangOpts().HLSL,754 /*OperatorLoc=*/SourceLocation(),755 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,756 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);757 }758 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);759}760 761ExprResult762Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,763 SourceLocation TemplateKWLoc,764 const DeclarationNameInfo &NameInfo,765 const TemplateArgumentListInfo *TemplateArgs) {766 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc767 if (!SS.isValid())768 return CreateRecoveryExpr(769 SS.getBeginLoc(),770 TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), {});771 772 return DependentScopeDeclRefExpr::Create(773 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,774 TemplateArgs);775}776 777ExprResult Sema::BuildSubstNonTypeTemplateParmExpr(778 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP,779 SourceLocation Loc, TemplateArgument Arg, UnsignedOrNone PackIndex,780 bool Final) {781 // The template argument itself might be an expression, in which case we just782 // return that expression. This happens when substituting into an alias783 // template.784 Expr *Replacement;785 bool refParam = true;786 if (Arg.getKind() == TemplateArgument::Expression) {787 Replacement = Arg.getAsExpr();788 refParam = Replacement->isLValue();789 if (refParam && Replacement->getType()->isRecordType()) {790 QualType ParamType =791 NTTP->isExpandedParameterPack()792 ? NTTP->getExpansionType(*SemaRef.ArgPackSubstIndex)793 : NTTP->getType();794 if (const auto *PET = dyn_cast<PackExpansionType>(ParamType))795 ParamType = PET->getPattern();796 refParam = ParamType->isReferenceType();797 }798 } else {799 ExprResult result =800 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);801 if (result.isInvalid())802 return ExprError();803 Replacement = result.get();804 refParam = Arg.getNonTypeTemplateArgumentType()->isReferenceType();805 }806 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(807 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,808 AssociatedDecl, NTTP->getIndex(), PackIndex, refParam, Final);809}810 811bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,812 NamedDecl *Instantiation,813 bool InstantiatedFromMember,814 const NamedDecl *Pattern,815 const NamedDecl *PatternDef,816 TemplateSpecializationKind TSK,817 bool Complain, bool *Unreachable) {818 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||819 isa<VarDecl>(Instantiation));820 821 bool IsEntityBeingDefined = false;822 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))823 IsEntityBeingDefined = TD->isBeingDefined();824 825 if (PatternDef && !IsEntityBeingDefined) {826 NamedDecl *SuggestedDef = nullptr;827 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),828 &SuggestedDef,829 /*OnlyNeedComplete*/ false)) {830 if (Unreachable)831 *Unreachable = true;832 // If we're allowed to diagnose this and recover, do so.833 bool Recover = Complain && !isSFINAEContext();834 if (Complain)835 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,836 Sema::MissingImportKind::Definition, Recover);837 return !Recover;838 }839 return false;840 }841 842 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))843 return true;844 845 CanQualType InstantiationTy;846 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))847 InstantiationTy = Context.getCanonicalTagType(TD);848 if (PatternDef) {849 Diag(PointOfInstantiation,850 diag::err_template_instantiate_within_definition)851 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)852 << InstantiationTy;853 // Not much point in noting the template declaration here, since854 // we're lexically inside it.855 Instantiation->setInvalidDecl();856 } else if (InstantiatedFromMember) {857 if (isa<FunctionDecl>(Instantiation)) {858 Diag(PointOfInstantiation,859 diag::err_explicit_instantiation_undefined_member)860 << /*member function*/ 1 << Instantiation->getDeclName()861 << Instantiation->getDeclContext();862 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);863 } else {864 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");865 Diag(PointOfInstantiation,866 diag::err_implicit_instantiate_member_undefined)867 << InstantiationTy;868 Diag(Pattern->getLocation(), diag::note_member_declared_at);869 }870 } else {871 if (isa<FunctionDecl>(Instantiation)) {872 Diag(PointOfInstantiation,873 diag::err_explicit_instantiation_undefined_func_template)874 << Pattern;875 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);876 } else if (isa<TagDecl>(Instantiation)) {877 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)878 << (TSK != TSK_ImplicitInstantiation)879 << InstantiationTy;880 NoteTemplateLocation(*Pattern);881 } else {882 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");883 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {884 Diag(PointOfInstantiation,885 diag::err_explicit_instantiation_undefined_var_template)886 << Instantiation;887 Instantiation->setInvalidDecl();888 } else889 Diag(PointOfInstantiation,890 diag::err_explicit_instantiation_undefined_member)891 << /*static data member*/ 2 << Instantiation->getDeclName()892 << Instantiation->getDeclContext();893 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);894 }895 }896 897 // In general, Instantiation isn't marked invalid to get more than one898 // error for multiple undefined instantiations. But the code that does899 // explicit declaration -> explicit definition conversion can't handle900 // invalid declarations, so mark as invalid in that case.901 if (TSK == TSK_ExplicitInstantiationDeclaration)902 Instantiation->setInvalidDecl();903 return true;904}905 906void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,907 bool SupportedForCompatibility) {908 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");909 910 // C++23 [temp.local]p6:911 // The name of a template-parameter shall not be bound to any following.912 // declaration whose locus is contained by the scope to which the913 // template-parameter belongs.914 //915 // When MSVC compatibility is enabled, the diagnostic is always a warning916 // by default. Otherwise, it an error unless SupportedForCompatibility is917 // true, in which case it is a default-to-error warning.918 unsigned DiagId =919 getLangOpts().MSVCCompat920 ? diag::ext_template_param_shadow921 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow922 : diag::err_template_param_shadow);923 const auto *ND = cast<NamedDecl>(PrevDecl);924 Diag(Loc, DiagId) << ND->getDeclName();925 NoteTemplateParameterLocation(*ND);926}927 928TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {929 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {930 D = Temp->getTemplatedDecl();931 return Temp;932 }933 return nullptr;934}935 936ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(937 SourceLocation EllipsisLoc) const {938 assert(Kind == Template &&939 "Only template template arguments can be pack expansions here");940 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&941 "Template template argument pack expansion without packs");942 ParsedTemplateArgument Result(*this);943 Result.EllipsisLoc = EllipsisLoc;944 return Result;945}946 947static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,948 const ParsedTemplateArgument &Arg) {949 950 switch (Arg.getKind()) {951 case ParsedTemplateArgument::Type: {952 TypeSourceInfo *TSI;953 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &TSI);954 if (!TSI)955 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getNameLoc());956 return TemplateArgumentLoc(TemplateArgument(T), TSI);957 }958 959 case ParsedTemplateArgument::NonType: {960 Expr *E = Arg.getAsExpr();961 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);962 }963 964 case ParsedTemplateArgument::Template: {965 TemplateName Template = Arg.getAsTemplate().get();966 TemplateArgument TArg;967 if (Arg.getEllipsisLoc().isValid())968 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);969 else970 TArg = Template;971 return TemplateArgumentLoc(972 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),973 Arg.getScopeSpec().getWithLocInContext(SemaRef.Context),974 Arg.getNameLoc(), Arg.getEllipsisLoc());975 }976 }977 978 llvm_unreachable("Unhandled parsed template argument");979}980 981void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,982 TemplateArgumentListInfo &TemplateArgs) {983 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)984 TemplateArgs.addArgument(translateTemplateArgument(*this,985 TemplateArgsIn[I]));986}987 988static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,989 SourceLocation Loc,990 const IdentifierInfo *Name) {991 NamedDecl *PrevDecl =992 SemaRef.LookupSingleName(S, Name, Loc, Sema::LookupOrdinaryName,993 RedeclarationKind::ForVisibleRedeclaration);994 if (PrevDecl && PrevDecl->isTemplateParameter())995 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);996}997 998ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {999 TypeSourceInfo *TInfo;1000 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);1001 if (T.isNull())1002 return ParsedTemplateArgument();1003 assert(TInfo && "template argument with no location");1004 1005 // If we might have formed a deduced template specialization type, convert1006 // it to a template template argument.1007 if (getLangOpts().CPlusPlus17) {1008 TypeLoc TL = TInfo->getTypeLoc();1009 SourceLocation EllipsisLoc;1010 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {1011 EllipsisLoc = PET.getEllipsisLoc();1012 TL = PET.getPatternLoc();1013 }1014 1015 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {1016 TemplateName Name = DTST.getTypePtr()->getTemplateName();1017 CXXScopeSpec SS;1018 SS.Adopt(DTST.getQualifierLoc());1019 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,1020 TemplateTy::make(Name),1021 DTST.getTemplateNameLoc());1022 if (EllipsisLoc.isValid())1023 Result = Result.getTemplatePackExpansion(EllipsisLoc);1024 return Result;1025 }1026 }1027 1028 // This is a normal type template argument. Note, if the type template1029 // argument is an injected-class-name for a template, it has a dual nature1030 // and can be used as either a type or a template. We handle that in1031 // convertTypeTemplateArgumentToTemplate.1032 return ParsedTemplateArgument(ParsedTemplateArgument::Type,1033 ParsedType.get().getAsOpaquePtr(),1034 TInfo->getTypeLoc().getBeginLoc());1035}1036 1037NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,1038 SourceLocation EllipsisLoc,1039 SourceLocation KeyLoc,1040 IdentifierInfo *ParamName,1041 SourceLocation ParamNameLoc,1042 unsigned Depth, unsigned Position,1043 SourceLocation EqualLoc,1044 ParsedType DefaultArg,1045 bool HasTypeConstraint) {1046 assert(S->isTemplateParamScope() &&1047 "Template type parameter not in template parameter scope!");1048 1049 bool IsParameterPack = EllipsisLoc.isValid();1050 TemplateTypeParmDecl *Param1051 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),1052 KeyLoc, ParamNameLoc, Depth, Position,1053 ParamName, Typename, IsParameterPack,1054 HasTypeConstraint);1055 Param->setAccess(AS_public);1056 1057 if (Param->isParameterPack())1058 if (auto *CSI = getEnclosingLambdaOrBlock())1059 CSI->LocalPacks.push_back(Param);1060 1061 if (ParamName) {1062 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);1063 1064 // Add the template parameter into the current scope.1065 S->AddDecl(Param);1066 IdResolver.AddDecl(Param);1067 }1068 1069 // C++0x [temp.param]p9:1070 // A default template-argument may be specified for any kind of1071 // template-parameter that is not a template parameter pack.1072 if (DefaultArg && IsParameterPack) {1073 Diag(EqualLoc, diag::err_template_param_pack_default_arg);1074 DefaultArg = nullptr;1075 }1076 1077 // Handle the default argument, if provided.1078 if (DefaultArg) {1079 TypeSourceInfo *DefaultTInfo;1080 GetTypeFromParser(DefaultArg, &DefaultTInfo);1081 1082 assert(DefaultTInfo && "expected source information for type");1083 1084 // Check for unexpanded parameter packs.1085 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,1086 UPPC_DefaultArgument))1087 return Param;1088 1089 // Check the template argument itself.1090 if (CheckTemplateArgument(DefaultTInfo)) {1091 Param->setInvalidDecl();1092 return Param;1093 }1094 1095 Param->setDefaultArgument(1096 Context, TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));1097 }1098 1099 return Param;1100}1101 1102/// Convert the parser's template argument list representation into our form.1103static TemplateArgumentListInfo1104makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {1105 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,1106 TemplateId.RAngleLoc);1107 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),1108 TemplateId.NumArgs);1109 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);1110 return TemplateArgs;1111}1112 1113bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {1114 1115 TemplateName TN = TypeConstr->Template.get();1116 NamedDecl *CD = nullptr;1117 bool IsTypeConcept = false;1118 bool RequiresArguments = false;1119 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TN.getAsTemplateDecl())) {1120 IsTypeConcept = TTP->isTypeConceptTemplateParam();1121 RequiresArguments =1122 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;1123 CD = TTP;1124 } else {1125 CD = TN.getAsTemplateDecl();1126 IsTypeConcept = cast<ConceptDecl>(CD)->isTypeConcept();1127 RequiresArguments = cast<ConceptDecl>(CD)1128 ->getTemplateParameters()1129 ->getMinRequiredArguments() > 1;1130 }1131 1132 // C++2a [temp.param]p4:1133 // [...] The concept designated by a type-constraint shall be a type1134 // concept ([temp.concept]).1135 if (!IsTypeConcept) {1136 Diag(TypeConstr->TemplateNameLoc,1137 diag::err_type_constraint_non_type_concept);1138 return true;1139 }1140 1141 if (CheckConceptUseInDefinition(CD, TypeConstr->TemplateNameLoc))1142 return true;1143 1144 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();1145 1146 if (!WereArgsSpecified && RequiresArguments) {1147 Diag(TypeConstr->TemplateNameLoc,1148 diag::err_type_constraint_missing_arguments)1149 << CD;1150 return true;1151 }1152 return false;1153}1154 1155bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,1156 TemplateIdAnnotation *TypeConstr,1157 TemplateTypeParmDecl *ConstrainedParameter,1158 SourceLocation EllipsisLoc) {1159 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,1160 false);1161}1162 1163bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,1164 TemplateIdAnnotation *TypeConstr,1165 TemplateTypeParmDecl *ConstrainedParameter,1166 SourceLocation EllipsisLoc,1167 bool AllowUnexpandedPack) {1168 1169 if (CheckTypeConstraint(TypeConstr))1170 return true;1171 1172 TemplateName TN = TypeConstr->Template.get();1173 TemplateDecl *CD = cast<TemplateDecl>(TN.getAsTemplateDecl());1174 UsingShadowDecl *USD = TN.getAsUsingShadowDecl();1175 1176 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),1177 TypeConstr->TemplateNameLoc);1178 1179 TemplateArgumentListInfo TemplateArgs;1180 if (TypeConstr->LAngleLoc.isValid()) {1181 TemplateArgs =1182 makeTemplateArgumentListInfo(*this, *TypeConstr);1183 1184 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {1185 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {1186 if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint))1187 return true;1188 }1189 }1190 }1191 return AttachTypeConstraint(1192 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),1193 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,1194 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,1195 ConstrainedParameter, EllipsisLoc);1196}1197 1198template <typename ArgumentLocAppender>1199static ExprResult formImmediatelyDeclaredConstraint(1200 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,1201 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,1202 SourceLocation RAngleLoc, QualType ConstrainedType,1203 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,1204 SourceLocation EllipsisLoc) {1205 1206 TemplateArgumentListInfo ConstraintArgs;1207 ConstraintArgs.addArgument(1208 S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),1209 /*NTTPType=*/QualType(), ParamNameLoc));1210 1211 ConstraintArgs.setRAngleLoc(RAngleLoc);1212 ConstraintArgs.setLAngleLoc(LAngleLoc);1213 Appender(ConstraintArgs);1214 1215 // C++2a [temp.param]p4:1216 // [...] This constraint-expression E is called the immediately-declared1217 // constraint of T. [...]1218 CXXScopeSpec SS;1219 SS.Adopt(NS);1220 ExprResult ImmediatelyDeclaredConstraint;1221 if (auto *CD = dyn_cast<ConceptDecl>(NamedConcept)) {1222 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(1223 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,1224 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, CD, &ConstraintArgs,1225 /*DoCheckConstraintSatisfaction=*/1226 !S.inParameterMappingSubstitution());1227 }1228 // We have a template template parameter1229 else {1230 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(NamedConcept);1231 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(1232 SS, NameInfo, CDT, SourceLocation(), &ConstraintArgs);1233 }1234 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())1235 return ImmediatelyDeclaredConstraint;1236 1237 // C++2a [temp.param]p4:1238 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).1239 //1240 // We have the following case:1241 //1242 // template<typename T> concept C1 = true;1243 // template<C1... T> struct s1;1244 //1245 // The constraint: (C1<T> && ...)1246 //1247 // Note that the type of C1<T> is known to be 'bool', so we don't need to do1248 // any unqualified lookups for 'operator&&' here.1249 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,1250 /*LParenLoc=*/SourceLocation(),1251 ImmediatelyDeclaredConstraint.get(), BO_LAnd,1252 EllipsisLoc, /*RHS=*/nullptr,1253 /*RParenLoc=*/SourceLocation(),1254 /*NumExpansions=*/std::nullopt);1255}1256 1257bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,1258 DeclarationNameInfo NameInfo,1259 TemplateDecl *NamedConcept,1260 NamedDecl *FoundDecl,1261 const TemplateArgumentListInfo *TemplateArgs,1262 TemplateTypeParmDecl *ConstrainedParameter,1263 SourceLocation EllipsisLoc) {1264 // C++2a [temp.param]p4:1265 // [...] If Q is of the form C<A1, ..., An>, then let E' be1266 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]1267 const ASTTemplateArgumentListInfo *ArgsAsWritten =1268 TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,1269 *TemplateArgs) : nullptr;1270 1271 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);1272 1273 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(1274 *this, NS, NameInfo, NamedConcept, FoundDecl,1275 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),1276 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),1277 ParamAsArgument, ConstrainedParameter->getLocation(),1278 [&](TemplateArgumentListInfo &ConstraintArgs) {1279 if (TemplateArgs)1280 for (const auto &ArgLoc : TemplateArgs->arguments())1281 ConstraintArgs.addArgument(ArgLoc);1282 },1283 EllipsisLoc);1284 if (ImmediatelyDeclaredConstraint.isInvalid())1285 return true;1286 1287 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,1288 /*TemplateKWLoc=*/SourceLocation{},1289 /*ConceptNameInfo=*/NameInfo,1290 /*FoundDecl=*/FoundDecl,1291 /*NamedConcept=*/NamedConcept,1292 /*ArgsWritten=*/ArgsAsWritten);1293 ConstrainedParameter->setTypeConstraint(1294 CL, ImmediatelyDeclaredConstraint.get(), std::nullopt);1295 return false;1296}1297 1298bool Sema::AttachTypeConstraint(AutoTypeLoc TL,1299 NonTypeTemplateParmDecl *NewConstrainedParm,1300 NonTypeTemplateParmDecl *OrigConstrainedParm,1301 SourceLocation EllipsisLoc) {1302 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||1303 TL.getAutoKeyword() != AutoTypeKeyword::Auto) {1304 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),1305 diag::err_unsupported_placeholder_constraint)1306 << NewConstrainedParm->getTypeSourceInfo()1307 ->getTypeLoc()1308 .getSourceRange();1309 return true;1310 }1311 // FIXME: Concepts: This should be the type of the placeholder, but this is1312 // unclear in the wording right now.1313 DeclRefExpr *Ref =1314 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),1315 VK_PRValue, OrigConstrainedParm->getLocation());1316 if (!Ref)1317 return true;1318 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(1319 *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),1320 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),1321 TL.getRAngleLoc(), BuildDecltypeType(Ref),1322 OrigConstrainedParm->getLocation(),1323 [&](TemplateArgumentListInfo &ConstraintArgs) {1324 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)1325 ConstraintArgs.addArgument(TL.getArgLoc(I));1326 },1327 EllipsisLoc);1328 if (ImmediatelyDeclaredConstraint.isInvalid() ||1329 !ImmediatelyDeclaredConstraint.isUsable())1330 return true;1331 1332 NewConstrainedParm->setPlaceholderTypeConstraint(1333 ImmediatelyDeclaredConstraint.get());1334 return false;1335}1336 1337QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,1338 SourceLocation Loc) {1339 if (TSI->getType()->isUndeducedType()) {1340 // C++17 [temp.dep.expr]p3:1341 // An id-expression is type-dependent if it contains1342 // - an identifier associated by name lookup with a non-type1343 // template-parameter declared with a type that contains a1344 // placeholder type (7.1.7.4),1345 TSI = SubstAutoTypeSourceInfoDependent(TSI);1346 }1347 1348 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);1349}1350 1351bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {1352 if (T->isDependentType())1353 return false;1354 1355 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))1356 return true;1357 1358 if (T->isStructuralType())1359 return false;1360 1361 // Structural types are required to be object types or lvalue references.1362 if (T->isRValueReferenceType()) {1363 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;1364 return true;1365 }1366 1367 // Don't mention structural types in our diagnostic prior to C++20. Also,1368 // there's not much more we can say about non-scalar non-class types --1369 // because we can't see functions or arrays here, those can only be language1370 // extensions.1371 if (!getLangOpts().CPlusPlus20 ||1372 (!T->isScalarType() && !T->isRecordType())) {1373 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;1374 return true;1375 }1376 1377 // Structural types are required to be literal types.1378 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))1379 return true;1380 1381 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;1382 1383 // Drill down into the reason why the class is non-structural.1384 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {1385 // All members are required to be public and non-mutable, and can't be of1386 // rvalue reference type. Check these conditions first to prefer a "local"1387 // reason over a more distant one.1388 for (const FieldDecl *FD : RD->fields()) {1389 if (FD->getAccess() != AS_public) {1390 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;1391 return true;1392 }1393 if (FD->isMutable()) {1394 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;1395 return true;1396 }1397 if (FD->getType()->isRValueReferenceType()) {1398 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)1399 << T;1400 return true;1401 }1402 }1403 1404 // All bases are required to be public.1405 for (const auto &BaseSpec : RD->bases()) {1406 if (BaseSpec.getAccessSpecifier() != AS_public) {1407 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)1408 << T << 1;1409 return true;1410 }1411 }1412 1413 // All subobjects are required to be of structural types.1414 SourceLocation SubLoc;1415 QualType SubType;1416 int Kind = -1;1417 1418 for (const FieldDecl *FD : RD->fields()) {1419 QualType T = Context.getBaseElementType(FD->getType());1420 if (!T->isStructuralType()) {1421 SubLoc = FD->getLocation();1422 SubType = T;1423 Kind = 0;1424 break;1425 }1426 }1427 1428 if (Kind == -1) {1429 for (const auto &BaseSpec : RD->bases()) {1430 QualType T = BaseSpec.getType();1431 if (!T->isStructuralType()) {1432 SubLoc = BaseSpec.getBaseTypeLoc();1433 SubType = T;1434 Kind = 1;1435 break;1436 }1437 }1438 }1439 1440 assert(Kind != -1 && "couldn't find reason why type is not structural");1441 Diag(SubLoc, diag::note_not_structural_subobject)1442 << T << Kind << SubType;1443 T = SubType;1444 RD = T->getAsCXXRecordDecl();1445 }1446 1447 return true;1448}1449 1450QualType Sema::CheckNonTypeTemplateParameterType(QualType T,1451 SourceLocation Loc) {1452 // We don't allow variably-modified types as the type of non-type template1453 // parameters.1454 if (T->isVariablyModifiedType()) {1455 Diag(Loc, diag::err_variably_modified_nontype_template_param)1456 << T;1457 return QualType();1458 }1459 1460 // C++ [temp.param]p4:1461 //1462 // A non-type template-parameter shall have one of the following1463 // (optionally cv-qualified) types:1464 //1465 // -- integral or enumeration type,1466 if (T->isIntegralOrEnumerationType() ||1467 // -- pointer to object or pointer to function,1468 T->isPointerType() ||1469 // -- lvalue reference to object or lvalue reference to function,1470 T->isLValueReferenceType() ||1471 // -- pointer to member,1472 T->isMemberPointerType() ||1473 // -- std::nullptr_t, or1474 T->isNullPtrType() ||1475 // -- a type that contains a placeholder type.1476 T->isUndeducedType()) {1477 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter1478 // are ignored when determining its type.1479 return T.getUnqualifiedType();1480 }1481 1482 // C++ [temp.param]p8:1483 //1484 // A non-type template-parameter of type "array of T" or1485 // "function returning T" is adjusted to be of type "pointer to1486 // T" or "pointer to function returning T", respectively.1487 if (T->isArrayType() || T->isFunctionType())1488 return Context.getDecayedType(T);1489 1490 // If T is a dependent type, we can't do the check now, so we1491 // assume that it is well-formed. Note that stripping off the1492 // qualifiers here is not really correct if T turns out to be1493 // an array type, but we'll recompute the type everywhere it's1494 // used during instantiation, so that should be OK. (Using the1495 // qualified type is equally wrong.)1496 if (T->isDependentType())1497 return T.getUnqualifiedType();1498 1499 // C++20 [temp.param]p6:1500 // -- a structural type1501 if (RequireStructuralType(T, Loc))1502 return QualType();1503 1504 if (!getLangOpts().CPlusPlus20) {1505 // FIXME: Consider allowing structural types as an extension in C++17. (In1506 // earlier language modes, the template argument evaluation rules are too1507 // inflexible.)1508 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;1509 return QualType();1510 }1511 1512 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;1513 return T.getUnqualifiedType();1514}1515 1516NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,1517 unsigned Depth,1518 unsigned Position,1519 SourceLocation EqualLoc,1520 Expr *Default) {1521 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);1522 1523 // Check that we have valid decl-specifiers specified.1524 auto CheckValidDeclSpecifiers = [this, &D] {1525 // C++ [temp.param]1526 // p11527 // template-parameter:1528 // ...1529 // parameter-declaration1530 // p21531 // ... A storage class shall not be specified in a template-parameter1532 // declaration.1533 // [dcl.typedef]p1:1534 // The typedef specifier [...] shall not be used in the decl-specifier-seq1535 // of a parameter-declaration1536 const DeclSpec &DS = D.getDeclSpec();1537 auto EmitDiag = [this](SourceLocation Loc) {1538 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)1539 << FixItHint::CreateRemoval(Loc);1540 };1541 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)1542 EmitDiag(DS.getStorageClassSpecLoc());1543 1544 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)1545 EmitDiag(DS.getThreadStorageClassSpecLoc());1546 1547 // [dcl.inline]p1:1548 // The inline specifier can be applied only to the declaration or1549 // definition of a variable or function.1550 1551 if (DS.isInlineSpecified())1552 EmitDiag(DS.getInlineSpecLoc());1553 1554 // [dcl.constexpr]p1:1555 // The constexpr specifier shall be applied only to the definition of a1556 // variable or variable template or the declaration of a function or1557 // function template.1558 1559 if (DS.hasConstexprSpecifier())1560 EmitDiag(DS.getConstexprSpecLoc());1561 1562 // [dcl.fct.spec]p1:1563 // Function-specifiers can be used only in function declarations.1564 1565 if (DS.isVirtualSpecified())1566 EmitDiag(DS.getVirtualSpecLoc());1567 1568 if (DS.hasExplicitSpecifier())1569 EmitDiag(DS.getExplicitSpecLoc());1570 1571 if (DS.isNoreturnSpecified())1572 EmitDiag(DS.getNoreturnSpecLoc());1573 };1574 1575 CheckValidDeclSpecifiers();1576 1577 if (const auto *T = TInfo->getType()->getContainedDeducedType())1578 if (isa<AutoType>(T))1579 Diag(D.getIdentifierLoc(),1580 diag::warn_cxx14_compat_template_nontype_parm_auto_type)1581 << QualType(TInfo->getType()->getContainedAutoType(), 0);1582 1583 assert(S->isTemplateParamScope() &&1584 "Non-type template parameter not in template parameter scope!");1585 bool Invalid = false;1586 1587 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());1588 if (T.isNull()) {1589 T = Context.IntTy; // Recover with an 'int' type.1590 Invalid = true;1591 }1592 1593 CheckFunctionOrTemplateParamDeclarator(S, D);1594 1595 const IdentifierInfo *ParamName = D.getIdentifier();1596 bool IsParameterPack = D.hasEllipsis();1597 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(1598 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),1599 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,1600 TInfo);1601 Param->setAccess(AS_public);1602 1603 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())1604 if (TL.isConstrained()) {1605 if (D.getEllipsisLoc().isInvalid() &&1606 T->containsUnexpandedParameterPack()) {1607 assert(TL.getConceptReference()->getTemplateArgsAsWritten());1608 for (auto &Loc :1609 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())1610 Invalid |= DiagnoseUnexpandedParameterPack(1611 Loc, UnexpandedParameterPackContext::UPPC_TypeConstraint);1612 }1613 if (!Invalid &&1614 AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))1615 Invalid = true;1616 }1617 1618 if (Invalid)1619 Param->setInvalidDecl();1620 1621 if (Param->isParameterPack())1622 if (auto *CSI = getEnclosingLambdaOrBlock())1623 CSI->LocalPacks.push_back(Param);1624 1625 if (ParamName) {1626 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),1627 ParamName);1628 1629 // Add the template parameter into the current scope.1630 S->AddDecl(Param);1631 IdResolver.AddDecl(Param);1632 }1633 1634 // C++0x [temp.param]p9:1635 // A default template-argument may be specified for any kind of1636 // template-parameter that is not a template parameter pack.1637 if (Default && IsParameterPack) {1638 Diag(EqualLoc, diag::err_template_param_pack_default_arg);1639 Default = nullptr;1640 }1641 1642 // Check the well-formedness of the default template argument, if provided.1643 if (Default) {1644 // Check for unexpanded parameter packs.1645 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))1646 return Param;1647 1648 Param->setDefaultArgument(1649 Context, getTrivialTemplateArgumentLoc(1650 TemplateArgument(Default, /*IsCanonical=*/false),1651 QualType(), SourceLocation()));1652 }1653 1654 return Param;1655}1656 1657/// ActOnTemplateTemplateParameter - Called when a C++ template template1658/// parameter (e.g. T in template <template \<typename> class T> class array)1659/// has been parsed. S is the current scope.1660NamedDecl *Sema::ActOnTemplateTemplateParameter(1661 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,1662 TemplateParameterList *Params, SourceLocation EllipsisLoc,1663 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,1664 unsigned Position, SourceLocation EqualLoc,1665 ParsedTemplateArgument Default) {1666 assert(S->isTemplateParamScope() &&1667 "Template template parameter not in template parameter scope!");1668 1669 bool IsParameterPack = EllipsisLoc.isValid();1670 1671 bool Invalid = false;1672 if (CheckTemplateParameterList(1673 Params,1674 /*OldParams=*/nullptr,1675 IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))1676 Invalid = true;1677 1678 // Construct the parameter object.1679 TemplateTemplateParmDecl *Param = TemplateTemplateParmDecl::Create(1680 Context, Context.getTranslationUnitDecl(),1681 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,1682 Name, Kind, Typename, Params);1683 Param->setAccess(AS_public);1684 1685 if (Param->isParameterPack())1686 if (auto *LSI = getEnclosingLambdaOrBlock())1687 LSI->LocalPacks.push_back(Param);1688 1689 // If the template template parameter has a name, then link the identifier1690 // into the scope and lookup mechanisms.1691 if (Name) {1692 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);1693 1694 S->AddDecl(Param);1695 IdResolver.AddDecl(Param);1696 }1697 1698 if (Params->size() == 0) {1699 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)1700 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());1701 Invalid = true;1702 }1703 1704 if (Invalid)1705 Param->setInvalidDecl();1706 1707 // C++0x [temp.param]p9:1708 // A default template-argument may be specified for any kind of1709 // template-parameter that is not a template parameter pack.1710 if (IsParameterPack && !Default.isInvalid()) {1711 Diag(EqualLoc, diag::err_template_param_pack_default_arg);1712 Default = ParsedTemplateArgument();1713 }1714 1715 if (!Default.isInvalid()) {1716 // Check only that we have a template template argument. We don't want to1717 // try to check well-formedness now, because our template template parameter1718 // might have dependent types in its template parameters, which we wouldn't1719 // be able to match now.1720 //1721 // If none of the template template parameter's template arguments mention1722 // other template parameters, we could actually perform more checking here.1723 // However, it isn't worth doing.1724 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);1725 if (DefaultArg.getArgument().getAsTemplate().isNull()) {1726 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)1727 << DefaultArg.getSourceRange();1728 return Param;1729 }1730 1731 TemplateName Name =1732 DefaultArg.getArgument().getAsTemplateOrTemplatePattern();1733 TemplateDecl *Template = Name.getAsTemplateDecl();1734 if (Template &&1735 !CheckDeclCompatibleWithTemplateTemplate(Template, Param, DefaultArg)) {1736 return Param;1737 }1738 1739 // Check for unexpanded parameter packs.1740 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),1741 DefaultArg.getArgument().getAsTemplate(),1742 UPPC_DefaultArgument))1743 return Param;1744 1745 Param->setDefaultArgument(Context, DefaultArg);1746 }1747 1748 return Param;1749}1750 1751namespace {1752class ConstraintRefersToContainingTemplateChecker1753 : public ConstDynamicRecursiveASTVisitor {1754 using inherited = ConstDynamicRecursiveASTVisitor;1755 bool Result = false;1756 const FunctionDecl *Friend = nullptr;1757 unsigned TemplateDepth = 0;1758 1759 // Check a record-decl that we've seen to see if it is a lexical parent of the1760 // Friend, likely because it was referred to without its template arguments.1761 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {1762 CheckingRD = CheckingRD->getMostRecentDecl();1763 if (!CheckingRD->isTemplated())1764 return true;1765 1766 for (const DeclContext *DC = Friend->getLexicalDeclContext();1767 DC && !DC->isFileContext(); DC = DC->getParent())1768 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))1769 if (CheckingRD == RD->getMostRecentDecl()) {1770 Result = true;1771 return false;1772 }1773 1774 return true;1775 }1776 1777 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {1778 if (D->getDepth() < TemplateDepth)1779 Result = true;1780 1781 // Necessary because the type of the NTTP might be what refers to the parent1782 // constriant.1783 return TraverseType(D->getType());1784 }1785 1786public:1787 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,1788 unsigned TemplateDepth)1789 : Friend(Friend), TemplateDepth(TemplateDepth) {}1790 1791 bool getResult() const { return Result; }1792 1793 // This should be the only template parm type that we have to deal with.1794 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and1795 // FunctionParmPackExpr are all partially substituted, which cannot happen1796 // with concepts at this point in translation.1797 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {1798 if (Type->getDecl()->getDepth() < TemplateDepth) {1799 Result = true;1800 return false;1801 }1802 return true;1803 }1804 1805 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {1806 return TraverseDecl(E->getDecl());1807 }1808 1809 bool TraverseTypedefType(const TypedefType *TT,1810 bool /*TraverseQualifier*/) override {1811 return TraverseType(TT->desugar());1812 }1813 1814 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {1815 // We don't care about TypeLocs. So traverse Types instead.1816 return TraverseType(TL.getType(), TraverseQualifier);1817 }1818 1819 bool VisitTagType(const TagType *T) override {1820 return TraverseDecl(T->getDecl());1821 }1822 1823 bool TraverseDecl(const Decl *D) override {1824 assert(D);1825 // FIXME : This is possibly an incomplete list, but it is unclear what other1826 // Decl kinds could be used to refer to the template parameters. This is a1827 // best guess so far based on examples currently available, but the1828 // unreachable should catch future instances/cases.1829 if (auto *TD = dyn_cast<TypedefNameDecl>(D))1830 return TraverseType(TD->getUnderlyingType());1831 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))1832 return CheckNonTypeTemplateParmDecl(NTTPD);1833 if (auto *VD = dyn_cast<ValueDecl>(D))1834 return TraverseType(VD->getType());1835 if (isa<TemplateDecl>(D))1836 return true;1837 if (auto *RD = dyn_cast<CXXRecordDecl>(D))1838 return CheckIfContainingRecord(RD);1839 1840 if (isa<NamedDecl, RequiresExprBodyDecl>(D)) {1841 // No direct types to visit here I believe.1842 } else1843 llvm_unreachable("Don't know how to handle this declaration type yet");1844 return true;1845 }1846};1847} // namespace1848 1849bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(1850 const FunctionDecl *Friend, unsigned TemplateDepth,1851 const Expr *Constraint) {1852 assert(Friend->getFriendObjectKind() && "Only works on a friend");1853 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);1854 Checker.TraverseStmt(Constraint);1855 return Checker.getResult();1856}1857 1858TemplateParameterList *1859Sema::ActOnTemplateParameterList(unsigned Depth,1860 SourceLocation ExportLoc,1861 SourceLocation TemplateLoc,1862 SourceLocation LAngleLoc,1863 ArrayRef<NamedDecl *> Params,1864 SourceLocation RAngleLoc,1865 Expr *RequiresClause) {1866 if (ExportLoc.isValid())1867 Diag(ExportLoc, diag::warn_template_export_unsupported);1868 1869 for (NamedDecl *P : Params)1870 warnOnReservedIdentifier(P);1871 1872 return TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,1873 llvm::ArrayRef(Params), RAngleLoc,1874 RequiresClause);1875}1876 1877static void SetNestedNameSpecifier(Sema &S, TagDecl *T,1878 const CXXScopeSpec &SS) {1879 if (SS.isSet())1880 T->setQualifierInfo(SS.getWithLocInContext(S.Context));1881}1882 1883// Returns the template parameter list with all default template argument1884// information.1885TemplateParameterList *Sema::GetTemplateParameterList(TemplateDecl *TD) {1886 // Make sure we get the template parameter list from the most1887 // recent declaration, since that is the only one that is guaranteed to1888 // have all the default template argument information.1889 Decl *D = TD->getMostRecentDecl();1890 // C++11 N3337 [temp.param]p12:1891 // A default template argument shall not be specified in a friend class1892 // template declaration.1893 //1894 // Skip past friend *declarations* because they are not supposed to contain1895 // default template arguments. Moreover, these declarations may introduce1896 // template parameters living in different template depths than the1897 // corresponding template parameters in TD, causing unmatched constraint1898 // substitution.1899 //1900 // FIXME: Diagnose such cases within a class template:1901 // template <class T>1902 // struct S {1903 // template <class = void> friend struct C;1904 // };1905 // template struct S<int>;1906 while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&1907 D->getPreviousDecl())1908 D = D->getPreviousDecl();1909 return cast<TemplateDecl>(D)->getTemplateParameters();1910}1911 1912DeclResult Sema::CheckClassTemplate(1913 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,1914 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,1915 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,1916 AccessSpecifier AS, SourceLocation ModulePrivateLoc,1917 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,1918 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {1919 assert(TemplateParams && TemplateParams->size() > 0 &&1920 "No template parameters");1921 assert(TUK != TagUseKind::Reference &&1922 "Can only declare or define class templates");1923 bool Invalid = false;1924 1925 // Check that we can declare a template here.1926 if (CheckTemplateDeclScope(S, TemplateParams))1927 return true;1928 1929 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);1930 assert(Kind != TagTypeKind::Enum &&1931 "can't build template of enumerated type");1932 1933 // There is no such thing as an unnamed class template.1934 if (!Name) {1935 Diag(KWLoc, diag::err_template_unnamed_class);1936 return true;1937 }1938 1939 // Find any previous declaration with this name. For a friend with no1940 // scope explicitly specified, we only look for tag declarations (per1941 // C++11 [basic.lookup.elab]p2).1942 DeclContext *SemanticContext;1943 LookupResult Previous(*this, Name, NameLoc,1944 (SS.isEmpty() && TUK == TagUseKind::Friend)1945 ? LookupTagName1946 : LookupOrdinaryName,1947 forRedeclarationInCurContext());1948 if (SS.isNotEmpty() && !SS.isInvalid()) {1949 SemanticContext = computeDeclContext(SS, true);1950 if (!SemanticContext) {1951 // FIXME: Horrible, horrible hack! We can't currently represent this1952 // in the AST, and historically we have just ignored such friend1953 // class templates, so don't complain here.1954 Diag(NameLoc, TUK == TagUseKind::Friend1955 ? diag::warn_template_qualified_friend_ignored1956 : diag::err_template_qualified_declarator_no_match)1957 << SS.getScopeRep() << SS.getRange();1958 return TUK != TagUseKind::Friend;1959 }1960 1961 if (RequireCompleteDeclContext(SS, SemanticContext))1962 return true;1963 1964 // If we're adding a template to a dependent context, we may need to1965 // rebuilding some of the types used within the template parameter list,1966 // now that we know what the current instantiation is.1967 if (SemanticContext->isDependentContext()) {1968 ContextRAII SavedContext(*this, SemanticContext);1969 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))1970 Invalid = true;1971 }1972 1973 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)1974 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,1975 /*TemplateId-*/ nullptr,1976 /*IsMemberSpecialization*/ false);1977 1978 LookupQualifiedName(Previous, SemanticContext);1979 } else {1980 SemanticContext = CurContext;1981 1982 // C++14 [class.mem]p14:1983 // If T is the name of a class, then each of the following shall have a1984 // name different from T:1985 // -- every member template of class T1986 if (TUK != TagUseKind::Friend &&1987 DiagnoseClassNameShadow(SemanticContext,1988 DeclarationNameInfo(Name, NameLoc)))1989 return true;1990 1991 LookupName(Previous, S);1992 }1993 1994 if (Previous.isAmbiguous())1995 return true;1996 1997 // Let the template parameter scope enter the lookup chain of the current1998 // class template. For example, given1999 //2000 // namespace ns {2001 // template <class> bool Param = false;2002 // template <class T> struct N;2003 // }2004 //2005 // template <class Param> struct ns::N { void foo(Param); };2006 //2007 // When we reference Param inside the function parameter list, our name lookup2008 // chain for it should be like:2009 // FunctionScope foo2010 // -> RecordScope N2011 // -> TemplateParamScope (where we will find Param)2012 // -> NamespaceScope ns2013 //2014 // See also CppLookupName().2015 if (S->isTemplateParamScope())2016 EnterTemplatedContext(S, SemanticContext);2017 2018 NamedDecl *PrevDecl = nullptr;2019 if (Previous.begin() != Previous.end())2020 PrevDecl = (*Previous.begin())->getUnderlyingDecl();2021 2022 if (PrevDecl && PrevDecl->isTemplateParameter()) {2023 // Maybe we will complain about the shadowed template parameter.2024 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);2025 // Just pretend that we didn't see the previous declaration.2026 PrevDecl = nullptr;2027 }2028 2029 // If there is a previous declaration with the same name, check2030 // whether this is a valid redeclaration.2031 ClassTemplateDecl *PrevClassTemplate =2032 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);2033 2034 // We may have found the injected-class-name of a class template,2035 // class template partial specialization, or class template specialization.2036 // In these cases, grab the template that is being defined or specialized.2037 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(PrevDecl) &&2038 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {2039 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());2040 PrevClassTemplate2041 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();2042 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {2043 PrevClassTemplate2044 = cast<ClassTemplateSpecializationDecl>(PrevDecl)2045 ->getSpecializedTemplate();2046 }2047 }2048 2049 if (TUK == TagUseKind::Friend) {2050 // C++ [namespace.memdef]p3:2051 // [...] When looking for a prior declaration of a class or a function2052 // declared as a friend, and when the name of the friend class or2053 // function is neither a qualified name nor a template-id, scopes outside2054 // the innermost enclosing namespace scope are not considered.2055 if (!SS.isSet()) {2056 DeclContext *OutermostContext = CurContext;2057 while (!OutermostContext->isFileContext())2058 OutermostContext = OutermostContext->getLookupParent();2059 2060 if (PrevDecl &&2061 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||2062 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {2063 SemanticContext = PrevDecl->getDeclContext();2064 } else {2065 // Declarations in outer scopes don't matter. However, the outermost2066 // context we computed is the semantic context for our new2067 // declaration.2068 PrevDecl = PrevClassTemplate = nullptr;2069 SemanticContext = OutermostContext;2070 2071 // Check that the chosen semantic context doesn't already contain a2072 // declaration of this name as a non-tag type.2073 Previous.clear(LookupOrdinaryName);2074 DeclContext *LookupContext = SemanticContext;2075 while (LookupContext->isTransparentContext())2076 LookupContext = LookupContext->getLookupParent();2077 LookupQualifiedName(Previous, LookupContext);2078 2079 if (Previous.isAmbiguous())2080 return true;2081 2082 if (Previous.begin() != Previous.end())2083 PrevDecl = (*Previous.begin())->getUnderlyingDecl();2084 }2085 }2086 } else if (PrevDecl && !isDeclInScope(Previous.getRepresentativeDecl(),2087 SemanticContext, S, SS.isValid()))2088 PrevDecl = PrevClassTemplate = nullptr;2089 2090 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(2091 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {2092 if (SS.isEmpty() &&2093 !(PrevClassTemplate &&2094 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(2095 SemanticContext->getRedeclContext()))) {2096 Diag(KWLoc, diag::err_using_decl_conflict_reverse);2097 Diag(Shadow->getTargetDecl()->getLocation(),2098 diag::note_using_decl_target);2099 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;2100 // Recover by ignoring the old declaration.2101 PrevDecl = PrevClassTemplate = nullptr;2102 }2103 }2104 2105 if (PrevClassTemplate) {2106 // Ensure that the template parameter lists are compatible. Skip this check2107 // for a friend in a dependent context: the template parameter list itself2108 // could be dependent.2109 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&2110 !TemplateParameterListsAreEqual(2111 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext2112 : CurContext,2113 CurContext, KWLoc),2114 TemplateParams, PrevClassTemplate,2115 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,2116 TPL_TemplateMatch))2117 return true;2118 2119 // C++ [temp.class]p4:2120 // In a redeclaration, partial specialization, explicit2121 // specialization or explicit instantiation of a class template,2122 // the class-key shall agree in kind with the original class2123 // template declaration (7.1.5.3).2124 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();2125 if (!isAcceptableTagRedeclaration(2126 PrevRecordDecl, Kind, TUK == TagUseKind::Definition, KWLoc, Name)) {2127 Diag(KWLoc, diag::err_use_with_wrong_tag)2128 << Name2129 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());2130 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);2131 Kind = PrevRecordDecl->getTagKind();2132 }2133 2134 // Check for redefinition of this class template.2135 if (TUK == TagUseKind::Definition) {2136 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {2137 // If we have a prior definition that is not visible, treat this as2138 // simply making that previous definition visible.2139 NamedDecl *Hidden = nullptr;2140 bool HiddenDefVisible = false;2141 if (SkipBody &&2142 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {2143 SkipBody->ShouldSkip = true;2144 SkipBody->Previous = Def;2145 if (!HiddenDefVisible && Hidden) {2146 auto *Tmpl =2147 cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();2148 assert(Tmpl && "original definition of a class template is not a "2149 "class template?");2150 makeMergedDefinitionVisible(Hidden);2151 makeMergedDefinitionVisible(Tmpl);2152 }2153 } else {2154 Diag(NameLoc, diag::err_redefinition) << Name;2155 Diag(Def->getLocation(), diag::note_previous_definition);2156 // FIXME: Would it make sense to try to "forget" the previous2157 // definition, as part of error recovery?2158 return true;2159 }2160 }2161 }2162 } else if (PrevDecl) {2163 // C++ [temp]p5:2164 // A class template shall not have the same name as any other2165 // template, class, function, object, enumeration, enumerator,2166 // namespace, or type in the same scope (3.3), except as specified2167 // in (14.5.4).2168 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;2169 Diag(PrevDecl->getLocation(), diag::note_previous_definition);2170 return true;2171 }2172 2173 // Check the template parameter list of this declaration, possibly2174 // merging in the template parameter list from the previous class2175 // template declaration. Skip this check for a friend in a dependent2176 // context, because the template parameter list might be dependent.2177 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&2178 CheckTemplateParameterList(2179 TemplateParams,2180 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)2181 : nullptr,2182 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&2183 SemanticContext->isDependentContext())2184 ? TPC_ClassTemplateMember2185 : TUK == TagUseKind::Friend ? TPC_FriendClassTemplate2186 : TPC_Other,2187 SkipBody))2188 Invalid = true;2189 2190 if (SS.isSet()) {2191 // If the name of the template was qualified, we must be defining the2192 // template out-of-line.2193 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {2194 Diag(NameLoc, TUK == TagUseKind::Friend2195 ? diag::err_friend_decl_does_not_match2196 : diag::err_member_decl_does_not_match)2197 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();2198 Invalid = true;2199 }2200 }2201 2202 // If this is a templated friend in a dependent context we should not put it2203 // on the redecl chain. In some cases, the templated friend can be the most2204 // recent declaration tricking the template instantiator to make substitutions2205 // there.2206 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious2207 bool ShouldAddRedecl =2208 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());2209 2210 CXXRecordDecl *NewClass = CXXRecordDecl::Create(2211 Context, Kind, SemanticContext, KWLoc, NameLoc, Name,2212 PrevClassTemplate && ShouldAddRedecl2213 ? PrevClassTemplate->getTemplatedDecl()2214 : nullptr);2215 SetNestedNameSpecifier(*this, NewClass, SS);2216 if (NumOuterTemplateParamLists > 0)2217 NewClass->setTemplateParameterListsInfo(2218 Context,2219 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));2220 2221 // Add alignment attributes if necessary; these attributes are checked when2222 // the ASTContext lays out the structure.2223 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {2224 if (LangOpts.HLSL)2225 NewClass->addAttr(PackedAttr::CreateImplicit(Context));2226 AddAlignmentAttributesForRecord(NewClass);2227 AddMsStructLayoutForRecord(NewClass);2228 }2229 2230 ClassTemplateDecl *NewTemplate2231 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,2232 DeclarationName(Name), TemplateParams,2233 NewClass);2234 2235 if (ShouldAddRedecl)2236 NewTemplate->setPreviousDecl(PrevClassTemplate);2237 2238 NewClass->setDescribedClassTemplate(NewTemplate);2239 2240 if (ModulePrivateLoc.isValid())2241 NewTemplate->setModulePrivate();2242 2243 // If we are providing an explicit specialization of a member that is a2244 // class template, make a note of that.2245 if (PrevClassTemplate &&2246 PrevClassTemplate->getInstantiatedFromMemberTemplate())2247 PrevClassTemplate->setMemberSpecialization();2248 2249 // Set the access specifier.2250 if (!Invalid && TUK != TagUseKind::Friend &&2251 NewTemplate->getDeclContext()->isRecord())2252 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);2253 2254 // Set the lexical context of these templates2255 NewClass->setLexicalDeclContext(CurContext);2256 NewTemplate->setLexicalDeclContext(CurContext);2257 2258 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))2259 NewClass->startDefinition();2260 2261 ProcessDeclAttributeList(S, NewClass, Attr);2262 2263 if (PrevClassTemplate)2264 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());2265 2266 AddPushedVisibilityAttribute(NewClass);2267 inferGslOwnerPointerAttribute(NewClass);2268 inferNullableClassAttribute(NewClass);2269 2270 if (TUK != TagUseKind::Friend) {2271 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.2272 Scope *Outer = S;2273 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)2274 Outer = Outer->getParent();2275 PushOnScopeChains(NewTemplate, Outer);2276 } else {2277 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {2278 NewTemplate->setAccess(PrevClassTemplate->getAccess());2279 NewClass->setAccess(PrevClassTemplate->getAccess());2280 }2281 2282 NewTemplate->setObjectOfFriendDecl();2283 2284 // Friend templates are visible in fairly strange ways.2285 if (!CurContext->isDependentContext()) {2286 DeclContext *DC = SemanticContext->getRedeclContext();2287 DC->makeDeclVisibleInContext(NewTemplate);2288 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))2289 PushOnScopeChains(NewTemplate, EnclosingScope,2290 /* AddToContext = */ false);2291 }2292 2293 FriendDecl *Friend = FriendDecl::Create(2294 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);2295 Friend->setAccess(AS_public);2296 CurContext->addDecl(Friend);2297 }2298 2299 if (PrevClassTemplate)2300 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);2301 2302 if (Invalid) {2303 NewTemplate->setInvalidDecl();2304 NewClass->setInvalidDecl();2305 }2306 2307 ActOnDocumentableDecl(NewTemplate);2308 2309 if (SkipBody && SkipBody->ShouldSkip)2310 return SkipBody->Previous;2311 2312 return NewTemplate;2313}2314 2315/// Diagnose the presence of a default template argument on a2316/// template parameter, which is ill-formed in certain contexts.2317///2318/// \returns true if the default template argument should be dropped.2319static bool DiagnoseDefaultTemplateArgument(Sema &S,2320 Sema::TemplateParamListContext TPC,2321 SourceLocation ParamLoc,2322 SourceRange DefArgRange) {2323 switch (TPC) {2324 case Sema::TPC_Other:2325 case Sema::TPC_TemplateTemplateParameterPack:2326 return false;2327 2328 case Sema::TPC_FunctionTemplate:2329 case Sema::TPC_FriendFunctionTemplateDefinition:2330 // C++ [temp.param]p9:2331 // A default template-argument shall not be specified in a2332 // function template declaration or a function template2333 // definition [...]2334 // If a friend function template declaration specifies a default2335 // template-argument, that declaration shall be a definition and shall be2336 // the only declaration of the function template in the translation unit.2337 // (C++98/03 doesn't have this wording; see DR226).2338 S.DiagCompat(ParamLoc, diag_compat::templ_default_in_function_templ)2339 << DefArgRange;2340 return false;2341 2342 case Sema::TPC_ClassTemplateMember:2343 // C++0x [temp.param]p9:2344 // A default template-argument shall not be specified in the2345 // template-parameter-lists of the definition of a member of a2346 // class template that appears outside of the member's class.2347 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)2348 << DefArgRange;2349 return true;2350 2351 case Sema::TPC_FriendClassTemplate:2352 case Sema::TPC_FriendFunctionTemplate:2353 // C++ [temp.param]p9:2354 // A default template-argument shall not be specified in a2355 // friend template declaration.2356 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)2357 << DefArgRange;2358 return true;2359 2360 // FIXME: C++0x [temp.param]p9 allows default template-arguments2361 // for friend function templates if there is only a single2362 // declaration (and it is a definition). Strange!2363 }2364 2365 llvm_unreachable("Invalid TemplateParamListContext!");2366}2367 2368/// Check for unexpanded parameter packs within the template parameters2369/// of a template template parameter, recursively.2370static bool DiagnoseUnexpandedParameterPacks(Sema &S,2371 TemplateTemplateParmDecl *TTP) {2372 // A template template parameter which is a parameter pack is also a pack2373 // expansion.2374 if (TTP->isParameterPack())2375 return false;2376 2377 TemplateParameterList *Params = TTP->getTemplateParameters();2378 for (unsigned I = 0, N = Params->size(); I != N; ++I) {2379 NamedDecl *P = Params->getParam(I);2380 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {2381 if (!TTP->isParameterPack())2382 if (const TypeConstraint *TC = TTP->getTypeConstraint())2383 if (TC->hasExplicitTemplateArgs())2384 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())2385 if (S.DiagnoseUnexpandedParameterPack(ArgLoc,2386 Sema::UPPC_TypeConstraint))2387 return true;2388 continue;2389 }2390 2391 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {2392 if (!NTTP->isParameterPack() &&2393 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),2394 NTTP->getTypeSourceInfo(),2395 Sema::UPPC_NonTypeTemplateParameterType))2396 return true;2397 2398 continue;2399 }2400 2401 if (TemplateTemplateParmDecl *InnerTTP2402 = dyn_cast<TemplateTemplateParmDecl>(P))2403 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))2404 return true;2405 }2406 2407 return false;2408}2409 2410bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,2411 TemplateParameterList *OldParams,2412 TemplateParamListContext TPC,2413 SkipBodyInfo *SkipBody) {2414 bool Invalid = false;2415 2416 // C++ [temp.param]p10:2417 // The set of default template-arguments available for use with a2418 // template declaration or definition is obtained by merging the2419 // default arguments from the definition (if in scope) and all2420 // declarations in scope in the same way default function2421 // arguments are (8.3.6).2422 bool SawDefaultArgument = false;2423 SourceLocation PreviousDefaultArgLoc;2424 2425 // Dummy initialization to avoid warnings.2426 TemplateParameterList::iterator OldParam = NewParams->end();2427 if (OldParams)2428 OldParam = OldParams->begin();2429 2430 bool RemoveDefaultArguments = false;2431 for (TemplateParameterList::iterator NewParam = NewParams->begin(),2432 NewParamEnd = NewParams->end();2433 NewParam != NewParamEnd; ++NewParam) {2434 // Whether we've seen a duplicate default argument in the same translation2435 // unit.2436 bool RedundantDefaultArg = false;2437 // Whether we've found inconsis inconsitent default arguments in different2438 // translation unit.2439 bool InconsistentDefaultArg = false;2440 // The name of the module which contains the inconsistent default argument.2441 std::string PrevModuleName;2442 2443 SourceLocation OldDefaultLoc;2444 SourceLocation NewDefaultLoc;2445 2446 // Variable used to diagnose missing default arguments2447 bool MissingDefaultArg = false;2448 2449 // Variable used to diagnose non-final parameter packs2450 bool SawParameterPack = false;2451 2452 if (TemplateTypeParmDecl *NewTypeParm2453 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {2454 // Check the presence of a default argument here.2455 if (NewTypeParm->hasDefaultArgument() &&2456 DiagnoseDefaultTemplateArgument(2457 *this, TPC, NewTypeParm->getLocation(),2458 NewTypeParm->getDefaultArgument().getSourceRange()))2459 NewTypeParm->removeDefaultArgument();2460 2461 // Merge default arguments for template type parameters.2462 TemplateTypeParmDecl *OldTypeParm2463 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;2464 if (NewTypeParm->isParameterPack()) {2465 assert(!NewTypeParm->hasDefaultArgument() &&2466 "Parameter packs can't have a default argument!");2467 SawParameterPack = true;2468 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&2469 NewTypeParm->hasDefaultArgument() &&2470 (!SkipBody || !SkipBody->ShouldSkip)) {2471 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();2472 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();2473 SawDefaultArgument = true;2474 2475 if (!OldTypeParm->getOwningModule())2476 RedundantDefaultArg = true;2477 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,2478 NewTypeParm)) {2479 InconsistentDefaultArg = true;2480 PrevModuleName =2481 OldTypeParm->getImportedOwningModule()->getFullModuleName();2482 }2483 PreviousDefaultArgLoc = NewDefaultLoc;2484 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {2485 // Merge the default argument from the old declaration to the2486 // new declaration.2487 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);2488 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();2489 } else if (NewTypeParm->hasDefaultArgument()) {2490 SawDefaultArgument = true;2491 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();2492 } else if (SawDefaultArgument)2493 MissingDefaultArg = true;2494 } else if (NonTypeTemplateParmDecl *NewNonTypeParm2495 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {2496 // Check for unexpanded parameter packs, except in a template template2497 // parameter pack, as in those any unexpanded packs should be expanded2498 // along with the parameter itself.2499 if (TPC != TPC_TemplateTemplateParameterPack &&2500 !NewNonTypeParm->isParameterPack() &&2501 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),2502 NewNonTypeParm->getTypeSourceInfo(),2503 UPPC_NonTypeTemplateParameterType)) {2504 Invalid = true;2505 continue;2506 }2507 2508 // Check the presence of a default argument here.2509 if (NewNonTypeParm->hasDefaultArgument() &&2510 DiagnoseDefaultTemplateArgument(2511 *this, TPC, NewNonTypeParm->getLocation(),2512 NewNonTypeParm->getDefaultArgument().getSourceRange())) {2513 NewNonTypeParm->removeDefaultArgument();2514 }2515 2516 // Merge default arguments for non-type template parameters2517 NonTypeTemplateParmDecl *OldNonTypeParm2518 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;2519 if (NewNonTypeParm->isParameterPack()) {2520 assert(!NewNonTypeParm->hasDefaultArgument() &&2521 "Parameter packs can't have a default argument!");2522 if (!NewNonTypeParm->isPackExpansion())2523 SawParameterPack = true;2524 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&2525 NewNonTypeParm->hasDefaultArgument() &&2526 (!SkipBody || !SkipBody->ShouldSkip)) {2527 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();2528 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();2529 SawDefaultArgument = true;2530 if (!OldNonTypeParm->getOwningModule())2531 RedundantDefaultArg = true;2532 else if (!getASTContext().isSameDefaultTemplateArgument(2533 OldNonTypeParm, NewNonTypeParm)) {2534 InconsistentDefaultArg = true;2535 PrevModuleName =2536 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();2537 }2538 PreviousDefaultArgLoc = NewDefaultLoc;2539 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {2540 // Merge the default argument from the old declaration to the2541 // new declaration.2542 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);2543 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();2544 } else if (NewNonTypeParm->hasDefaultArgument()) {2545 SawDefaultArgument = true;2546 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();2547 } else if (SawDefaultArgument)2548 MissingDefaultArg = true;2549 } else {2550 TemplateTemplateParmDecl *NewTemplateParm2551 = cast<TemplateTemplateParmDecl>(*NewParam);2552 2553 // Check for unexpanded parameter packs, recursively.2554 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {2555 Invalid = true;2556 continue;2557 }2558 2559 // Check the presence of a default argument here.2560 if (NewTemplateParm->hasDefaultArgument() &&2561 DiagnoseDefaultTemplateArgument(*this, TPC,2562 NewTemplateParm->getLocation(),2563 NewTemplateParm->getDefaultArgument().getSourceRange()))2564 NewTemplateParm->removeDefaultArgument();2565 2566 // Merge default arguments for template template parameters2567 TemplateTemplateParmDecl *OldTemplateParm2568 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;2569 if (NewTemplateParm->isParameterPack()) {2570 assert(!NewTemplateParm->hasDefaultArgument() &&2571 "Parameter packs can't have a default argument!");2572 if (!NewTemplateParm->isPackExpansion())2573 SawParameterPack = true;2574 } else if (OldTemplateParm &&2575 hasVisibleDefaultArgument(OldTemplateParm) &&2576 NewTemplateParm->hasDefaultArgument() &&2577 (!SkipBody || !SkipBody->ShouldSkip)) {2578 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();2579 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();2580 SawDefaultArgument = true;2581 if (!OldTemplateParm->getOwningModule())2582 RedundantDefaultArg = true;2583 else if (!getASTContext().isSameDefaultTemplateArgument(2584 OldTemplateParm, NewTemplateParm)) {2585 InconsistentDefaultArg = true;2586 PrevModuleName =2587 OldTemplateParm->getImportedOwningModule()->getFullModuleName();2588 }2589 PreviousDefaultArgLoc = NewDefaultLoc;2590 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {2591 // Merge the default argument from the old declaration to the2592 // new declaration.2593 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);2594 PreviousDefaultArgLoc2595 = OldTemplateParm->getDefaultArgument().getLocation();2596 } else if (NewTemplateParm->hasDefaultArgument()) {2597 SawDefaultArgument = true;2598 PreviousDefaultArgLoc2599 = NewTemplateParm->getDefaultArgument().getLocation();2600 } else if (SawDefaultArgument)2601 MissingDefaultArg = true;2602 }2603 2604 // C++11 [temp.param]p11:2605 // If a template parameter of a primary class template or alias template2606 // is a template parameter pack, it shall be the last template parameter.2607 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&2608 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {2609 Diag((*NewParam)->getLocation(),2610 diag::err_template_param_pack_must_be_last_template_parameter);2611 Invalid = true;2612 }2613 2614 // [basic.def.odr]/13:2615 // There can be more than one definition of a2616 // ...2617 // default template argument2618 // ...2619 // in a program provided that each definition appears in a different2620 // translation unit and the definitions satisfy the [same-meaning2621 // criteria of the ODR].2622 //2623 // Simply, the design of modules allows the definition of template default2624 // argument to be repeated across translation unit. Note that the ODR is2625 // checked elsewhere. But it is still not allowed to repeat template default2626 // argument in the same translation unit.2627 if (RedundantDefaultArg) {2628 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);2629 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);2630 Invalid = true;2631 } else if (InconsistentDefaultArg) {2632 // We could only diagnose about the case that the OldParam is imported.2633 // The case NewParam is imported should be handled in ASTReader.2634 Diag(NewDefaultLoc,2635 diag::err_template_param_default_arg_inconsistent_redefinition);2636 Diag(OldDefaultLoc,2637 diag::note_template_param_prev_default_arg_in_other_module)2638 << PrevModuleName;2639 Invalid = true;2640 } else if (MissingDefaultArg &&2641 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||2642 TPC == TPC_FriendClassTemplate)) {2643 // C++ 23[temp.param]p14:2644 // If a template-parameter of a class template, variable template, or2645 // alias template has a default template argument, each subsequent2646 // template-parameter shall either have a default template argument2647 // supplied or be a template parameter pack.2648 Diag((*NewParam)->getLocation(),2649 diag::err_template_param_default_arg_missing);2650 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);2651 Invalid = true;2652 RemoveDefaultArguments = true;2653 }2654 2655 // If we have an old template parameter list that we're merging2656 // in, move on to the next parameter.2657 if (OldParams)2658 ++OldParam;2659 }2660 2661 // We were missing some default arguments at the end of the list, so remove2662 // all of the default arguments.2663 if (RemoveDefaultArguments) {2664 for (TemplateParameterList::iterator NewParam = NewParams->begin(),2665 NewParamEnd = NewParams->end();2666 NewParam != NewParamEnd; ++NewParam) {2667 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))2668 TTP->removeDefaultArgument();2669 else if (NonTypeTemplateParmDecl *NTTP2670 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))2671 NTTP->removeDefaultArgument();2672 else2673 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();2674 }2675 }2676 2677 return Invalid;2678}2679 2680namespace {2681 2682/// A class which looks for a use of a certain level of template2683/// parameter.2684struct DependencyChecker : DynamicRecursiveASTVisitor {2685 unsigned Depth;2686 2687 // Whether we're looking for a use of a template parameter that makes the2688 // overall construct type-dependent / a dependent type. This is strictly2689 // best-effort for now; we may fail to match at all for a dependent type2690 // in some cases if this is set.2691 bool IgnoreNonTypeDependent;2692 2693 bool Match;2694 SourceLocation MatchLoc;2695 2696 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)2697 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),2698 Match(false) {}2699 2700 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)2701 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {2702 NamedDecl *ND = Params->getParam(0);2703 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {2704 Depth = PD->getDepth();2705 } else if (NonTypeTemplateParmDecl *PD =2706 dyn_cast<NonTypeTemplateParmDecl>(ND)) {2707 Depth = PD->getDepth();2708 } else {2709 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();2710 }2711 }2712 2713 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {2714 if (ParmDepth >= Depth) {2715 Match = true;2716 MatchLoc = Loc;2717 return true;2718 }2719 return false;2720 }2721 2722 bool TraverseStmt(Stmt *S) override {2723 // Prune out non-type-dependent expressions if requested. This can2724 // sometimes result in us failing to find a template parameter reference2725 // (if a value-dependent expression creates a dependent type), but this2726 // mode is best-effort only.2727 if (auto *E = dyn_cast_or_null<Expr>(S))2728 if (IgnoreNonTypeDependent && !E->isTypeDependent())2729 return true;2730 return DynamicRecursiveASTVisitor::TraverseStmt(S);2731 }2732 2733 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {2734 if (IgnoreNonTypeDependent && !TL.isNull() &&2735 !TL.getType()->isDependentType())2736 return true;2737 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);2738 }2739 2740 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {2741 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());2742 }2743 2744 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {2745 // For a best-effort search, keep looking until we find a location.2746 return IgnoreNonTypeDependent || !Matches(T->getDepth());2747 }2748 2749 bool TraverseTemplateName(TemplateName N) override {2750 if (TemplateTemplateParmDecl *PD =2751 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))2752 if (Matches(PD->getDepth()))2753 return false;2754 return DynamicRecursiveASTVisitor::TraverseTemplateName(N);2755 }2756 2757 bool VisitDeclRefExpr(DeclRefExpr *E) override {2758 if (NonTypeTemplateParmDecl *PD =2759 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))2760 if (Matches(PD->getDepth(), E->getExprLoc()))2761 return false;2762 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(E);2763 }2764 2765 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {2766 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {2767 if (auto *TTP = ULE->getTemplateTemplateDecl()) {2768 if (Matches(TTP->getDepth(), ULE->getExprLoc()))2769 return false;2770 }2771 for (auto &TLoc : ULE->template_arguments())2772 DynamicRecursiveASTVisitor::TraverseTemplateArgumentLoc(TLoc);2773 }2774 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(ULE);2775 }2776 2777 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {2778 return TraverseType(T->getReplacementType());2779 }2780 2781 bool VisitSubstTemplateTypeParmPackType(2782 SubstTemplateTypeParmPackType *T) override {2783 return TraverseTemplateArgument(T->getArgumentPack());2784 }2785 2786 bool TraverseInjectedClassNameType(InjectedClassNameType *T,2787 bool TraverseQualifier) override {2788 // An InjectedClassNameType will never have a dependent template name,2789 // so no need to traverse it.2790 return TraverseTemplateArguments(2791 T->getTemplateArgs(T->getDecl()->getASTContext()));2792 }2793};2794} // end anonymous namespace2795 2796/// Determines whether a given type depends on the given parameter2797/// list.2798static bool2799DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {2800 if (!Params->size())2801 return false;2802 2803 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);2804 Checker.TraverseType(T);2805 return Checker.Match;2806}2807 2808// Find the source range corresponding to the named type in the given2809// nested-name-specifier, if any.2810static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,2811 QualType T,2812 const CXXScopeSpec &SS) {2813 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());2814 for (;;) {2815 NestedNameSpecifier NNS = NNSLoc.getNestedNameSpecifier();2816 if (NNS.getKind() != NestedNameSpecifier::Kind::Type)2817 break;2818 if (Context.hasSameUnqualifiedType(T, QualType(NNS.getAsType(), 0)))2819 return NNSLoc.castAsTypeLoc().getSourceRange();2820 // FIXME: This will always be empty.2821 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;2822 }2823 2824 return SourceRange();2825}2826 2827TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(2828 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,2829 TemplateIdAnnotation *TemplateId,2830 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,2831 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {2832 IsMemberSpecialization = false;2833 Invalid = false;2834 2835 // The sequence of nested types to which we will match up the template2836 // parameter lists. We first build this list by starting with the type named2837 // by the nested-name-specifier and walking out until we run out of types.2838 SmallVector<QualType, 4> NestedTypes;2839 QualType T;2840 if (NestedNameSpecifier Qualifier = SS.getScopeRep();2841 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {2842 if (CXXRecordDecl *Record =2843 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))2844 T = Context.getCanonicalTagType(Record);2845 else2846 T = QualType(Qualifier.getAsType(), 0);2847 }2848 2849 // If we found an explicit specialization that prevents us from needing2850 // 'template<>' headers, this will be set to the location of that2851 // explicit specialization.2852 SourceLocation ExplicitSpecLoc;2853 2854 while (!T.isNull()) {2855 NestedTypes.push_back(T);2856 2857 // Retrieve the parent of a record type.2858 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {2859 // If this type is an explicit specialization, we're done.2860 if (ClassTemplateSpecializationDecl *Spec2861 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {2862 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&2863 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {2864 ExplicitSpecLoc = Spec->getLocation();2865 break;2866 }2867 } else if (Record->getTemplateSpecializationKind()2868 == TSK_ExplicitSpecialization) {2869 ExplicitSpecLoc = Record->getLocation();2870 break;2871 }2872 2873 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))2874 T = Context.getTypeDeclType(Parent);2875 else2876 T = QualType();2877 continue;2878 }2879 2880 if (const TemplateSpecializationType *TST2881 = T->getAs<TemplateSpecializationType>()) {2882 TemplateName Name = TST->getTemplateName();2883 if (const auto *DTS = Name.getAsDependentTemplateName()) {2884 // Look one step prior in a dependent template specialization type.2885 if (NestedNameSpecifier NNS = DTS->getQualifier();2886 NNS.getKind() == NestedNameSpecifier::Kind::Type)2887 T = QualType(NNS.getAsType(), 0);2888 else2889 T = QualType();2890 continue;2891 }2892 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {2893 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))2894 T = Context.getTypeDeclType(Parent);2895 else2896 T = QualType();2897 continue;2898 }2899 }2900 2901 // Look one step prior in a dependent name type.2902 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){2903 if (NestedNameSpecifier NNS = DependentName->getQualifier();2904 NNS.getKind() == NestedNameSpecifier::Kind::Type)2905 T = QualType(NNS.getAsType(), 0);2906 else2907 T = QualType();2908 continue;2909 }2910 2911 // Retrieve the parent of an enumeration type.2912 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {2913 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization2914 // check here.2915 EnumDecl *Enum = EnumT->getDecl();2916 2917 // Get to the parent type.2918 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))2919 T = Context.getCanonicalTypeDeclType(Parent);2920 else2921 T = QualType();2922 continue;2923 }2924 2925 T = QualType();2926 }2927 // Reverse the nested types list, since we want to traverse from the outermost2928 // to the innermost while checking template-parameter-lists.2929 std::reverse(NestedTypes.begin(), NestedTypes.end());2930 2931 // C++0x [temp.expl.spec]p17:2932 // A member or a member template may be nested within many2933 // enclosing class templates. In an explicit specialization for2934 // such a member, the member declaration shall be preceded by a2935 // template<> for each enclosing class template that is2936 // explicitly specialized.2937 bool SawNonEmptyTemplateParameterList = false;2938 2939 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {2940 if (SawNonEmptyTemplateParameterList) {2941 if (!SuppressDiagnostic)2942 Diag(DeclLoc, diag::err_specialize_member_of_template)2943 << !Recovery << Range;2944 Invalid = true;2945 IsMemberSpecialization = false;2946 return true;2947 }2948 2949 return false;2950 };2951 2952 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {2953 // Check that we can have an explicit specialization here.2954 if (CheckExplicitSpecialization(Range, true))2955 return true;2956 2957 // We don't have a template header, but we should.2958 SourceLocation ExpectedTemplateLoc;2959 if (!ParamLists.empty())2960 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();2961 else2962 ExpectedTemplateLoc = DeclStartLoc;2963 2964 if (!SuppressDiagnostic)2965 Diag(DeclLoc, diag::err_template_spec_needs_header)2966 << Range2967 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");2968 return false;2969 };2970 2971 unsigned ParamIdx = 0;2972 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;2973 ++TypeIdx) {2974 T = NestedTypes[TypeIdx];2975 2976 // Whether we expect a 'template<>' header.2977 bool NeedEmptyTemplateHeader = false;2978 2979 // Whether we expect a template header with parameters.2980 bool NeedNonemptyTemplateHeader = false;2981 2982 // For a dependent type, the set of template parameters that we2983 // expect to see.2984 TemplateParameterList *ExpectedTemplateParams = nullptr;2985 2986 // C++0x [temp.expl.spec]p15:2987 // A member or a member template may be nested within many enclosing2988 // class templates. In an explicit specialization for such a member, the2989 // member declaration shall be preceded by a template<> for each2990 // enclosing class template that is explicitly specialized.2991 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {2992 if (ClassTemplatePartialSpecializationDecl *Partial2993 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {2994 ExpectedTemplateParams = Partial->getTemplateParameters();2995 NeedNonemptyTemplateHeader = true;2996 } else if (Record->isDependentType()) {2997 if (Record->getDescribedClassTemplate()) {2998 ExpectedTemplateParams = Record->getDescribedClassTemplate()2999 ->getTemplateParameters();3000 NeedNonemptyTemplateHeader = true;3001 }3002 } else if (ClassTemplateSpecializationDecl *Spec3003 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {3004 // C++0x [temp.expl.spec]p4:3005 // Members of an explicitly specialized class template are defined3006 // in the same manner as members of normal classes, and not using3007 // the template<> syntax.3008 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)3009 NeedEmptyTemplateHeader = true;3010 else3011 continue;3012 } else if (Record->getTemplateSpecializationKind()) {3013 if (Record->getTemplateSpecializationKind()3014 != TSK_ExplicitSpecialization &&3015 TypeIdx == NumTypes - 1)3016 IsMemberSpecialization = true;3017 3018 continue;3019 }3020 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {3021 TemplateName Name = TST->getTemplateName();3022 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {3023 ExpectedTemplateParams = Template->getTemplateParameters();3024 NeedNonemptyTemplateHeader = true;3025 } else if (Name.getAsDeducedTemplateName()) {3026 // FIXME: We actually could/should check the template arguments here3027 // against the corresponding template parameter list.3028 NeedNonemptyTemplateHeader = false;3029 }3030 }3031 3032 // C++ [temp.expl.spec]p16:3033 // In an explicit specialization declaration for a member of a class3034 // template or a member template that appears in namespace scope, the3035 // member template and some of its enclosing class templates may remain3036 // unspecialized, except that the declaration shall not explicitly3037 // specialize a class member template if its enclosing class templates3038 // are not explicitly specialized as well.3039 if (ParamIdx < ParamLists.size()) {3040 if (ParamLists[ParamIdx]->size() == 0) {3041 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),3042 false))3043 return nullptr;3044 } else3045 SawNonEmptyTemplateParameterList = true;3046 }3047 3048 if (NeedEmptyTemplateHeader) {3049 // If we're on the last of the types, and we need a 'template<>' header3050 // here, then it's a member specialization.3051 if (TypeIdx == NumTypes - 1)3052 IsMemberSpecialization = true;3053 3054 if (ParamIdx < ParamLists.size()) {3055 if (ParamLists[ParamIdx]->size() > 0) {3056 // The header has template parameters when it shouldn't. Complain.3057 if (!SuppressDiagnostic)3058 Diag(ParamLists[ParamIdx]->getTemplateLoc(),3059 diag::err_template_param_list_matches_nontemplate)3060 << T3061 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),3062 ParamLists[ParamIdx]->getRAngleLoc())3063 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);3064 Invalid = true;3065 return nullptr;3066 }3067 3068 // Consume this template header.3069 ++ParamIdx;3070 continue;3071 }3072 3073 if (!IsFriend)3074 if (DiagnoseMissingExplicitSpecialization(3075 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))3076 return nullptr;3077 3078 continue;3079 }3080 3081 if (NeedNonemptyTemplateHeader) {3082 // In friend declarations we can have template-ids which don't3083 // depend on the corresponding template parameter lists. But3084 // assume that empty parameter lists are supposed to match this3085 // template-id.3086 if (IsFriend && T->isDependentType()) {3087 if (ParamIdx < ParamLists.size() &&3088 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))3089 ExpectedTemplateParams = nullptr;3090 else3091 continue;3092 }3093 3094 if (ParamIdx < ParamLists.size()) {3095 // Check the template parameter list, if we can.3096 if (ExpectedTemplateParams &&3097 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],3098 ExpectedTemplateParams,3099 !SuppressDiagnostic, TPL_TemplateMatch))3100 Invalid = true;3101 3102 if (!Invalid &&3103 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,3104 TPC_ClassTemplateMember))3105 Invalid = true;3106 3107 ++ParamIdx;3108 continue;3109 }3110 3111 if (!SuppressDiagnostic)3112 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)3113 << T3114 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);3115 Invalid = true;3116 continue;3117 }3118 }3119 3120 // If there were at least as many template-ids as there were template3121 // parameter lists, then there are no template parameter lists remaining for3122 // the declaration itself.3123 if (ParamIdx >= ParamLists.size()) {3124 if (TemplateId && !IsFriend) {3125 // We don't have a template header for the declaration itself, but we3126 // should.3127 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,3128 TemplateId->RAngleLoc));3129 3130 // Fabricate an empty template parameter list for the invented header.3131 return TemplateParameterList::Create(Context, SourceLocation(),3132 SourceLocation(), {},3133 SourceLocation(), nullptr);3134 }3135 3136 return nullptr;3137 }3138 3139 // If there were too many template parameter lists, complain about that now.3140 if (ParamIdx < ParamLists.size() - 1) {3141 bool HasAnyExplicitSpecHeader = false;3142 bool AllExplicitSpecHeaders = true;3143 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {3144 if (ParamLists[I]->size() == 0)3145 HasAnyExplicitSpecHeader = true;3146 else3147 AllExplicitSpecHeaders = false;3148 }3149 3150 if (!SuppressDiagnostic)3151 Diag(ParamLists[ParamIdx]->getTemplateLoc(),3152 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers3153 : diag::err_template_spec_extra_headers)3154 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),3155 ParamLists[ParamLists.size() - 2]->getRAngleLoc());3156 3157 // If there was a specialization somewhere, such that 'template<>' is3158 // not required, and there were any 'template<>' headers, note where the3159 // specialization occurred.3160 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&3161 !SuppressDiagnostic)3162 Diag(ExplicitSpecLoc,3163 diag::note_explicit_template_spec_does_not_need_header)3164 << NestedTypes.back();3165 3166 // We have a template parameter list with no corresponding scope, which3167 // means that the resulting template declaration can't be instantiated3168 // properly (we'll end up with dependent nodes when we shouldn't).3169 if (!AllExplicitSpecHeaders)3170 Invalid = true;3171 }3172 3173 // C++ [temp.expl.spec]p16:3174 // In an explicit specialization declaration for a member of a class3175 // template or a member template that ap- pears in namespace scope, the3176 // member template and some of its enclosing class templates may remain3177 // unspecialized, except that the declaration shall not explicitly3178 // specialize a class member template if its en- closing class templates3179 // are not explicitly specialized as well.3180 if (ParamLists.back()->size() == 0 &&3181 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),3182 false))3183 return nullptr;3184 3185 // Return the last template parameter list, which corresponds to the3186 // entity being declared.3187 return ParamLists.back();3188}3189 3190void Sema::NoteAllFoundTemplates(TemplateName Name) {3191 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {3192 Diag(Template->getLocation(), diag::note_template_declared_here)3193 << (isa<FunctionTemplateDecl>(Template)3194 ? 03195 : isa<ClassTemplateDecl>(Template)3196 ? 13197 : isa<VarTemplateDecl>(Template)3198 ? 23199 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)3200 << Template->getDeclName();3201 return;3202 }3203 3204 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {3205 for (OverloadedTemplateStorage::iterator I = OST->begin(),3206 IEnd = OST->end();3207 I != IEnd; ++I)3208 Diag((*I)->getLocation(), diag::note_template_declared_here)3209 << 0 << (*I)->getDeclName();3210 3211 return;3212 }3213}3214 3215static QualType InstantiateTemplate(Sema &S, ElaboratedTypeKeyword Keyword,3216 TemplateName Template,3217 ArrayRef<TemplateArgument> Args,3218 SourceLocation Loc) {3219 TemplateArgumentListInfo ArgList;3220 for (auto Arg : Args) {3221 if (Arg.getKind() == TemplateArgument::Type) {3222 ArgList.addArgument(TemplateArgumentLoc(3223 Arg, S.Context.getTrivialTypeSourceInfo(Arg.getAsType())));3224 } else {3225 ArgList.addArgument(3226 S.getTrivialTemplateArgumentLoc(Arg, QualType(), Loc));3227 }3228 }3229 3230 EnterExpressionEvaluationContext UnevaluatedContext(3231 S, Sema::ExpressionEvaluationContext::Unevaluated);3232 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);3233 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());3234 3235 QualType Instantiation =3236 S.CheckTemplateIdType(Keyword, Template, Loc, ArgList, /*Scope=*/nullptr,3237 /*ForNestedNameSpecifier=*/false);3238 3239 if (SFINAE.hasErrorOccurred())3240 return QualType();3241 3242 return Instantiation;3243}3244 3245static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword,3246 TemplateName BaseTemplate,3247 SourceLocation TemplateLoc,3248 ArrayRef<TemplateArgument> Ts) {3249 auto lookUpCommonType = [&](TemplateArgument T1,3250 TemplateArgument T2) -> QualType {3251 // Don't bother looking for other specializations if both types are3252 // builtins - users aren't allowed to specialize for them3253 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())3254 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,3255 {T1, T2});3256 3257 return InstantiateTemplate(S, Keyword, BaseTemplate, {T1, T2}, TemplateLoc);3258 };3259 3260 // Note A: For the common_type trait applied to a template parameter pack T of3261 // types, the member type shall be either defined or not present as follows:3262 switch (Ts.size()) {3263 3264 // If sizeof...(T) is zero, there shall be no member type.3265 case 0:3266 return QualType();3267 3268 // If sizeof...(T) is one, let T0 denote the sole type constituting the3269 // pack T. The member typedef-name type shall denote the same type, if any, as3270 // common_type_t<T0, T0>; otherwise there shall be no member type.3271 case 1:3272 return lookUpCommonType(Ts[0], Ts[0]);3273 3274 // If sizeof...(T) is two, let the first and second types constituting T be3275 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types3276 // as decay_t<T1> and decay_t<T2>, respectively.3277 case 2: {3278 QualType T1 = Ts[0].getAsType();3279 QualType T2 = Ts[1].getAsType();3280 QualType D1 = S.BuiltinDecay(T1, {});3281 QualType D2 = S.BuiltinDecay(T2, {});3282 3283 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote3284 // the same type, if any, as common_type_t<D1, D2>.3285 if (!S.Context.hasSameType(T1, D1) || !S.Context.hasSameType(T2, D2))3286 return lookUpCommonType(D1, D2);3287 3288 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>3289 // denotes a valid type, let C denote that type.3290 {3291 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {3292 EnterExpressionEvaluationContext UnevaluatedContext(3293 S, Sema::ExpressionEvaluationContext::Unevaluated);3294 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);3295 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());3296 3297 // false3298 OpaqueValueExpr CondExpr(SourceLocation(), S.Context.BoolTy,3299 VK_PRValue);3300 ExprResult Cond = &CondExpr;3301 3302 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;3303 if (ConstRefQual) {3304 D1.addConst();3305 D2.addConst();3306 }3307 3308 // declval<D1>()3309 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);3310 ExprResult LHS = &LHSExpr;3311 3312 // declval<D2>()3313 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);3314 ExprResult RHS = &RHSExpr;3315 3316 ExprValueKind VK = VK_PRValue;3317 ExprObjectKind OK = OK_Ordinary;3318 3319 // decltype(false ? declval<D1>() : declval<D2>())3320 QualType Result =3321 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, TemplateLoc);3322 3323 if (Result.isNull() || SFINAE.hasErrorOccurred())3324 return QualType();3325 3326 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>3327 return S.BuiltinDecay(Result, TemplateLoc);3328 };3329 3330 if (auto Res = CheckConditionalOperands(false); !Res.isNull())3331 return Res;3332 3333 // Let:3334 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,3335 // COND-RES(X, Y) be3336 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).3337 3338 // C++20 only3339 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote3340 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.3341 if (!S.Context.getLangOpts().CPlusPlus20)3342 return QualType();3343 return CheckConditionalOperands(true);3344 }3345 }3346 3347 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,3348 // denote the first, second, and (pack of) remaining types constituting T. Let3349 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such3350 // a type C, the member typedef-name type shall denote the same type, if any,3351 // as common_type_t<C, R...>. Otherwise, there shall be no member type.3352 default: {3353 QualType Result = Ts.front().getAsType();3354 for (auto T : llvm::drop_begin(Ts)) {3355 Result = lookUpCommonType(Result, T.getAsType());3356 if (Result.isNull())3357 return QualType();3358 }3359 return Result;3360 }3361 }3362}3363 3364static QualType CopyCV(QualType From, QualType To) {3365 if (From.isConstQualified())3366 To.addConst();3367 if (From.isVolatileQualified())3368 To.addVolatile();3369 return To;3370}3371 3372// Let COND-RES(X, Y) be3373// decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()())3374static QualType CondRes(Sema &S, QualType X, QualType Y, SourceLocation Loc) {3375 EnterExpressionEvaluationContext UnevaluatedContext(3376 S, Sema::ExpressionEvaluationContext::Unevaluated);3377 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);3378 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());3379 3380 // false3381 OpaqueValueExpr CondExpr(SourceLocation(), S.Context.BoolTy, VK_PRValue);3382 ExprResult Cond = &CondExpr;3383 3384 // declval<X(&)()>()()3385 OpaqueValueExpr LHSExpr(Loc, X.getNonLValueExprType(S.Context),3386 Expr::getValueKindForType(X));3387 ExprResult LHS = &LHSExpr;3388 3389 // declval<Y(&)()>()()3390 OpaqueValueExpr RHSExpr(Loc, Y.getNonLValueExprType(S.Context),3391 Expr::getValueKindForType(Y));3392 ExprResult RHS = &RHSExpr;3393 3394 ExprValueKind VK = VK_PRValue;3395 ExprObjectKind OK = OK_Ordinary;3396 3397 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()())3398 QualType Result = S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, Loc);3399 3400 if (SFINAE.hasErrorOccurred())3401 return QualType();3402 if (VK == VK_LValue)3403 return S.BuiltinAddLValueReference(Result, Loc);3404 if (VK == VK_XValue)3405 return S.BuiltinAddRValueReference(Result, Loc);3406 return Result;3407}3408 3409static QualType CommonRef(Sema &S, QualType A, QualType B, SourceLocation Loc) {3410 // Given types A and B, let X be remove_reference_t<A>, let Y be3411 // remove_reference_t<B>, and let COMMON-REF(A, B) be:3412 assert(A->isReferenceType() && B->isReferenceType() &&3413 "A and B have to be ref qualified for a COMMON-REF");3414 auto X = A.getNonReferenceType();3415 auto Y = B.getNonReferenceType();3416 3417 // If A and B are both lvalue reference types, COMMON-REF(A, B) is3418 // COND-RES(COPYCV(X, Y) &, COPYCV(Y, X) &) if that type exists and is a3419 // reference type.3420 if (A->isLValueReferenceType() && B->isLValueReferenceType()) {3421 auto CR = CondRes(S, S.BuiltinAddLValueReference(CopyCV(X, Y), Loc),3422 S.BuiltinAddLValueReference(CopyCV(Y, X), Loc), Loc);3423 if (CR.isNull() || !CR->isReferenceType())3424 return QualType();3425 return CR;3426 }3427 3428 // Otherwise, let C be remove_reference_t<COMMON-REF(X&, Y&)>&&. If A and B3429 // are both rvalue reference types, C is well-formed, and3430 // is_convertible_v<A, C> && is_convertible_v<B, C> is true, then3431 // COMMON-REF(A, B) is C.3432 if (A->isRValueReferenceType() && B->isRValueReferenceType()) {3433 auto C = CommonRef(S, S.BuiltinAddLValueReference(X, Loc),3434 S.BuiltinAddLValueReference(Y, Loc), Loc);3435 if (C.isNull())3436 return QualType();3437 3438 C = C.getNonReferenceType();3439 3440 if (S.BuiltinIsConvertible(A, C, Loc) && S.BuiltinIsConvertible(B, C, Loc))3441 return S.BuiltinAddRValueReference(C, Loc);3442 return QualType();3443 }3444 3445 // Otherwise, if A is an lvalue reference and B is an rvalue reference, then3446 // COMMON-REF(A, B) is COMMON-REF(B, A).3447 if (A->isLValueReferenceType() && B->isRValueReferenceType())3448 std::swap(A, B);3449 3450 // Otherwise, let D be COMMON-REF(const X&, Y&). If A is an rvalue reference3451 // and B is an lvalue reference and D is well-formed and3452 // is_convertible_v<A, D> is true, then COMMON-REF(A, B) is D.3453 if (A->isRValueReferenceType() && B->isLValueReferenceType()) {3454 auto X2 = X;3455 X2.addConst();3456 auto D = CommonRef(S, S.BuiltinAddLValueReference(X2, Loc),3457 S.BuiltinAddLValueReference(Y, Loc), Loc);3458 if (!D.isNull() && S.BuiltinIsConvertible(A, D, Loc))3459 return D;3460 return QualType();3461 }3462 3463 // Otherwise, COMMON-REF(A, B) is ill-formed.3464 // This is implemented by returning from the individual branches above.3465 3466 llvm_unreachable("The above cases should be exhaustive");3467}3468 3469static QualType builtinCommonReferenceImpl(Sema &S,3470 ElaboratedTypeKeyword Keyword,3471 TemplateName CommonReference,3472 TemplateName CommonType,3473 SourceLocation TemplateLoc,3474 ArrayRef<TemplateArgument> Ts) {3475 switch (Ts.size()) {3476 // If sizeof...(T) is zero, there shall be no member type.3477 case 0:3478 return QualType();3479 3480 // Otherwise, if sizeof...(T) is one, let T0 denote the sole type in the3481 // pack T. The member typedef type shall denote the same type as T0.3482 case 1:3483 return Ts[0].getAsType();3484 3485 // Otherwise, if sizeof...(T) is two, let T1 and T2 denote the two types in3486 // the pack T. Then3487 case 2: {3488 auto T1 = Ts[0].getAsType();3489 auto T2 = Ts[1].getAsType();3490 3491 // Let R be COMMON-REF(T1, T2). If T1 and T2 are reference types, R is3492 // well-formed, and is_convertible_v<add_pointer_t<T1>, add_pointer_t<R>> &&3493 // is_convertible_v<add_pointer_t<T2>, add_pointer_t<R>> is true, then the3494 // member typedef type denotes R.3495 if (T1->isReferenceType() && T2->isReferenceType()) {3496 QualType R = CommonRef(S, T1, T2, TemplateLoc);3497 if (!R.isNull()) {3498 if (S.BuiltinIsConvertible(S.BuiltinAddPointer(T1, TemplateLoc),3499 S.BuiltinAddPointer(R, TemplateLoc),3500 TemplateLoc) &&3501 S.BuiltinIsConvertible(S.BuiltinAddPointer(T2, TemplateLoc),3502 S.BuiltinAddPointer(R, TemplateLoc),3503 TemplateLoc)) {3504 return R;3505 }3506 }3507 }3508 3509 // Otherwise, if basic_common_reference<remove_cvref_t<T1>,3510 // remove_cvref_t<T2>, XREF(T1), XREF(T2)>::type is well-formed,3511 // then the member typedef type denotes that type.3512 {3513 auto getXRef = [&](QualType T) {3514 BuiltinTemplateDecl *Quals[12] = {3515 S.Context.get__clang_internal_xref_Decl(),3516 S.Context.get__clang_internal_xref_constDecl(),3517 S.Context.get__clang_internal_xref_volatileDecl(),3518 S.Context.get__clang_internal_xref_constvolatileDecl(),3519 S.Context.get__clang_internal_xref_lvalueDecl(),3520 S.Context.get__clang_internal_xref_lvalueconstDecl(),3521 S.Context.get__clang_internal_xref_lvaluevolatileDecl(),3522 S.Context.get__clang_internal_xref_lvalueconstvolatileDecl(),3523 S.Context.get__clang_internal_xref_rvalueDecl(),3524 S.Context.get__clang_internal_xref_rvalueconstDecl(),3525 S.Context.get__clang_internal_xref_rvaluevolatileDecl(),3526 S.Context.get__clang_internal_xref_rvalueconstvolatileDecl(),3527 };3528 size_t Index = 0;3529 if (T->isLValueReferenceType()) {3530 T = T.getNonReferenceType();3531 Index += 4;3532 } else if (T->isRValueReferenceType()) {3533 T = T.getNonReferenceType();3534 Index += 8;3535 }3536 if (T.isConstQualified())3537 Index += 1;3538 3539 if (T.isVolatileQualified())3540 Index += 2;3541 3542 return Quals[Index];3543 };3544 3545 auto BCR = InstantiateTemplate(S, Keyword, CommonReference,3546 {S.BuiltinRemoveCVRef(T1, TemplateLoc),3547 S.BuiltinRemoveCVRef(T2, TemplateLoc),3548 TemplateName{getXRef(T1)},3549 TemplateName{getXRef(T2)}},3550 TemplateLoc);3551 if (!BCR.isNull())3552 return BCR;3553 }3554 3555 // Otherwise, if COND-RES(T1, T2) is well-formed, then the member typedef3556 // type denotes that type.3557 if (auto CR = CondRes(S, T1, T2, TemplateLoc); !CR.isNull())3558 return CR;3559 3560 // Otherwise, if common_type_t<T1, T2> is well-formed, then the member3561 // typedef type denotes that type.3562 if (auto CT =3563 InstantiateTemplate(S, Keyword, CommonType, {T1, T2}, TemplateLoc);3564 !CT.isNull())3565 return CT;3566 3567 // Otherwise, there shall be no member type.3568 return QualType();3569 }3570 3571 // Otherwise, if sizeof...(T) is greater than two, let T1, T2, and Rest,3572 // respectively, denote the first, second, and (pack of) remaining types3573 // comprising T. Let C be the type common_reference_t<T1, T2>. Then:3574 default: {3575 auto T1 = Ts[0];3576 auto T2 = Ts[1];3577 auto Rest = Ts.drop_front(2);3578 auto C = builtinCommonReferenceImpl(S, Keyword, CommonReference, CommonType,3579 TemplateLoc, {T1, T2});3580 if (C.isNull())3581 return QualType();3582 llvm::SmallVector<TemplateArgument, 4> Args;3583 Args.emplace_back(C);3584 Args.append(Rest.begin(), Rest.end());3585 return builtinCommonReferenceImpl(S, Keyword, CommonReference, CommonType,3586 TemplateLoc, Args);3587 }3588 }3589}3590 3591static bool isInVkNamespace(const RecordType *RT) {3592 DeclContext *DC = RT->getDecl()->getDeclContext();3593 if (!DC)3594 return false;3595 3596 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);3597 if (!ND)3598 return false;3599 3600 return ND->getQualifiedNameAsString() == "hlsl::vk";3601}3602 3603static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,3604 QualType OperandArg,3605 SourceLocation Loc) {3606 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {3607 bool Literal = false;3608 SourceLocation LiteralLoc;3609 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {3610 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());3611 assert(SpecDecl);3612 3613 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();3614 QualType ConstantType = LiteralArgs[0].getAsType();3615 RT = ConstantType->getAsCanonical<RecordType>();3616 Literal = true;3617 LiteralLoc = SpecDecl->getSourceRange().getBegin();3618 }3619 3620 if (RT && isInVkNamespace(RT) &&3621 RT->getDecl()->getName() == "integral_constant") {3622 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());3623 assert(SpecDecl);3624 3625 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();3626 3627 QualType ConstantType = ConstantArgs[0].getAsType();3628 llvm::APInt Value = ConstantArgs[1].getAsIntegral();3629 3630 if (Literal)3631 return SpirvOperand::createLiteral(Value);3632 return SpirvOperand::createConstant(ConstantType, Value);3633 } else if (Literal) {3634 SemaRef.Diag(LiteralLoc, diag::err_hlsl_vk_literal_must_contain_constant);3635 return SpirvOperand();3636 }3637 }3638 if (SemaRef.RequireCompleteType(Loc, OperandArg,3639 diag::err_call_incomplete_argument))3640 return SpirvOperand();3641 return SpirvOperand::createType(OperandArg);3642}3643 3644static QualType checkBuiltinTemplateIdType(3645 Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD,3646 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,3647 TemplateArgumentListInfo &TemplateArgs) {3648 ASTContext &Context = SemaRef.getASTContext();3649 3650 switch (BTD->getBuiltinTemplateKind()) {3651 case BTK__make_integer_seq: {3652 // Specializations of __make_integer_seq<S, T, N> are treated like3653 // S<T, 0, ..., N-1>.3654 3655 QualType OrigType = Converted[1].getAsType();3656 // C++14 [inteseq.intseq]p1:3657 // T shall be an integer type.3658 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {3659 SemaRef.Diag(TemplateArgs[1].getLocation(),3660 diag::err_integer_sequence_integral_element_type);3661 return QualType();3662 }3663 3664 TemplateArgument NumArgsArg = Converted[2];3665 if (NumArgsArg.isDependent())3666 return QualType();3667 3668 TemplateArgumentListInfo SyntheticTemplateArgs;3669 // The type argument, wrapped in substitution sugar, gets reused as the3670 // first template argument in the synthetic template argument list.3671 SyntheticTemplateArgs.addArgument(3672 TemplateArgumentLoc(TemplateArgument(OrigType),3673 SemaRef.Context.getTrivialTypeSourceInfo(3674 OrigType, TemplateArgs[1].getLocation())));3675 3676 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {3677 // Expand N into 0 ... N-1.3678 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());3679 I < NumArgs; ++I) {3680 TemplateArgument TA(Context, I, OrigType);3681 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(3682 TA, OrigType, TemplateArgs[2].getLocation()));3683 }3684 } else {3685 // C++14 [inteseq.make]p1:3686 // If N is negative the program is ill-formed.3687 SemaRef.Diag(TemplateArgs[2].getLocation(),3688 diag::err_integer_sequence_negative_length);3689 return QualType();3690 }3691 3692 // The first template argument will be reused as the template decl that3693 // our synthetic template arguments will be applied to.3694 return SemaRef.CheckTemplateIdType(Keyword, Converted[0].getAsTemplate(),3695 TemplateLoc, SyntheticTemplateArgs,3696 /*Scope=*/nullptr,3697 /*ForNestedNameSpecifier=*/false);3698 }3699 3700 case BTK__type_pack_element: {3701 // Specializations of3702 // __type_pack_element<Index, T_1, ..., T_N>3703 // are treated like T_Index.3704 assert(Converted.size() == 2 &&3705 "__type_pack_element should be given an index and a parameter pack");3706 3707 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];3708 if (IndexArg.isDependent() || Ts.isDependent())3709 return QualType();3710 3711 llvm::APSInt Index = IndexArg.getAsIntegral();3712 assert(Index >= 0 && "the index used with __type_pack_element should be of "3713 "type std::size_t, and hence be non-negative");3714 // If the Index is out of bounds, the program is ill-formed.3715 if (Index >= Ts.pack_size()) {3716 SemaRef.Diag(TemplateArgs[0].getLocation(),3717 diag::err_type_pack_element_out_of_bounds);3718 return QualType();3719 }3720 3721 // We simply return the type at index `Index`.3722 int64_t N = Index.getExtValue();3723 return Ts.getPackAsArray()[N].getAsType();3724 }3725 3726 case BTK__builtin_common_type: {3727 assert(Converted.size() == 4);3728 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))3729 return QualType();3730 3731 TemplateName BaseTemplate = Converted[0].getAsTemplate();3732 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();3733 if (auto CT = builtinCommonTypeImpl(SemaRef, Keyword, BaseTemplate,3734 TemplateLoc, Ts);3735 !CT.isNull()) {3736 TemplateArgumentListInfo TAs;3737 TAs.addArgument(TemplateArgumentLoc(3738 TemplateArgument(CT), SemaRef.Context.getTrivialTypeSourceInfo(3739 CT, TemplateArgs[1].getLocation())));3740 TemplateName HasTypeMember = Converted[1].getAsTemplate();3741 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,3742 TAs, /*Scope=*/nullptr,3743 /*ForNestedNameSpecifier=*/false);3744 }3745 QualType HasNoTypeMember = Converted[2].getAsType();3746 return HasNoTypeMember;3747 }3748 3749 case BTK__builtin_common_reference: {3750 assert(Converted.size() == 5);3751 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))3752 return QualType();3753 3754 TemplateName BasicCommonReference = Converted[0].getAsTemplate();3755 TemplateName CommonType = Converted[1].getAsTemplate();3756 TemplateName HasTypeMember = Converted[2].getAsTemplate();3757 QualType HasNoTypeMember = Converted[3].getAsType();3758 ArrayRef<TemplateArgument> Ts = Converted[4].getPackAsArray();3759 if (auto CR =3760 builtinCommonReferenceImpl(SemaRef, Keyword, BasicCommonReference,3761 CommonType, TemplateLoc, Ts);3762 !CR.isNull()) {3763 TemplateArgumentListInfo TAs;3764 TAs.addArgument(TemplateArgumentLoc(3765 TemplateArgument(CR), SemaRef.Context.getTrivialTypeSourceInfo(3766 CR, TemplateArgs[1].getLocation())));3767 return SemaRef.CheckTemplateIdType(Keyword, HasTypeMember, TemplateLoc,3768 TAs, /*Scope=*/nullptr,3769 /*ForNestedNameSpecifier=*/false);3770 }3771 return HasNoTypeMember;3772 }3773 3774 case BTK__clang_internal_xref_:3775 case BTK__clang_internal_xref_const:3776 case BTK__clang_internal_xref_volatile:3777 case BTK__clang_internal_xref_constvolatile:3778 case BTK__clang_internal_xref_lvalue:3779 case BTK__clang_internal_xref_lvalueconst:3780 case BTK__clang_internal_xref_lvaluevolatile:3781 case BTK__clang_internal_xref_lvalueconstvolatile:3782 case BTK__clang_internal_xref_rvalue:3783 case BTK__clang_internal_xref_rvalueconst:3784 case BTK__clang_internal_xref_rvaluevolatile:3785 case BTK__clang_internal_xref_rvalueconstvolatile: {3786 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))3787 return QualType();3788 3789 auto BTK = BTD->getBuiltinTemplateKind();3790 auto anyOf = [&](auto... Vals) { return ((BTK == Vals) || ...); };3791 3792 bool AddCV = anyOf(BTK__clang_internal_xref_constvolatile,3793 BTK__clang_internal_xref_lvalueconstvolatile,3794 BTK__clang_internal_xref_rvalueconstvolatile);3795 3796 bool AddConst = AddCV || anyOf(BTK__clang_internal_xref_const,3797 BTK__clang_internal_xref_lvalueconst,3798 BTK__clang_internal_xref_rvalueconst);3799 3800 bool AddVolatile = AddCV || anyOf(BTK__clang_internal_xref_volatile,3801 BTK__clang_internal_xref_lvaluevolatile,3802 BTK__clang_internal_xref_rvaluevolatile);3803 3804 bool AddLValue = anyOf(BTK__clang_internal_xref_lvalue,3805 BTK__clang_internal_xref_lvalueconst,3806 BTK__clang_internal_xref_lvaluevolatile,3807 BTK__clang_internal_xref_lvalueconstvolatile);3808 3809 bool AddRValue = anyOf(BTK__clang_internal_xref_rvalue,3810 BTK__clang_internal_xref_rvalueconst,3811 BTK__clang_internal_xref_rvaluevolatile,3812 BTK__clang_internal_xref_rvalueconstvolatile);3813 3814 assert(Converted.size() == 1);3815 3816 QualType T = Converted[0].getAsType();3817 3818 if (AddConst)3819 T.addConst();3820 3821 if (AddVolatile)3822 T.addVolatile();3823 3824 if (AddLValue)3825 T = SemaRef.BuiltinAddLValueReference(T, TemplateLoc);3826 else if (AddRValue)3827 T = SemaRef.BuiltinAddRValueReference(T, TemplateLoc);3828 3829 return T;3830 }3831 3832 case BTK__hlsl_spirv_type: {3833 assert(Converted.size() == 4);3834 3835 if (!Context.getTargetInfo().getTriple().isSPIRV()) {3836 SemaRef.Diag(TemplateLoc, diag::err_hlsl_spirv_only) << BTD;3837 }3838 3839 if (llvm::any_of(Converted, [](auto &C) { return C.isDependent(); }))3840 return QualType();3841 3842 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();3843 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();3844 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();3845 3846 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();3847 3848 llvm::SmallVector<SpirvOperand> Operands;3849 3850 for (auto &OperandTA : OperandArgs) {3851 QualType OperandArg = OperandTA.getAsType();3852 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,3853 TemplateArgs[3].getLocation());3854 if (!Operand.isValid())3855 return QualType();3856 Operands.push_back(Operand);3857 }3858 3859 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);3860 }3861 case BTK__builtin_dedup_pack: {3862 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "3863 "a parameter pack");3864 TemplateArgument Ts = Converted[0];3865 // Delay the computation until we can compute the final result. We choose3866 // not to remove the duplicates upfront before substitution to keep the code3867 // simple.3868 if (Ts.isDependent())3869 return QualType();3870 assert(Ts.getKind() == clang::TemplateArgument::Pack);3871 llvm::SmallVector<TemplateArgument> OutArgs;3872 llvm::SmallDenseSet<QualType> Seen;3873 // Synthesize a new template argument list, removing duplicates.3874 for (auto T : Ts.getPackAsArray()) {3875 assert(T.getKind() == clang::TemplateArgument::Type);3876 if (!Seen.insert(T.getAsType().getCanonicalType()).second)3877 continue;3878 OutArgs.push_back(T);3879 }3880 return Context.getSubstBuiltinTemplatePack(3881 TemplateArgument::CreatePackCopy(Context, OutArgs));3882 }3883 }3884 llvm_unreachable("unexpected BuiltinTemplateDecl!");3885}3886 3887/// Determine whether this alias template is "enable_if_t".3888/// libc++ >=14 uses "__enable_if_t" in C++11 mode.3889static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {3890 return AliasTemplate->getName() == "enable_if_t" ||3891 AliasTemplate->getName() == "__enable_if_t";3892}3893 3894/// Collect all of the separable terms in the given condition, which3895/// might be a conjunction.3896///3897/// FIXME: The right answer is to convert the logical expression into3898/// disjunctive normal form, so we can find the first failed term3899/// within each possible clause.3900static void collectConjunctionTerms(Expr *Clause,3901 SmallVectorImpl<Expr *> &Terms) {3902 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {3903 if (BinOp->getOpcode() == BO_LAnd) {3904 collectConjunctionTerms(BinOp->getLHS(), Terms);3905 collectConjunctionTerms(BinOp->getRHS(), Terms);3906 return;3907 }3908 }3909 3910 Terms.push_back(Clause);3911}3912 3913// The ranges-v3 library uses an odd pattern of a top-level "||" with3914// a left-hand side that is value-dependent but never true. Identify3915// the idiom and ignore that term.3916static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {3917 // Top-level '||'.3918 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());3919 if (!BinOp) return Cond;3920 3921 if (BinOp->getOpcode() != BO_LOr) return Cond;3922 3923 // With an inner '==' that has a literal on the right-hand side.3924 Expr *LHS = BinOp->getLHS();3925 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());3926 if (!InnerBinOp) return Cond;3927 3928 if (InnerBinOp->getOpcode() != BO_EQ ||3929 !isa<IntegerLiteral>(InnerBinOp->getRHS()))3930 return Cond;3931 3932 // If the inner binary operation came from a macro expansion named3933 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side3934 // of the '||', which is the real, user-provided condition.3935 SourceLocation Loc = InnerBinOp->getExprLoc();3936 if (!Loc.isMacroID()) return Cond;3937 3938 StringRef MacroName = PP.getImmediateMacroName(Loc);3939 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")3940 return BinOp->getRHS();3941 3942 return Cond;3943}3944 3945namespace {3946 3947// A PrinterHelper that prints more helpful diagnostics for some sub-expressions3948// within failing boolean expression, such as substituting template parameters3949// for actual types.3950class FailedBooleanConditionPrinterHelper : public PrinterHelper {3951public:3952 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)3953 : Policy(P) {}3954 3955 bool handledStmt(Stmt *E, raw_ostream &OS) override {3956 const auto *DR = dyn_cast<DeclRefExpr>(E);3957 if (DR && DR->getQualifier()) {3958 // If this is a qualified name, expand the template arguments in nested3959 // qualifiers.3960 DR->getQualifier().print(OS, Policy, true);3961 // Then print the decl itself.3962 const ValueDecl *VD = DR->getDecl();3963 OS << VD->getName();3964 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {3965 // This is a template variable, print the expanded template arguments.3966 printTemplateArgumentList(3967 OS, IV->getTemplateArgs().asArray(), Policy,3968 IV->getSpecializedTemplate()->getTemplateParameters());3969 }3970 return true;3971 }3972 return false;3973 }3974 3975private:3976 const PrintingPolicy Policy;3977};3978 3979} // end anonymous namespace3980 3981std::pair<Expr *, std::string>3982Sema::findFailedBooleanCondition(Expr *Cond) {3983 Cond = lookThroughRangesV3Condition(PP, Cond);3984 3985 // Separate out all of the terms in a conjunction.3986 SmallVector<Expr *, 4> Terms;3987 collectConjunctionTerms(Cond, Terms);3988 3989 // Determine which term failed.3990 Expr *FailedCond = nullptr;3991 for (Expr *Term : Terms) {3992 Expr *TermAsWritten = Term->IgnoreParenImpCasts();3993 3994 // Literals are uninteresting.3995 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||3996 isa<IntegerLiteral>(TermAsWritten))3997 continue;3998 3999 // The initialization of the parameter from the argument is4000 // a constant-evaluated context.4001 EnterExpressionEvaluationContext ConstantEvaluated(4002 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);4003 4004 bool Succeeded;4005 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&4006 !Succeeded) {4007 FailedCond = TermAsWritten;4008 break;4009 }4010 }4011 if (!FailedCond)4012 FailedCond = Cond->IgnoreParenImpCasts();4013 4014 std::string Description;4015 {4016 llvm::raw_string_ostream Out(Description);4017 PrintingPolicy Policy = getPrintingPolicy();4018 Policy.PrintAsCanonical = true;4019 FailedBooleanConditionPrinterHelper Helper(Policy);4020 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);4021 }4022 return { FailedCond, Description };4023}4024 4025static TemplateName4026resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope,4027 const AssumedTemplateStorage *ATN,4028 SourceLocation NameLoc) {4029 // We assumed this undeclared identifier to be an (ADL-only) function4030 // template name, but it was used in a context where a type was required.4031 // Try to typo-correct it now.4032 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);4033 struct CandidateCallback : CorrectionCandidateCallback {4034 bool ValidateCandidate(const TypoCorrection &TC) override {4035 return TC.getCorrectionDecl() &&4036 getAsTypeTemplateDecl(TC.getCorrectionDecl());4037 }4038 std::unique_ptr<CorrectionCandidateCallback> clone() override {4039 return std::make_unique<CandidateCallback>(*this);4040 }4041 } FilterCCC;4042 4043 TypoCorrection Corrected =4044 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Scope,4045 /*SS=*/nullptr, FilterCCC, CorrectTypoKind::ErrorRecovery);4046 if (Corrected && Corrected.getFoundDecl()) {4047 S.diagnoseTypo(Corrected, S.PDiag(diag::err_no_template_suggest)4048 << ATN->getDeclName());4049 return S.Context.getQualifiedTemplateName(4050 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,4051 TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()));4052 }4053 4054 return TemplateName();4055}4056 4057QualType Sema::CheckTemplateIdType(ElaboratedTypeKeyword Keyword,4058 TemplateName Name,4059 SourceLocation TemplateLoc,4060 TemplateArgumentListInfo &TemplateArgs,4061 Scope *Scope, bool ForNestedNameSpecifier) {4062 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();4063 4064 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();4065 if (!Template) {4066 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {4067 Template = S->getParameterPack();4068 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {4069 if (DTN->getName().getIdentifier())4070 // When building a template-id where the template-name is dependent,4071 // assume the template is a type template. Either our assumption is4072 // correct, or the code is ill-formed and will be diagnosed when the4073 // dependent name is substituted.4074 return Context.getTemplateSpecializationType(Keyword, Name,4075 TemplateArgs.arguments(),4076 /*CanonicalArgs=*/{});4077 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {4078 if (TemplateName CorrectedName = ::resolveAssumedTemplateNameAsType(4079 *this, Scope, ATN, TemplateLoc);4080 CorrectedName.isNull()) {4081 Diag(TemplateLoc, diag::err_no_template) << ATN->getDeclName();4082 return QualType();4083 } else {4084 Name = CorrectedName;4085 Template = Name.getAsTemplateDecl();4086 }4087 }4088 }4089 if (!Template ||4090 isa<FunctionTemplateDecl, VarTemplateDecl, ConceptDecl>(Template)) {4091 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());4092 if (ForNestedNameSpecifier)4093 Diag(TemplateLoc, diag::err_non_type_template_in_nested_name_specifier)4094 << isa_and_nonnull<VarTemplateDecl>(Template) << Name << R;4095 else4096 Diag(TemplateLoc, diag::err_template_id_not_a_type) << Name << R;4097 NoteAllFoundTemplates(Name);4098 return QualType();4099 }4100 4101 // Check that the template argument list is well-formed for this4102 // template.4103 CheckTemplateArgumentInfo CTAI;4104 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,4105 DefaultArgs, /*PartialTemplateArgs=*/false,4106 CTAI,4107 /*UpdateArgsWithConversions=*/true))4108 return QualType();4109 4110 QualType CanonType;4111 4112 if (isa<TemplateTemplateParmDecl>(Template)) {4113 // We might have a substituted template template parameter pack. If so,4114 // build a template specialization type for it.4115 } else if (TypeAliasTemplateDecl *AliasTemplate =4116 dyn_cast<TypeAliasTemplateDecl>(Template)) {4117 4118 // C++0x [dcl.type.elab]p2:4119 // If the identifier resolves to a typedef-name or the simple-template-id4120 // resolves to an alias template specialization, the4121 // elaborated-type-specifier is ill-formed.4122 if (Keyword != ElaboratedTypeKeyword::None &&4123 Keyword != ElaboratedTypeKeyword::Typename) {4124 SemaRef.Diag(TemplateLoc, diag::err_tag_reference_non_tag)4125 << AliasTemplate << NonTagKind::TypeAliasTemplate4126 << KeywordHelpers::getTagTypeKindForKeyword(Keyword);4127 SemaRef.Diag(AliasTemplate->getLocation(), diag::note_declared_at);4128 }4129 4130 // Find the canonical type for this type alias template specialization.4131 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();4132 if (Pattern->isInvalidDecl())4133 return QualType();4134 4135 // Only substitute for the innermost template argument list.4136 MultiLevelTemplateArgumentList TemplateArgLists;4137 TemplateArgLists.addOuterTemplateArguments(Template, CTAI.SugaredConverted,4138 /*Final=*/true);4139 TemplateArgLists.addOuterRetainedLevels(4140 AliasTemplate->getTemplateParameters()->getDepth());4141 4142 LocalInstantiationScope Scope(*this);4143 4144 // Diagnose uses of this alias.4145 (void)DiagnoseUseOfDecl(AliasTemplate, TemplateLoc);4146 4147 // FIXME: The TemplateArgs passed here are not used for the context note,4148 // nor they should, because this note will be pointing to the specialization4149 // anyway. These arguments are needed for a hack for instantiating lambdas4150 // in the pattern of the alias. In getTemplateInstantiationArgs, these4151 // arguments will be used for collating the template arguments needed to4152 // instantiate the lambda.4153 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,4154 /*Entity=*/AliasTemplate,4155 /*TemplateArgs=*/CTAI.SugaredConverted);4156 if (Inst.isInvalid())4157 return QualType();4158 4159 std::optional<ContextRAII> SavedContext;4160 if (!AliasTemplate->getDeclContext()->isFileContext())4161 SavedContext.emplace(*this, AliasTemplate->getDeclContext());4162 4163 CanonType =4164 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,4165 AliasTemplate->getLocation(), AliasTemplate->getDeclName());4166 if (CanonType.isNull()) {4167 // If this was enable_if and we failed to find the nested type4168 // within enable_if in a SFINAE context, dig out the specific4169 // enable_if condition that failed and present that instead.4170 if (isEnableIfAliasTemplate(AliasTemplate)) {4171 if (SFINAETrap *Trap = getSFINAEContext();4172 TemplateDeductionInfo *DeductionInfo =4173 Trap ? Trap->getDeductionInfo() : nullptr) {4174 if (DeductionInfo->hasSFINAEDiagnostic() &&4175 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==4176 diag::err_typename_nested_not_found_enable_if &&4177 TemplateArgs[0].getArgument().getKind() ==4178 TemplateArgument::Expression) {4179 Expr *FailedCond;4180 std::string FailedDescription;4181 std::tie(FailedCond, FailedDescription) =4182 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());4183 4184 // Remove the old SFINAE diagnostic.4185 PartialDiagnosticAt OldDiag =4186 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};4187 DeductionInfo->takeSFINAEDiagnostic(OldDiag);4188 4189 // Add a new SFINAE diagnostic specifying which condition4190 // failed.4191 DeductionInfo->addSFINAEDiagnostic(4192 OldDiag.first,4193 PDiag(diag::err_typename_nested_not_found_requirement)4194 << FailedDescription << FailedCond->getSourceRange());4195 }4196 }4197 }4198 4199 return QualType();4200 }4201 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {4202 CanonType = checkBuiltinTemplateIdType(4203 *this, Keyword, BTD, CTAI.SugaredConverted, TemplateLoc, TemplateArgs);4204 } else if (Name.isDependent() ||4205 TemplateSpecializationType::anyDependentTemplateArguments(4206 TemplateArgs, CTAI.CanonicalConverted)) {4207 // This class template specialization is a dependent4208 // type. Therefore, its canonical type is another class template4209 // specialization type that contains all of the converted4210 // arguments in canonical form. This ensures that, e.g., A<T> and4211 // A<T, T> have identical types when A is declared as:4212 //4213 // template<typename T, typename U = T> struct A;4214 CanonType = Context.getCanonicalTemplateSpecializationType(4215 ElaboratedTypeKeyword::None,4216 Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),4217 CTAI.CanonicalConverted);4218 assert(CanonType->isCanonicalUnqualified());4219 4220 // This might work out to be a current instantiation, in which4221 // case the canonical type needs to be the InjectedClassNameType.4222 //4223 // TODO: in theory this could be a simple hashtable lookup; most4224 // changes to CurContext don't change the set of current4225 // instantiations.4226 if (isa<ClassTemplateDecl>(Template)) {4227 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {4228 // If we get out to a namespace, we're done.4229 if (Ctx->isFileContext()) break;4230 4231 // If this isn't a record, keep looking.4232 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);4233 if (!Record) continue;4234 4235 // Look for one of the two cases with InjectedClassNameTypes4236 // and check whether it's the same template.4237 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&4238 !Record->getDescribedClassTemplate())4239 continue;4240 4241 // Fetch the injected class name type and check whether its4242 // injected type is equal to the type we just built.4243 CanQualType ICNT = Context.getCanonicalTagType(Record);4244 CanQualType Injected =4245 Record->getCanonicalTemplateSpecializationType(Context);4246 4247 if (CanonType != Injected)4248 continue;4249 4250 // If so, the canonical type of this TST is the injected4251 // class name type of the record we just found.4252 CanonType = ICNT;4253 break;4254 }4255 }4256 } else if (ClassTemplateDecl *ClassTemplate =4257 dyn_cast<ClassTemplateDecl>(Template)) {4258 // Find the class template specialization declaration that4259 // corresponds to these arguments.4260 void *InsertPos = nullptr;4261 ClassTemplateSpecializationDecl *Decl =4262 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);4263 if (!Decl) {4264 // This is the first time we have referenced this class template4265 // specialization. Create the canonical declaration and add it to4266 // the set of specializations.4267 Decl = ClassTemplateSpecializationDecl::Create(4268 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),4269 ClassTemplate->getDeclContext(),4270 ClassTemplate->getTemplatedDecl()->getBeginLoc(),4271 ClassTemplate->getLocation(), ClassTemplate, CTAI.CanonicalConverted,4272 CTAI.StrictPackMatch, nullptr);4273 ClassTemplate->AddSpecialization(Decl, InsertPos);4274 if (ClassTemplate->isOutOfLine())4275 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());4276 }4277 4278 if (Decl->getSpecializationKind() == TSK_Undeclared &&4279 ClassTemplate->getTemplatedDecl()->hasAttrs()) {4280 NonSFINAEContext _(*this);4281 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);4282 if (!Inst.isInvalid()) {4283 MultiLevelTemplateArgumentList TemplateArgLists(Template,4284 CTAI.CanonicalConverted,4285 /*Final=*/false);4286 InstantiateAttrsForDecl(TemplateArgLists,4287 ClassTemplate->getTemplatedDecl(), Decl);4288 }4289 }4290 4291 // Diagnose uses of this specialization.4292 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);4293 4294 CanonType = Context.getCanonicalTagType(Decl);4295 assert(isa<RecordType>(CanonType) &&4296 "type of non-dependent specialization is not a RecordType");4297 } else {4298 llvm_unreachable("Unhandled template kind");4299 }4300 4301 // Build the fully-sugared type for this class template4302 // specialization, which refers back to the class template4303 // specialization we created or found.4304 return Context.getTemplateSpecializationType(4305 Keyword, Name, TemplateArgs.arguments(), CTAI.CanonicalConverted,4306 CanonType);4307}4308 4309void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,4310 TemplateNameKind &TNK,4311 SourceLocation NameLoc,4312 IdentifierInfo *&II) {4313 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");4314 4315 auto *ATN = ParsedName.get().getAsAssumedTemplateName();4316 assert(ATN && "not an assumed template name");4317 II = ATN->getDeclName().getAsIdentifierInfo();4318 4319 if (TemplateName Name =4320 ::resolveAssumedTemplateNameAsType(*this, S, ATN, NameLoc);4321 !Name.isNull()) {4322 // Resolved to a type template name.4323 ParsedName = TemplateTy::make(Name);4324 TNK = TNK_Type_template;4325 }4326}4327 4328TypeResult Sema::ActOnTemplateIdType(4329 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,4330 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,4331 SourceLocation TemplateKWLoc, TemplateTy TemplateD,4332 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,4333 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,4334 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,4335 ImplicitTypenameContext AllowImplicitTypename) {4336 if (SS.isInvalid())4337 return true;4338 4339 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {4340 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);4341 4342 // C++ [temp.res]p3:4343 // A qualified-id that refers to a type and in which the4344 // nested-name-specifier depends on a template-parameter (14.6.2)4345 // shall be prefixed by the keyword typename to indicate that the4346 // qualified-id denotes a type, forming an4347 // elaborated-type-specifier (7.1.5.3).4348 if (!LookupCtx && isDependentScopeSpecifier(SS)) {4349 // C++2a relaxes some of those restrictions in [temp.res]p5.4350 QualType DNT = Context.getDependentNameType(ElaboratedTypeKeyword::None,4351 SS.getScopeRep(), TemplateII);4352 NestedNameSpecifier NNS(DNT.getTypePtr());4353 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {4354 auto DB = DiagCompat(SS.getBeginLoc(), diag_compat::implicit_typename)4355 << NNS;4356 if (!getLangOpts().CPlusPlus20)4357 DB << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");4358 } else4359 Diag(SS.getBeginLoc(), diag::err_typename_missing_template) << NNS;4360 4361 // FIXME: This is not quite correct recovery as we don't transform SS4362 // into the corresponding dependent form (and we don't diagnose missing4363 // 'template' keywords within SS as a result).4364 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,4365 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,4366 TemplateArgsIn, RAngleLoc);4367 }4368 4369 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,4370 // it's not actually allowed to be used as a type in most cases. Because4371 // we annotate it before we know whether it's valid, we have to check for4372 // this case here.4373 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);4374 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {4375 Diag(TemplateIILoc,4376 TemplateKWLoc.isInvalid()4377 ? diag::err_out_of_line_qualified_id_type_names_constructor4378 : diag::ext_out_of_line_qualified_id_type_names_constructor)4379 << TemplateII << 0 /*injected-class-name used as template name*/4380 << 1 /*if any keyword was present, it was 'template'*/;4381 }4382 }4383 4384 // Translate the parser's template argument list in our AST format.4385 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);4386 translateTemplateArguments(TemplateArgsIn, TemplateArgs);4387 4388 QualType SpecTy = CheckTemplateIdType(4389 ElaboratedKeyword, TemplateD.get(), TemplateIILoc, TemplateArgs,4390 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);4391 if (SpecTy.isNull())4392 return true;4393 4394 // Build type-source information.4395 TypeLocBuilder TLB;4396 TLB.push<TemplateSpecializationTypeLoc>(SpecTy).set(4397 ElaboratedKeywordLoc, SS.getWithLocInContext(Context), TemplateKWLoc,4398 TemplateIILoc, TemplateArgs);4399 return CreateParsedType(SpecTy, TLB.getTypeSourceInfo(Context, SpecTy));4400}4401 4402TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,4403 TypeSpecifierType TagSpec,4404 SourceLocation TagLoc,4405 CXXScopeSpec &SS,4406 SourceLocation TemplateKWLoc,4407 TemplateTy TemplateD,4408 SourceLocation TemplateLoc,4409 SourceLocation LAngleLoc,4410 ASTTemplateArgsPtr TemplateArgsIn,4411 SourceLocation RAngleLoc) {4412 if (SS.isInvalid())4413 return TypeResult(true);4414 4415 // Translate the parser's template argument list in our AST format.4416 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);4417 translateTemplateArguments(TemplateArgsIn, TemplateArgs);4418 4419 // Determine the tag kind4420 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);4421 ElaboratedTypeKeyword Keyword4422 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);4423 4424 QualType Result =4425 CheckTemplateIdType(Keyword, TemplateD.get(), TemplateLoc, TemplateArgs,4426 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);4427 if (Result.isNull())4428 return TypeResult(true);4429 4430 // Check the tag kind4431 if (const RecordType *RT = Result->getAs<RecordType>()) {4432 RecordDecl *D = RT->getDecl();4433 4434 IdentifierInfo *Id = D->getIdentifier();4435 assert(Id && "templated class must have an identifier");4436 4437 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TagUseKind::Definition,4438 TagLoc, Id)) {4439 Diag(TagLoc, diag::err_use_with_wrong_tag)4440 << Result4441 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());4442 Diag(D->getLocation(), diag::note_previous_use);4443 }4444 }4445 4446 // Provide source-location information for the template specialization.4447 TypeLocBuilder TLB;4448 TLB.push<TemplateSpecializationTypeLoc>(Result).set(4449 TagLoc, SS.getWithLocInContext(Context), TemplateKWLoc, TemplateLoc,4450 TemplateArgs);4451 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));4452}4453 4454static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,4455 NamedDecl *PrevDecl,4456 SourceLocation Loc,4457 bool IsPartialSpecialization);4458 4459static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);4460 4461static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg,4462 unsigned Depth,4463 unsigned Index) {4464 switch (Arg.getKind()) {4465 case TemplateArgument::Null:4466 case TemplateArgument::NullPtr:4467 case TemplateArgument::Integral:4468 case TemplateArgument::Declaration:4469 case TemplateArgument::StructuralValue:4470 case TemplateArgument::Pack:4471 case TemplateArgument::TemplateExpansion:4472 return false;4473 4474 case TemplateArgument::Type: {4475 QualType Type = Arg.getAsType();4476 const TemplateTypeParmType *TPT =4477 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();4478 return TPT && !Type.hasQualifiers() &&4479 TPT->getDepth() == Depth && TPT->getIndex() == Index;4480 }4481 4482 case TemplateArgument::Expression: {4483 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());4484 if (!DRE || !DRE->getDecl())4485 return false;4486 const NonTypeTemplateParmDecl *NTTP =4487 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());4488 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;4489 }4490 4491 case TemplateArgument::Template:4492 const TemplateTemplateParmDecl *TTP =4493 dyn_cast_or_null<TemplateTemplateParmDecl>(4494 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());4495 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;4496 }4497 llvm_unreachable("unexpected kind of template argument");4498}4499 4500static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,4501 TemplateParameterList *SpecParams,4502 ArrayRef<TemplateArgument> Args) {4503 if (Params->size() != Args.size() || Params->size() != SpecParams->size())4504 return false;4505 4506 unsigned Depth = Params->getDepth();4507 4508 for (unsigned I = 0, N = Args.size(); I != N; ++I) {4509 TemplateArgument Arg = Args[I];4510 4511 // If the parameter is a pack expansion, the argument must be a pack4512 // whose only element is a pack expansion.4513 if (Params->getParam(I)->isParameterPack()) {4514 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||4515 !Arg.pack_begin()->isPackExpansion())4516 return false;4517 Arg = Arg.pack_begin()->getPackExpansionPattern();4518 }4519 4520 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))4521 return false;4522 4523 // For NTTPs further specialization is allowed via deduced types, so4524 // we need to make sure to only reject here if primary template and4525 // specialization use the same type for the NTTP.4526 if (auto *SpecNTTP =4527 dyn_cast<NonTypeTemplateParmDecl>(SpecParams->getParam(I))) {4528 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(I));4529 if (!NTTP || NTTP->getType().getCanonicalType() !=4530 SpecNTTP->getType().getCanonicalType())4531 return false;4532 }4533 }4534 4535 return true;4536}4537 4538template<typename PartialSpecDecl>4539static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {4540 if (Partial->getDeclContext()->isDependentContext())4541 return;4542 4543 // FIXME: Get the TDK from deduction in order to provide better diagnostics4544 // for non-substitution-failure issues?4545 TemplateDeductionInfo Info(Partial->getLocation());4546 if (S.isMoreSpecializedThanPrimary(Partial, Info))4547 return;4548 4549 auto *Template = Partial->getSpecializedTemplate();4550 S.Diag(Partial->getLocation(),4551 diag::ext_partial_spec_not_more_specialized_than_primary)4552 << isa<VarTemplateDecl>(Template);4553 4554 if (Info.hasSFINAEDiagnostic()) {4555 PartialDiagnosticAt Diag = {SourceLocation(),4556 PartialDiagnostic::NullDiagnostic()};4557 Info.takeSFINAEDiagnostic(Diag);4558 SmallString<128> SFINAEArgString;4559 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);4560 S.Diag(Diag.first,4561 diag::note_partial_spec_not_more_specialized_than_primary)4562 << SFINAEArgString;4563 }4564 4565 S.NoteTemplateLocation(*Template);4566 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;4567 Template->getAssociatedConstraints(TemplateAC);4568 Partial->getAssociatedConstraints(PartialAC);4569 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,4570 TemplateAC);4571}4572 4573static void4574noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,4575 const llvm::SmallBitVector &DeducibleParams) {4576 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {4577 if (!DeducibleParams[I]) {4578 NamedDecl *Param = TemplateParams->getParam(I);4579 if (Param->getDeclName())4580 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)4581 << Param->getDeclName();4582 else4583 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)4584 << "(anonymous)";4585 }4586 }4587}4588 4589 4590template<typename PartialSpecDecl>4591static void checkTemplatePartialSpecialization(Sema &S,4592 PartialSpecDecl *Partial) {4593 // C++1z [temp.class.spec]p8: (DR1495)4594 // - The specialization shall be more specialized than the primary4595 // template (14.5.5.2).4596 checkMoreSpecializedThanPrimary(S, Partial);4597 4598 // C++ [temp.class.spec]p8: (DR1315)4599 // - Each template-parameter shall appear at least once in the4600 // template-id outside a non-deduced context.4601 // C++1z [temp.class.spec.match]p3 (P0127R2)4602 // If the template arguments of a partial specialization cannot be4603 // deduced because of the structure of its template-parameter-list4604 // and the template-id, the program is ill-formed.4605 auto *TemplateParams = Partial->getTemplateParameters();4606 llvm::SmallBitVector DeducibleParams(TemplateParams->size());4607 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,4608 TemplateParams->getDepth(), DeducibleParams);4609 4610 if (!DeducibleParams.all()) {4611 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();4612 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)4613 << isa<VarTemplatePartialSpecializationDecl>(Partial)4614 << (NumNonDeducible > 1)4615 << SourceRange(Partial->getLocation(),4616 Partial->getTemplateArgsAsWritten()->RAngleLoc);4617 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);4618 }4619}4620 4621void Sema::CheckTemplatePartialSpecialization(4622 ClassTemplatePartialSpecializationDecl *Partial) {4623 checkTemplatePartialSpecialization(*this, Partial);4624}4625 4626void Sema::CheckTemplatePartialSpecialization(4627 VarTemplatePartialSpecializationDecl *Partial) {4628 checkTemplatePartialSpecialization(*this, Partial);4629}4630 4631void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {4632 // C++1z [temp.param]p11:4633 // A template parameter of a deduction guide template that does not have a4634 // default-argument shall be deducible from the parameter-type-list of the4635 // deduction guide template.4636 auto *TemplateParams = TD->getTemplateParameters();4637 llvm::SmallBitVector DeducibleParams(TemplateParams->size());4638 MarkDeducedTemplateParameters(TD, DeducibleParams);4639 for (unsigned I = 0; I != TemplateParams->size(); ++I) {4640 // A parameter pack is deducible (to an empty pack).4641 auto *Param = TemplateParams->getParam(I);4642 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))4643 DeducibleParams[I] = true;4644 }4645 4646 if (!DeducibleParams.all()) {4647 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();4648 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)4649 << (NumNonDeducible > 1);4650 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);4651 }4652}4653 4654DeclResult Sema::ActOnVarTemplateSpecialization(4655 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,4656 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,4657 StorageClass SC, bool IsPartialSpecialization) {4658 // D must be variable template id.4659 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&4660 "Variable template specialization is declared with a template id.");4661 4662 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;4663 TemplateArgumentListInfo TemplateArgs =4664 makeTemplateArgumentListInfo(*this, *TemplateId);4665 SourceLocation TemplateNameLoc = D.getIdentifierLoc();4666 SourceLocation LAngleLoc = TemplateId->LAngleLoc;4667 SourceLocation RAngleLoc = TemplateId->RAngleLoc;4668 4669 TemplateName Name = TemplateId->Template.get();4670 4671 // The template-id must name a variable template.4672 VarTemplateDecl *VarTemplate =4673 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());4674 if (!VarTemplate) {4675 NamedDecl *FnTemplate;4676 if (auto *OTS = Name.getAsOverloadedTemplate())4677 FnTemplate = *OTS->begin();4678 else4679 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());4680 if (FnTemplate)4681 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)4682 << FnTemplate->getDeclName();4683 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)4684 << IsPartialSpecialization;4685 }4686 4687 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {4688 auto Message = DSA->getMessage();4689 Diag(TemplateNameLoc, diag::warn_invalid_specialization)4690 << VarTemplate << !Message.empty() << Message;4691 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;4692 }4693 4694 // Check for unexpanded parameter packs in any of the template arguments.4695 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)4696 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],4697 IsPartialSpecialization4698 ? UPPC_PartialSpecialization4699 : UPPC_ExplicitSpecialization))4700 return true;4701 4702 // Check that the template argument list is well-formed for this4703 // template.4704 CheckTemplateArgumentInfo CTAI;4705 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,4706 /*DefaultArgs=*/{},4707 /*PartialTemplateArgs=*/false, CTAI,4708 /*UpdateArgsWithConversions=*/true))4709 return true;4710 4711 // Find the variable template (partial) specialization declaration that4712 // corresponds to these arguments.4713 if (IsPartialSpecialization) {4714 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,4715 TemplateArgs.size(),4716 CTAI.CanonicalConverted))4717 return true;4718 4719 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so4720 // we also do them during instantiation.4721 if (!Name.isDependent() &&4722 !TemplateSpecializationType::anyDependentTemplateArguments(4723 TemplateArgs, CTAI.CanonicalConverted)) {4724 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)4725 << VarTemplate->getDeclName();4726 IsPartialSpecialization = false;4727 }4728 4729 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),4730 TemplateParams, CTAI.CanonicalConverted) &&4731 (!Context.getLangOpts().CPlusPlus20 ||4732 !TemplateParams->hasAssociatedConstraints())) {4733 // C++ [temp.class.spec]p9b3:4734 //4735 // -- The argument list of the specialization shall not be identical4736 // to the implicit argument list of the primary template.4737 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)4738 << /*variable template*/ 14739 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())4740 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));4741 // FIXME: Recover from this by treating the declaration as a4742 // redeclaration of the primary template.4743 return true;4744 }4745 }4746 4747 void *InsertPos = nullptr;4748 VarTemplateSpecializationDecl *PrevDecl = nullptr;4749 4750 if (IsPartialSpecialization)4751 PrevDecl = VarTemplate->findPartialSpecialization(4752 CTAI.CanonicalConverted, TemplateParams, InsertPos);4753 else4754 PrevDecl =4755 VarTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);4756 4757 VarTemplateSpecializationDecl *Specialization = nullptr;4758 4759 // Check whether we can declare a variable template specialization in4760 // the current scope.4761 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,4762 TemplateNameLoc,4763 IsPartialSpecialization))4764 return true;4765 4766 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {4767 // Since the only prior variable template specialization with these4768 // arguments was referenced but not declared, reuse that4769 // declaration node as our own, updating its source location and4770 // the list of outer template parameters to reflect our new declaration.4771 Specialization = PrevDecl;4772 Specialization->setLocation(TemplateNameLoc);4773 PrevDecl = nullptr;4774 } else if (IsPartialSpecialization) {4775 // Create a new class template partial specialization declaration node.4776 VarTemplatePartialSpecializationDecl *PrevPartial =4777 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);4778 VarTemplatePartialSpecializationDecl *Partial =4779 VarTemplatePartialSpecializationDecl::Create(4780 Context, VarTemplate->getDeclContext(), TemplateKWLoc,4781 TemplateNameLoc, TemplateParams, VarTemplate, TSI->getType(), TSI,4782 SC, CTAI.CanonicalConverted);4783 Partial->setTemplateArgsAsWritten(TemplateArgs);4784 4785 if (!PrevPartial)4786 VarTemplate->AddPartialSpecialization(Partial, InsertPos);4787 Specialization = Partial;4788 4789 // If we are providing an explicit specialization of a member variable4790 // template specialization, make a note of that.4791 if (PrevPartial && PrevPartial->getInstantiatedFromMember())4792 PrevPartial->setMemberSpecialization();4793 4794 CheckTemplatePartialSpecialization(Partial);4795 } else {4796 // Create a new class template specialization declaration node for4797 // this explicit specialization or friend declaration.4798 Specialization = VarTemplateSpecializationDecl::Create(4799 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,4800 VarTemplate, TSI->getType(), TSI, SC, CTAI.CanonicalConverted);4801 Specialization->setTemplateArgsAsWritten(TemplateArgs);4802 4803 if (!PrevDecl)4804 VarTemplate->AddSpecialization(Specialization, InsertPos);4805 }4806 4807 // C++ [temp.expl.spec]p6:4808 // If a template, a member template or the member of a class template is4809 // explicitly specialized then that specialization shall be declared4810 // before the first use of that specialization that would cause an implicit4811 // instantiation to take place, in every translation unit in which such a4812 // use occurs; no diagnostic is required.4813 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {4814 bool Okay = false;4815 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {4816 // Is there any previous explicit specialization declaration?4817 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {4818 Okay = true;4819 break;4820 }4821 }4822 4823 if (!Okay) {4824 SourceRange Range(TemplateNameLoc, RAngleLoc);4825 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)4826 << Name << Range;4827 4828 Diag(PrevDecl->getPointOfInstantiation(),4829 diag::note_instantiation_required_here)4830 << (PrevDecl->getTemplateSpecializationKind() !=4831 TSK_ImplicitInstantiation);4832 return true;4833 }4834 }4835 4836 Specialization->setLexicalDeclContext(CurContext);4837 4838 // Add the specialization into its lexical context, so that it can4839 // be seen when iterating through the list of declarations in that4840 // context. However, specializations are not found by name lookup.4841 CurContext->addDecl(Specialization);4842 4843 // Note that this is an explicit specialization.4844 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);4845 4846 Previous.clear();4847 if (PrevDecl)4848 Previous.addDecl(PrevDecl);4849 else if (Specialization->isStaticDataMember() &&4850 Specialization->isOutOfLine())4851 Specialization->setAccess(VarTemplate->getAccess());4852 4853 return Specialization;4854}4855 4856namespace {4857/// A partial specialization whose template arguments have matched4858/// a given template-id.4859struct PartialSpecMatchResult {4860 VarTemplatePartialSpecializationDecl *Partial;4861 TemplateArgumentList *Args;4862};4863 4864// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)4865// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=1201904866static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {4867 if (Var->getName() != "format_kind" ||4868 !Var->getDeclContext()->isStdNamespace())4869 return false;4870 4871 // Checking old versions of libstdc++ is not needed because 15.1 is the first4872 // release in which users can access std::format_kind.4873 // We can use 20250520 as the final date, see the following commits.4874 // GCC releases/gcc-15 branch:4875 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c512054876 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f1606504877 // GCC master branch:4878 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b2784879 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c759304880 return PP.NeedsStdLibCxxWorkaroundBefore(2025'05'20);4881}4882} // end anonymous namespace4883 4884DeclResult4885Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,4886 SourceLocation TemplateNameLoc,4887 const TemplateArgumentListInfo &TemplateArgs,4888 bool SetWrittenArgs) {4889 assert(Template && "A variable template id without template?");4890 4891 // Check that the template argument list is well-formed for this template.4892 CheckTemplateArgumentInfo CTAI;4893 if (CheckTemplateArgumentList(4894 Template, TemplateNameLoc,4895 const_cast<TemplateArgumentListInfo &>(TemplateArgs),4896 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,4897 /*UpdateArgsWithConversions=*/true))4898 return true;4899 4900 // Produce a placeholder value if the specialization is dependent.4901 if (Template->getDeclContext()->isDependentContext() ||4902 TemplateSpecializationType::anyDependentTemplateArguments(4903 TemplateArgs, CTAI.CanonicalConverted)) {4904 if (ParsingInitForAutoVars.empty())4905 return DeclResult();4906 4907 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,4908 const TemplateArgument &Arg2) {4909 return Context.isSameTemplateArgument(Arg1, Arg2);4910 };4911 4912 if (VarDecl *Var = Template->getTemplatedDecl();4913 ParsingInitForAutoVars.count(Var) &&4914 // See comments on this function definition4915 !IsLibstdcxxStdFormatKind(PP, Var) &&4916 llvm::equal(4917 CTAI.CanonicalConverted,4918 Template->getTemplateParameters()->getInjectedTemplateArgs(Context),4919 IsSameTemplateArg)) {4920 Diag(TemplateNameLoc,4921 diag::err_auto_variable_cannot_appear_in_own_initializer)4922 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();4923 return true;4924 }4925 4926 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;4927 Template->getPartialSpecializations(PartialSpecs);4928 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)4929 if (ParsingInitForAutoVars.count(Partial) &&4930 llvm::equal(CTAI.CanonicalConverted,4931 Partial->getTemplateArgs().asArray(),4932 IsSameTemplateArg)) {4933 Diag(TemplateNameLoc,4934 diag::err_auto_variable_cannot_appear_in_own_initializer)4935 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial4936 << Partial->getType();4937 return true;4938 }4939 4940 return DeclResult();4941 }4942 4943 // Find the variable template specialization declaration that4944 // corresponds to these arguments.4945 void *InsertPos = nullptr;4946 if (VarTemplateSpecializationDecl *Spec =4947 Template->findSpecialization(CTAI.CanonicalConverted, InsertPos)) {4948 checkSpecializationReachability(TemplateNameLoc, Spec);4949 if (Spec->getType()->isUndeducedType()) {4950 if (ParsingInitForAutoVars.count(Spec))4951 Diag(TemplateNameLoc,4952 diag::err_auto_variable_cannot_appear_in_own_initializer)4953 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec4954 << Spec->getType();4955 else4956 // We are substituting the initializer of this variable template4957 // specialization.4958 Diag(TemplateNameLoc, diag::err_var_template_spec_type_depends_on_self)4959 << Spec << Spec->getType();4960 4961 return true;4962 }4963 // If we already have a variable template specialization, return it.4964 return Spec;4965 }4966 4967 // This is the first time we have referenced this variable template4968 // specialization. Create the canonical declaration and add it to4969 // the set of specializations, based on the closest partial specialization4970 // that it represents. That is,4971 VarDecl *InstantiationPattern = Template->getTemplatedDecl();4972 const TemplateArgumentList *PartialSpecArgs = nullptr;4973 bool AmbiguousPartialSpec = false;4974 typedef PartialSpecMatchResult MatchResult;4975 SmallVector<MatchResult, 4> Matched;4976 SourceLocation PointOfInstantiation = TemplateNameLoc;4977 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,4978 /*ForTakingAddress=*/false);4979 4980 // 1. Attempt to find the closest partial specialization that this4981 // specializes, if any.4982 // TODO: Unify with InstantiateClassTemplateSpecialization()?4983 // Perhaps better after unification of DeduceTemplateArguments() and4984 // getMoreSpecializedPartialSpecialization().4985 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;4986 Template->getPartialSpecializations(PartialSpecs);4987 4988 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {4989 // C++ [temp.spec.partial.member]p2:4990 // If the primary member template is explicitly specialized for a given4991 // (implicit) specialization of the enclosing class template, the partial4992 // specializations of the member template are ignored for this4993 // specialization of the enclosing class template. If a partial4994 // specialization of the member template is explicitly specialized for a4995 // given (implicit) specialization of the enclosing class template, the4996 // primary member template and its other partial specializations are still4997 // considered for this specialization of the enclosing class template.4998 if (Template->getMostRecentDecl()->isMemberSpecialization() &&4999 !Partial->getMostRecentDecl()->isMemberSpecialization())5000 continue;5001 5002 TemplateDeductionInfo Info(FailedCandidates.getLocation());5003 5004 if (TemplateDeductionResult Result =5005 DeduceTemplateArguments(Partial, CTAI.SugaredConverted, Info);5006 Result != TemplateDeductionResult::Success) {5007 // Store the failed-deduction information for use in diagnostics, later.5008 // TODO: Actually use the failed-deduction info?5009 FailedCandidates.addCandidate().set(5010 DeclAccessPair::make(Template, AS_public), Partial,5011 MakeDeductionFailureInfo(Context, Result, Info));5012 (void)Result;5013 } else {5014 Matched.push_back(PartialSpecMatchResult());5015 Matched.back().Partial = Partial;5016 Matched.back().Args = Info.takeSugared();5017 }5018 }5019 5020 if (Matched.size() >= 1) {5021 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();5022 if (Matched.size() == 1) {5023 // -- If exactly one matching specialization is found, the5024 // instantiation is generated from that specialization.5025 // We don't need to do anything for this.5026 } else {5027 // -- If more than one matching specialization is found, the5028 // partial order rules (14.5.4.2) are used to determine5029 // whether one of the specializations is more specialized5030 // than the others. If none of the specializations is more5031 // specialized than all of the other matching5032 // specializations, then the use of the variable template is5033 // ambiguous and the program is ill-formed.5034 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,5035 PEnd = Matched.end();5036 P != PEnd; ++P) {5037 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,5038 PointOfInstantiation) ==5039 P->Partial)5040 Best = P;5041 }5042 5043 // Determine if the best partial specialization is more specialized than5044 // the others.5045 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),5046 PEnd = Matched.end();5047 P != PEnd; ++P) {5048 if (P != Best && getMoreSpecializedPartialSpecialization(5049 P->Partial, Best->Partial,5050 PointOfInstantiation) != Best->Partial) {5051 AmbiguousPartialSpec = true;5052 break;5053 }5054 }5055 }5056 5057 // Instantiate using the best variable template partial specialization.5058 InstantiationPattern = Best->Partial;5059 PartialSpecArgs = Best->Args;5060 } else {5061 // -- If no match is found, the instantiation is generated5062 // from the primary template.5063 // InstantiationPattern = Template->getTemplatedDecl();5064 }5065 5066 // 2. Create the canonical declaration.5067 // Note that we do not instantiate a definition until we see an odr-use5068 // in DoMarkVarDeclReferenced().5069 // FIXME: LateAttrs et al.?5070 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(5071 Template, InstantiationPattern, PartialSpecArgs, CTAI.CanonicalConverted,5072 TemplateNameLoc /*, LateAttrs, StartingScope*/);5073 if (!Decl)5074 return true;5075 if (SetWrittenArgs)5076 Decl->setTemplateArgsAsWritten(TemplateArgs);5077 5078 if (AmbiguousPartialSpec) {5079 // Partial ordering did not produce a clear winner. Complain.5080 Decl->setInvalidDecl();5081 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)5082 << Decl;5083 5084 // Print the matching partial specializations.5085 for (MatchResult P : Matched)5086 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)5087 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),5088 *P.Args);5089 return true;5090 }5091 5092 if (VarTemplatePartialSpecializationDecl *D =5093 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))5094 Decl->setInstantiationOf(D, PartialSpecArgs);5095 5096 checkSpecializationReachability(TemplateNameLoc, Decl);5097 5098 assert(Decl && "No variable template specialization?");5099 return Decl;5100}5101 5102ExprResult Sema::CheckVarTemplateId(5103 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,5104 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,5105 const TemplateArgumentListInfo *TemplateArgs) {5106 5107 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),5108 *TemplateArgs, /*SetWrittenArgs=*/false);5109 if (Decl.isInvalid())5110 return ExprError();5111 5112 if (!Decl.get())5113 return ExprResult();5114 5115 VarDecl *Var = cast<VarDecl>(Decl.get());5116 if (!Var->getTemplateSpecializationKind())5117 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,5118 NameInfo.getLoc());5119 5120 // Build an ordinary singleton decl ref.5121 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);5122}5123 5124ExprResult Sema::CheckVarOrConceptTemplateTemplateId(5125 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,5126 TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc,5127 const TemplateArgumentListInfo *TemplateArgs) {5128 assert(Template && "A variable template id without template?");5129 5130 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&5131 Template->templateParameterKind() !=5132 TemplateNameKind::TNK_Concept_template)5133 return ExprResult();5134 5135 // Check that the template argument list is well-formed for this template.5136 CheckTemplateArgumentInfo CTAI;5137 if (CheckTemplateArgumentList(5138 Template, TemplateLoc,5139 // FIXME: TemplateArgs will not be modified because5140 // UpdateArgsWithConversions is false, however, we should5141 // CheckTemplateArgumentList to be const-correct.5142 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),5143 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,5144 /*UpdateArgsWithConversions=*/false))5145 return true;5146 5147 UnresolvedSet<1> R;5148 R.addDecl(Template);5149 5150 // FIXME: We model references to variable template and concept parameters5151 // as an UnresolvedLookupExpr. This is because they encapsulate the same5152 // data, can generally be used in the same places and work the same way.5153 // However, it might be cleaner to use a dedicated AST node in the long run.5154 return UnresolvedLookupExpr::Create(5155 getASTContext(), nullptr, SS.getWithLocInContext(getASTContext()),5156 SourceLocation(), NameInfo, false, TemplateArgs, R.begin(), R.end(),5157 /*KnownDependent=*/false,5158 /*KnownInstantiationDependent=*/false);5159}5160 5161void Sema::diagnoseMissingTemplateArguments(TemplateName Name,5162 SourceLocation Loc) {5163 Diag(Loc, diag::err_template_missing_args)5164 << (int)getTemplateNameKindForDiagnostics(Name) << Name;5165 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {5166 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());5167 }5168}5169 5170void Sema::diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,5171 bool TemplateKeyword,5172 TemplateDecl *TD,5173 SourceLocation Loc) {5174 TemplateName Name = Context.getQualifiedTemplateName(5175 SS.getScopeRep(), TemplateKeyword, TemplateName(TD));5176 diagnoseMissingTemplateArguments(Name, Loc);5177}5178 5179ExprResult Sema::CheckConceptTemplateId(5180 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,5181 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,5182 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,5183 bool DoCheckConstraintSatisfaction) {5184 assert(NamedConcept && "A concept template id without a template?");5185 5186 if (NamedConcept->isInvalidDecl())5187 return ExprError();5188 5189 CheckTemplateArgumentInfo CTAI;5190 if (CheckTemplateArgumentList(5191 NamedConcept, ConceptNameInfo.getLoc(),5192 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),5193 /*DefaultArgs=*/{},5194 /*PartialTemplateArgs=*/false, CTAI,5195 /*UpdateArgsWithConversions=*/false))5196 return ExprError();5197 5198 DiagnoseUseOfDecl(NamedConcept, ConceptNameInfo.getLoc());5199 5200 // There's a bug with CTAI.CanonicalConverted.5201 // If the template argument contains a DependentDecltypeType that includes a5202 // TypeAliasType, and the same written type had occurred previously in the5203 // source, then the DependentDecltypeType would be canonicalized to that5204 // previous type which would mess up the substitution.5205 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!5206 auto *CSD = ImplicitConceptSpecializationDecl::Create(5207 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),5208 CTAI.SugaredConverted);5209 ConstraintSatisfaction Satisfaction;5210 bool AreArgsDependent =5211 TemplateSpecializationType::anyDependentTemplateArguments(5212 *TemplateArgs, CTAI.SugaredConverted);5213 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,5214 /*Final=*/false);5215 auto *CL = ConceptReference::Create(5216 Context,5217 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},5218 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,5219 ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs));5220 5221 bool Error = false;5222 if (const auto *Concept = dyn_cast<ConceptDecl>(NamedConcept);5223 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&5224 DoCheckConstraintSatisfaction) {5225 5226 LocalInstantiationScope Scope(*this);5227 5228 EnterExpressionEvaluationContext EECtx{5229 *this, ExpressionEvaluationContext::Unevaluated, CSD};5230 5231 Error = CheckConstraintSatisfaction(5232 NamedConcept, AssociatedConstraint(Concept->getConstraintExpr()), MLTAL,5233 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),5234 TemplateArgs->getRAngleLoc()),5235 Satisfaction, CL);5236 Satisfaction.ContainsErrors = Error;5237 }5238 5239 if (Error)5240 return ExprError();5241 5242 return ConceptSpecializationExpr::Create(5243 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);5244}5245 5246ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,5247 SourceLocation TemplateKWLoc,5248 LookupResult &R,5249 bool RequiresADL,5250 const TemplateArgumentListInfo *TemplateArgs) {5251 // FIXME: Can we do any checking at this point? I guess we could check the5252 // template arguments that we have against the template name, if the template5253 // name refers to a single template. That's not a terribly common case,5254 // though.5255 // foo<int> could identify a single function unambiguously5256 // This approach does NOT work, since f<int>(1);5257 // gets resolved prior to resorting to overload resolution5258 // i.e., template<class T> void f(double);5259 // vs template<class T, class U> void f(U);5260 5261 // These should be filtered out by our callers.5262 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");5263 5264 // Non-function templates require a template argument list.5265 if (auto *TD = R.getAsSingle<TemplateDecl>()) {5266 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {5267 diagnoseMissingTemplateArguments(5268 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, R.getNameLoc());5269 return ExprError();5270 }5271 }5272 bool KnownDependent = false;5273 // In C++1y, check variable template ids.5274 if (R.getAsSingle<VarTemplateDecl>()) {5275 ExprResult Res = CheckVarTemplateId(5276 SS, R.getLookupNameInfo(), R.getAsSingle<VarTemplateDecl>(),5277 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);5278 if (Res.isInvalid() || Res.isUsable())5279 return Res;5280 // Result is dependent. Carry on to build an UnresolvedLookupExpr.5281 KnownDependent = true;5282 }5283 5284 // We don't want lookup warnings at this point.5285 R.suppressDiagnostics();5286 5287 if (R.getAsSingle<ConceptDecl>()) {5288 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),5289 R.getRepresentativeDecl(),5290 R.getAsSingle<ConceptDecl>(), TemplateArgs);5291 }5292 5293 // Check variable template ids (C++17) and concept template parameters5294 // (C++26).5295 UnresolvedLookupExpr *ULE;5296 if (R.getAsSingle<TemplateTemplateParmDecl>())5297 return CheckVarOrConceptTemplateTemplateId(5298 SS, R.getLookupNameInfo(), R.getAsSingle<TemplateTemplateParmDecl>(),5299 TemplateKWLoc, TemplateArgs);5300 5301 // Function templates5302 ULE = UnresolvedLookupExpr::Create(5303 Context, R.getNamingClass(), SS.getWithLocInContext(Context),5304 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,5305 R.begin(), R.end(), KnownDependent,5306 /*KnownInstantiationDependent=*/false);5307 // Model the templates with UnresolvedTemplateTy. The expression should then5308 // either be transformed in an instantiation or be diagnosed in5309 // CheckPlaceholderExpr.5310 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&5311 !R.getFoundDecl()->getAsFunction())5312 ULE->setType(Context.UnresolvedTemplateTy);5313 5314 return ULE;5315}5316 5317ExprResult Sema::BuildQualifiedTemplateIdExpr(5318 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,5319 const DeclarationNameInfo &NameInfo,5320 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {5321 assert(TemplateArgs || TemplateKWLoc.isValid());5322 5323 LookupResult R(*this, NameInfo, LookupOrdinaryName);5324 if (LookupTemplateName(R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),5325 /*EnteringContext=*/false, TemplateKWLoc))5326 return ExprError();5327 5328 if (R.isAmbiguous())5329 return ExprError();5330 5331 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())5332 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);5333 5334 if (R.empty()) {5335 DeclContext *DC = computeDeclContext(SS);5336 Diag(NameInfo.getLoc(), diag::err_no_member)5337 << NameInfo.getName() << DC << SS.getRange();5338 return ExprError();5339 }5340 5341 // If necessary, build an implicit class member access.5342 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))5343 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,5344 /*S=*/nullptr);5345 5346 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/false, TemplateArgs);5347}5348 5349TemplateNameKind Sema::ActOnTemplateName(Scope *S,5350 CXXScopeSpec &SS,5351 SourceLocation TemplateKWLoc,5352 const UnqualifiedId &Name,5353 ParsedType ObjectType,5354 bool EnteringContext,5355 TemplateTy &Result,5356 bool AllowInjectedClassName) {5357 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())5358 Diag(TemplateKWLoc,5359 getLangOpts().CPlusPlus11 ?5360 diag::warn_cxx98_compat_template_outside_of_template :5361 diag::ext_template_outside_of_template)5362 << FixItHint::CreateRemoval(TemplateKWLoc);5363 5364 if (SS.isInvalid())5365 return TNK_Non_template;5366 5367 // Figure out where isTemplateName is going to look.5368 DeclContext *LookupCtx = nullptr;5369 if (SS.isNotEmpty())5370 LookupCtx = computeDeclContext(SS, EnteringContext);5371 else if (ObjectType)5372 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));5373 5374 // C++0x [temp.names]p5:5375 // If a name prefixed by the keyword template is not the name of5376 // a template, the program is ill-formed. [Note: the keyword5377 // template may not be applied to non-template members of class5378 // templates. -end note ] [ Note: as is the case with the5379 // typename prefix, the template prefix is allowed in cases5380 // where it is not strictly necessary; i.e., when the5381 // nested-name-specifier or the expression on the left of the ->5382 // or . is not dependent on a template-parameter, or the use5383 // does not appear in the scope of a template. -end note]5384 //5385 // Note: C++03 was more strict here, because it banned the use of5386 // the "template" keyword prior to a template-name that was not a5387 // dependent name. C++ DR468 relaxed this requirement (the5388 // "template" keyword is now permitted). We follow the C++0x5389 // rules, even in C++03 mode with a warning, retroactively applying the DR.5390 bool MemberOfUnknownSpecialization;5391 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,5392 ObjectType, EnteringContext, Result,5393 MemberOfUnknownSpecialization);5394 if (TNK != TNK_Non_template) {5395 // We resolved this to a (non-dependent) template name. Return it.5396 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);5397 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&5398 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&5399 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {5400 // C++14 [class.qual]p2:5401 // In a lookup in which function names are not ignored and the5402 // nested-name-specifier nominates a class C, if the name specified5403 // [...] is the injected-class-name of C, [...] the name is instead5404 // considered to name the constructor5405 //5406 // We don't get here if naming the constructor would be valid, so we5407 // just reject immediately and recover by treating the5408 // injected-class-name as naming the template.5409 Diag(Name.getBeginLoc(),5410 diag::ext_out_of_line_qualified_id_type_names_constructor)5411 << Name.Identifier5412 << 0 /*injected-class-name used as template name*/5413 << TemplateKWLoc.isValid();5414 }5415 return TNK;5416 }5417 5418 if (!MemberOfUnknownSpecialization) {5419 // Didn't find a template name, and the lookup wasn't dependent.5420 // Do the lookup again to determine if this is a "nothing found" case or5421 // a "not a template" case. FIXME: Refactor isTemplateName so we don't5422 // need to do this.5423 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);5424 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),5425 LookupOrdinaryName);5426 // Tell LookupTemplateName that we require a template so that it diagnoses5427 // cases where it finds a non-template.5428 RequiredTemplateKind RTK = TemplateKWLoc.isValid()5429 ? RequiredTemplateKind(TemplateKWLoc)5430 : TemplateNameIsRequired;5431 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, RTK,5432 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&5433 !R.isAmbiguous()) {5434 if (LookupCtx)5435 Diag(Name.getBeginLoc(), diag::err_no_member)5436 << DNI.getName() << LookupCtx << SS.getRange();5437 else5438 Diag(Name.getBeginLoc(), diag::err_undeclared_use)5439 << DNI.getName() << SS.getRange();5440 }5441 return TNK_Non_template;5442 }5443 5444 NestedNameSpecifier Qualifier = SS.getScopeRep();5445 5446 switch (Name.getKind()) {5447 case UnqualifiedIdKind::IK_Identifier:5448 Result = TemplateTy::make(Context.getDependentTemplateName(5449 {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));5450 return TNK_Dependent_template_name;5451 5452 case UnqualifiedIdKind::IK_OperatorFunctionId:5453 Result = TemplateTy::make(Context.getDependentTemplateName(5454 {Qualifier, Name.OperatorFunctionId.Operator,5455 TemplateKWLoc.isValid()}));5456 return TNK_Function_template;5457 5458 case UnqualifiedIdKind::IK_LiteralOperatorId:5459 // This is a kind of template name, but can never occur in a dependent5460 // scope (literal operators can only be declared at namespace scope).5461 break;5462 5463 default:5464 break;5465 }5466 5467 // This name cannot possibly name a dependent template. Diagnose this now5468 // rather than building a dependent template name that can never be valid.5469 Diag(Name.getBeginLoc(),5470 diag::err_template_kw_refers_to_dependent_non_template)5471 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()5472 << TemplateKWLoc.isValid() << TemplateKWLoc;5473 return TNK_Non_template;5474}5475 5476bool Sema::CheckTemplateTypeArgument(5477 TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,5478 SmallVectorImpl<TemplateArgument> &SugaredConverted,5479 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {5480 const TemplateArgument &Arg = AL.getArgument();5481 QualType ArgType;5482 TypeSourceInfo *TSI = nullptr;5483 5484 // Check template type parameter.5485 switch(Arg.getKind()) {5486 case TemplateArgument::Type:5487 // C++ [temp.arg.type]p1:5488 // A template-argument for a template-parameter which is a5489 // type shall be a type-id.5490 ArgType = Arg.getAsType();5491 TSI = AL.getTypeSourceInfo();5492 break;5493 case TemplateArgument::Template:5494 case TemplateArgument::TemplateExpansion: {5495 // We have a template type parameter but the template argument5496 // is a template without any arguments.5497 SourceRange SR = AL.getSourceRange();5498 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();5499 diagnoseMissingTemplateArguments(Name, SR.getEnd());5500 return true;5501 }5502 case TemplateArgument::Expression: {5503 // We have a template type parameter but the template argument is an5504 // expression; see if maybe it is missing the "typename" keyword.5505 CXXScopeSpec SS;5506 DeclarationNameInfo NameInfo;5507 5508 if (DependentScopeDeclRefExpr *ArgExpr =5509 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {5510 SS.Adopt(ArgExpr->getQualifierLoc());5511 NameInfo = ArgExpr->getNameInfo();5512 } else if (CXXDependentScopeMemberExpr *ArgExpr =5513 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {5514 if (ArgExpr->isImplicitAccess()) {5515 SS.Adopt(ArgExpr->getQualifierLoc());5516 NameInfo = ArgExpr->getMemberNameInfo();5517 }5518 }5519 5520 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {5521 LookupResult Result(*this, NameInfo, LookupOrdinaryName);5522 LookupParsedName(Result, CurScope, &SS, /*ObjectType=*/QualType());5523 5524 if (Result.getAsSingle<TypeDecl>() ||5525 Result.wasNotFoundInCurrentInstantiation()) {5526 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");5527 // Suggest that the user add 'typename' before the NNS.5528 SourceLocation Loc = AL.getSourceRange().getBegin();5529 Diag(Loc, getLangOpts().MSVCCompat5530 ? diag::ext_ms_template_type_arg_missing_typename5531 : diag::err_template_arg_must_be_type_suggest)5532 << FixItHint::CreateInsertion(Loc, "typename ");5533 NoteTemplateParameterLocation(*Param);5534 5535 // Recover by synthesizing a type using the location information that we5536 // already have.5537 ArgType = Context.getDependentNameType(ElaboratedTypeKeyword::None,5538 SS.getScopeRep(), II);5539 TypeLocBuilder TLB;5540 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);5541 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));5542 TL.setQualifierLoc(SS.getWithLocInContext(Context));5543 TL.setNameLoc(NameInfo.getLoc());5544 TSI = TLB.getTypeSourceInfo(Context, ArgType);5545 5546 // Overwrite our input TemplateArgumentLoc so that we can recover5547 // properly.5548 AL = TemplateArgumentLoc(TemplateArgument(ArgType),5549 TemplateArgumentLocInfo(TSI));5550 5551 break;5552 }5553 }5554 // fallthrough5555 [[fallthrough]];5556 }5557 default: {5558 // We allow instantiating a template with template argument packs when5559 // building deduction guides or mapping constraint template parameters.5560 if (Arg.getKind() == TemplateArgument::Pack &&5561 (CodeSynthesisContexts.back().Kind ==5562 Sema::CodeSynthesisContext::BuildingDeductionGuides ||5563 inParameterMappingSubstitution())) {5564 SugaredConverted.push_back(Arg);5565 CanonicalConverted.push_back(Arg);5566 return false;5567 }5568 // We have a template type parameter but the template argument5569 // is not a type.5570 SourceRange SR = AL.getSourceRange();5571 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;5572 NoteTemplateParameterLocation(*Param);5573 5574 return true;5575 }5576 }5577 5578 if (CheckTemplateArgument(TSI))5579 return true;5580 5581 // Objective-C ARC:5582 // If an explicitly-specified template argument type is a lifetime type5583 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.5584 if (getLangOpts().ObjCAutoRefCount &&5585 ArgType->isObjCLifetimeType() &&5586 !ArgType.getObjCLifetime()) {5587 Qualifiers Qs;5588 Qs.setObjCLifetime(Qualifiers::OCL_Strong);5589 ArgType = Context.getQualifiedType(ArgType, Qs);5590 }5591 5592 SugaredConverted.push_back(TemplateArgument(ArgType));5593 CanonicalConverted.push_back(5594 TemplateArgument(Context.getCanonicalType(ArgType)));5595 return false;5596}5597 5598/// Substitute template arguments into the default template argument for5599/// the given template type parameter.5600///5601/// \param SemaRef the semantic analysis object for which we are performing5602/// the substitution.5603///5604/// \param Template the template that we are synthesizing template arguments5605/// for.5606///5607/// \param TemplateLoc the location of the template name that started the5608/// template-id we are checking.5609///5610/// \param RAngleLoc the location of the right angle bracket ('>') that5611/// terminates the template-id.5612///5613/// \param Param the template template parameter whose default we are5614/// substituting into.5615///5616/// \param Converted the list of template arguments provided for template5617/// parameters that precede \p Param in the template parameter list.5618///5619/// \param Output the resulting substituted template argument.5620///5621/// \returns true if an error occurred.5622static bool SubstDefaultTemplateArgument(5623 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,5624 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,5625 ArrayRef<TemplateArgument> SugaredConverted,5626 ArrayRef<TemplateArgument> CanonicalConverted,5627 TemplateArgumentLoc &Output) {5628 Output = Param->getDefaultArgument();5629 5630 // If the argument type is dependent, instantiate it now based5631 // on the previously-computed template arguments.5632 if (Output.getArgument().isInstantiationDependent()) {5633 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,5634 SugaredConverted,5635 SourceRange(TemplateLoc, RAngleLoc));5636 if (Inst.isInvalid())5637 return true;5638 5639 // Only substitute for the innermost template argument list.5640 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,5641 /*Final=*/true);5642 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)5643 TemplateArgLists.addOuterTemplateArguments(std::nullopt);5644 5645 bool ForLambdaCallOperator = false;5646 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))5647 ForLambdaCallOperator = Rec->isLambda();5648 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),5649 !ForLambdaCallOperator);5650 5651 if (SemaRef.SubstTemplateArgument(Output, TemplateArgLists, Output,5652 Param->getDefaultArgumentLoc(),5653 Param->getDeclName()))5654 return true;5655 }5656 5657 return false;5658}5659 5660/// Substitute template arguments into the default template argument for5661/// the given non-type template parameter.5662///5663/// \param SemaRef the semantic analysis object for which we are performing5664/// the substitution.5665///5666/// \param Template the template that we are synthesizing template arguments5667/// for.5668///5669/// \param TemplateLoc the location of the template name that started the5670/// template-id we are checking.5671///5672/// \param RAngleLoc the location of the right angle bracket ('>') that5673/// terminates the template-id.5674///5675/// \param Param the non-type template parameter whose default we are5676/// substituting into.5677///5678/// \param Converted the list of template arguments provided for template5679/// parameters that precede \p Param in the template parameter list.5680///5681/// \returns the substituted template argument, or NULL if an error occurred.5682static bool SubstDefaultTemplateArgument(5683 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,5684 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,5685 ArrayRef<TemplateArgument> SugaredConverted,5686 ArrayRef<TemplateArgument> CanonicalConverted,5687 TemplateArgumentLoc &Output) {5688 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,5689 SugaredConverted,5690 SourceRange(TemplateLoc, RAngleLoc));5691 if (Inst.isInvalid())5692 return true;5693 5694 // Only substitute for the innermost template argument list.5695 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,5696 /*Final=*/true);5697 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)5698 TemplateArgLists.addOuterTemplateArguments(std::nullopt);5699 5700 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());5701 EnterExpressionEvaluationContext ConstantEvaluated(5702 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);5703 return SemaRef.SubstTemplateArgument(Param->getDefaultArgument(),5704 TemplateArgLists, Output);5705}5706 5707/// Substitute template arguments into the default template argument for5708/// the given template template parameter.5709///5710/// \param SemaRef the semantic analysis object for which we are performing5711/// the substitution.5712///5713/// \param Template the template that we are synthesizing template arguments5714/// for.5715///5716/// \param TemplateLoc the location of the template name that started the5717/// template-id we are checking.5718///5719/// \param RAngleLoc the location of the right angle bracket ('>') that5720/// terminates the template-id.5721///5722/// \param Param the template template parameter whose default we are5723/// substituting into.5724///5725/// \param Converted the list of template arguments provided for template5726/// parameters that precede \p Param in the template parameter list.5727///5728/// \param QualifierLoc Will be set to the nested-name-specifier (with5729/// source-location information) that precedes the template name.5730///5731/// \returns the substituted template argument, or NULL if an error occurred.5732static TemplateName SubstDefaultTemplateArgument(5733 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,5734 SourceLocation TemplateLoc, SourceLocation RAngleLoc,5735 TemplateTemplateParmDecl *Param,5736 ArrayRef<TemplateArgument> SugaredConverted,5737 ArrayRef<TemplateArgument> CanonicalConverted,5738 NestedNameSpecifierLoc &QualifierLoc) {5739 Sema::InstantiatingTemplate Inst(5740 SemaRef, TemplateLoc, TemplateParameter(Param), Template,5741 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));5742 if (Inst.isInvalid())5743 return TemplateName();5744 5745 // Only substitute for the innermost template argument list.5746 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,5747 /*Final=*/true);5748 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)5749 TemplateArgLists.addOuterTemplateArguments(std::nullopt);5750 5751 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());5752 5753 const TemplateArgumentLoc &A = Param->getDefaultArgument();5754 QualifierLoc = A.getTemplateQualifierLoc();5755 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,5756 A.getArgument().getAsTemplate(),5757 A.getTemplateNameLoc(), TemplateArgLists);5758}5759 5760TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(5761 TemplateDecl *Template, SourceLocation TemplateKWLoc,5762 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,5763 ArrayRef<TemplateArgument> SugaredConverted,5764 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {5765 HasDefaultArg = false;5766 5767 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {5768 if (!hasReachableDefaultArgument(TypeParm))5769 return TemplateArgumentLoc();5770 5771 HasDefaultArg = true;5772 TemplateArgumentLoc Output;5773 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,5774 RAngleLoc, TypeParm, SugaredConverted,5775 CanonicalConverted, Output))5776 return TemplateArgumentLoc();5777 return Output;5778 }5779 5780 if (NonTypeTemplateParmDecl *NonTypeParm5781 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {5782 if (!hasReachableDefaultArgument(NonTypeParm))5783 return TemplateArgumentLoc();5784 5785 HasDefaultArg = true;5786 TemplateArgumentLoc Output;5787 if (SubstDefaultTemplateArgument(*this, Template, TemplateNameLoc,5788 RAngleLoc, NonTypeParm, SugaredConverted,5789 CanonicalConverted, Output))5790 return TemplateArgumentLoc();5791 return Output;5792 }5793 5794 TemplateTemplateParmDecl *TempTempParm5795 = cast<TemplateTemplateParmDecl>(Param);5796 if (!hasReachableDefaultArgument(TempTempParm))5797 return TemplateArgumentLoc();5798 5799 HasDefaultArg = true;5800 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();5801 NestedNameSpecifierLoc QualifierLoc;5802 TemplateName TName = SubstDefaultTemplateArgument(5803 *this, Template, TemplateKWLoc, TemplateNameLoc, RAngleLoc, TempTempParm,5804 SugaredConverted, CanonicalConverted, QualifierLoc);5805 if (TName.isNull())5806 return TemplateArgumentLoc();5807 5808 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,5809 QualifierLoc, A.getTemplateNameLoc());5810}5811 5812/// Convert a template-argument that we parsed as a type into a template, if5813/// possible. C++ permits injected-class-names to perform dual service as5814/// template template arguments and as template type arguments.5815static TemplateArgumentLoc5816convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {5817 auto TagLoc = TLoc.getAs<TagTypeLoc>();5818 if (!TagLoc)5819 return TemplateArgumentLoc();5820 5821 // If this type was written as an injected-class-name, it can be used as a5822 // template template argument.5823 // If this type was written as an injected-class-name, it may have been5824 // converted to a RecordType during instantiation. If the RecordType is5825 // *not* wrapped in a TemplateSpecializationType and denotes a class5826 // template specialization, it must have come from an injected-class-name.5827 5828 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Context);5829 if (Name.isNull())5830 return TemplateArgumentLoc();5831 5832 return TemplateArgumentLoc(Context, Name,5833 /*TemplateKWLoc=*/SourceLocation(),5834 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());5835}5836 5837bool Sema::CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &ArgLoc,5838 NamedDecl *Template,5839 SourceLocation TemplateLoc,5840 SourceLocation RAngleLoc,5841 unsigned ArgumentPackIndex,5842 CheckTemplateArgumentInfo &CTAI,5843 CheckTemplateArgumentKind CTAK) {5844 // Check template type parameters.5845 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))5846 return CheckTemplateTypeArgument(TTP, ArgLoc, CTAI.SugaredConverted,5847 CTAI.CanonicalConverted);5848 5849 const TemplateArgument &Arg = ArgLoc.getArgument();5850 // Check non-type template parameters.5851 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {5852 // Do substitution on the type of the non-type template parameter5853 // with the template arguments we've seen thus far. But if the5854 // template has a dependent context then we cannot substitute yet.5855 QualType NTTPType = NTTP->getType();5856 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())5857 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);5858 5859 if (NTTPType->isInstantiationDependentType()) {5860 // Do substitution on the type of the non-type template parameter.5861 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,5862 CTAI.SugaredConverted,5863 SourceRange(TemplateLoc, RAngleLoc));5864 if (Inst.isInvalid())5865 return true;5866 5867 MultiLevelTemplateArgumentList MLTAL(Template, CTAI.SugaredConverted,5868 /*Final=*/true);5869 MLTAL.addOuterRetainedLevels(NTTP->getDepth());5870 // If the parameter is a pack expansion, expand this slice of the pack.5871 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {5872 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);5873 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),5874 NTTP->getDeclName());5875 } else {5876 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),5877 NTTP->getDeclName());5878 }5879 5880 // If that worked, check the non-type template parameter type5881 // for validity.5882 if (!NTTPType.isNull())5883 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,5884 NTTP->getLocation());5885 if (NTTPType.isNull())5886 return true;5887 }5888 5889 auto checkExpr = [&](Expr *E) -> Expr * {5890 TemplateArgument SugaredResult, CanonicalResult;5891 ExprResult Res = CheckTemplateArgument(5892 NTTP, NTTPType, E, SugaredResult, CanonicalResult,5893 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);5894 // If the current template argument causes an error, give up now.5895 if (Res.isInvalid())5896 return nullptr;5897 CTAI.SugaredConverted.push_back(SugaredResult);5898 CTAI.CanonicalConverted.push_back(CanonicalResult);5899 return Res.get();5900 };5901 5902 switch (Arg.getKind()) {5903 case TemplateArgument::Null:5904 llvm_unreachable("Should never see a NULL template argument here");5905 5906 case TemplateArgument::Expression: {5907 Expr *E = Arg.getAsExpr();5908 Expr *R = checkExpr(E);5909 if (!R)5910 return true;5911 // If the resulting expression is new, then use it in place of the5912 // old expression in the template argument.5913 if (R != E) {5914 TemplateArgument TA(R, /*IsCanonical=*/false);5915 ArgLoc = TemplateArgumentLoc(TA, R);5916 }5917 break;5918 }5919 5920 // As for the converted NTTP kinds, they still might need another5921 // conversion, as the new corresponding parameter might be different.5922 // Ideally, we would always perform substitution starting with sugared types5923 // and never need these, as we would still have expressions. Since these are5924 // needed so rarely, it's probably a better tradeoff to just convert them5925 // back to expressions.5926 case TemplateArgument::Integral:5927 case TemplateArgument::Declaration:5928 case TemplateArgument::NullPtr:5929 case TemplateArgument::StructuralValue: {5930 // FIXME: StructuralValue is untested here.5931 ExprResult R =5932 BuildExpressionFromNonTypeTemplateArgument(Arg, SourceLocation());5933 assert(R.isUsable());5934 if (!checkExpr(R.get()))5935 return true;5936 break;5937 }5938 5939 case TemplateArgument::Template:5940 case TemplateArgument::TemplateExpansion:5941 // We were given a template template argument. It may not be ill-formed;5942 // see below.5943 if (DependentTemplateName *DTN = Arg.getAsTemplateOrTemplatePattern()5944 .getAsDependentTemplateName()) {5945 // We have a template argument such as \c T::template X, which we5946 // parsed as a template template argument. However, since we now5947 // know that we need a non-type template argument, convert this5948 // template name into an expression.5949 5950 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),5951 ArgLoc.getTemplateNameLoc());5952 5953 CXXScopeSpec SS;5954 SS.Adopt(ArgLoc.getTemplateQualifierLoc());5955 // FIXME: the template-template arg was a DependentTemplateName,5956 // so it was provided with a template keyword. However, its source5957 // location is not stored in the template argument structure.5958 SourceLocation TemplateKWLoc;5959 ExprResult E = DependentScopeDeclRefExpr::Create(5960 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,5961 nullptr);5962 5963 // If we parsed the template argument as a pack expansion, create a5964 // pack expansion expression.5965 if (Arg.getKind() == TemplateArgument::TemplateExpansion) {5966 E = ActOnPackExpansion(E.get(), ArgLoc.getTemplateEllipsisLoc());5967 if (E.isInvalid())5968 return true;5969 }5970 5971 TemplateArgument SugaredResult, CanonicalResult;5972 E = CheckTemplateArgument(5973 NTTP, NTTPType, E.get(), SugaredResult, CanonicalResult,5974 /*StrictCheck=*/CTAI.PartialOrdering, CTAK_Specified);5975 if (E.isInvalid())5976 return true;5977 5978 CTAI.SugaredConverted.push_back(SugaredResult);5979 CTAI.CanonicalConverted.push_back(CanonicalResult);5980 break;5981 }5982 5983 // We have a template argument that actually does refer to a class5984 // template, alias template, or template template parameter, and5985 // therefore cannot be a non-type template argument.5986 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_expr)5987 << ArgLoc.getSourceRange();5988 NoteTemplateParameterLocation(*Param);5989 5990 return true;5991 5992 case TemplateArgument::Type: {5993 // We have a non-type template parameter but the template5994 // argument is a type.5995 5996 // C++ [temp.arg]p2:5997 // In a template-argument, an ambiguity between a type-id and5998 // an expression is resolved to a type-id, regardless of the5999 // form of the corresponding template-parameter.6000 //6001 // We warn specifically about this case, since it can be rather6002 // confusing for users.6003 QualType T = Arg.getAsType();6004 SourceRange SR = ArgLoc.getSourceRange();6005 if (T->isFunctionType())6006 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;6007 else6008 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;6009 NoteTemplateParameterLocation(*Param);6010 return true;6011 }6012 6013 case TemplateArgument::Pack:6014 llvm_unreachable("Caller must expand template argument packs");6015 }6016 6017 return false;6018 }6019 6020 6021 // Check template template parameters.6022 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);6023 6024 TemplateParameterList *Params = TempParm->getTemplateParameters();6025 if (TempParm->isExpandedParameterPack())6026 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);6027 6028 // Substitute into the template parameter list of the template6029 // template parameter, since previously-supplied template arguments6030 // may appear within the template template parameter.6031 //6032 // FIXME: Skip this if the parameters aren't instantiation-dependent.6033 {6034 // Set up a template instantiation context.6035 LocalInstantiationScope Scope(*this);6036 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,6037 CTAI.SugaredConverted,6038 SourceRange(TemplateLoc, RAngleLoc));6039 if (Inst.isInvalid())6040 return true;6041 6042 Params = SubstTemplateParams(6043 Params, CurContext,6044 MultiLevelTemplateArgumentList(Template, CTAI.SugaredConverted,6045 /*Final=*/true),6046 /*EvaluateConstraints=*/false);6047 if (!Params)6048 return true;6049 }6050 6051 // C++1z [temp.local]p1: (DR1004)6052 // When [the injected-class-name] is used [...] as a template-argument for6053 // a template template-parameter [...] it refers to the class template6054 // itself.6055 if (Arg.getKind() == TemplateArgument::Type) {6056 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(6057 Context, ArgLoc.getTypeSourceInfo()->getTypeLoc());6058 if (!ConvertedArg.getArgument().isNull())6059 ArgLoc = ConvertedArg;6060 }6061 6062 switch (Arg.getKind()) {6063 case TemplateArgument::Null:6064 llvm_unreachable("Should never see a NULL template argument here");6065 6066 case TemplateArgument::Template:6067 case TemplateArgument::TemplateExpansion:6068 if (CheckTemplateTemplateArgument(TempParm, Params, ArgLoc,6069 CTAI.PartialOrdering,6070 &CTAI.StrictPackMatch))6071 return true;6072 6073 CTAI.SugaredConverted.push_back(Arg);6074 CTAI.CanonicalConverted.push_back(6075 Context.getCanonicalTemplateArgument(Arg));6076 break;6077 6078 case TemplateArgument::Expression:6079 case TemplateArgument::Type: {6080 auto Kind = 0;6081 switch (TempParm->templateParameterKind()) {6082 case TemplateNameKind::TNK_Var_template:6083 Kind = 1;6084 break;6085 case TemplateNameKind::TNK_Concept_template:6086 Kind = 2;6087 break;6088 default:6089 break;6090 }6091 6092 // We have a template template parameter but the template6093 // argument does not refer to a template.6094 Diag(ArgLoc.getLocation(), diag::err_template_arg_must_be_template)6095 << Kind << getLangOpts().CPlusPlus11;6096 return true;6097 }6098 6099 case TemplateArgument::Declaration:6100 case TemplateArgument::Integral:6101 case TemplateArgument::StructuralValue:6102 case TemplateArgument::NullPtr:6103 llvm_unreachable("non-type argument with template template parameter");6104 6105 case TemplateArgument::Pack:6106 llvm_unreachable("Caller must expand template argument packs");6107 }6108 6109 return false;6110}6111 6112/// Diagnose a missing template argument.6113template<typename TemplateParmDecl>6114static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,6115 TemplateDecl *TD,6116 const TemplateParmDecl *D,6117 TemplateArgumentListInfo &Args) {6118 // Dig out the most recent declaration of the template parameter; there may be6119 // declarations of the template that are more recent than TD.6120 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())6121 ->getTemplateParameters()6122 ->getParam(D->getIndex()));6123 6124 // If there's a default argument that's not reachable, diagnose that we're6125 // missing a module import.6126 llvm::SmallVector<Module*, 8> Modules;6127 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {6128 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),6129 D->getDefaultArgumentLoc(), Modules,6130 Sema::MissingImportKind::DefaultArgument,6131 /*Recover*/true);6132 return true;6133 }6134 6135 // FIXME: If there's a more recent default argument that *is* visible,6136 // diagnose that it was declared too late.6137 6138 TemplateParameterList *Params = TD->getTemplateParameters();6139 6140 S.Diag(Loc, diag::err_template_arg_list_different_arity)6141 << /*not enough args*/06142 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))6143 << TD;6144 S.NoteTemplateLocation(*TD, Params->getSourceRange());6145 return true;6146}6147 6148/// Check that the given template argument list is well-formed6149/// for specializing the given template.6150bool Sema::CheckTemplateArgumentList(6151 TemplateDecl *Template, SourceLocation TemplateLoc,6152 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,6153 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,6154 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {6155 return CheckTemplateArgumentList(6156 Template, GetTemplateParameterList(Template), TemplateLoc, TemplateArgs,6157 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,6158 ConstraintsNotSatisfied);6159}6160 6161/// Check that the given template argument list is well-formed6162/// for specializing the given template.6163bool Sema::CheckTemplateArgumentList(6164 TemplateDecl *Template, TemplateParameterList *Params,6165 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,6166 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,6167 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,6168 bool *ConstraintsNotSatisfied) {6169 6170 if (ConstraintsNotSatisfied)6171 *ConstraintsNotSatisfied = false;6172 6173 // Make a copy of the template arguments for processing. Only make the6174 // changes at the end when successful in matching the arguments to the6175 // template.6176 TemplateArgumentListInfo NewArgs = TemplateArgs;6177 6178 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();6179 6180 // C++23 [temp.arg.general]p1:6181 // [...] The type and form of each template-argument specified in6182 // a template-id shall match the type and form specified for the6183 // corresponding parameter declared by the template in its6184 // template-parameter-list.6185 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);6186 SmallVector<TemplateArgument, 2> SugaredArgumentPack;6187 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;6188 unsigned ArgIdx = 0, NumArgs = NewArgs.size();6189 LocalInstantiationScope InstScope(*this, true);6190 for (TemplateParameterList::iterator ParamBegin = Params->begin(),6191 ParamEnd = Params->end(),6192 Param = ParamBegin;6193 Param != ParamEnd;6194 /* increment in loop */) {6195 if (size_t ParamIdx = Param - ParamBegin;6196 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {6197 // All written arguments should have been consumed by this point.6198 assert(ArgIdx == NumArgs && "bad default argument deduction");6199 if (ParamIdx == DefaultArgs.StartPos) {6200 assert(Param + DefaultArgs.Args.size() <= ParamEnd);6201 // Default arguments from a DeducedTemplateName are already converted.6202 for (const TemplateArgument &DefArg : DefaultArgs.Args) {6203 CTAI.SugaredConverted.push_back(DefArg);6204 CTAI.CanonicalConverted.push_back(6205 Context.getCanonicalTemplateArgument(DefArg));6206 ++Param;6207 }6208 continue;6209 }6210 }6211 6212 // If we have an expanded parameter pack, make sure we don't have too6213 // many arguments.6214 if (UnsignedOrNone Expansions = getExpandedPackSize(*Param)) {6215 if (*Expansions == SugaredArgumentPack.size()) {6216 // We're done with this parameter pack. Pack up its arguments and add6217 // them to the list.6218 CTAI.SugaredConverted.push_back(6219 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));6220 SugaredArgumentPack.clear();6221 6222 CTAI.CanonicalConverted.push_back(6223 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));6224 CanonicalArgumentPack.clear();6225 6226 // This argument is assigned to the next parameter.6227 ++Param;6228 continue;6229 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {6230 // Not enough arguments for this parameter pack.6231 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)6232 << /*not enough args*/06233 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))6234 << Template;6235 NoteTemplateLocation(*Template, Params->getSourceRange());6236 return true;6237 }6238 }6239 6240 // Check for builtins producing template packs in this context, we do not6241 // support them yet.6242 if (const NonTypeTemplateParmDecl *NTTP =6243 dyn_cast<NonTypeTemplateParmDecl>(*Param);6244 NTTP && NTTP->isPackExpansion()) {6245 auto TL = NTTP->getTypeSourceInfo()6246 ->getTypeLoc()6247 .castAs<PackExpansionTypeLoc>();6248 llvm::SmallVector<UnexpandedParameterPack> Unexpanded;6249 collectUnexpandedParameterPacks(TL.getPatternLoc(), Unexpanded);6250 for (const auto &UPP : Unexpanded) {6251 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();6252 if (!TST)6253 continue;6254 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));6255 // Expanding a built-in pack in this context is not yet supported.6256 Diag(TL.getEllipsisLoc(),6257 diag::err_unsupported_builtin_template_pack_expansion)6258 << TST->getTemplateName();6259 return true;6260 }6261 }6262 6263 if (ArgIdx < NumArgs) {6264 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];6265 bool NonPackParameter =6266 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param);6267 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();6268 6269 if (ArgIsExpansion && CTAI.MatchingTTP) {6270 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);6271 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;6272 ++Param) {6273 TemplateArgument &Arg = Args[Param - First];6274 Arg = ArgLoc.getArgument();6275 if (!(*Param)->isTemplateParameterPack() ||6276 getExpandedPackSize(*Param))6277 Arg = Arg.getPackExpansionPattern();6278 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());6279 SaveAndRestore _1(CTAI.PartialOrdering, false);6280 SaveAndRestore _2(CTAI.MatchingTTP, true);6281 if (CheckTemplateArgument(*Param, NewArgLoc, Template, TemplateLoc,6282 RAngleLoc, SugaredArgumentPack.size(), CTAI,6283 CTAK_Specified))6284 return true;6285 Arg = NewArgLoc.getArgument();6286 CTAI.CanonicalConverted.back().setIsDefaulted(6287 clang::isSubstitutedDefaultArgument(Context, Arg, *Param,6288 CTAI.CanonicalConverted,6289 Params->getDepth()));6290 }6291 ArgLoc =6292 TemplateArgumentLoc(TemplateArgument::CreatePackCopy(Context, Args),6293 ArgLoc.getLocInfo());6294 } else {6295 SaveAndRestore _1(CTAI.PartialOrdering, false);6296 if (CheckTemplateArgument(*Param, ArgLoc, Template, TemplateLoc,6297 RAngleLoc, SugaredArgumentPack.size(), CTAI,6298 CTAK_Specified))6299 return true;6300 CTAI.CanonicalConverted.back().setIsDefaulted(6301 clang::isSubstitutedDefaultArgument(Context, ArgLoc.getArgument(),6302 *Param, CTAI.CanonicalConverted,6303 Params->getDepth()));6304 if (ArgIsExpansion && NonPackParameter) {6305 // CWG1430/CWG2686: we have a pack expansion as an argument to an6306 // alias template or concept, and it's not part of a parameter pack.6307 // This can't be canonicalized, so reject it now.6308 if (isa<TypeAliasTemplateDecl, ConceptDecl>(Template)) {6309 Diag(ArgLoc.getLocation(),6310 diag::err_template_expansion_into_fixed_list)6311 << (isa<ConceptDecl>(Template) ? 1 : 0)6312 << ArgLoc.getSourceRange();6313 NoteTemplateParameterLocation(**Param);6314 return true;6315 }6316 }6317 }6318 6319 // We're now done with this argument.6320 ++ArgIdx;6321 6322 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {6323 // Directly convert the remaining arguments, because we don't know what6324 // parameters they'll match up with.6325 6326 if (!SugaredArgumentPack.empty()) {6327 // If we were part way through filling in an expanded parameter pack,6328 // fall back to just producing individual arguments.6329 CTAI.SugaredConverted.insert(CTAI.SugaredConverted.end(),6330 SugaredArgumentPack.begin(),6331 SugaredArgumentPack.end());6332 SugaredArgumentPack.clear();6333 6334 CTAI.CanonicalConverted.insert(CTAI.CanonicalConverted.end(),6335 CanonicalArgumentPack.begin(),6336 CanonicalArgumentPack.end());6337 CanonicalArgumentPack.clear();6338 }6339 6340 while (ArgIdx < NumArgs) {6341 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();6342 CTAI.SugaredConverted.push_back(Arg);6343 CTAI.CanonicalConverted.push_back(6344 Context.getCanonicalTemplateArgument(Arg));6345 ++ArgIdx;6346 }6347 6348 return false;6349 }6350 6351 if ((*Param)->isTemplateParameterPack()) {6352 // The template parameter was a template parameter pack, so take the6353 // deduced argument and place it on the argument pack. Note that we6354 // stay on the same template parameter so that we can deduce more6355 // arguments.6356 SugaredArgumentPack.push_back(CTAI.SugaredConverted.pop_back_val());6357 CanonicalArgumentPack.push_back(CTAI.CanonicalConverted.pop_back_val());6358 } else {6359 // Move to the next template parameter.6360 ++Param;6361 }6362 continue;6363 }6364 6365 // If we're checking a partial template argument list, we're done.6366 if (PartialTemplateArgs) {6367 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {6368 CTAI.SugaredConverted.push_back(6369 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));6370 CTAI.CanonicalConverted.push_back(6371 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));6372 }6373 return false;6374 }6375 6376 // If we have a template parameter pack with no more corresponding6377 // arguments, just break out now and we'll fill in the argument pack below.6378 if ((*Param)->isTemplateParameterPack()) {6379 assert(!getExpandedPackSize(*Param) &&6380 "Should have dealt with this already");6381 6382 // A non-expanded parameter pack before the end of the parameter list6383 // only occurs for an ill-formed template parameter list, unless we've6384 // got a partial argument list for a function template, so just bail out.6385 if (Param + 1 != ParamEnd) {6386 assert(6387 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&6388 "Concept templates must have parameter packs at the end.");6389 return true;6390 }6391 6392 CTAI.SugaredConverted.push_back(6393 TemplateArgument::CreatePackCopy(Context, SugaredArgumentPack));6394 SugaredArgumentPack.clear();6395 6396 CTAI.CanonicalConverted.push_back(6397 TemplateArgument::CreatePackCopy(Context, CanonicalArgumentPack));6398 CanonicalArgumentPack.clear();6399 6400 ++Param;6401 continue;6402 }6403 6404 // Check whether we have a default argument.6405 bool HasDefaultArg;6406 6407 // Retrieve the default template argument from the template6408 // parameter. For each kind of template parameter, we substitute the6409 // template arguments provided thus far and any "outer" template arguments6410 // (when the template parameter was part of a nested template) into6411 // the default argument.6412 TemplateArgumentLoc Arg = SubstDefaultTemplateArgumentIfAvailable(6413 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateLoc, RAngleLoc,6414 *Param, CTAI.SugaredConverted, CTAI.CanonicalConverted, HasDefaultArg);6415 6416 if (Arg.getArgument().isNull()) {6417 if (!HasDefaultArg) {6418 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param))6419 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,6420 NewArgs);6421 if (NonTypeTemplateParmDecl *NTTP =6422 dyn_cast<NonTypeTemplateParmDecl>(*Param))6423 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,6424 NewArgs);6425 return diagnoseMissingArgument(*this, TemplateLoc, Template,6426 cast<TemplateTemplateParmDecl>(*Param),6427 NewArgs);6428 }6429 return true;6430 }6431 6432 // Introduce an instantiation record that describes where we are using6433 // the default template argument. We're not actually instantiating a6434 // template here, we just create this object to put a note into the6435 // context stack.6436 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,6437 CTAI.SugaredConverted,6438 SourceRange(TemplateLoc, RAngleLoc));6439 if (Inst.isInvalid())6440 return true;6441 6442 SaveAndRestore _1(CTAI.PartialOrdering, false);6443 SaveAndRestore _2(CTAI.MatchingTTP, false);6444 SaveAndRestore _3(CTAI.StrictPackMatch, {});6445 // Check the default template argument.6446 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,6447 CTAI, CTAK_Specified))6448 return true;6449 6450 CTAI.SugaredConverted.back().setIsDefaulted(true);6451 CTAI.CanonicalConverted.back().setIsDefaulted(true);6452 6453 // Core issue 150 (assumed resolution): if this is a template template6454 // parameter, keep track of the default template arguments from the6455 // template definition.6456 if (isTemplateTemplateParameter)6457 NewArgs.addArgument(Arg);6458 6459 // Move to the next template parameter and argument.6460 ++Param;6461 ++ArgIdx;6462 }6463 6464 // If we're performing a partial argument substitution, allow any trailing6465 // pack expansions; they might be empty. This can happen even if6466 // PartialTemplateArgs is false (the list of arguments is complete but6467 // still dependent).6468 if (CTAI.MatchingTTP ||6469 (CurrentInstantiationScope &&6470 CurrentInstantiationScope->getPartiallySubstitutedPack())) {6471 while (ArgIdx < NumArgs &&6472 NewArgs[ArgIdx].getArgument().isPackExpansion()) {6473 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();6474 CTAI.SugaredConverted.push_back(Arg);6475 CTAI.CanonicalConverted.push_back(6476 Context.getCanonicalTemplateArgument(Arg));6477 }6478 }6479 6480 // If we have any leftover arguments, then there were too many arguments.6481 // Complain and fail.6482 if (ArgIdx < NumArgs) {6483 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)6484 << /*too many args*/16485 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))6486 << Template6487 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());6488 NoteTemplateLocation(*Template, Params->getSourceRange());6489 return true;6490 }6491 6492 // No problems found with the new argument list, propagate changes back6493 // to caller.6494 if (UpdateArgsWithConversions)6495 TemplateArgs = std::move(NewArgs);6496 6497 if (!PartialTemplateArgs) {6498 // Setup the context/ThisScope for the case where we are needing to6499 // re-instantiate constraints outside of normal instantiation.6500 DeclContext *NewContext = Template->getDeclContext();6501 6502 // If this template is in a template, make sure we extract the templated6503 // decl.6504 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))6505 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());6506 auto *RD = dyn_cast<CXXRecordDecl>(NewContext);6507 6508 Qualifiers ThisQuals;6509 if (const auto *Method =6510 dyn_cast_or_null<CXXMethodDecl>(Template->getTemplatedDecl()))6511 ThisQuals = Method->getMethodQualifiers();6512 6513 ContextRAII Context(*this, NewContext);6514 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);6515 6516 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(6517 Template, NewContext, /*Final=*/true, CTAI.SugaredConverted,6518 /*RelativeToPrimary=*/true,6519 /*Pattern=*/nullptr,6520 /*ForConceptInstantiation=*/true);6521 if (!isa<ConceptDecl>(Template) &&6522 EnsureTemplateArgumentListConstraints(6523 Template, MLTAL,6524 SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {6525 if (ConstraintsNotSatisfied)6526 *ConstraintsNotSatisfied = true;6527 return true;6528 }6529 }6530 6531 return false;6532}6533 6534namespace {6535 class UnnamedLocalNoLinkageFinder6536 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>6537 {6538 Sema &S;6539 SourceRange SR;6540 6541 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;6542 6543 public:6544 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }6545 6546 bool Visit(QualType T) {6547 return T.isNull() ? false : inherited::Visit(T.getTypePtr());6548 }6549 6550#define TYPE(Class, Parent) \6551 bool Visit##Class##Type(const Class##Type *);6552#define ABSTRACT_TYPE(Class, Parent) \6553 bool Visit##Class##Type(const Class##Type *) { return false; }6554#define NON_CANONICAL_TYPE(Class, Parent) \6555 bool Visit##Class##Type(const Class##Type *) { return false; }6556#include "clang/AST/TypeNodes.inc"6557 6558 bool VisitTagDecl(const TagDecl *Tag);6559 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);6560 };6561} // end anonymous namespace6562 6563bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {6564 return false;6565}6566 6567bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {6568 return Visit(T->getElementType());6569}6570 6571bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {6572 return Visit(T->getPointeeType());6573}6574 6575bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(6576 const BlockPointerType* T) {6577 return Visit(T->getPointeeType());6578}6579 6580bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(6581 const LValueReferenceType* T) {6582 return Visit(T->getPointeeType());6583}6584 6585bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(6586 const RValueReferenceType* T) {6587 return Visit(T->getPointeeType());6588}6589 6590bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(6591 const MemberPointerType *T) {6592 if (Visit(T->getPointeeType()))6593 return true;6594 if (auto *RD = T->getMostRecentCXXRecordDecl())6595 return VisitTagDecl(RD);6596 return VisitNestedNameSpecifier(T->getQualifier());6597}6598 6599bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(6600 const ConstantArrayType* T) {6601 return Visit(T->getElementType());6602}6603 6604bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(6605 const IncompleteArrayType* T) {6606 return Visit(T->getElementType());6607}6608 6609bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(6610 const VariableArrayType* T) {6611 return Visit(T->getElementType());6612}6613 6614bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(6615 const DependentSizedArrayType* T) {6616 return Visit(T->getElementType());6617}6618 6619bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(6620 const DependentSizedExtVectorType* T) {6621 return Visit(T->getElementType());6622}6623 6624bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(6625 const DependentSizedMatrixType *T) {6626 return Visit(T->getElementType());6627}6628 6629bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(6630 const DependentAddressSpaceType *T) {6631 return Visit(T->getPointeeType());6632}6633 6634bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {6635 return Visit(T->getElementType());6636}6637 6638bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(6639 const DependentVectorType *T) {6640 return Visit(T->getElementType());6641}6642 6643bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {6644 return Visit(T->getElementType());6645}6646 6647bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(6648 const ConstantMatrixType *T) {6649 return Visit(T->getElementType());6650}6651 6652bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(6653 const FunctionProtoType* T) {6654 for (const auto &A : T->param_types()) {6655 if (Visit(A))6656 return true;6657 }6658 6659 return Visit(T->getReturnType());6660}6661 6662bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(6663 const FunctionNoProtoType* T) {6664 return Visit(T->getReturnType());6665}6666 6667bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(6668 const UnresolvedUsingType*) {6669 return false;6670}6671 6672bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {6673 return false;6674}6675 6676bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {6677 return Visit(T->getUnmodifiedType());6678}6679 6680bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {6681 return false;6682}6683 6684bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(6685 const PackIndexingType *) {6686 return false;6687}6688 6689bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(6690 const UnaryTransformType*) {6691 return false;6692}6693 6694bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {6695 return Visit(T->getDeducedType());6696}6697 6698bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(6699 const DeducedTemplateSpecializationType *T) {6700 return Visit(T->getDeducedType());6701}6702 6703bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {6704 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());6705}6706 6707bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {6708 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());6709}6710 6711bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(6712 const TemplateTypeParmType*) {6713 return false;6714}6715 6716bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(6717 const SubstTemplateTypeParmPackType *) {6718 return false;6719}6720 6721bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(6722 const SubstBuiltinTemplatePackType *) {6723 return false;6724}6725 6726bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(6727 const TemplateSpecializationType*) {6728 return false;6729}6730 6731bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(6732 const InjectedClassNameType* T) {6733 return VisitTagDecl(T->getDecl()->getDefinitionOrSelf());6734}6735 6736bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(6737 const DependentNameType* T) {6738 return VisitNestedNameSpecifier(T->getQualifier());6739}6740 6741bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(6742 const PackExpansionType* T) {6743 return Visit(T->getPattern());6744}6745 6746bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {6747 return false;6748}6749 6750bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(6751 const ObjCInterfaceType *) {6752 return false;6753}6754 6755bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(6756 const ObjCObjectPointerType *) {6757 return false;6758}6759 6760bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {6761 return Visit(T->getValueType());6762}6763 6764bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {6765 return false;6766}6767 6768bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {6769 return false;6770}6771 6772bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(6773 const ArrayParameterType *T) {6774 return VisitConstantArrayType(T);6775}6776 6777bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(6778 const DependentBitIntType *T) {6779 return false;6780}6781 6782bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {6783 if (Tag->getDeclContext()->isFunctionOrMethod()) {6784 S.Diag(SR.getBegin(), S.getLangOpts().CPlusPlus116785 ? diag::warn_cxx98_compat_template_arg_local_type6786 : diag::ext_template_arg_local_type)6787 << S.Context.getCanonicalTagType(Tag) << SR;6788 return true;6789 }6790 6791 if (!Tag->hasNameForLinkage()) {6792 S.Diag(SR.getBegin(),6793 S.getLangOpts().CPlusPlus11 ?6794 diag::warn_cxx98_compat_template_arg_unnamed_type :6795 diag::ext_template_arg_unnamed_type) << SR;6796 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);6797 return true;6798 }6799 6800 return false;6801}6802 6803bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(6804 NestedNameSpecifier NNS) {6805 switch (NNS.getKind()) {6806 case NestedNameSpecifier::Kind::Null:6807 case NestedNameSpecifier::Kind::Namespace:6808 case NestedNameSpecifier::Kind::Global:6809 case NestedNameSpecifier::Kind::MicrosoftSuper:6810 return false;6811 case NestedNameSpecifier::Kind::Type:6812 return Visit(QualType(NNS.getAsType(), 0));6813 }6814 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");6815}6816 6817bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(6818 const HLSLAttributedResourceType *T) {6819 if (T->hasContainedType() && Visit(T->getContainedType()))6820 return true;6821 return Visit(T->getWrappedType());6822}6823 6824bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(6825 const HLSLInlineSpirvType *T) {6826 for (auto &Operand : T->getOperands())6827 if (Operand.isConstant() && Operand.isLiteral())6828 if (Visit(Operand.getResultType()))6829 return true;6830 return false;6831}6832 6833bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {6834 assert(ArgInfo && "invalid TypeSourceInfo");6835 QualType Arg = ArgInfo->getType();6836 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();6837 QualType CanonArg = Context.getCanonicalType(Arg);6838 6839 if (CanonArg->isVariablyModifiedType()) {6840 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;6841 } else if (Context.hasSameUnqualifiedType(Arg, Context.OverloadTy)) {6842 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;6843 }6844 6845 // C++03 [temp.arg.type]p2:6846 // A local type, a type with no linkage, an unnamed type or a type6847 // compounded from any of these types shall not be used as a6848 // template-argument for a template type-parameter.6849 //6850 // C++11 allows these, and even in C++03 we allow them as an extension with6851 // a warning.6852 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {6853 UnnamedLocalNoLinkageFinder Finder(*this, SR);6854 (void)Finder.Visit(CanonArg);6855 }6856 6857 return false;6858}6859 6860enum NullPointerValueKind {6861 NPV_NotNullPointer,6862 NPV_NullPointer,6863 NPV_Error6864};6865 6866/// Determine whether the given template argument is a null pointer6867/// value of the appropriate type.6868static NullPointerValueKind6869isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param,6870 QualType ParamType, Expr *Arg,6871 Decl *Entity = nullptr) {6872 if (Arg->isValueDependent() || Arg->isTypeDependent())6873 return NPV_NotNullPointer;6874 6875 // dllimport'd entities aren't constant but are available inside of template6876 // arguments.6877 if (Entity && Entity->hasAttr<DLLImportAttr>())6878 return NPV_NotNullPointer;6879 6880 if (!S.isCompleteType(Arg->getExprLoc(), ParamType))6881 llvm_unreachable(6882 "Incomplete parameter type in isNullPointerValueTemplateArgument!");6883 6884 if (!S.getLangOpts().CPlusPlus11)6885 return NPV_NotNullPointer;6886 6887 // Determine whether we have a constant expression.6888 ExprResult ArgRV = S.DefaultFunctionArrayConversion(Arg);6889 if (ArgRV.isInvalid())6890 return NPV_Error;6891 Arg = ArgRV.get();6892 6893 Expr::EvalResult EvalResult;6894 SmallVector<PartialDiagnosticAt, 8> Notes;6895 EvalResult.Diag = &Notes;6896 if (!Arg->EvaluateAsRValue(EvalResult, S.Context) ||6897 EvalResult.HasSideEffects) {6898 SourceLocation DiagLoc = Arg->getExprLoc();6899 6900 // If our only note is the usual "invalid subexpression" note, just point6901 // the caret at its location rather than producing an essentially6902 // redundant note.6903 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==6904 diag::note_invalid_subexpr_in_const_expr) {6905 DiagLoc = Notes[0].first;6906 Notes.clear();6907 }6908 6909 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)6910 << Arg->getType() << Arg->getSourceRange();6911 for (unsigned I = 0, N = Notes.size(); I != N; ++I)6912 S.Diag(Notes[I].first, Notes[I].second);6913 6914 S.NoteTemplateParameterLocation(*Param);6915 return NPV_Error;6916 }6917 6918 // C++11 [temp.arg.nontype]p1:6919 // - an address constant expression of type std::nullptr_t6920 if (Arg->getType()->isNullPtrType())6921 return NPV_NullPointer;6922 6923 // - a constant expression that evaluates to a null pointer value (4.10); or6924 // - a constant expression that evaluates to a null member pointer value6925 // (4.11); or6926 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||6927 (EvalResult.Val.isMemberPointer() &&6928 !EvalResult.Val.getMemberPointerDecl())) {6929 // If our expression has an appropriate type, we've succeeded.6930 bool ObjCLifetimeConversion;6931 if (S.Context.hasSameUnqualifiedType(Arg->getType(), ParamType) ||6932 S.IsQualificationConversion(Arg->getType(), ParamType, false,6933 ObjCLifetimeConversion))6934 return NPV_NullPointer;6935 6936 // The types didn't match, but we know we got a null pointer; complain,6937 // then recover as if the types were correct.6938 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)6939 << Arg->getType() << ParamType << Arg->getSourceRange();6940 S.NoteTemplateParameterLocation(*Param);6941 return NPV_NullPointer;6942 }6943 6944 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {6945 // We found a pointer that isn't null, but doesn't refer to an object.6946 // We could just return NPV_NotNullPointer, but we can print a better6947 // message with the information we have here.6948 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)6949 << EvalResult.Val.getAsString(S.Context, ParamType);6950 S.NoteTemplateParameterLocation(*Param);6951 return NPV_Error;6952 }6953 6954 // If we don't have a null pointer value, but we do have a NULL pointer6955 // constant, suggest a cast to the appropriate type.6956 if (Arg->isNullPointerConstant(S.Context, Expr::NPC_NeverValueDependent)) {6957 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";6958 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)6959 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)6960 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),6961 ")");6962 S.NoteTemplateParameterLocation(*Param);6963 return NPV_NullPointer;6964 }6965 6966 // FIXME: If we ever want to support general, address-constant expressions6967 // as non-type template arguments, we should return the ExprResult here to6968 // be interpreted by the caller.6969 return NPV_NotNullPointer;6970}6971 6972/// Checks whether the given template argument is compatible with its6973/// template parameter.6974static bool6975CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param,6976 QualType ParamType, Expr *ArgIn,6977 Expr *Arg, QualType ArgType) {6978 bool ObjCLifetimeConversion;6979 if (ParamType->isPointerType() &&6980 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&6981 S.IsQualificationConversion(ArgType, ParamType, false,6982 ObjCLifetimeConversion)) {6983 // For pointer-to-object types, qualification conversions are6984 // permitted.6985 } else {6986 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {6987 if (!ParamRef->getPointeeType()->isFunctionType()) {6988 // C++ [temp.arg.nontype]p5b3:6989 // For a non-type template-parameter of type reference to6990 // object, no conversions apply. The type referred to by the6991 // reference may be more cv-qualified than the (otherwise6992 // identical) type of the template- argument. The6993 // template-parameter is bound directly to the6994 // template-argument, which shall be an lvalue.6995 6996 // FIXME: Other qualifiers?6997 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();6998 unsigned ArgQuals = ArgType.getCVRQualifiers();6999 7000 if ((ParamQuals | ArgQuals) != ParamQuals) {7001 S.Diag(Arg->getBeginLoc(),7002 diag::err_template_arg_ref_bind_ignores_quals)7003 << ParamType << Arg->getType() << Arg->getSourceRange();7004 S.NoteTemplateParameterLocation(*Param);7005 return true;7006 }7007 }7008 }7009 7010 // At this point, the template argument refers to an object or7011 // function with external linkage. We now need to check whether the7012 // argument and parameter types are compatible.7013 if (!S.Context.hasSameUnqualifiedType(ArgType,7014 ParamType.getNonReferenceType())) {7015 // We can't perform this conversion or binding.7016 if (ParamType->isReferenceType())7017 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)7018 << ParamType << ArgIn->getType() << Arg->getSourceRange();7019 else7020 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)7021 << ArgIn->getType() << ParamType << Arg->getSourceRange();7022 S.NoteTemplateParameterLocation(*Param);7023 return true;7024 }7025 }7026 7027 return false;7028}7029 7030/// Checks whether the given template argument is the address7031/// of an object or function according to C++ [temp.arg.nontype]p1.7032static bool CheckTemplateArgumentAddressOfObjectOrFunction(7033 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,7034 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {7035 bool Invalid = false;7036 Expr *Arg = ArgIn;7037 QualType ArgType = Arg->getType();7038 7039 bool AddressTaken = false;7040 SourceLocation AddrOpLoc;7041 if (S.getLangOpts().MicrosoftExt) {7042 // Microsoft Visual C++ strips all casts, allows an arbitrary number of7043 // dereference and address-of operators.7044 Arg = Arg->IgnoreParenCasts();7045 7046 bool ExtWarnMSTemplateArg = false;7047 UnaryOperatorKind FirstOpKind;7048 SourceLocation FirstOpLoc;7049 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {7050 UnaryOperatorKind UnOpKind = UnOp->getOpcode();7051 if (UnOpKind == UO_Deref)7052 ExtWarnMSTemplateArg = true;7053 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {7054 Arg = UnOp->getSubExpr()->IgnoreParenCasts();7055 if (!AddrOpLoc.isValid()) {7056 FirstOpKind = UnOpKind;7057 FirstOpLoc = UnOp->getOperatorLoc();7058 }7059 } else7060 break;7061 }7062 if (FirstOpLoc.isValid()) {7063 if (ExtWarnMSTemplateArg)7064 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)7065 << ArgIn->getSourceRange();7066 7067 if (FirstOpKind == UO_AddrOf)7068 AddressTaken = true;7069 else if (Arg->getType()->isPointerType()) {7070 // We cannot let pointers get dereferenced here, that is obviously not a7071 // constant expression.7072 assert(FirstOpKind == UO_Deref);7073 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)7074 << Arg->getSourceRange();7075 }7076 }7077 } else {7078 // See through any implicit casts we added to fix the type.7079 Arg = Arg->IgnoreImpCasts();7080 7081 // C++ [temp.arg.nontype]p1:7082 //7083 // A template-argument for a non-type, non-template7084 // template-parameter shall be one of: [...]7085 //7086 // -- the address of an object or function with external7087 // linkage, including function templates and function7088 // template-ids but excluding non-static class members,7089 // expressed as & id-expression where the & is optional if7090 // the name refers to a function or array, or if the7091 // corresponding template-parameter is a reference; or7092 7093 // In C++98/03 mode, give an extension warning on any extra parentheses.7094 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#7737095 bool ExtraParens = false;7096 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {7097 if (!Invalid && !ExtraParens) {7098 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)7099 << Arg->getSourceRange();7100 ExtraParens = true;7101 }7102 7103 Arg = Parens->getSubExpr();7104 }7105 7106 while (SubstNonTypeTemplateParmExpr *subst =7107 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))7108 Arg = subst->getReplacement()->IgnoreImpCasts();7109 7110 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {7111 if (UnOp->getOpcode() == UO_AddrOf) {7112 Arg = UnOp->getSubExpr();7113 AddressTaken = true;7114 AddrOpLoc = UnOp->getOperatorLoc();7115 }7116 }7117 7118 while (SubstNonTypeTemplateParmExpr *subst =7119 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))7120 Arg = subst->getReplacement()->IgnoreImpCasts();7121 }7122 7123 ValueDecl *Entity = nullptr;7124 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg))7125 Entity = DRE->getDecl();7126 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Arg))7127 Entity = CUE->getGuidDecl();7128 7129 // If our parameter has pointer type, check for a null template value.7130 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {7131 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,7132 Entity)) {7133 case NPV_NullPointer:7134 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);7135 SugaredConverted = TemplateArgument(ParamType,7136 /*isNullPtr=*/true);7137 CanonicalConverted =7138 TemplateArgument(S.Context.getCanonicalType(ParamType),7139 /*isNullPtr=*/true);7140 return false;7141 7142 case NPV_Error:7143 return true;7144 7145 case NPV_NotNullPointer:7146 break;7147 }7148 }7149 7150 // Stop checking the precise nature of the argument if it is value dependent,7151 // it should be checked when instantiated.7152 if (Arg->isValueDependent()) {7153 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);7154 CanonicalConverted =7155 S.Context.getCanonicalTemplateArgument(SugaredConverted);7156 return false;7157 }7158 7159 if (!Entity) {7160 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)7161 << Arg->getSourceRange();7162 S.NoteTemplateParameterLocation(*Param);7163 return true;7164 }7165 7166 // Cannot refer to non-static data members7167 if (isa<FieldDecl>(Entity) || isa<IndirectFieldDecl>(Entity)) {7168 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)7169 << Entity << Arg->getSourceRange();7170 S.NoteTemplateParameterLocation(*Param);7171 return true;7172 }7173 7174 // Cannot refer to non-static member functions7175 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Entity)) {7176 if (!Method->isStatic()) {7177 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)7178 << Method << Arg->getSourceRange();7179 S.NoteTemplateParameterLocation(*Param);7180 return true;7181 }7182 }7183 7184 FunctionDecl *Func = dyn_cast<FunctionDecl>(Entity);7185 VarDecl *Var = dyn_cast<VarDecl>(Entity);7186 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Entity);7187 7188 // A non-type template argument must refer to an object or function.7189 if (!Func && !Var && !Guid) {7190 // We found something, but we don't know specifically what it is.7191 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)7192 << Arg->getSourceRange();7193 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);7194 return true;7195 }7196 7197 // Address / reference template args must have external linkage in C++98.7198 if (Entity->getFormalLinkage() == Linkage::Internal) {7199 S.Diag(Arg->getBeginLoc(),7200 S.getLangOpts().CPlusPlus117201 ? diag::warn_cxx98_compat_template_arg_object_internal7202 : diag::ext_template_arg_object_internal)7203 << !Func << Entity << Arg->getSourceRange();7204 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)7205 << !Func;7206 } else if (!Entity->hasLinkage()) {7207 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)7208 << !Func << Entity << Arg->getSourceRange();7209 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)7210 << !Func;7211 return true;7212 }7213 7214 if (Var) {7215 // A value of reference type is not an object.7216 if (Var->getType()->isReferenceType()) {7217 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)7218 << Var->getType() << Arg->getSourceRange();7219 S.NoteTemplateParameterLocation(*Param);7220 return true;7221 }7222 7223 // A template argument must have static storage duration.7224 if (Var->getTLSKind()) {7225 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)7226 << Arg->getSourceRange();7227 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);7228 return true;7229 }7230 }7231 7232 if (AddressTaken && ParamType->isReferenceType()) {7233 // If we originally had an address-of operator, but the7234 // parameter has reference type, complain and (if things look7235 // like they will work) drop the address-of operator.7236 if (!S.Context.hasSameUnqualifiedType(Entity->getType(),7237 ParamType.getNonReferenceType())) {7238 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)7239 << ParamType;7240 S.NoteTemplateParameterLocation(*Param);7241 return true;7242 }7243 7244 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)7245 << ParamType7246 << FixItHint::CreateRemoval(AddrOpLoc);7247 S.NoteTemplateParameterLocation(*Param);7248 7249 ArgType = Entity->getType();7250 }7251 7252 // If the template parameter has pointer type, either we must have taken the7253 // address or the argument must decay to a pointer.7254 if (!AddressTaken && ParamType->isPointerType()) {7255 if (Func) {7256 // Function-to-pointer decay.7257 ArgType = S.Context.getPointerType(Func->getType());7258 } else if (Entity->getType()->isArrayType()) {7259 // Array-to-pointer decay.7260 ArgType = S.Context.getArrayDecayedType(Entity->getType());7261 } else {7262 // If the template parameter has pointer type but the address of7263 // this object was not taken, complain and (possibly) recover by7264 // taking the address of the entity.7265 ArgType = S.Context.getPointerType(Entity->getType());7266 if (!S.Context.hasSameUnqualifiedType(ArgType, ParamType)) {7267 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)7268 << ParamType;7269 S.NoteTemplateParameterLocation(*Param);7270 return true;7271 }7272 7273 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)7274 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");7275 7276 S.NoteTemplateParameterLocation(*Param);7277 }7278 }7279 7280 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,7281 Arg, ArgType))7282 return true;7283 7284 // Create the template argument.7285 SugaredConverted = TemplateArgument(Entity, ParamType);7286 CanonicalConverted =7287 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),7288 S.Context.getCanonicalType(ParamType));7289 S.MarkAnyDeclReferenced(Arg->getBeginLoc(), Entity, false);7290 return false;7291}7292 7293/// Checks whether the given template argument is a pointer to7294/// member constant according to C++ [temp.arg.nontype]p1.7295static bool CheckTemplateArgumentPointerToMember(7296 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,7297 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {7298 bool Invalid = false;7299 7300 Expr *Arg = ResultArg;7301 bool ObjCLifetimeConversion;7302 7303 // C++ [temp.arg.nontype]p1:7304 //7305 // A template-argument for a non-type, non-template7306 // template-parameter shall be one of: [...]7307 //7308 // -- a pointer to member expressed as described in 5.3.1.7309 DeclRefExpr *DRE = nullptr;7310 7311 // In C++98/03 mode, give an extension warning on any extra parentheses.7312 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#7737313 bool ExtraParens = false;7314 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Arg)) {7315 if (!Invalid && !ExtraParens) {7316 S.DiagCompat(Arg->getBeginLoc(), diag_compat::template_arg_extra_parens)7317 << Arg->getSourceRange();7318 ExtraParens = true;7319 }7320 7321 Arg = Parens->getSubExpr();7322 }7323 7324 while (SubstNonTypeTemplateParmExpr *subst =7325 dyn_cast<SubstNonTypeTemplateParmExpr>(Arg))7326 Arg = subst->getReplacement()->IgnoreImpCasts();7327 7328 // A pointer-to-member constant written &Class::member.7329 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Arg)) {7330 if (UnOp->getOpcode() == UO_AddrOf) {7331 DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr());7332 if (DRE && !DRE->getQualifier())7333 DRE = nullptr;7334 }7335 }7336 // A constant of pointer-to-member type.7337 else if ((DRE = dyn_cast<DeclRefExpr>(Arg))) {7338 ValueDecl *VD = DRE->getDecl();7339 if (VD->getType()->isMemberPointerType()) {7340 if (isa<NonTypeTemplateParmDecl>(VD)) {7341 if (Arg->isTypeDependent() || Arg->isValueDependent()) {7342 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);7343 CanonicalConverted =7344 S.Context.getCanonicalTemplateArgument(SugaredConverted);7345 } else {7346 SugaredConverted = TemplateArgument(VD, ParamType);7347 CanonicalConverted =7348 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),7349 S.Context.getCanonicalType(ParamType));7350 }7351 return Invalid;7352 }7353 }7354 7355 DRE = nullptr;7356 }7357 7358 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;7359 7360 // Check for a null pointer value.7361 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,7362 Entity)) {7363 case NPV_Error:7364 return true;7365 case NPV_NullPointer:7366 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);7367 SugaredConverted = TemplateArgument(ParamType,7368 /*isNullPtr*/ true);7369 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(ParamType),7370 /*isNullPtr*/ true);7371 return false;7372 case NPV_NotNullPointer:7373 break;7374 }7375 7376 if (S.IsQualificationConversion(ResultArg->getType(),7377 ParamType.getNonReferenceType(), false,7378 ObjCLifetimeConversion)) {7379 ResultArg = S.ImpCastExprToType(ResultArg, ParamType, CK_NoOp,7380 ResultArg->getValueKind())7381 .get();7382 } else if (!S.Context.hasSameUnqualifiedType(7383 ResultArg->getType(), ParamType.getNonReferenceType())) {7384 // We can't perform this conversion.7385 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)7386 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();7387 S.NoteTemplateParameterLocation(*Param);7388 return true;7389 }7390 7391 if (!DRE)7392 return S.Diag(Arg->getBeginLoc(),7393 diag::err_template_arg_not_pointer_to_member_form)7394 << Arg->getSourceRange();7395 7396 if (isa<FieldDecl>(DRE->getDecl()) ||7397 isa<IndirectFieldDecl>(DRE->getDecl()) ||7398 isa<CXXMethodDecl>(DRE->getDecl())) {7399 assert((isa<FieldDecl>(DRE->getDecl()) ||7400 isa<IndirectFieldDecl>(DRE->getDecl()) ||7401 cast<CXXMethodDecl>(DRE->getDecl())7402 ->isImplicitObjectMemberFunction()) &&7403 "Only non-static member pointers can make it here");7404 7405 // Okay: this is the address of a non-static member, and therefore7406 // a member pointer constant.7407 if (Arg->isTypeDependent() || Arg->isValueDependent()) {7408 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);7409 CanonicalConverted =7410 S.Context.getCanonicalTemplateArgument(SugaredConverted);7411 } else {7412 ValueDecl *D = DRE->getDecl();7413 SugaredConverted = TemplateArgument(D, ParamType);7414 CanonicalConverted =7415 TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),7416 S.Context.getCanonicalType(ParamType));7417 }7418 return Invalid;7419 }7420 7421 // We found something else, but we don't know specifically what it is.7422 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)7423 << Arg->getSourceRange();7424 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);7425 return true;7426}7427 7428/// Check a template argument against its corresponding7429/// non-type template parameter.7430///7431/// This routine implements the semantics of C++ [temp.arg.nontype].7432/// If an error occurred, it returns ExprError(); otherwise, it7433/// returns the converted template argument. \p ParamType is the7434/// type of the non-type template parameter after it has been instantiated.7435ExprResult Sema::CheckTemplateArgument(NamedDecl *Param, QualType ParamType,7436 Expr *Arg,7437 TemplateArgument &SugaredConverted,7438 TemplateArgument &CanonicalConverted,7439 bool StrictCheck,7440 CheckTemplateArgumentKind CTAK) {7441 SourceLocation StartLoc = Arg->getBeginLoc();7442 auto *ArgPE = dyn_cast<PackExpansionExpr>(Arg);7443 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;7444 auto setDeductionArg = [&](Expr *NewDeductionArg) {7445 DeductionArg = NewDeductionArg;7446 if (ArgPE) {7447 // Recreate a pack expansion if we unwrapped one.7448 Arg = new (Context) PackExpansionExpr(7449 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());7450 } else {7451 Arg = DeductionArg;7452 }7453 };7454 7455 // If the parameter type somehow involves auto, deduce the type now.7456 DeducedType *DeducedT = ParamType->getContainedDeducedType();7457 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();7458 if (IsDeduced) {7459 // When checking a deduced template argument, deduce from its type even if7460 // the type is dependent, in order to check the types of non-type template7461 // arguments line up properly in partial ordering.7462 TypeSourceInfo *TSI =7463 Context.getTrivialTypeSourceInfo(ParamType, Param->getLocation());7464 if (isa<DeducedTemplateSpecializationType>(DeducedT)) {7465 InitializedEntity Entity =7466 InitializedEntity::InitializeTemplateParameter(ParamType, Param);7467 InitializationKind Kind = InitializationKind::CreateForInit(7468 DeductionArg->getBeginLoc(), /*DirectInit*/false, DeductionArg);7469 Expr *Inits[1] = {DeductionArg};7470 ParamType =7471 DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, Inits);7472 if (ParamType.isNull())7473 return ExprError();7474 } else {7475 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),7476 Param->getTemplateDepth() + 1);7477 ParamType = QualType();7478 TemplateDeductionResult Result =7479 DeduceAutoType(TSI->getTypeLoc(), DeductionArg, ParamType, Info,7480 /*DependentDeduction=*/true,7481 // We do not check constraints right now because the7482 // immediately-declared constraint of the auto type is7483 // also an associated constraint, and will be checked7484 // along with the other associated constraints after7485 // checking the template argument list.7486 /*IgnoreConstraints=*/true);7487 if (Result != TemplateDeductionResult::Success) {7488 ParamType = TSI->getType();7489 if (StrictCheck || !DeductionArg->isTypeDependent()) {7490 if (Result == TemplateDeductionResult::AlreadyDiagnosed)7491 return ExprError();7492 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param))7493 Diag(Arg->getExprLoc(),7494 diag::err_non_type_template_parm_type_deduction_failure)7495 << Param->getDeclName() << NTTP->getType() << Arg->getType()7496 << Arg->getSourceRange();7497 NoteTemplateParameterLocation(*Param);7498 return ExprError();7499 }7500 ParamType = SubstAutoTypeDependent(ParamType);7501 assert(!ParamType.isNull() && "substituting DependentTy can't fail");7502 }7503 }7504 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's7505 // an error. The error message normally references the parameter7506 // declaration, but here we'll pass the argument location because that's7507 // where the parameter type is deduced.7508 ParamType = CheckNonTypeTemplateParameterType(ParamType, Arg->getExprLoc());7509 if (ParamType.isNull()) {7510 NoteTemplateParameterLocation(*Param);7511 return ExprError();7512 }7513 }7514 7515 // We should have already dropped all cv-qualifiers by now.7516 assert(!ParamType.hasQualifiers() &&7517 "non-type template parameter type cannot be qualified");7518 7519 // If either the parameter has a dependent type or the argument is7520 // type-dependent, there's nothing we can check now.7521 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {7522 // Force the argument to the type of the parameter to maintain invariants.7523 if (!IsDeduced) {7524 ExprResult E = ImpCastExprToType(7525 DeductionArg, ParamType.getNonLValueExprType(Context), CK_Dependent,7526 ParamType->isLValueReferenceType() ? VK_LValue7527 : ParamType->isRValueReferenceType() ? VK_XValue7528 : VK_PRValue);7529 if (E.isInvalid())7530 return ExprError();7531 setDeductionArg(E.get());7532 }7533 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);7534 CanonicalConverted = TemplateArgument(7535 Context.getCanonicalTemplateArgument(SugaredConverted));7536 return Arg;7537 }7538 7539 // FIXME: When Param is a reference, should we check that Arg is an lvalue?7540 if (CTAK == CTAK_Deduced && !StrictCheck &&7541 (ParamType->isReferenceType()7542 ? !Context.hasSameType(ParamType.getNonReferenceType(),7543 DeductionArg->getType())7544 : !Context.hasSameUnqualifiedType(ParamType,7545 DeductionArg->getType()))) {7546 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,7547 // we should actually be checking the type of the template argument in P,7548 // not the type of the template argument deduced from A, against the7549 // template parameter type.7550 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)7551 << Arg->getType() << ParamType.getUnqualifiedType();7552 NoteTemplateParameterLocation(*Param);7553 return ExprError();7554 }7555 7556 // If the argument is a pack expansion, we don't know how many times it would7557 // expand. If we continue checking the argument, this will make the template7558 // definition ill-formed if it would be ill-formed for any number of7559 // expansions during instantiation time. When partial ordering or matching7560 // template template parameters, this is exactly what we want. Otherwise, the7561 // normal template rules apply: we accept the template if it would be valid7562 // for any number of expansions (i.e. none).7563 if (ArgPE && !StrictCheck) {7564 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);7565 CanonicalConverted = TemplateArgument(7566 Context.getCanonicalTemplateArgument(SugaredConverted));7567 return Arg;7568 }7569 7570 // Avoid making a copy when initializing a template parameter of class type7571 // from a template parameter object of the same type. This is going beyond7572 // the standard, but is required for soundness: in7573 // template<A a> struct X { X *p; X<a> *q; };7574 // ... we need p and q to have the same type.7575 //7576 // Similarly, don't inject a call to a copy constructor when initializing7577 // from a template parameter of the same type.7578 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();7579 if (ParamType->isRecordType() && isa<DeclRefExpr>(InnerArg) &&7580 Context.hasSameUnqualifiedType(ParamType, InnerArg->getType())) {7581 NamedDecl *ND = cast<DeclRefExpr>(InnerArg)->getDecl();7582 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {7583 7584 SugaredConverted = TemplateArgument(TPO, ParamType);7585 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),7586 ParamType.getCanonicalType());7587 return Arg;7588 }7589 if (isa<NonTypeTemplateParmDecl>(ND)) {7590 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);7591 CanonicalConverted =7592 Context.getCanonicalTemplateArgument(SugaredConverted);7593 return Arg;7594 }7595 }7596 7597 // The initialization of the parameter from the argument is7598 // a constant-evaluated context.7599 EnterExpressionEvaluationContext ConstantEvaluated(7600 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);7601 7602 bool IsConvertedConstantExpression = true;7603 if (isa<InitListExpr>(DeductionArg) || ParamType->isRecordType()) {7604 InitializationKind Kind = InitializationKind::CreateForInit(7605 StartLoc, /*DirectInit=*/false, DeductionArg);7606 Expr *Inits[1] = {DeductionArg};7607 InitializedEntity Entity =7608 InitializedEntity::InitializeTemplateParameter(ParamType, Param);7609 InitializationSequence InitSeq(*this, Entity, Kind, Inits);7610 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Inits);7611 if (Result.isInvalid() || !Result.get())7612 return ExprError();7613 Result = ActOnConstantExpression(Result.get());7614 if (Result.isInvalid() || !Result.get())7615 return ExprError();7616 setDeductionArg(ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),7617 /*DiscardedValue=*/false,7618 /*IsConstexpr=*/true,7619 /*IsTemplateArgument=*/true)7620 .get());7621 IsConvertedConstantExpression = false;7622 }7623 7624 if (getLangOpts().CPlusPlus17 || StrictCheck) {7625 // C++17 [temp.arg.nontype]p1:7626 // A template-argument for a non-type template parameter shall be7627 // a converted constant expression of the type of the template-parameter.7628 APValue Value;7629 ExprResult ArgResult;7630 if (IsConvertedConstantExpression) {7631 ArgResult = BuildConvertedConstantExpression(7632 DeductionArg, ParamType,7633 StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Param);7634 assert(!ArgResult.isUnset());7635 if (ArgResult.isInvalid()) {7636 NoteTemplateParameterLocation(*Param);7637 return ExprError();7638 }7639 } else {7640 ArgResult = DeductionArg;7641 }7642 7643 // For a value-dependent argument, CheckConvertedConstantExpression is7644 // permitted (and expected) to be unable to determine a value.7645 if (ArgResult.get()->isValueDependent()) {7646 setDeductionArg(ArgResult.get());7647 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);7648 CanonicalConverted =7649 Context.getCanonicalTemplateArgument(SugaredConverted);7650 return Arg;7651 }7652 7653 APValue PreNarrowingValue;7654 ArgResult = EvaluateConvertedConstantExpression(7655 ArgResult.get(), ParamType, Value, CCEKind::TemplateArg, /*RequireInt=*/7656 false, PreNarrowingValue);7657 if (ArgResult.isInvalid())7658 return ExprError();7659 setDeductionArg(ArgResult.get());7660 7661 if (Value.isLValue()) {7662 APValue::LValueBase Base = Value.getLValueBase();7663 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());7664 // For a non-type template-parameter of pointer or reference type,7665 // the value of the constant expression shall not refer to7666 assert(ParamType->isPointerOrReferenceType() ||7667 ParamType->isNullPtrType());7668 // -- a temporary object7669 // -- a string literal7670 // -- the result of a typeid expression, or7671 // -- a predefined __func__ variable7672 if (Base &&7673 (!VD ||7674 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(VD))) {7675 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)7676 << Arg->getSourceRange();7677 return ExprError();7678 }7679 7680 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&7681 VD->getType()->isArrayType() &&7682 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&7683 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {7684 if (ArgPE) {7685 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);7686 CanonicalConverted =7687 Context.getCanonicalTemplateArgument(SugaredConverted);7688 } else {7689 SugaredConverted = TemplateArgument(VD, ParamType);7690 CanonicalConverted =7691 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),7692 ParamType.getCanonicalType());7693 }7694 return Arg;7695 }7696 7697 // -- a subobject [until C++20]7698 if (!getLangOpts().CPlusPlus20) {7699 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||7700 Value.isLValueOnePastTheEnd()) {7701 Diag(StartLoc, diag::err_non_type_template_arg_subobject)7702 << Value.getAsString(Context, ParamType);7703 return ExprError();7704 }7705 assert((VD || !ParamType->isReferenceType()) &&7706 "null reference should not be a constant expression");7707 assert((!VD || !ParamType->isNullPtrType()) &&7708 "non-null value of type nullptr_t?");7709 }7710 }7711 7712 if (Value.isAddrLabelDiff())7713 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);7714 7715 if (ArgPE) {7716 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);7717 CanonicalConverted =7718 Context.getCanonicalTemplateArgument(SugaredConverted);7719 } else {7720 SugaredConverted = TemplateArgument(Context, ParamType, Value);7721 CanonicalConverted =7722 TemplateArgument(Context, ParamType.getCanonicalType(), Value);7723 }7724 return Arg;7725 }7726 7727 // These should have all been handled above using the C++17 rules.7728 assert(!ArgPE && !StrictCheck);7729 7730 // C++ [temp.arg.nontype]p5:7731 // The following conversions are performed on each expression used7732 // as a non-type template-argument. If a non-type7733 // template-argument cannot be converted to the type of the7734 // corresponding template-parameter then the program is7735 // ill-formed.7736 if (ParamType->isIntegralOrEnumerationType()) {7737 // C++11:7738 // -- for a non-type template-parameter of integral or7739 // enumeration type, conversions permitted in a converted7740 // constant expression are applied.7741 //7742 // C++98:7743 // -- for a non-type template-parameter of integral or7744 // enumeration type, integral promotions (4.5) and integral7745 // conversions (4.7) are applied.7746 7747 if (getLangOpts().CPlusPlus11) {7748 // C++ [temp.arg.nontype]p1:7749 // A template-argument for a non-type, non-template template-parameter7750 // shall be one of:7751 //7752 // -- for a non-type template-parameter of integral or enumeration7753 // type, a converted constant expression of the type of the7754 // template-parameter; or7755 llvm::APSInt Value;7756 ExprResult ArgResult = CheckConvertedConstantExpression(7757 Arg, ParamType, Value, CCEKind::TemplateArg);7758 if (ArgResult.isInvalid())7759 return ExprError();7760 Arg = ArgResult.get();7761 7762 // We can't check arbitrary value-dependent arguments.7763 if (Arg->isValueDependent()) {7764 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);7765 CanonicalConverted =7766 Context.getCanonicalTemplateArgument(SugaredConverted);7767 return Arg;7768 }7769 7770 // Widen the argument value to sizeof(parameter type). This is almost7771 // always a no-op, except when the parameter type is bool. In7772 // that case, this may extend the argument from 1 bit to 8 bits.7773 QualType IntegerType = ParamType;7774 if (const auto *ED = IntegerType->getAsEnumDecl())7775 IntegerType = ED->getIntegerType();7776 Value = Value.extOrTrunc(IntegerType->isBitIntType()7777 ? Context.getIntWidth(IntegerType)7778 : Context.getTypeSize(IntegerType));7779 7780 SugaredConverted = TemplateArgument(Context, Value, ParamType);7781 CanonicalConverted =7782 TemplateArgument(Context, Value, Context.getCanonicalType(ParamType));7783 return Arg;7784 }7785 7786 ExprResult ArgResult = DefaultLvalueConversion(Arg);7787 if (ArgResult.isInvalid())7788 return ExprError();7789 Arg = ArgResult.get();7790 7791 QualType ArgType = Arg->getType();7792 7793 // C++ [temp.arg.nontype]p1:7794 // A template-argument for a non-type, non-template7795 // template-parameter shall be one of:7796 //7797 // -- an integral constant-expression of integral or enumeration7798 // type; or7799 // -- the name of a non-type template-parameter; or7800 llvm::APSInt Value;7801 if (!ArgType->isIntegralOrEnumerationType()) {7802 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)7803 << ArgType << Arg->getSourceRange();7804 NoteTemplateParameterLocation(*Param);7805 return ExprError();7806 }7807 if (!Arg->isValueDependent()) {7808 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {7809 QualType T;7810 7811 public:7812 TmplArgICEDiagnoser(QualType T) : T(T) { }7813 7814 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,7815 SourceLocation Loc) override {7816 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;7817 }7818 } Diagnoser(ArgType);7819 7820 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();7821 if (!Arg)7822 return ExprError();7823 }7824 7825 // From here on out, all we care about is the unqualified form7826 // of the argument type.7827 ArgType = ArgType.getUnqualifiedType();7828 7829 // Try to convert the argument to the parameter's type.7830 if (Context.hasSameType(ParamType, ArgType)) {7831 // Okay: no conversion necessary7832 } else if (ParamType->isBooleanType()) {7833 // This is an integral-to-boolean conversion.7834 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralToBoolean).get();7835 } else if (IsIntegralPromotion(Arg, ArgType, ParamType) ||7836 !ParamType->isEnumeralType()) {7837 // This is an integral promotion or conversion.7838 Arg = ImpCastExprToType(Arg, ParamType, CK_IntegralCast).get();7839 } else {7840 // We can't perform this conversion.7841 Diag(StartLoc, diag::err_template_arg_not_convertible)7842 << Arg->getType() << ParamType << Arg->getSourceRange();7843 NoteTemplateParameterLocation(*Param);7844 return ExprError();7845 }7846 7847 // Add the value of this argument to the list of converted7848 // arguments. We use the bitwidth and signedness of the template7849 // parameter.7850 if (Arg->isValueDependent()) {7851 // The argument is value-dependent. Create a new7852 // TemplateArgument with the converted expression.7853 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);7854 CanonicalConverted =7855 Context.getCanonicalTemplateArgument(SugaredConverted);7856 return Arg;7857 }7858 7859 QualType IntegerType = ParamType;7860 if (const auto *ED = IntegerType->getAsEnumDecl()) {7861 IntegerType = ED->getIntegerType();7862 }7863 7864 if (ParamType->isBooleanType()) {7865 // Value must be zero or one.7866 Value = Value != 0;7867 unsigned AllowedBits = Context.getTypeSize(IntegerType);7868 if (Value.getBitWidth() != AllowedBits)7869 Value = Value.extOrTrunc(AllowedBits);7870 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());7871 } else {7872 llvm::APSInt OldValue = Value;7873 7874 // Coerce the template argument's value to the value it will have7875 // based on the template parameter's type.7876 unsigned AllowedBits = IntegerType->isBitIntType()7877 ? Context.getIntWidth(IntegerType)7878 : Context.getTypeSize(IntegerType);7879 if (Value.getBitWidth() != AllowedBits)7880 Value = Value.extOrTrunc(AllowedBits);7881 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());7882 7883 // Complain if an unsigned parameter received a negative value.7884 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&7885 (OldValue.isSigned() && OldValue.isNegative())) {7886 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)7887 << toString(OldValue, 10) << toString(Value, 10) << ParamType7888 << Arg->getSourceRange();7889 NoteTemplateParameterLocation(*Param);7890 }7891 7892 // Complain if we overflowed the template parameter's type.7893 unsigned RequiredBits;7894 if (IntegerType->isUnsignedIntegerOrEnumerationType())7895 RequiredBits = OldValue.getActiveBits();7896 else if (OldValue.isUnsigned())7897 RequiredBits = OldValue.getActiveBits() + 1;7898 else7899 RequiredBits = OldValue.getSignificantBits();7900 if (RequiredBits > AllowedBits) {7901 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)7902 << toString(OldValue, 10) << toString(Value, 10) << ParamType7903 << Arg->getSourceRange();7904 NoteTemplateParameterLocation(*Param);7905 }7906 }7907 7908 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;7909 SugaredConverted = TemplateArgument(Context, Value, T);7910 CanonicalConverted =7911 TemplateArgument(Context, Value, Context.getCanonicalType(T));7912 return Arg;7913 }7914 7915 QualType ArgType = Arg->getType();7916 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction7917 7918 // Handle pointer-to-function, reference-to-function, and7919 // pointer-to-member-function all in (roughly) the same way.7920 if (// -- For a non-type template-parameter of type pointer to7921 // function, only the function-to-pointer conversion (4.3) is7922 // applied. If the template-argument represents a set of7923 // overloaded functions (or a pointer to such), the matching7924 // function is selected from the set (13.4).7925 (ParamType->isPointerType() &&7926 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||7927 // -- For a non-type template-parameter of type reference to7928 // function, no conversions apply. If the template-argument7929 // represents a set of overloaded functions, the matching7930 // function is selected from the set (13.4).7931 (ParamType->isReferenceType() &&7932 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||7933 // -- For a non-type template-parameter of type pointer to7934 // member function, no conversions apply. If the7935 // template-argument represents a set of overloaded member7936 // functions, the matching member function is selected from7937 // the set (13.4).7938 (ParamType->isMemberPointerType() &&7939 ParamType->castAs<MemberPointerType>()->getPointeeType()7940 ->isFunctionType())) {7941 7942 if (Arg->getType() == Context.OverloadTy) {7943 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg, ParamType,7944 true,7945 FoundResult)) {7946 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))7947 return ExprError();7948 7949 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);7950 if (Res.isInvalid())7951 return ExprError();7952 Arg = Res.get();7953 ArgType = Arg->getType();7954 } else7955 return ExprError();7956 }7957 7958 if (!ParamType->isMemberPointerType()) {7959 if (CheckTemplateArgumentAddressOfObjectOrFunction(7960 *this, Param, ParamType, Arg, SugaredConverted,7961 CanonicalConverted))7962 return ExprError();7963 return Arg;7964 }7965 7966 if (CheckTemplateArgumentPointerToMember(7967 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))7968 return ExprError();7969 return Arg;7970 }7971 7972 if (ParamType->isPointerType()) {7973 // -- for a non-type template-parameter of type pointer to7974 // object, qualification conversions (4.4) and the7975 // array-to-pointer conversion (4.2) are applied.7976 // C++0x also allows a value of std::nullptr_t.7977 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&7978 "Only object pointers allowed here");7979 7980 if (CheckTemplateArgumentAddressOfObjectOrFunction(7981 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))7982 return ExprError();7983 return Arg;7984 }7985 7986 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {7987 // -- For a non-type template-parameter of type reference to7988 // object, no conversions apply. The type referred to by the7989 // reference may be more cv-qualified than the (otherwise7990 // identical) type of the template-argument. The7991 // template-parameter is bound directly to the7992 // template-argument, which must be an lvalue.7993 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&7994 "Only object references allowed here");7995 7996 if (Arg->getType() == Context.OverloadTy) {7997 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(Arg,7998 ParamRefType->getPointeeType(),7999 true,8000 FoundResult)) {8001 if (DiagnoseUseOfDecl(Fn, Arg->getBeginLoc()))8002 return ExprError();8003 ExprResult Res = FixOverloadedFunctionReference(Arg, FoundResult, Fn);8004 if (Res.isInvalid())8005 return ExprError();8006 Arg = Res.get();8007 ArgType = Arg->getType();8008 } else8009 return ExprError();8010 }8011 8012 if (CheckTemplateArgumentAddressOfObjectOrFunction(8013 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))8014 return ExprError();8015 return Arg;8016 }8017 8018 // Deal with parameters of type std::nullptr_t.8019 if (ParamType->isNullPtrType()) {8020 if (Arg->isTypeDependent() || Arg->isValueDependent()) {8021 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);8022 CanonicalConverted =8023 Context.getCanonicalTemplateArgument(SugaredConverted);8024 return Arg;8025 }8026 8027 switch (isNullPointerValueTemplateArgument(*this, Param, ParamType, Arg)) {8028 case NPV_NotNullPointer:8029 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)8030 << Arg->getType() << ParamType;8031 NoteTemplateParameterLocation(*Param);8032 return ExprError();8033 8034 case NPV_Error:8035 return ExprError();8036 8037 case NPV_NullPointer:8038 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);8039 SugaredConverted = TemplateArgument(ParamType,8040 /*isNullPtr=*/true);8041 CanonicalConverted = TemplateArgument(Context.getCanonicalType(ParamType),8042 /*isNullPtr=*/true);8043 return Arg;8044 }8045 }8046 8047 // -- For a non-type template-parameter of type pointer to data8048 // member, qualification conversions (4.4) are applied.8049 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");8050 8051 if (CheckTemplateArgumentPointerToMember(8052 *this, Param, ParamType, Arg, SugaredConverted, CanonicalConverted))8053 return ExprError();8054 return Arg;8055}8056 8057static void DiagnoseTemplateParameterListArityMismatch(8058 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,8059 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);8060 8061bool Sema::CheckDeclCompatibleWithTemplateTemplate(8062 TemplateDecl *Template, TemplateTemplateParmDecl *Param,8063 const TemplateArgumentLoc &Arg) {8064 // C++0x [temp.arg.template]p1:8065 // A template-argument for a template template-parameter shall be8066 // the name of a class template or an alias template, expressed as an8067 // id-expression. When the template-argument names a class template, only8068 // primary class templates are considered when matching the8069 // template template argument with the corresponding parameter;8070 // partial specializations are not considered even if their8071 // parameter lists match that of the template template parameter.8072 //8073 8074 TemplateNameKind Kind = TNK_Non_template;8075 unsigned DiagFoundKind = 0;8076 8077 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Template)) {8078 switch (TTP->templateParameterKind()) {8079 case TemplateNameKind::TNK_Concept_template:8080 DiagFoundKind = 3;8081 break;8082 case TemplateNameKind::TNK_Var_template:8083 DiagFoundKind = 2;8084 break;8085 default:8086 DiagFoundKind = 1;8087 break;8088 }8089 Kind = TTP->templateParameterKind();8090 } else if (isa<ConceptDecl>(Template)) {8091 Kind = TemplateNameKind::TNK_Concept_template;8092 DiagFoundKind = 3;8093 } else if (isa<FunctionTemplateDecl>(Template)) {8094 Kind = TemplateNameKind::TNK_Function_template;8095 DiagFoundKind = 0;8096 } else if (isa<VarTemplateDecl>(Template)) {8097 Kind = TemplateNameKind::TNK_Var_template;8098 DiagFoundKind = 2;8099 } else if (isa<ClassTemplateDecl>(Template) ||8100 isa<TypeAliasTemplateDecl>(Template) ||8101 isa<BuiltinTemplateDecl>(Template)) {8102 Kind = TemplateNameKind::TNK_Type_template;8103 DiagFoundKind = 1;8104 } else {8105 assert(false && "Unexpected Decl");8106 }8107 8108 if (Kind == Param->templateParameterKind()) {8109 return true;8110 }8111 8112 unsigned DiagKind = 0;8113 switch (Param->templateParameterKind()) {8114 case TemplateNameKind::TNK_Concept_template:8115 DiagKind = 2;8116 break;8117 case TemplateNameKind::TNK_Var_template:8118 DiagKind = 1;8119 break;8120 default:8121 DiagKind = 0;8122 break;8123 }8124 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template)8125 << DiagKind;8126 Diag(Template->getLocation(), diag::note_template_arg_refers_to_template_here)8127 << DiagFoundKind << Template;8128 return false;8129}8130 8131/// Check a template argument against its corresponding8132/// template template parameter.8133///8134/// This routine implements the semantics of C++ [temp.arg.template].8135/// It returns true if an error occurred, and false otherwise.8136bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,8137 TemplateParameterList *Params,8138 TemplateArgumentLoc &Arg,8139 bool PartialOrdering,8140 bool *StrictPackMatch) {8141 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();8142 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();8143 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();8144 if (!Template) {8145 // FIXME: Handle AssumedTemplateNames8146 // Any dependent template name is fine.8147 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");8148 return false;8149 }8150 8151 if (Template->isInvalidDecl())8152 return true;8153 8154 if (!CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg)) {8155 return true;8156 }8157 8158 // C++1z [temp.arg.template]p3: (DR 150)8159 // A template-argument matches a template template-parameter P when P8160 // is at least as specialized as the template-argument A.8161 if (!isTemplateTemplateParameterAtLeastAsSpecializedAs(8162 Params, Param, Template, DefaultArgs, Arg.getLocation(),8163 PartialOrdering, StrictPackMatch))8164 return true;8165 // P21138166 // C++20[temp.func.order]p28167 // [...] If both deductions succeed, the partial ordering selects the8168 // more constrained template (if one exists) as determined below.8169 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;8170 Params->getAssociatedConstraints(ParamsAC);8171 // C++20[temp.arg.template]p38172 // [...] In this comparison, if P is unconstrained, the constraints on A8173 // are not considered.8174 if (ParamsAC.empty())8175 return false;8176 8177 Template->getAssociatedConstraints(TemplateAC);8178 8179 bool IsParamAtLeastAsConstrained;8180 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,8181 IsParamAtLeastAsConstrained))8182 return true;8183 if (!IsParamAtLeastAsConstrained) {8184 Diag(Arg.getLocation(),8185 diag::err_template_template_parameter_not_at_least_as_constrained)8186 << Template << Param << Arg.getSourceRange();8187 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;8188 Diag(Template->getLocation(), diag::note_entity_declared_at) << Template;8189 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,8190 TemplateAC);8191 return true;8192 }8193 return false;8194}8195 8196static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,8197 unsigned HereDiagID,8198 unsigned ExternalDiagID) {8199 if (Decl.getLocation().isValid())8200 return S.Diag(Decl.getLocation(), HereDiagID);8201 8202 SmallString<128> Str;8203 llvm::raw_svector_ostream Out(Str);8204 PrintingPolicy PP = S.getPrintingPolicy();8205 PP.TerseOutput = 1;8206 Decl.print(Out, PP);8207 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();8208}8209 8210void Sema::NoteTemplateLocation(const NamedDecl &Decl,8211 std::optional<SourceRange> ParamRange) {8212 SemaDiagnosticBuilder DB =8213 noteLocation(*this, Decl, diag::note_template_decl_here,8214 diag::note_template_decl_external);8215 if (ParamRange && ParamRange->isValid()) {8216 assert(Decl.getLocation().isValid() &&8217 "Parameter range has location when Decl does not");8218 DB << *ParamRange;8219 }8220}8221 8222void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {8223 noteLocation(*this, Decl, diag::note_template_param_here,8224 diag::note_template_param_external);8225}8226 8227/// Given a non-type template argument that refers to a8228/// declaration and the type of its corresponding non-type template8229/// parameter, produce an expression that properly refers to that8230/// declaration.8231ExprResult Sema::BuildExpressionFromDeclTemplateArgument(8232 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,8233 NamedDecl *TemplateParam) {8234 // C++ [temp.param]p8:8235 //8236 // A non-type template-parameter of type "array of T" or8237 // "function returning T" is adjusted to be of type "pointer to8238 // T" or "pointer to function returning T", respectively.8239 if (ParamType->isArrayType())8240 ParamType = Context.getArrayDecayedType(ParamType);8241 else if (ParamType->isFunctionType())8242 ParamType = Context.getPointerType(ParamType);8243 8244 // For a NULL non-type template argument, return nullptr casted to the8245 // parameter's type.8246 if (Arg.getKind() == TemplateArgument::NullPtr) {8247 return ImpCastExprToType(8248 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),8249 ParamType,8250 ParamType->getAs<MemberPointerType>()8251 ? CK_NullToMemberPointer8252 : CK_NullToPointer);8253 }8254 assert(Arg.getKind() == TemplateArgument::Declaration &&8255 "Only declaration template arguments permitted here");8256 8257 ValueDecl *VD = Arg.getAsDecl();8258 8259 CXXScopeSpec SS;8260 if (ParamType->isMemberPointerType()) {8261 // If this is a pointer to member, we need to use a qualified name to8262 // form a suitable pointer-to-member constant.8263 assert(VD->getDeclContext()->isRecord() &&8264 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||8265 isa<IndirectFieldDecl>(VD)));8266 CanQualType ClassType =8267 Context.getCanonicalTagType(cast<RecordDecl>(VD->getDeclContext()));8268 NestedNameSpecifier Qualifier(ClassType.getTypePtr());8269 SS.MakeTrivial(Context, Qualifier, Loc);8270 }8271 8272 ExprResult RefExpr = BuildDeclarationNameExpr(8273 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);8274 if (RefExpr.isInvalid())8275 return ExprError();8276 8277 // For a pointer, the argument declaration is the pointee. Take its address.8278 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);8279 if (ParamType->isPointerType() && !ElemT.isNull() &&8280 Context.hasSimilarType(ElemT, ParamType->getPointeeType())) {8281 // Decay an array argument if we want a pointer to its first element.8282 RefExpr = DefaultFunctionArrayConversion(RefExpr.get());8283 if (RefExpr.isInvalid())8284 return ExprError();8285 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {8286 // For any other pointer, take the address (or form a pointer-to-member).8287 RefExpr = CreateBuiltinUnaryOp(Loc, UO_AddrOf, RefExpr.get());8288 if (RefExpr.isInvalid())8289 return ExprError();8290 } else if (ParamType->isRecordType()) {8291 assert(isa<TemplateParamObjectDecl>(VD) &&8292 "arg for class template param not a template parameter object");8293 // No conversions apply in this case.8294 return RefExpr;8295 } else {8296 assert(ParamType->isReferenceType() &&8297 "unexpected type for decl template argument");8298 if (NonTypeTemplateParmDecl *NTTP =8299 dyn_cast_if_present<NonTypeTemplateParmDecl>(TemplateParam)) {8300 QualType TemplateParamType = NTTP->getType();8301 const AutoType *AT = TemplateParamType->getAs<AutoType>();8302 if (AT && AT->isDecltypeAuto()) {8303 RefExpr = new (getASTContext()) SubstNonTypeTemplateParmExpr(8304 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),8305 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),8306 /*PackIndex=*/std::nullopt,8307 /*RefParam=*/true, /*Final=*/true);8308 }8309 }8310 }8311 8312 // At this point we should have the right value category.8313 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&8314 "value kind mismatch for non-type template argument");8315 8316 // The type of the template parameter can differ from the type of the8317 // argument in various ways; convert it now if necessary.8318 QualType DestExprType = ParamType.getNonLValueExprType(Context);8319 if (!Context.hasSameType(RefExpr.get()->getType(), DestExprType)) {8320 CastKind CK;8321 if (Context.hasSimilarType(RefExpr.get()->getType(), DestExprType) ||8322 IsFunctionConversion(RefExpr.get()->getType(), DestExprType)) {8323 CK = CK_NoOp;8324 } else if (ParamType->isVoidPointerType() &&8325 RefExpr.get()->getType()->isPointerType()) {8326 CK = CK_BitCast;8327 } else {8328 // FIXME: Pointers to members can need conversion derived-to-base or8329 // base-to-derived conversions. We currently don't retain enough8330 // information to convert properly (we need to track a cast path or8331 // subobject number in the template argument).8332 llvm_unreachable(8333 "unexpected conversion required for non-type template argument");8334 }8335 RefExpr = ImpCastExprToType(RefExpr.get(), DestExprType, CK,8336 RefExpr.get()->getValueKind());8337 }8338 8339 return RefExpr;8340}8341 8342/// Construct a new expression that refers to the given8343/// integral template argument with the given source-location8344/// information.8345///8346/// This routine takes care of the mapping from an integral template8347/// argument (which may have any integral type) to the appropriate8348/// literal value.8349static Expr *BuildExpressionFromIntegralTemplateArgumentValue(8350 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {8351 assert(OrigT->isIntegralOrEnumerationType());8352 8353 // If this is an enum type that we're instantiating, we need to use an integer8354 // type the same size as the enumerator. We don't want to build an8355 // IntegerLiteral with enum type. The integer type of an enum type can be of8356 // any integral type with C++11 enum classes, make sure we create the right8357 // type of literal for it.8358 QualType T = OrigT;8359 if (const auto *ED = OrigT->getAsEnumDecl())8360 T = ED->getIntegerType();8361 8362 Expr *E;8363 if (T->isAnyCharacterType()) {8364 CharacterLiteralKind Kind;8365 if (T->isWideCharType())8366 Kind = CharacterLiteralKind::Wide;8367 else if (T->isChar8Type() && S.getLangOpts().Char8)8368 Kind = CharacterLiteralKind::UTF8;8369 else if (T->isChar16Type())8370 Kind = CharacterLiteralKind::UTF16;8371 else if (T->isChar32Type())8372 Kind = CharacterLiteralKind::UTF32;8373 else8374 Kind = CharacterLiteralKind::Ascii;8375 8376 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);8377 } else if (T->isBooleanType()) {8378 E = CXXBoolLiteralExpr::Create(S.Context, Int.getBoolValue(), T, Loc);8379 } else {8380 E = IntegerLiteral::Create(S.Context, Int, T, Loc);8381 }8382 8383 if (OrigT->isEnumeralType()) {8384 // FIXME: This is a hack. We need a better way to handle substituted8385 // non-type template parameters.8386 E = CStyleCastExpr::Create(S.Context, OrigT, VK_PRValue, CK_IntegralCast, E,8387 nullptr, S.CurFPFeatureOverrides(),8388 S.Context.getTrivialTypeSourceInfo(OrigT, Loc),8389 Loc, Loc);8390 }8391 8392 return E;8393}8394 8395static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(8396 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {8397 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {8398 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);8399 ILE->setType(T);8400 return ILE;8401 };8402 8403 switch (Val.getKind()) {8404 case APValue::AddrLabelDiff:8405 // This cannot occur in a template argument at all.8406 case APValue::Array:8407 case APValue::Struct:8408 case APValue::Union:8409 // These can only occur within a template parameter object, which is8410 // represented as a TemplateArgument::Declaration.8411 llvm_unreachable("unexpected template argument value");8412 8413 case APValue::Int:8414 return BuildExpressionFromIntegralTemplateArgumentValue(S, T, Val.getInt(),8415 Loc);8416 8417 case APValue::Float:8418 return FloatingLiteral::Create(S.Context, Val.getFloat(), /*IsExact=*/true,8419 T, Loc);8420 8421 case APValue::FixedPoint:8422 return FixedPointLiteral::CreateFromRawInt(8423 S.Context, Val.getFixedPoint().getValue(), T, Loc,8424 Val.getFixedPoint().getScale());8425 8426 case APValue::ComplexInt: {8427 QualType ElemT = T->castAs<ComplexType>()->getElementType();8428 return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(8429 S, ElemT, Val.getComplexIntReal(), Loc),8430 BuildExpressionFromIntegralTemplateArgumentValue(8431 S, ElemT, Val.getComplexIntImag(), Loc)});8432 }8433 8434 case APValue::ComplexFloat: {8435 QualType ElemT = T->castAs<ComplexType>()->getElementType();8436 return MakeInitList(8437 {FloatingLiteral::Create(S.Context, Val.getComplexFloatReal(), true,8438 ElemT, Loc),8439 FloatingLiteral::Create(S.Context, Val.getComplexFloatImag(), true,8440 ElemT, Loc)});8441 }8442 8443 case APValue::Vector: {8444 QualType ElemT = T->castAs<VectorType>()->getElementType();8445 llvm::SmallVector<Expr *, 8> Elts;8446 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)8447 Elts.push_back(BuildExpressionFromNonTypeTemplateArgumentValue(8448 S, ElemT, Val.getVectorElt(I), Loc));8449 return MakeInitList(Elts);8450 }8451 8452 case APValue::None:8453 case APValue::Indeterminate:8454 llvm_unreachable("Unexpected APValue kind.");8455 case APValue::LValue:8456 case APValue::MemberPointer:8457 // There isn't necessarily a valid equivalent source-level syntax for8458 // these; in particular, a naive lowering might violate access control.8459 // So for now we lower to a ConstantExpr holding the value, wrapped around8460 // an OpaqueValueExpr.8461 // FIXME: We should have a better representation for this.8462 ExprValueKind VK = VK_PRValue;8463 if (T->isReferenceType()) {8464 T = T->getPointeeType();8465 VK = VK_LValue;8466 }8467 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);8468 return ConstantExpr::Create(S.Context, OVE, Val);8469 }8470 llvm_unreachable("Unhandled APValue::ValueKind enum");8471}8472 8473ExprResult8474Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,8475 SourceLocation Loc) {8476 switch (Arg.getKind()) {8477 case TemplateArgument::Null:8478 case TemplateArgument::Type:8479 case TemplateArgument::Template:8480 case TemplateArgument::TemplateExpansion:8481 case TemplateArgument::Pack:8482 llvm_unreachable("not a non-type template argument");8483 8484 case TemplateArgument::Expression:8485 return Arg.getAsExpr();8486 8487 case TemplateArgument::NullPtr:8488 case TemplateArgument::Declaration:8489 return BuildExpressionFromDeclTemplateArgument(8490 Arg, Arg.getNonTypeTemplateArgumentType(), Loc);8491 8492 case TemplateArgument::Integral:8493 return BuildExpressionFromIntegralTemplateArgumentValue(8494 *this, Arg.getIntegralType(), Arg.getAsIntegral(), Loc);8495 8496 case TemplateArgument::StructuralValue:8497 return BuildExpressionFromNonTypeTemplateArgumentValue(8498 *this, Arg.getStructuralValueType(), Arg.getAsStructuralValue(), Loc);8499 }8500 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");8501}8502 8503/// Match two template parameters within template parameter lists.8504static bool MatchTemplateParameterKind(8505 Sema &S, NamedDecl *New,8506 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,8507 const NamedDecl *OldInstFrom, bool Complain,8508 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {8509 // Check the actual kind (type, non-type, template).8510 if (Old->getKind() != New->getKind()) {8511 if (Complain) {8512 unsigned NextDiag = diag::err_template_param_different_kind;8513 if (TemplateArgLoc.isValid()) {8514 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);8515 NextDiag = diag::note_template_param_different_kind;8516 }8517 S.Diag(New->getLocation(), NextDiag)8518 << (Kind != Sema::TPL_TemplateMatch);8519 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)8520 << (Kind != Sema::TPL_TemplateMatch);8521 }8522 8523 return false;8524 }8525 8526 // Check that both are parameter packs or neither are parameter packs.8527 // However, if we are matching a template template argument to a8528 // template template parameter, the template template parameter can have8529 // a parameter pack where the template template argument does not.8530 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {8531 if (Complain) {8532 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;8533 if (TemplateArgLoc.isValid()) {8534 S.Diag(TemplateArgLoc,8535 diag::err_template_arg_template_params_mismatch);8536 NextDiag = diag::note_template_parameter_pack_non_pack;8537 }8538 8539 unsigned ParamKind = isa<TemplateTypeParmDecl>(New)? 08540 : isa<NonTypeTemplateParmDecl>(New)? 18541 : 2;8542 S.Diag(New->getLocation(), NextDiag)8543 << ParamKind << New->isParameterPack();8544 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)8545 << ParamKind << Old->isParameterPack();8546 }8547 8548 return false;8549 }8550 // For non-type template parameters, check the type of the parameter.8551 if (NonTypeTemplateParmDecl *OldNTTP =8552 dyn_cast<NonTypeTemplateParmDecl>(Old)) {8553 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(New);8554 8555 // If we are matching a template template argument to a template8556 // template parameter and one of the non-type template parameter types8557 // is dependent, then we must wait until template instantiation time8558 // to actually compare the arguments.8559 if (Kind != Sema::TPL_TemplateTemplateParmMatch ||8560 (!OldNTTP->getType()->isDependentType() &&8561 !NewNTTP->getType()->isDependentType())) {8562 // C++20 [temp.over.link]p6:8563 // Two [non-type] template-parameters are equivalent [if] they have8564 // equivalent types ignoring the use of type-constraints for8565 // placeholder types8566 QualType OldType = S.Context.getUnconstrainedType(OldNTTP->getType());8567 QualType NewType = S.Context.getUnconstrainedType(NewNTTP->getType());8568 if (!S.Context.hasSameType(OldType, NewType)) {8569 if (Complain) {8570 unsigned NextDiag = diag::err_template_nontype_parm_different_type;8571 if (TemplateArgLoc.isValid()) {8572 S.Diag(TemplateArgLoc,8573 diag::err_template_arg_template_params_mismatch);8574 NextDiag = diag::note_template_nontype_parm_different_type;8575 }8576 S.Diag(NewNTTP->getLocation(), NextDiag)8577 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);8578 S.Diag(OldNTTP->getLocation(),8579 diag::note_template_nontype_parm_prev_declaration)8580 << OldNTTP->getType();8581 }8582 return false;8583 }8584 }8585 }8586 // For template template parameters, check the template parameter types.8587 // The template parameter lists of template template8588 // parameters must agree.8589 else if (TemplateTemplateParmDecl *OldTTP =8590 dyn_cast<TemplateTemplateParmDecl>(Old)) {8591 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(New);8592 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())8593 return false;8594 if (!S.TemplateParameterListsAreEqual(8595 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,8596 OldTTP->getTemplateParameters(), Complain,8597 (Kind == Sema::TPL_TemplateMatch8598 ? Sema::TPL_TemplateTemplateParmMatch8599 : Kind),8600 TemplateArgLoc))8601 return false;8602 }8603 8604 if (Kind != Sema::TPL_TemplateParamsEquivalent &&8605 Kind != Sema::TPL_TemplateTemplateParmMatch &&8606 !isa<TemplateTemplateParmDecl>(Old)) {8607 const Expr *NewC = nullptr, *OldC = nullptr;8608 8609 if (isa<TemplateTypeParmDecl>(New)) {8610 if (const auto *TC = cast<TemplateTypeParmDecl>(New)->getTypeConstraint())8611 NewC = TC->getImmediatelyDeclaredConstraint();8612 if (const auto *TC = cast<TemplateTypeParmDecl>(Old)->getTypeConstraint())8613 OldC = TC->getImmediatelyDeclaredConstraint();8614 } else if (isa<NonTypeTemplateParmDecl>(New)) {8615 if (const Expr *E = cast<NonTypeTemplateParmDecl>(New)8616 ->getPlaceholderTypeConstraint())8617 NewC = E;8618 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Old)8619 ->getPlaceholderTypeConstraint())8620 OldC = E;8621 } else8622 llvm_unreachable("unexpected template parameter type");8623 8624 auto Diagnose = [&] {8625 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),8626 diag::err_template_different_type_constraint);8627 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),8628 diag::note_template_prev_declaration) << /*declaration*/0;8629 };8630 8631 if (!NewC != !OldC) {8632 if (Complain)8633 Diagnose();8634 return false;8635 }8636 8637 if (NewC) {8638 if (!S.AreConstraintExpressionsEqual(OldInstFrom, OldC, NewInstFrom,8639 NewC)) {8640 if (Complain)8641 Diagnose();8642 return false;8643 }8644 }8645 }8646 8647 return true;8648}8649 8650/// Diagnose a known arity mismatch when comparing template argument8651/// lists.8652static8653void DiagnoseTemplateParameterListArityMismatch(Sema &S,8654 TemplateParameterList *New,8655 TemplateParameterList *Old,8656 Sema::TemplateParameterListEqualKind Kind,8657 SourceLocation TemplateArgLoc) {8658 unsigned NextDiag = diag::err_template_param_list_different_arity;8659 if (TemplateArgLoc.isValid()) {8660 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);8661 NextDiag = diag::note_template_param_list_different_arity;8662 }8663 S.Diag(New->getTemplateLoc(), NextDiag)8664 << (New->size() > Old->size())8665 << (Kind != Sema::TPL_TemplateMatch)8666 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());8667 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)8668 << (Kind != Sema::TPL_TemplateMatch)8669 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());8670}8671 8672bool Sema::TemplateParameterListsAreEqual(8673 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,8674 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,8675 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {8676 if (Old->size() != New->size()) {8677 if (Complain)8678 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,8679 TemplateArgLoc);8680 8681 return false;8682 }8683 8684 // C++0x [temp.arg.template]p3:8685 // A template-argument matches a template template-parameter (call it P)8686 // when each of the template parameters in the template-parameter-list of8687 // the template-argument's corresponding class template or alias template8688 // (call it A) matches the corresponding template parameter in the8689 // template-parameter-list of P. [...]8690 TemplateParameterList::iterator NewParm = New->begin();8691 TemplateParameterList::iterator NewParmEnd = New->end();8692 for (TemplateParameterList::iterator OldParm = Old->begin(),8693 OldParmEnd = Old->end();8694 OldParm != OldParmEnd; ++OldParm, ++NewParm) {8695 if (NewParm == NewParmEnd) {8696 if (Complain)8697 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,8698 TemplateArgLoc);8699 return false;8700 }8701 if (!MatchTemplateParameterKind(*this, *NewParm, NewInstFrom, *OldParm,8702 OldInstFrom, Complain, Kind,8703 TemplateArgLoc))8704 return false;8705 }8706 8707 // Make sure we exhausted all of the arguments.8708 if (NewParm != NewParmEnd) {8709 if (Complain)8710 DiagnoseTemplateParameterListArityMismatch(*this, New, Old, Kind,8711 TemplateArgLoc);8712 8713 return false;8714 }8715 8716 if (Kind != TPL_TemplateParamsEquivalent) {8717 const Expr *NewRC = New->getRequiresClause();8718 const Expr *OldRC = Old->getRequiresClause();8719 8720 auto Diagnose = [&] {8721 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),8722 diag::err_template_different_requires_clause);8723 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),8724 diag::note_template_prev_declaration) << /*declaration*/0;8725 };8726 8727 if (!NewRC != !OldRC) {8728 if (Complain)8729 Diagnose();8730 return false;8731 }8732 8733 if (NewRC) {8734 if (!AreConstraintExpressionsEqual(OldInstFrom, OldRC, NewInstFrom,8735 NewRC)) {8736 if (Complain)8737 Diagnose();8738 return false;8739 }8740 }8741 }8742 8743 return true;8744}8745 8746bool8747Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {8748 if (!S)8749 return false;8750 8751 // Find the nearest enclosing declaration scope.8752 S = S->getDeclParent();8753 8754 // C++ [temp.pre]p6: [P2096]8755 // A template, explicit specialization, or partial specialization shall not8756 // have C linkage.8757 DeclContext *Ctx = S->getEntity();8758 if (Ctx && Ctx->isExternCContext()) {8759 SourceRange Range =8760 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()8761 ? TemplateParams->getParam(0)->getSourceRange()8762 : TemplateParams->getSourceRange();8763 Diag(Range.getBegin(), diag::err_template_linkage) << Range;8764 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())8765 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);8766 return true;8767 }8768 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;8769 8770 // C++ [temp]p2:8771 // A template-declaration can appear only as a namespace scope or8772 // class scope declaration.8773 // C++ [temp.expl.spec]p3:8774 // An explicit specialization may be declared in any scope in which the8775 // corresponding primary template may be defined.8776 // C++ [temp.class.spec]p6: [P2096]8777 // A partial specialization may be declared in any scope in which the8778 // corresponding primary template may be defined.8779 if (Ctx) {8780 if (Ctx->isFileContext())8781 return false;8782 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Ctx)) {8783 // C++ [temp.mem]p2:8784 // A local class shall not have member templates.8785 if (RD->isLocalClass())8786 return Diag(TemplateParams->getTemplateLoc(),8787 diag::err_template_inside_local_class)8788 << TemplateParams->getSourceRange();8789 else8790 return false;8791 }8792 }8793 8794 return Diag(TemplateParams->getTemplateLoc(),8795 diag::err_template_outside_namespace_or_class_scope)8796 << TemplateParams->getSourceRange();8797}8798 8799/// Determine what kind of template specialization the given declaration8800/// is.8801static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {8802 if (!D)8803 return TSK_Undeclared;8804 8805 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D))8806 return Record->getTemplateSpecializationKind();8807 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D))8808 return Function->getTemplateSpecializationKind();8809 if (VarDecl *Var = dyn_cast<VarDecl>(D))8810 return Var->getTemplateSpecializationKind();8811 8812 return TSK_Undeclared;8813}8814 8815/// Check whether a specialization is well-formed in the current8816/// context.8817///8818/// This routine determines whether a template specialization can be declared8819/// in the current context (C++ [temp.expl.spec]p2).8820///8821/// \param S the semantic analysis object for which this check is being8822/// performed.8823///8824/// \param Specialized the entity being specialized or instantiated, which8825/// may be a kind of template (class template, function template, etc.) or8826/// a member of a class template (member function, static data member,8827/// member class).8828///8829/// \param PrevDecl the previous declaration of this entity, if any.8830///8831/// \param Loc the location of the explicit specialization or instantiation of8832/// this entity.8833///8834/// \param IsPartialSpecialization whether this is a partial specialization of8835/// a class template.8836///8837/// \returns true if there was an error that we cannot recover from, false8838/// otherwise.8839static bool CheckTemplateSpecializationScope(Sema &S,8840 NamedDecl *Specialized,8841 NamedDecl *PrevDecl,8842 SourceLocation Loc,8843 bool IsPartialSpecialization) {8844 // Keep these "kind" numbers in sync with the %select statements in the8845 // various diagnostics emitted by this routine.8846 int EntityKind = 0;8847 if (isa<ClassTemplateDecl>(Specialized))8848 EntityKind = IsPartialSpecialization? 1 : 0;8849 else if (isa<VarTemplateDecl>(Specialized))8850 EntityKind = IsPartialSpecialization ? 3 : 2;8851 else if (isa<FunctionTemplateDecl>(Specialized))8852 EntityKind = 4;8853 else if (isa<CXXMethodDecl>(Specialized))8854 EntityKind = 5;8855 else if (isa<VarDecl>(Specialized))8856 EntityKind = 6;8857 else if (isa<RecordDecl>(Specialized))8858 EntityKind = 7;8859 else if (isa<EnumDecl>(Specialized) && S.getLangOpts().CPlusPlus11)8860 EntityKind = 8;8861 else {8862 S.Diag(Loc, diag::err_template_spec_unknown_kind)8863 << S.getLangOpts().CPlusPlus11;8864 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);8865 return true;8866 }8867 8868 // C++ [temp.expl.spec]p2:8869 // An explicit specialization may be declared in any scope in which8870 // the corresponding primary template may be defined.8871 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {8872 S.Diag(Loc, diag::err_template_spec_decl_function_scope)8873 << Specialized;8874 return true;8875 }8876 8877 // C++ [temp.class.spec]p6:8878 // A class template partial specialization may be declared in any8879 // scope in which the primary template may be defined.8880 DeclContext *SpecializedContext =8881 Specialized->getDeclContext()->getRedeclContext();8882 DeclContext *DC = S.CurContext->getRedeclContext();8883 8884 // Make sure that this redeclaration (or definition) occurs in the same8885 // scope or an enclosing namespace.8886 if (!(DC->isFileContext() ? DC->Encloses(SpecializedContext)8887 : DC->Equals(SpecializedContext))) {8888 if (isa<TranslationUnitDecl>(SpecializedContext))8889 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)8890 << EntityKind << Specialized;8891 else {8892 auto *ND = cast<NamedDecl>(SpecializedContext);8893 int Diag = diag::err_template_spec_redecl_out_of_scope;8894 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())8895 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;8896 S.Diag(Loc, Diag) << EntityKind << Specialized8897 << ND << isa<CXXRecordDecl>(ND);8898 }8899 8900 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);8901 8902 // Don't allow specializing in the wrong class during error recovery.8903 // Otherwise, things can go horribly wrong.8904 if (DC->isRecord())8905 return true;8906 }8907 8908 return false;8909}8910 8911static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {8912 if (!E->isTypeDependent())8913 return SourceLocation();8914 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);8915 Checker.TraverseStmt(E);8916 if (Checker.MatchLoc.isInvalid())8917 return E->getSourceRange();8918 return Checker.MatchLoc;8919}8920 8921static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {8922 if (!TL.getType()->isDependentType())8923 return SourceLocation();8924 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);8925 Checker.TraverseTypeLoc(TL);8926 if (Checker.MatchLoc.isInvalid())8927 return TL.getSourceRange();8928 return Checker.MatchLoc;8929}8930 8931/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs8932/// that checks non-type template partial specialization arguments.8933static bool CheckNonTypeTemplatePartialSpecializationArgs(8934 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,8935 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {8936 bool HasError = false;8937 for (unsigned I = 0; I != NumArgs; ++I) {8938 if (Args[I].getKind() == TemplateArgument::Pack) {8939 if (CheckNonTypeTemplatePartialSpecializationArgs(8940 S, TemplateNameLoc, Param, Args[I].pack_begin(),8941 Args[I].pack_size(), IsDefaultArgument))8942 return true;8943 8944 continue;8945 }8946 8947 if (Args[I].getKind() != TemplateArgument::Expression)8948 continue;8949 8950 Expr *ArgExpr = Args[I].getAsExpr();8951 if (ArgExpr->containsErrors()) {8952 HasError = true;8953 continue;8954 }8955 8956 // We can have a pack expansion of any of the bullets below.8957 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(ArgExpr))8958 ArgExpr = Expansion->getPattern();8959 8960 // Strip off any implicit casts we added as part of type checking.8961 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))8962 ArgExpr = ICE->getSubExpr();8963 8964 // C++ [temp.class.spec]p8:8965 // A non-type argument is non-specialized if it is the name of a8966 // non-type parameter. All other non-type arguments are8967 // specialized.8968 //8969 // Below, we check the two conditions that only apply to8970 // specialized non-type arguments, so skip any non-specialized8971 // arguments.8972 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ArgExpr))8973 if (isa<NonTypeTemplateParmDecl>(DRE->getDecl()))8974 continue;8975 8976 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(ArgExpr);8977 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {8978 continue;8979 }8980 8981 // C++ [temp.class.spec]p9:8982 // Within the argument list of a class template partial8983 // specialization, the following restrictions apply:8984 // -- A partially specialized non-type argument expression8985 // shall not involve a template parameter of the partial8986 // specialization except when the argument expression is a8987 // simple identifier.8988 // -- The type of a template parameter corresponding to a8989 // specialized non-type argument shall not be dependent on a8990 // parameter of the specialization.8991 // DR1315 removes the first bullet, leaving an incoherent set of rules.8992 // We implement a compromise between the original rules and DR1315:8993 // -- A specialized non-type template argument shall not be8994 // type-dependent and the corresponding template parameter8995 // shall have a non-dependent type.8996 SourceRange ParamUseRange =8997 findTemplateParameterInType(Param->getDepth(), ArgExpr);8998 if (ParamUseRange.isValid()) {8999 if (IsDefaultArgument) {9000 S.Diag(TemplateNameLoc,9001 diag::err_dependent_non_type_arg_in_partial_spec);9002 S.Diag(ParamUseRange.getBegin(),9003 diag::note_dependent_non_type_default_arg_in_partial_spec)9004 << ParamUseRange;9005 } else {9006 S.Diag(ParamUseRange.getBegin(),9007 diag::err_dependent_non_type_arg_in_partial_spec)9008 << ParamUseRange;9009 }9010 return true;9011 }9012 9013 ParamUseRange = findTemplateParameter(9014 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());9015 if (ParamUseRange.isValid()) {9016 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),9017 diag::err_dependent_typed_non_type_arg_in_partial_spec)9018 << Param->getType();9019 S.NoteTemplateParameterLocation(*Param);9020 return true;9021 }9022 }9023 9024 return HasError;9025}9026 9027bool Sema::CheckTemplatePartialSpecializationArgs(9028 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,9029 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {9030 // We have to be conservative when checking a template in a dependent9031 // context.9032 if (PrimaryTemplate->getDeclContext()->isDependentContext())9033 return false;9034 9035 TemplateParameterList *TemplateParams =9036 PrimaryTemplate->getTemplateParameters();9037 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {9038 NonTypeTemplateParmDecl *Param9039 = dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(I));9040 if (!Param)9041 continue;9042 9043 if (CheckNonTypeTemplatePartialSpecializationArgs(*this, TemplateNameLoc,9044 Param, &TemplateArgs[I],9045 1, I >= NumExplicit))9046 return true;9047 }9048 9049 return false;9050}9051 9052DeclResult Sema::ActOnClassTemplateSpecialization(9053 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,9054 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,9055 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,9056 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {9057 assert(TUK != TagUseKind::Reference && "References are not specializations");9058 9059 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;9060 SourceLocation LAngleLoc = TemplateId.LAngleLoc;9061 SourceLocation RAngleLoc = TemplateId.RAngleLoc;9062 9063 // Find the class template we're specializing9064 TemplateName Name = TemplateId.Template.get();9065 ClassTemplateDecl *ClassTemplate9066 = dyn_cast_or_null<ClassTemplateDecl>(Name.getAsTemplateDecl());9067 9068 if (!ClassTemplate) {9069 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)9070 << (Name.getAsTemplateDecl() &&9071 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));9072 return true;9073 }9074 9075 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {9076 auto Message = DSA->getMessage();9077 Diag(TemplateNameLoc, diag::warn_invalid_specialization)9078 << ClassTemplate << !Message.empty() << Message;9079 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;9080 }9081 9082 if (S->isTemplateParamScope())9083 EnterTemplatedContext(S, ClassTemplate->getTemplatedDecl());9084 9085 DeclContext *DC = ClassTemplate->getDeclContext();9086 9087 bool isMemberSpecialization = false;9088 bool isPartialSpecialization = false;9089 9090 if (SS.isSet()) {9091 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&9092 diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),9093 TemplateNameLoc, &TemplateId,9094 /*IsMemberSpecialization=*/false))9095 return true;9096 }9097 9098 // Check the validity of the template headers that introduce this9099 // template.9100 // FIXME: We probably shouldn't complain about these headers for9101 // friend declarations.9102 bool Invalid = false;9103 TemplateParameterList *TemplateParams =9104 MatchTemplateParametersToScopeSpecifier(9105 KWLoc, TemplateNameLoc, SS, &TemplateId, TemplateParameterLists,9106 TUK == TagUseKind::Friend, isMemberSpecialization, Invalid);9107 if (Invalid)9108 return true;9109 9110 // Check that we can declare a template specialization here.9111 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))9112 return true;9113 9114 if (TemplateParams && DC->isDependentContext()) {9115 ContextRAII SavedContext(*this, DC);9116 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))9117 return true;9118 }9119 9120 if (TemplateParams && TemplateParams->size() > 0) {9121 isPartialSpecialization = true;9122 9123 if (TUK == TagUseKind::Friend) {9124 Diag(KWLoc, diag::err_partial_specialization_friend)9125 << SourceRange(LAngleLoc, RAngleLoc);9126 return true;9127 }9128 9129 // C++ [temp.class.spec]p10:9130 // The template parameter list of a specialization shall not9131 // contain default template argument values.9132 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {9133 Decl *Param = TemplateParams->getParam(I);9134 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) {9135 if (TTP->hasDefaultArgument()) {9136 Diag(TTP->getDefaultArgumentLoc(),9137 diag::err_default_arg_in_partial_spec);9138 TTP->removeDefaultArgument();9139 }9140 } else if (NonTypeTemplateParmDecl *NTTP9141 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {9142 if (NTTP->hasDefaultArgument()) {9143 Diag(NTTP->getDefaultArgumentLoc(),9144 diag::err_default_arg_in_partial_spec)9145 << NTTP->getDefaultArgument().getSourceRange();9146 NTTP->removeDefaultArgument();9147 }9148 } else {9149 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Param);9150 if (TTP->hasDefaultArgument()) {9151 Diag(TTP->getDefaultArgument().getLocation(),9152 diag::err_default_arg_in_partial_spec)9153 << TTP->getDefaultArgument().getSourceRange();9154 TTP->removeDefaultArgument();9155 }9156 }9157 }9158 } else if (TemplateParams) {9159 if (TUK == TagUseKind::Friend)9160 Diag(KWLoc, diag::err_template_spec_friend)9161 << FixItHint::CreateRemoval(9162 SourceRange(TemplateParams->getTemplateLoc(),9163 TemplateParams->getRAngleLoc()))9164 << SourceRange(LAngleLoc, RAngleLoc);9165 } else {9166 assert(TUK == TagUseKind::Friend &&9167 "should have a 'template<>' for this decl");9168 }9169 9170 // Check that the specialization uses the same tag kind as the9171 // original template.9172 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);9173 assert(Kind != TagTypeKind::Enum &&9174 "Invalid enum tag in class template spec!");9175 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(), Kind,9176 TUK == TagUseKind::Definition, KWLoc,9177 ClassTemplate->getIdentifier())) {9178 Diag(KWLoc, diag::err_use_with_wrong_tag)9179 << ClassTemplate9180 << FixItHint::CreateReplacement(KWLoc,9181 ClassTemplate->getTemplatedDecl()->getKindName());9182 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),9183 diag::note_previous_use);9184 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();9185 }9186 9187 // Translate the parser's template argument list in our AST format.9188 TemplateArgumentListInfo TemplateArgs =9189 makeTemplateArgumentListInfo(*this, TemplateId);9190 9191 // Check for unexpanded parameter packs in any of the template arguments.9192 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)9193 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],9194 isPartialSpecialization9195 ? UPPC_PartialSpecialization9196 : UPPC_ExplicitSpecialization))9197 return true;9198 9199 // Check that the template argument list is well-formed for this9200 // template.9201 CheckTemplateArgumentInfo CTAI;9202 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,9203 /*DefaultArgs=*/{},9204 /*PartialTemplateArgs=*/false, CTAI,9205 /*UpdateArgsWithConversions=*/true))9206 return true;9207 9208 // Find the class template (partial) specialization declaration that9209 // corresponds to these arguments.9210 if (isPartialSpecialization) {9211 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,9212 TemplateArgs.size(),9213 CTAI.CanonicalConverted))9214 return true;9215 9216 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we9217 // also do it during instantiation.9218 if (!Name.isDependent() &&9219 !TemplateSpecializationType::anyDependentTemplateArguments(9220 TemplateArgs, CTAI.CanonicalConverted)) {9221 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)9222 << ClassTemplate->getDeclName();9223 isPartialSpecialization = false;9224 Invalid = true;9225 }9226 }9227 9228 void *InsertPos = nullptr;9229 ClassTemplateSpecializationDecl *PrevDecl = nullptr;9230 9231 if (isPartialSpecialization)9232 PrevDecl = ClassTemplate->findPartialSpecialization(9233 CTAI.CanonicalConverted, TemplateParams, InsertPos);9234 else9235 PrevDecl =9236 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);9237 9238 ClassTemplateSpecializationDecl *Specialization = nullptr;9239 9240 // Check whether we can declare a class template specialization in9241 // the current scope.9242 if (TUK != TagUseKind::Friend &&9243 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,9244 TemplateNameLoc,9245 isPartialSpecialization))9246 return true;9247 9248 if (!isPartialSpecialization) {9249 // Create a new class template specialization declaration node for9250 // this explicit specialization or friend declaration.9251 Specialization = ClassTemplateSpecializationDecl::Create(9252 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,9253 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);9254 Specialization->setTemplateArgsAsWritten(TemplateArgs);9255 SetNestedNameSpecifier(*this, Specialization, SS);9256 if (TemplateParameterLists.size() > 0) {9257 Specialization->setTemplateParameterListsInfo(Context,9258 TemplateParameterLists);9259 }9260 9261 if (!PrevDecl)9262 ClassTemplate->AddSpecialization(Specialization, InsertPos);9263 } else {9264 CanQualType CanonType = CanQualType::CreateUnsafe(9265 Context.getCanonicalTemplateSpecializationType(9266 ElaboratedTypeKeyword::None,9267 TemplateName(ClassTemplate->getCanonicalDecl()),9268 CTAI.CanonicalConverted));9269 if (Context.hasSameType(9270 CanonType,9271 ClassTemplate->getCanonicalInjectedSpecializationType(Context)) &&9272 (!Context.getLangOpts().CPlusPlus20 ||9273 !TemplateParams->hasAssociatedConstraints())) {9274 // C++ [temp.class.spec]p9b3:9275 //9276 // -- The argument list of the specialization shall not be identical9277 // to the implicit argument list of the primary template.9278 //9279 // This rule has since been removed, because it's redundant given DR1495,9280 // but we keep it because it produces better diagnostics and recovery.9281 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)9282 << /*class template*/ 0 << (TUK == TagUseKind::Definition)9283 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));9284 return CheckClassTemplate(9285 S, TagSpec, TUK, KWLoc, SS, ClassTemplate->getIdentifier(),9286 TemplateNameLoc, Attr, TemplateParams, AS_none,9287 /*ModulePrivateLoc=*/SourceLocation(),9288 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,9289 TemplateParameterLists.data());9290 }9291 9292 // Create a new class template partial specialization declaration node.9293 ClassTemplatePartialSpecializationDecl *PrevPartial =9294 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl);9295 ClassTemplatePartialSpecializationDecl *Partial =9296 ClassTemplatePartialSpecializationDecl::Create(9297 Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,9298 ClassTemplate, CTAI.CanonicalConverted, CanonType, PrevPartial);9299 Partial->setTemplateArgsAsWritten(TemplateArgs);9300 SetNestedNameSpecifier(*this, Partial, SS);9301 if (TemplateParameterLists.size() > 1 && SS.isSet()) {9302 Partial->setTemplateParameterListsInfo(9303 Context, TemplateParameterLists.drop_back(1));9304 }9305 9306 if (!PrevPartial)9307 ClassTemplate->AddPartialSpecialization(Partial, InsertPos);9308 Specialization = Partial;9309 9310 // If we are providing an explicit specialization of a member class9311 // template specialization, make a note of that.9312 if (PrevPartial && PrevPartial->getInstantiatedFromMember())9313 PrevPartial->setMemberSpecialization();9314 9315 CheckTemplatePartialSpecialization(Partial);9316 }9317 9318 // C++ [temp.expl.spec]p6:9319 // If a template, a member template or the member of a class template is9320 // explicitly specialized then that specialization shall be declared9321 // before the first use of that specialization that would cause an implicit9322 // instantiation to take place, in every translation unit in which such a9323 // use occurs; no diagnostic is required.9324 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {9325 bool Okay = false;9326 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {9327 // Is there any previous explicit specialization declaration?9328 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {9329 Okay = true;9330 break;9331 }9332 }9333 9334 if (!Okay) {9335 SourceRange Range(TemplateNameLoc, RAngleLoc);9336 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)9337 << Context.getCanonicalTagType(Specialization) << Range;9338 9339 Diag(PrevDecl->getPointOfInstantiation(),9340 diag::note_instantiation_required_here)9341 << (PrevDecl->getTemplateSpecializationKind()9342 != TSK_ImplicitInstantiation);9343 return true;9344 }9345 }9346 9347 // If this is not a friend, note that this is an explicit specialization.9348 if (TUK != TagUseKind::Friend)9349 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);9350 9351 // Check that this isn't a redefinition of this specialization.9352 if (TUK == TagUseKind::Definition) {9353 RecordDecl *Def = Specialization->getDefinition();9354 NamedDecl *Hidden = nullptr;9355 bool HiddenDefVisible = false;9356 if (Def && SkipBody &&9357 isRedefinitionAllowedFor(Def, &Hidden, HiddenDefVisible)) {9358 SkipBody->ShouldSkip = true;9359 SkipBody->Previous = Def;9360 if (!HiddenDefVisible && Hidden)9361 makeMergedDefinitionVisible(Hidden);9362 } else if (Def) {9363 SourceRange Range(TemplateNameLoc, RAngleLoc);9364 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;9365 Diag(Def->getLocation(), diag::note_previous_definition);9366 Specialization->setInvalidDecl();9367 return true;9368 }9369 }9370 9371 ProcessDeclAttributeList(S, Specialization, Attr);9372 ProcessAPINotes(Specialization);9373 9374 // Add alignment attributes if necessary; these attributes are checked when9375 // the ASTContext lays out the structure.9376 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {9377 if (LangOpts.HLSL)9378 Specialization->addAttr(PackedAttr::CreateImplicit(Context));9379 AddAlignmentAttributesForRecord(Specialization);9380 AddMsStructLayoutForRecord(Specialization);9381 }9382 9383 if (ModulePrivateLoc.isValid())9384 Diag(Specialization->getLocation(), diag::err_module_private_specialization)9385 << (isPartialSpecialization? 1 : 0)9386 << FixItHint::CreateRemoval(ModulePrivateLoc);9387 9388 // C++ [temp.expl.spec]p9:9389 // A template explicit specialization is in the scope of the9390 // namespace in which the template was defined.9391 //9392 // We actually implement this paragraph where we set the semantic9393 // context (in the creation of the ClassTemplateSpecializationDecl),9394 // but we also maintain the lexical context where the actual9395 // definition occurs.9396 Specialization->setLexicalDeclContext(CurContext);9397 9398 // We may be starting the definition of this specialization.9399 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))9400 Specialization->startDefinition();9401 9402 if (TUK == TagUseKind::Friend) {9403 CanQualType CanonType = Context.getCanonicalTagType(Specialization);9404 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(9405 ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),9406 SS.getWithLocInContext(Context),9407 /*TemplateKeywordLoc=*/SourceLocation(), Name, TemplateNameLoc,9408 TemplateArgs, CTAI.CanonicalConverted, CanonType);9409 9410 // Build the fully-sugared type for this class template9411 // specialization as the user wrote in the specialization9412 // itself. This means that we'll pretty-print the type retrieved9413 // from the specialization's declaration the way that the user9414 // actually wrote the specialization, rather than formatting the9415 // name based on the "canonical" representation used to store the9416 // template arguments in the specialization.9417 FriendDecl *Friend = FriendDecl::Create(Context, CurContext,9418 TemplateNameLoc,9419 WrittenTy,9420 /*FIXME:*/KWLoc);9421 Friend->setAccess(AS_public);9422 CurContext->addDecl(Friend);9423 } else {9424 // Add the specialization into its lexical context, so that it can9425 // be seen when iterating through the list of declarations in that9426 // context. However, specializations are not found by name lookup.9427 CurContext->addDecl(Specialization);9428 }9429 9430 if (SkipBody && SkipBody->ShouldSkip)9431 return SkipBody->Previous;9432 9433 Specialization->setInvalidDecl(Invalid);9434 inferGslOwnerPointerAttribute(Specialization);9435 return Specialization;9436}9437 9438Decl *Sema::ActOnTemplateDeclarator(Scope *S,9439 MultiTemplateParamsArg TemplateParameterLists,9440 Declarator &D) {9441 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);9442 ActOnDocumentableDecl(NewDecl);9443 return NewDecl;9444}9445 9446ConceptDecl *Sema::ActOnStartConceptDefinition(9447 Scope *S, MultiTemplateParamsArg TemplateParameterLists,9448 const IdentifierInfo *Name, SourceLocation NameLoc) {9449 DeclContext *DC = CurContext;9450 9451 if (!DC->getRedeclContext()->isFileContext()) {9452 Diag(NameLoc,9453 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);9454 return nullptr;9455 }9456 9457 if (TemplateParameterLists.size() > 1) {9458 Diag(NameLoc, diag::err_concept_extra_headers);9459 return nullptr;9460 }9461 9462 TemplateParameterList *Params = TemplateParameterLists.front();9463 9464 if (Params->size() == 0) {9465 Diag(NameLoc, diag::err_concept_no_parameters);9466 return nullptr;9467 }9468 9469 // Ensure that the parameter pack, if present, is the last parameter in the9470 // template.9471 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),9472 ParamEnd = Params->end();9473 ParamIt != ParamEnd; ++ParamIt) {9474 Decl const *Param = *ParamIt;9475 if (Param->isParameterPack()) {9476 if (++ParamIt == ParamEnd)9477 break;9478 Diag(Param->getLocation(),9479 diag::err_template_param_pack_must_be_last_template_parameter);9480 return nullptr;9481 }9482 }9483 9484 ConceptDecl *NewDecl =9485 ConceptDecl::Create(Context, DC, NameLoc, Name, Params);9486 9487 if (NewDecl->hasAssociatedConstraints()) {9488 // C++2a [temp.concept]p4:9489 // A concept shall not have associated constraints.9490 Diag(NameLoc, diag::err_concept_no_associated_constraints);9491 NewDecl->setInvalidDecl();9492 }9493 9494 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());9495 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,9496 forRedeclarationInCurContext());9497 LookupName(Previous, S);9498 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,9499 /*AllowInlineNamespace*/ false);9500 9501 // We cannot properly handle redeclarations until we parse the constraint9502 // expression, so only inject the name if we are sure we are not redeclaring a9503 // symbol9504 if (Previous.empty())9505 PushOnScopeChains(NewDecl, S, true);9506 9507 return NewDecl;9508}9509 9510static bool RemoveLookupResult(LookupResult &R, NamedDecl *C) {9511 bool Found = false;9512 LookupResult::Filter F = R.makeFilter();9513 while (F.hasNext()) {9514 NamedDecl *D = F.next();9515 if (D == C) {9516 F.erase();9517 Found = true;9518 break;9519 }9520 }9521 F.done();9522 return Found;9523}9524 9525ConceptDecl *9526Sema::ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,9527 Expr *ConstraintExpr,9528 const ParsedAttributesView &Attrs) {9529 assert(!C->hasDefinition() && "Concept already defined");9530 if (DiagnoseUnexpandedParameterPack(ConstraintExpr)) {9531 C->setInvalidDecl();9532 return nullptr;9533 }9534 C->setDefinition(ConstraintExpr);9535 ProcessDeclAttributeList(S, C, Attrs);9536 9537 // Check for conflicting previous declaration.9538 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());9539 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,9540 forRedeclarationInCurContext());9541 LookupName(Previous, S);9542 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage=*/false,9543 /*AllowInlineNamespace*/ false);9544 bool WasAlreadyAdded = RemoveLookupResult(Previous, C);9545 bool AddToScope = true;9546 CheckConceptRedefinition(C, Previous, AddToScope);9547 9548 ActOnDocumentableDecl(C);9549 if (!WasAlreadyAdded && AddToScope)9550 PushOnScopeChains(C, S);9551 9552 return C;9553}9554 9555void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,9556 LookupResult &Previous, bool &AddToScope) {9557 AddToScope = true;9558 9559 if (Previous.empty())9560 return;9561 9562 auto *OldConcept = dyn_cast<ConceptDecl>(Previous.getRepresentativeDecl()->getUnderlyingDecl());9563 if (!OldConcept) {9564 auto *Old = Previous.getRepresentativeDecl();9565 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)9566 << NewDecl->getDeclName();9567 notePreviousDefinition(Old, NewDecl->getLocation());9568 AddToScope = false;9569 return;9570 }9571 // Check if we can merge with a concept declaration.9572 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);9573 if (!IsSame) {9574 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)9575 << NewDecl->getDeclName();9576 notePreviousDefinition(OldConcept, NewDecl->getLocation());9577 AddToScope = false;9578 return;9579 }9580 if (hasReachableDefinition(OldConcept) &&9581 IsRedefinitionInModule(NewDecl, OldConcept)) {9582 Diag(NewDecl->getLocation(), diag::err_redefinition)9583 << NewDecl->getDeclName();9584 notePreviousDefinition(OldConcept, NewDecl->getLocation());9585 AddToScope = false;9586 return;9587 }9588 if (!Previous.isSingleResult()) {9589 // FIXME: we should produce an error in case of ambig and failed lookups.9590 // Other decls (e.g. namespaces) also have this shortcoming.9591 return;9592 }9593 // We unwrap canonical decl late to check for module visibility.9594 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());9595}9596 9597bool Sema::CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc) {9598 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Concept);9599 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {9600 Diag(Loc, diag::err_recursive_concept) << CE;9601 Diag(CE->getLocation(), diag::note_declared_at);9602 return true;9603 }9604 // Concept template parameters don't have a definition and can't9605 // be defined recursively.9606 return false;9607}9608 9609/// \brief Strips various properties off an implicit instantiation9610/// that has just been explicitly specialized.9611static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {9612 if (MinGW || (isa<FunctionDecl>(D) &&9613 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))9614 D->dropAttrs<DLLImportAttr, DLLExportAttr>();9615 9616 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))9617 FD->setInlineSpecified(false);9618}9619 9620/// Compute the diagnostic location for an explicit instantiation9621// declaration or definition.9622static SourceLocation DiagLocForExplicitInstantiation(9623 NamedDecl* D, SourceLocation PointOfInstantiation) {9624 // Explicit instantiations following a specialization have no effect and9625 // hence no PointOfInstantiation. In that case, walk decl backwards9626 // until a valid name loc is found.9627 SourceLocation PrevDiagLoc = PointOfInstantiation;9628 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();9629 Prev = Prev->getPreviousDecl()) {9630 PrevDiagLoc = Prev->getLocation();9631 }9632 assert(PrevDiagLoc.isValid() &&9633 "Explicit instantiation without point of instantiation?");9634 return PrevDiagLoc;9635}9636 9637bool9638Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,9639 TemplateSpecializationKind NewTSK,9640 NamedDecl *PrevDecl,9641 TemplateSpecializationKind PrevTSK,9642 SourceLocation PrevPointOfInstantiation,9643 bool &HasNoEffect) {9644 HasNoEffect = false;9645 9646 switch (NewTSK) {9647 case TSK_Undeclared:9648 case TSK_ImplicitInstantiation:9649 assert(9650 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&9651 "previous declaration must be implicit!");9652 return false;9653 9654 case TSK_ExplicitSpecialization:9655 switch (PrevTSK) {9656 case TSK_Undeclared:9657 case TSK_ExplicitSpecialization:9658 // Okay, we're just specializing something that is either already9659 // explicitly specialized or has merely been mentioned without any9660 // instantiation.9661 return false;9662 9663 case TSK_ImplicitInstantiation:9664 if (PrevPointOfInstantiation.isInvalid()) {9665 // The declaration itself has not actually been instantiated, so it is9666 // still okay to specialize it.9667 StripImplicitInstantiation(9668 PrevDecl, Context.getTargetInfo().getTriple().isOSCygMing());9669 return false;9670 }9671 // Fall through9672 [[fallthrough]];9673 9674 case TSK_ExplicitInstantiationDeclaration:9675 case TSK_ExplicitInstantiationDefinition:9676 assert((PrevTSK == TSK_ImplicitInstantiation ||9677 PrevPointOfInstantiation.isValid()) &&9678 "Explicit instantiation without point of instantiation?");9679 9680 // C++ [temp.expl.spec]p6:9681 // If a template, a member template or the member of a class template9682 // is explicitly specialized then that specialization shall be declared9683 // before the first use of that specialization that would cause an9684 // implicit instantiation to take place, in every translation unit in9685 // which such a use occurs; no diagnostic is required.9686 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {9687 // Is there any previous explicit specialization declaration?9688 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization)9689 return false;9690 }9691 9692 Diag(NewLoc, diag::err_specialization_after_instantiation)9693 << PrevDecl;9694 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)9695 << (PrevTSK != TSK_ImplicitInstantiation);9696 9697 return true;9698 }9699 llvm_unreachable("The switch over PrevTSK must be exhaustive.");9700 9701 case TSK_ExplicitInstantiationDeclaration:9702 switch (PrevTSK) {9703 case TSK_ExplicitInstantiationDeclaration:9704 // This explicit instantiation declaration is redundant (that's okay).9705 HasNoEffect = true;9706 return false;9707 9708 case TSK_Undeclared:9709 case TSK_ImplicitInstantiation:9710 // We're explicitly instantiating something that may have already been9711 // implicitly instantiated; that's fine.9712 return false;9713 9714 case TSK_ExplicitSpecialization:9715 // C++0x [temp.explicit]p4:9716 // For a given set of template parameters, if an explicit instantiation9717 // of a template appears after a declaration of an explicit9718 // specialization for that template, the explicit instantiation has no9719 // effect.9720 HasNoEffect = true;9721 return false;9722 9723 case TSK_ExplicitInstantiationDefinition:9724 // C++0x [temp.explicit]p10:9725 // If an entity is the subject of both an explicit instantiation9726 // declaration and an explicit instantiation definition in the same9727 // translation unit, the definition shall follow the declaration.9728 Diag(NewLoc,9729 diag::err_explicit_instantiation_declaration_after_definition);9730 9731 // Explicit instantiations following a specialization have no effect and9732 // hence no PrevPointOfInstantiation. In that case, walk decl backwards9733 // until a valid name loc is found.9734 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),9735 diag::note_explicit_instantiation_definition_here);9736 HasNoEffect = true;9737 return false;9738 }9739 llvm_unreachable("Unexpected TemplateSpecializationKind!");9740 9741 case TSK_ExplicitInstantiationDefinition:9742 switch (PrevTSK) {9743 case TSK_Undeclared:9744 case TSK_ImplicitInstantiation:9745 // We're explicitly instantiating something that may have already been9746 // implicitly instantiated; that's fine.9747 return false;9748 9749 case TSK_ExplicitSpecialization:9750 // C++ DR 259, C++0x [temp.explicit]p4:9751 // For a given set of template parameters, if an explicit9752 // instantiation of a template appears after a declaration of9753 // an explicit specialization for that template, the explicit9754 // instantiation has no effect.9755 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)9756 << PrevDecl;9757 Diag(PrevDecl->getLocation(),9758 diag::note_previous_template_specialization);9759 HasNoEffect = true;9760 return false;9761 9762 case TSK_ExplicitInstantiationDeclaration:9763 // We're explicitly instantiating a definition for something for which we9764 // were previously asked to suppress instantiations. That's fine.9765 9766 // C++0x [temp.explicit]p4:9767 // For a given set of template parameters, if an explicit instantiation9768 // of a template appears after a declaration of an explicit9769 // specialization for that template, the explicit instantiation has no9770 // effect.9771 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {9772 // Is there any previous explicit specialization declaration?9773 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {9774 HasNoEffect = true;9775 break;9776 }9777 }9778 9779 return false;9780 9781 case TSK_ExplicitInstantiationDefinition:9782 // C++0x [temp.spec]p5:9783 // For a given template and a given set of template-arguments,9784 // - an explicit instantiation definition shall appear at most once9785 // in a program,9786 9787 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.9788 Diag(NewLoc, (getLangOpts().MSVCCompat)9789 ? diag::ext_explicit_instantiation_duplicate9790 : diag::err_explicit_instantiation_duplicate)9791 << PrevDecl;9792 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),9793 diag::note_previous_explicit_instantiation);9794 HasNoEffect = true;9795 return false;9796 }9797 }9798 9799 llvm_unreachable("Missing specialization/instantiation case?");9800}9801 9802bool Sema::CheckDependentFunctionTemplateSpecialization(9803 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,9804 LookupResult &Previous) {9805 // Remove anything from Previous that isn't a function template in9806 // the correct context.9807 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();9808 LookupResult::Filter F = Previous.makeFilter();9809 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };9810 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;9811 while (F.hasNext()) {9812 NamedDecl *D = F.next()->getUnderlyingDecl();9813 if (!isa<FunctionTemplateDecl>(D)) {9814 F.erase();9815 DiscardedCandidates.push_back(std::make_pair(NotAFunctionTemplate, D));9816 continue;9817 }9818 9819 if (!FDLookupContext->InEnclosingNamespaceSetOf(9820 D->getDeclContext()->getRedeclContext())) {9821 F.erase();9822 DiscardedCandidates.push_back(std::make_pair(NotAMemberOfEnclosing, D));9823 continue;9824 }9825 }9826 F.done();9827 9828 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;9829 if (Previous.empty()) {9830 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)9831 << IsFriend;9832 for (auto &P : DiscardedCandidates)9833 Diag(P.second->getLocation(),9834 diag::note_dependent_function_template_spec_discard_reason)9835 << P.first << IsFriend;9836 return true;9837 }9838 9839 FD->setDependentTemplateSpecialization(Context, Previous.asUnresolvedSet(),9840 ExplicitTemplateArgs);9841 return false;9842}9843 9844bool Sema::CheckFunctionTemplateSpecialization(9845 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,9846 LookupResult &Previous, bool QualifiedFriend) {9847 // The set of function template specializations that could match this9848 // explicit function template specialization.9849 UnresolvedSet<8> Candidates;9850 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),9851 /*ForTakingAddress=*/false);9852 9853 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>9854 ConvertedTemplateArgs;9855 9856 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();9857 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();9858 I != E; ++I) {9859 NamedDecl *Ovl = (*I)->getUnderlyingDecl();9860 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Ovl)) {9861 // Only consider templates found within the same semantic lookup scope as9862 // FD.9863 if (!FDLookupContext->InEnclosingNamespaceSetOf(9864 Ovl->getDeclContext()->getRedeclContext()))9865 continue;9866 9867 QualType FT = FD->getType();9868 // C++11 [dcl.constexpr]p8:9869 // A constexpr specifier for a non-static member function that is not9870 // a constructor declares that member function to be const.9871 //9872 // When matching a constexpr member function template specialization9873 // against the primary template, we don't yet know whether the9874 // specialization has an implicit 'const' (because we don't know whether9875 // it will be a static member function until we know which template it9876 // specializes). This rule was removed in C++14.9877 if (auto *NewMD = dyn_cast<CXXMethodDecl>(FD);9878 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&9879 !isa<CXXConstructorDecl, CXXDestructorDecl>(NewMD)) {9880 auto *OldMD = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());9881 if (OldMD && OldMD->isConst()) {9882 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();9883 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();9884 EPI.TypeQuals.addConst();9885 FT = Context.getFunctionType(FPT->getReturnType(),9886 FPT->getParamTypes(), EPI);9887 }9888 }9889 9890 TemplateArgumentListInfo Args;9891 if (ExplicitTemplateArgs)9892 Args = *ExplicitTemplateArgs;9893 9894 // C++ [temp.expl.spec]p11:9895 // A trailing template-argument can be left unspecified in the9896 // template-id naming an explicit function template specialization9897 // provided it can be deduced from the function argument type.9898 // Perform template argument deduction to determine whether we may be9899 // specializing this template.9900 // FIXME: It is somewhat wasteful to build9901 TemplateDeductionInfo Info(FailedCandidates.getLocation());9902 FunctionDecl *Specialization = nullptr;9903 if (TemplateDeductionResult TDK = DeduceTemplateArguments(9904 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),9905 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);9906 TDK != TemplateDeductionResult::Success) {9907 // Template argument deduction failed; record why it failed, so9908 // that we can provide nifty diagnostics.9909 FailedCandidates.addCandidate().set(9910 I.getPair(), FunTmpl->getTemplatedDecl(),9911 MakeDeductionFailureInfo(Context, TDK, Info));9912 (void)TDK;9913 continue;9914 }9915 9916 // Target attributes are part of the cuda function signature, so9917 // the deduced template's cuda target must match that of the9918 // specialization. Given that C++ template deduction does not9919 // take target attributes into account, we reject candidates9920 // here that have a different target.9921 if (LangOpts.CUDA &&9922 CUDA().IdentifyTarget(Specialization,9923 /* IgnoreImplicitHDAttr = */ true) !=9924 CUDA().IdentifyTarget(FD, /* IgnoreImplicitHDAttr = */ true)) {9925 FailedCandidates.addCandidate().set(9926 I.getPair(), FunTmpl->getTemplatedDecl(),9927 MakeDeductionFailureInfo(9928 Context, TemplateDeductionResult::CUDATargetMismatch, Info));9929 continue;9930 }9931 9932 // Record this candidate.9933 if (ExplicitTemplateArgs)9934 ConvertedTemplateArgs[Specialization] = std::move(Args);9935 Candidates.addDecl(Specialization, I.getAccess());9936 }9937 }9938 9939 // For a qualified friend declaration (with no explicit marker to indicate9940 // that a template specialization was intended), note all (template and9941 // non-template) candidates.9942 if (QualifiedFriend && Candidates.empty()) {9943 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)9944 << FD->getDeclName() << FDLookupContext;9945 // FIXME: We should form a single candidate list and diagnose all9946 // candidates at once, to get proper sorting and limiting.9947 for (auto *OldND : Previous) {9948 if (auto *OldFD = dyn_cast<FunctionDecl>(OldND->getUnderlyingDecl()))9949 NoteOverloadCandidate(OldND, OldFD, CRK_None, FD->getType(), false);9950 }9951 FailedCandidates.NoteCandidates(*this, FD->getLocation());9952 return true;9953 }9954 9955 // Find the most specialized function template.9956 UnresolvedSetIterator Result = getMostSpecialized(9957 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),9958 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),9959 PDiag(diag::err_function_template_spec_ambiguous)9960 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),9961 PDiag(diag::note_function_template_spec_matched));9962 9963 if (Result == Candidates.end())9964 return true;9965 9966 // Ignore access information; it doesn't figure into redeclaration checking.9967 FunctionDecl *Specialization = cast<FunctionDecl>(*Result);9968 9969 if (const auto *PT = Specialization->getPrimaryTemplate();9970 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {9971 auto Message = DSA->getMessage();9972 Diag(FD->getLocation(), diag::warn_invalid_specialization)9973 << PT << !Message.empty() << Message;9974 Diag(DSA->getLoc(), diag::note_marked_here) << DSA;9975 }9976 9977 // C++23 [except.spec]p13:9978 // An exception specification is considered to be needed when:9979 // - [...]9980 // - the exception specification is compared to that of another declaration9981 // (e.g., an explicit specialization or an overriding virtual function);9982 // - [...]9983 //9984 // The exception specification of a defaulted function is evaluated as9985 // described above only when needed; similarly, the noexcept-specifier of a9986 // specialization of a function template or member function of a class9987 // template is instantiated only when needed.9988 //9989 // The standard doesn't specify what the "comparison with another declaration"9990 // entails, nor the exact circumstances in which it occurs. Moreover, it does9991 // not state which properties of an explicit specialization must match the9992 // primary template.9993 //9994 // We assume that an explicit specialization must correspond with (per9995 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)9996 // the declaration produced by substitution into the function template.9997 //9998 // Since the determination whether two function declarations correspond does9999 // not consider exception specification, we only need to instantiate it once10000 // we determine the primary template when comparing types per10001 // [basic.link]p11.1.10002 auto *SpecializationFPT =10003 Specialization->getType()->castAs<FunctionProtoType>();10004 // If the function has a dependent exception specification, resolve it after10005 // we have selected the primary template so we can check whether it matches.10006 if (getLangOpts().CPlusPlus17 &&10007 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&10008 !ResolveExceptionSpec(FD->getLocation(), SpecializationFPT))10009 return true;10010 10011 FunctionTemplateSpecializationInfo *SpecInfo10012 = Specialization->getTemplateSpecializationInfo();10013 assert(SpecInfo && "Function template specialization info missing?");10014 10015 // Note: do not overwrite location info if previous template10016 // specialization kind was explicit.10017 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();10018 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {10019 Specialization->setLocation(FD->getLocation());10020 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());10021 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr10022 // function can differ from the template declaration with respect to10023 // the constexpr specifier.10024 // FIXME: We need an update record for this AST mutation.10025 // FIXME: What if there are multiple such prior declarations (for instance,10026 // from different modules)?10027 Specialization->setConstexprKind(FD->getConstexprKind());10028 }10029 10030 // FIXME: Check if the prior specialization has a point of instantiation.10031 // If so, we have run afoul of .10032 10033 // If this is a friend declaration, then we're not really declaring10034 // an explicit specialization.10035 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);10036 10037 // Check the scope of this explicit specialization.10038 if (!isFriend &&10039 CheckTemplateSpecializationScope(*this,10040 Specialization->getPrimaryTemplate(),10041 Specialization, FD->getLocation(),10042 false))10043 return true;10044 10045 // C++ [temp.expl.spec]p6:10046 // If a template, a member template or the member of a class template is10047 // explicitly specialized then that specialization shall be declared10048 // before the first use of that specialization that would cause an implicit10049 // instantiation to take place, in every translation unit in which such a10050 // use occurs; no diagnostic is required.10051 bool HasNoEffect = false;10052 if (!isFriend &&10053 CheckSpecializationInstantiationRedecl(FD->getLocation(),10054 TSK_ExplicitSpecialization,10055 Specialization,10056 SpecInfo->getTemplateSpecializationKind(),10057 SpecInfo->getPointOfInstantiation(),10058 HasNoEffect))10059 return true;10060 10061 // Mark the prior declaration as an explicit specialization, so that later10062 // clients know that this is an explicit specialization.10063 // A dependent friend specialization which has a definition should be treated10064 // as explicit specialization, despite being invalid.10065 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();10066 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {10067 // Since explicit specializations do not inherit '=delete' from their10068 // primary function template - check if the 'specialization' that was10069 // implicitly generated (during template argument deduction for partial10070 // ordering) from the most specialized of all the function templates that10071 // 'FD' could have been specializing, has a 'deleted' definition. If so,10072 // first check that it was implicitly generated during template argument10073 // deduction by making sure it wasn't referenced, and then reset the deleted10074 // flag to not-deleted, so that we can inherit that information from 'FD'.10075 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&10076 !Specialization->getCanonicalDecl()->isReferenced()) {10077 // FIXME: This assert will not hold in the presence of modules.10078 assert(10079 Specialization->getCanonicalDecl() == Specialization &&10080 "This must be the only existing declaration of this specialization");10081 // FIXME: We need an update record for this AST mutation.10082 Specialization->setDeletedAsWritten(false);10083 }10084 // FIXME: We need an update record for this AST mutation.10085 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);10086 MarkUnusedFileScopedDecl(Specialization);10087 }10088 10089 // Turn the given function declaration into a function template10090 // specialization, with the template arguments from the previous10091 // specialization.10092 // Take copies of (semantic and syntactic) template argument lists.10093 TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy(10094 Context, Specialization->getTemplateSpecializationArgs()->asArray());10095 FD->setFunctionTemplateSpecialization(10096 Specialization->getPrimaryTemplate(), TemplArgs, /*InsertPos=*/nullptr,10097 SpecInfo->getTemplateSpecializationKind(),10098 ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);10099 10100 // A function template specialization inherits the target attributes10101 // of its template. (We require the attributes explicitly in the10102 // code to match, but a template may have implicit attributes by10103 // virtue e.g. of being constexpr, and it passes these implicit10104 // attributes on to its specializations.)10105 if (LangOpts.CUDA)10106 CUDA().inheritTargetAttrs(FD, *Specialization->getPrimaryTemplate());10107 10108 // The "previous declaration" for this function template specialization is10109 // the prior function template specialization.10110 Previous.clear();10111 Previous.addDecl(Specialization);10112 return false;10113}10114 10115bool10116Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {10117 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&10118 "Only for non-template members");10119 10120 // Try to find the member we are instantiating.10121 NamedDecl *FoundInstantiation = nullptr;10122 NamedDecl *Instantiation = nullptr;10123 NamedDecl *InstantiatedFrom = nullptr;10124 MemberSpecializationInfo *MSInfo = nullptr;10125 10126 if (Previous.empty()) {10127 // Nowhere to look anyway.10128 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Member)) {10129 UnresolvedSet<8> Candidates;10130 for (NamedDecl *Candidate : Previous) {10131 auto *Method = dyn_cast<CXXMethodDecl>(Candidate->getUnderlyingDecl());10132 // Ignore any candidates that aren't member functions.10133 if (!Method)10134 continue;10135 10136 QualType Adjusted = Function->getType();10137 if (!hasExplicitCallingConv(Adjusted))10138 Adjusted = adjustCCAndNoReturn(Adjusted, Method->getType());10139 // Ignore any candidates with the wrong type.10140 // This doesn't handle deduced return types, but both function10141 // declarations should be undeduced at this point.10142 // FIXME: The exception specification should probably be ignored when10143 // comparing the types.10144 if (!Context.hasSameType(Adjusted, Method->getType()))10145 continue;10146 10147 // Ignore any candidates with unsatisfied constraints.10148 if (ConstraintSatisfaction Satisfaction;10149 Method->getTrailingRequiresClause() &&10150 (CheckFunctionConstraints(Method, Satisfaction,10151 /*UsageLoc=*/Member->getLocation(),10152 /*ForOverloadResolution=*/true) ||10153 !Satisfaction.IsSatisfied))10154 continue;10155 10156 Candidates.addDecl(Candidate);10157 }10158 10159 // If we have no viable candidates left after filtering, we are done.10160 if (Candidates.empty())10161 return false;10162 10163 // Find the function that is more constrained than every other function it10164 // has been compared to.10165 UnresolvedSetIterator Best = Candidates.begin();10166 CXXMethodDecl *BestMethod = nullptr;10167 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();10168 I != E; ++I) {10169 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());10170 if (I == Best ||10171 getMoreConstrainedFunction(Method, BestMethod) == Method) {10172 Best = I;10173 BestMethod = Method;10174 }10175 }10176 10177 FoundInstantiation = *Best;10178 Instantiation = BestMethod;10179 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();10180 MSInfo = BestMethod->getMemberSpecializationInfo();10181 10182 // Make sure the best candidate is more constrained than all of the others.10183 bool Ambiguous = false;10184 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();10185 I != E; ++I) {10186 auto *Method = cast<CXXMethodDecl>(I->getUnderlyingDecl());10187 if (I != Best &&10188 getMoreConstrainedFunction(Method, BestMethod) != BestMethod) {10189 Ambiguous = true;10190 break;10191 }10192 }10193 10194 if (Ambiguous) {10195 Diag(Member->getLocation(), diag::err_function_member_spec_ambiguous)10196 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);10197 for (NamedDecl *Candidate : Candidates) {10198 Candidate = Candidate->getUnderlyingDecl();10199 Diag(Candidate->getLocation(), diag::note_function_member_spec_matched)10200 << Candidate;10201 }10202 return true;10203 }10204 } else if (isa<VarDecl>(Member)) {10205 VarDecl *PrevVar;10206 if (Previous.isSingleResult() &&10207 (PrevVar = dyn_cast<VarDecl>(Previous.getFoundDecl())))10208 if (PrevVar->isStaticDataMember()) {10209 FoundInstantiation = Previous.getRepresentativeDecl();10210 Instantiation = PrevVar;10211 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();10212 MSInfo = PrevVar->getMemberSpecializationInfo();10213 }10214 } else if (isa<RecordDecl>(Member)) {10215 CXXRecordDecl *PrevRecord;10216 if (Previous.isSingleResult() &&10217 (PrevRecord = dyn_cast<CXXRecordDecl>(Previous.getFoundDecl()))) {10218 FoundInstantiation = Previous.getRepresentativeDecl();10219 Instantiation = PrevRecord;10220 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();10221 MSInfo = PrevRecord->getMemberSpecializationInfo();10222 }10223 } else if (isa<EnumDecl>(Member)) {10224 EnumDecl *PrevEnum;10225 if (Previous.isSingleResult() &&10226 (PrevEnum = dyn_cast<EnumDecl>(Previous.getFoundDecl()))) {10227 FoundInstantiation = Previous.getRepresentativeDecl();10228 Instantiation = PrevEnum;10229 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();10230 MSInfo = PrevEnum->getMemberSpecializationInfo();10231 }10232 }10233 10234 if (!Instantiation) {10235 // There is no previous declaration that matches. Since member10236 // specializations are always out-of-line, the caller will complain about10237 // this mismatch later.10238 return false;10239 }10240 10241 // A member specialization in a friend declaration isn't really declaring10242 // an explicit specialization, just identifying a specific (possibly implicit)10243 // specialization. Don't change the template specialization kind.10244 //10245 // FIXME: Is this really valid? Other compilers reject.10246 if (Member->getFriendObjectKind() != Decl::FOK_None) {10247 // Preserve instantiation information.10248 if (InstantiatedFrom && isa<CXXMethodDecl>(Member)) {10249 cast<CXXMethodDecl>(Member)->setInstantiationOfMemberFunction(10250 cast<CXXMethodDecl>(InstantiatedFrom),10251 cast<CXXMethodDecl>(Instantiation)->getTemplateSpecializationKind());10252 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Member)) {10253 cast<CXXRecordDecl>(Member)->setInstantiationOfMemberClass(10254 cast<CXXRecordDecl>(InstantiatedFrom),10255 cast<CXXRecordDecl>(Instantiation)->getTemplateSpecializationKind());10256 }10257 10258 Previous.clear();10259 Previous.addDecl(FoundInstantiation);10260 return false;10261 }10262 10263 // Make sure that this is a specialization of a member.10264 if (!InstantiatedFrom) {10265 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)10266 << Member;10267 Diag(Instantiation->getLocation(), diag::note_specialized_decl);10268 return true;10269 }10270 10271 // C++ [temp.expl.spec]p6:10272 // If a template, a member template or the member of a class template is10273 // explicitly specialized then that specialization shall be declared10274 // before the first use of that specialization that would cause an implicit10275 // instantiation to take place, in every translation unit in which such a10276 // use occurs; no diagnostic is required.10277 assert(MSInfo && "Member specialization info missing?");10278 10279 bool HasNoEffect = false;10280 if (CheckSpecializationInstantiationRedecl(Member->getLocation(),10281 TSK_ExplicitSpecialization,10282 Instantiation,10283 MSInfo->getTemplateSpecializationKind(),10284 MSInfo->getPointOfInstantiation(),10285 HasNoEffect))10286 return true;10287 10288 // Check the scope of this explicit specialization.10289 if (CheckTemplateSpecializationScope(*this,10290 InstantiatedFrom,10291 Instantiation, Member->getLocation(),10292 false))10293 return true;10294 10295 // Note that this member specialization is an "instantiation of" the10296 // corresponding member of the original template.10297 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Member)) {10298 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Instantiation);10299 if (InstantiationFunction->getTemplateSpecializationKind() ==10300 TSK_ImplicitInstantiation) {10301 // Explicit specializations of member functions of class templates do not10302 // inherit '=delete' from the member function they are specializing.10303 if (InstantiationFunction->isDeleted()) {10304 // FIXME: This assert will not hold in the presence of modules.10305 assert(InstantiationFunction->getCanonicalDecl() ==10306 InstantiationFunction);10307 // FIXME: We need an update record for this AST mutation.10308 InstantiationFunction->setDeletedAsWritten(false);10309 }10310 }10311 10312 MemberFunction->setInstantiationOfMemberFunction(10313 cast<CXXMethodDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);10314 } else if (auto *MemberVar = dyn_cast<VarDecl>(Member)) {10315 MemberVar->setInstantiationOfStaticDataMember(10316 cast<VarDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);10317 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Member)) {10318 MemberClass->setInstantiationOfMemberClass(10319 cast<CXXRecordDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);10320 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Member)) {10321 MemberEnum->setInstantiationOfMemberEnum(10322 cast<EnumDecl>(InstantiatedFrom), TSK_ExplicitSpecialization);10323 } else {10324 llvm_unreachable("unknown member specialization kind");10325 }10326 10327 // Save the caller the trouble of having to figure out which declaration10328 // this specialization matches.10329 Previous.clear();10330 Previous.addDecl(FoundInstantiation);10331 return false;10332}10333 10334/// Complete the explicit specialization of a member of a class template by10335/// updating the instantiated member to be marked as an explicit specialization.10336///10337/// \param OrigD The member declaration instantiated from the template.10338/// \param Loc The location of the explicit specialization of the member.10339template<typename DeclT>10340static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,10341 SourceLocation Loc) {10342 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)10343 return;10344 10345 // FIXME: Inform AST mutation listeners of this AST mutation.10346 // FIXME: If there are multiple in-class declarations of the member (from10347 // multiple modules, or a declaration and later definition of a member type),10348 // should we update all of them?10349 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);10350 OrigD->setLocation(Loc);10351}10352 10353void Sema::CompleteMemberSpecialization(NamedDecl *Member,10354 LookupResult &Previous) {10355 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());10356 if (Instantiation == Member)10357 return;10358 10359 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))10360 completeMemberSpecializationImpl(*this, Function, Member->getLocation());10361 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))10362 completeMemberSpecializationImpl(*this, Var, Member->getLocation());10363 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))10364 completeMemberSpecializationImpl(*this, Record, Member->getLocation());10365 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))10366 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());10367 else10368 llvm_unreachable("unknown member specialization kind");10369}10370 10371/// Check the scope of an explicit instantiation.10372///10373/// \returns true if a serious error occurs, false otherwise.10374static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,10375 SourceLocation InstLoc,10376 bool WasQualifiedName) {10377 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();10378 DeclContext *CurContext = S.CurContext->getRedeclContext();10379 10380 if (CurContext->isRecord()) {10381 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)10382 << D;10383 return true;10384 }10385 10386 // C++11 [temp.explicit]p3:10387 // An explicit instantiation shall appear in an enclosing namespace of its10388 // template. If the name declared in the explicit instantiation is an10389 // unqualified name, the explicit instantiation shall appear in the10390 // namespace where its template is declared or, if that namespace is inline10391 // (7.3.1), any namespace from its enclosing namespace set.10392 //10393 // This is DR275, which we do not retroactively apply to C++98/03.10394 if (WasQualifiedName) {10395 if (CurContext->Encloses(OrigContext))10396 return false;10397 } else {10398 if (CurContext->InEnclosingNamespaceSetOf(OrigContext))10399 return false;10400 }10401 10402 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(OrigContext)) {10403 if (WasQualifiedName)10404 S.Diag(InstLoc,10405 S.getLangOpts().CPlusPlus11?10406 diag::err_explicit_instantiation_out_of_scope :10407 diag::warn_explicit_instantiation_out_of_scope_0x)10408 << D << NS;10409 else10410 S.Diag(InstLoc,10411 S.getLangOpts().CPlusPlus11?10412 diag::err_explicit_instantiation_unqualified_wrong_namespace :10413 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)10414 << D << NS;10415 } else10416 S.Diag(InstLoc,10417 S.getLangOpts().CPlusPlus11?10418 diag::err_explicit_instantiation_must_be_global :10419 diag::warn_explicit_instantiation_must_be_global_0x)10420 << D;10421 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);10422 return false;10423}10424 10425/// Common checks for whether an explicit instantiation of \p D is valid.10426static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,10427 SourceLocation InstLoc,10428 bool WasQualifiedName,10429 TemplateSpecializationKind TSK) {10430 // C++ [temp.explicit]p13:10431 // An explicit instantiation declaration shall not name a specialization of10432 // a template with internal linkage.10433 if (TSK == TSK_ExplicitInstantiationDeclaration &&10434 D->getFormalLinkage() == Linkage::Internal) {10435 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;10436 return true;10437 }10438 10439 // C++11 [temp.explicit]p3: [DR 275]10440 // An explicit instantiation shall appear in an enclosing namespace of its10441 // template.10442 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))10443 return true;10444 10445 return false;10446}10447 10448/// Determine whether the given scope specifier has a template-id in it.10449static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {10450 // C++11 [temp.explicit]p3:10451 // If the explicit instantiation is for a member function, a member class10452 // or a static data member of a class template specialization, the name of10453 // the class template specialization in the qualified-id for the member10454 // name shall be a simple-template-id.10455 //10456 // C++98 has the same restriction, just worded differently.10457 for (NestedNameSpecifier NNS = SS.getScopeRep();10458 NNS.getKind() == NestedNameSpecifier::Kind::Type;10459 /**/) {10460 const Type *T = NNS.getAsType();10461 if (isa<TemplateSpecializationType>(T))10462 return true;10463 NNS = T->getPrefix();10464 }10465 return false;10466}10467 10468/// Make a dllexport or dllimport attr on a class template specialization take10469/// effect.10470static void dllExportImportClassTemplateSpecialization(10471 Sema &S, ClassTemplateSpecializationDecl *Def) {10472 auto *A = cast_or_null<InheritableAttr>(getDLLAttr(Def));10473 assert(A && "dllExportImportClassTemplateSpecialization called "10474 "on Def without dllexport or dllimport");10475 10476 // We reject explicit instantiations in class scope, so there should10477 // never be any delayed exported classes to worry about.10478 assert(S.DelayedDllExportClasses.empty() &&10479 "delayed exports present at explicit instantiation");10480 S.checkClassLevelDLLAttribute(Def);10481 10482 // Propagate attribute to base class templates.10483 for (auto &B : Def->bases()) {10484 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(10485 B.getType()->getAsCXXRecordDecl()))10486 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());10487 }10488 10489 S.referenceDLLExportedClassMethods();10490}10491 10492DeclResult Sema::ActOnExplicitInstantiation(10493 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,10494 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,10495 TemplateTy TemplateD, SourceLocation TemplateNameLoc,10496 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,10497 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {10498 // Find the class template we're specializing10499 TemplateName Name = TemplateD.get();10500 TemplateDecl *TD = Name.getAsTemplateDecl();10501 // Check that the specialization uses the same tag kind as the10502 // original template.10503 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);10504 assert(Kind != TagTypeKind::Enum &&10505 "Invalid enum tag in class template explicit instantiation!");10506 10507 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(TD);10508 10509 if (!ClassTemplate) {10510 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);10511 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag) << TD << NTK << Kind;10512 Diag(TD->getLocation(), diag::note_previous_use);10513 return true;10514 }10515 10516 if (!isAcceptableTagRedeclaration(ClassTemplate->getTemplatedDecl(),10517 Kind, /*isDefinition*/false, KWLoc,10518 ClassTemplate->getIdentifier())) {10519 Diag(KWLoc, diag::err_use_with_wrong_tag)10520 << ClassTemplate10521 << FixItHint::CreateReplacement(KWLoc,10522 ClassTemplate->getTemplatedDecl()->getKindName());10523 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),10524 diag::note_previous_use);10525 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();10526 }10527 10528 // C++0x [temp.explicit]p2:10529 // There are two forms of explicit instantiation: an explicit instantiation10530 // definition and an explicit instantiation declaration. An explicit10531 // instantiation declaration begins with the extern keyword. [...]10532 TemplateSpecializationKind TSK = ExternLoc.isInvalid()10533 ? TSK_ExplicitInstantiationDefinition10534 : TSK_ExplicitInstantiationDeclaration;10535 10536 if (TSK == TSK_ExplicitInstantiationDeclaration &&10537 !Context.getTargetInfo().getTriple().isOSCygMing()) {10538 // Check for dllexport class template instantiation declarations,10539 // except for MinGW mode.10540 for (const ParsedAttr &AL : Attr) {10541 if (AL.getKind() == ParsedAttr::AT_DLLExport) {10542 Diag(ExternLoc,10543 diag::warn_attribute_dllexport_explicit_instantiation_decl);10544 Diag(AL.getLoc(), diag::note_attribute);10545 break;10546 }10547 }10548 10549 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {10550 Diag(ExternLoc,10551 diag::warn_attribute_dllexport_explicit_instantiation_decl);10552 Diag(A->getLocation(), diag::note_attribute);10553 }10554 }10555 10556 // In MSVC mode, dllimported explicit instantiation definitions are treated as10557 // instantiation declarations for most purposes.10558 bool DLLImportExplicitInstantiationDef = false;10559 if (TSK == TSK_ExplicitInstantiationDefinition &&10560 Context.getTargetInfo().getCXXABI().isMicrosoft()) {10561 // Check for dllimport class template instantiation definitions.10562 bool DLLImport =10563 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();10564 for (const ParsedAttr &AL : Attr) {10565 if (AL.getKind() == ParsedAttr::AT_DLLImport)10566 DLLImport = true;10567 if (AL.getKind() == ParsedAttr::AT_DLLExport) {10568 // dllexport trumps dllimport here.10569 DLLImport = false;10570 break;10571 }10572 }10573 if (DLLImport) {10574 TSK = TSK_ExplicitInstantiationDeclaration;10575 DLLImportExplicitInstantiationDef = true;10576 }10577 }10578 10579 // Translate the parser's template argument list in our AST format.10580 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);10581 translateTemplateArguments(TemplateArgsIn, TemplateArgs);10582 10583 // Check that the template argument list is well-formed for this10584 // template.10585 CheckTemplateArgumentInfo CTAI;10586 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,10587 /*DefaultArgs=*/{}, false, CTAI,10588 /*UpdateArgsWithConversions=*/true,10589 /*ConstraintsNotSatisfied=*/nullptr))10590 return true;10591 10592 // Find the class template specialization declaration that10593 // corresponds to these arguments.10594 void *InsertPos = nullptr;10595 ClassTemplateSpecializationDecl *PrevDecl =10596 ClassTemplate->findSpecialization(CTAI.CanonicalConverted, InsertPos);10597 10598 TemplateSpecializationKind PrevDecl_TSK10599 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;10600 10601 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&10602 Context.getTargetInfo().getTriple().isOSCygMing()) {10603 // Check for dllexport class template instantiation definitions in MinGW10604 // mode, if a previous declaration of the instantiation was seen.10605 for (const ParsedAttr &AL : Attr) {10606 if (AL.getKind() == ParsedAttr::AT_DLLExport) {10607 Diag(AL.getLoc(),10608 diag::warn_attribute_dllexport_explicit_instantiation_def);10609 break;10610 }10611 }10612 }10613 10614 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,10615 SS.isSet(), TSK))10616 return true;10617 10618 ClassTemplateSpecializationDecl *Specialization = nullptr;10619 10620 bool HasNoEffect = false;10621 if (PrevDecl) {10622 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,10623 PrevDecl, PrevDecl_TSK,10624 PrevDecl->getPointOfInstantiation(),10625 HasNoEffect))10626 return PrevDecl;10627 10628 // Even though HasNoEffect == true means that this explicit instantiation10629 // has no effect on semantics, we go on to put its syntax in the AST.10630 10631 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||10632 PrevDecl_TSK == TSK_Undeclared) {10633 // Since the only prior class template specialization with these10634 // arguments was referenced but not declared, reuse that10635 // declaration node as our own, updating the source location10636 // for the template name to reflect our new declaration.10637 // (Other source locations will be updated later.)10638 Specialization = PrevDecl;10639 Specialization->setLocation(TemplateNameLoc);10640 PrevDecl = nullptr;10641 }10642 10643 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&10644 DLLImportExplicitInstantiationDef) {10645 // The new specialization might add a dllimport attribute.10646 HasNoEffect = false;10647 }10648 }10649 10650 if (!Specialization) {10651 // Create a new class template specialization declaration node for10652 // this explicit specialization.10653 Specialization = ClassTemplateSpecializationDecl::Create(10654 Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,10655 ClassTemplate, CTAI.CanonicalConverted, CTAI.StrictPackMatch, PrevDecl);10656 SetNestedNameSpecifier(*this, Specialization, SS);10657 10658 // A MSInheritanceAttr attached to the previous declaration must be10659 // propagated to the new node prior to instantiation.10660 if (PrevDecl) {10661 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {10662 auto *Clone = A->clone(getASTContext());10663 Clone->setInherited(true);10664 Specialization->addAttr(Clone);10665 Consumer.AssignInheritanceModel(Specialization);10666 }10667 }10668 10669 if (!HasNoEffect && !PrevDecl) {10670 // Insert the new specialization.10671 ClassTemplate->AddSpecialization(Specialization, InsertPos);10672 }10673 }10674 10675 Specialization->setTemplateArgsAsWritten(TemplateArgs);10676 10677 // Set source locations for keywords.10678 Specialization->setExternKeywordLoc(ExternLoc);10679 Specialization->setTemplateKeywordLoc(TemplateLoc);10680 Specialization->setBraceRange(SourceRange());10681 10682 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();10683 ProcessDeclAttributeList(S, Specialization, Attr);10684 ProcessAPINotes(Specialization);10685 10686 // Add the explicit instantiation into its lexical context. However,10687 // since explicit instantiations are never found by name lookup, we10688 // just put it into the declaration context directly.10689 Specialization->setLexicalDeclContext(CurContext);10690 CurContext->addDecl(Specialization);10691 10692 // Syntax is now OK, so return if it has no other effect on semantics.10693 if (HasNoEffect) {10694 // Set the template specialization kind.10695 Specialization->setTemplateSpecializationKind(TSK);10696 return Specialization;10697 }10698 10699 // C++ [temp.explicit]p3:10700 // A definition of a class template or class member template10701 // shall be in scope at the point of the explicit instantiation of10702 // the class template or class member template.10703 //10704 // This check comes when we actually try to perform the10705 // instantiation.10706 ClassTemplateSpecializationDecl *Def10707 = cast_or_null<ClassTemplateSpecializationDecl>(10708 Specialization->getDefinition());10709 if (!Def)10710 InstantiateClassTemplateSpecialization(TemplateNameLoc, Specialization, TSK,10711 /*Complain=*/true,10712 CTAI.StrictPackMatch);10713 else if (TSK == TSK_ExplicitInstantiationDefinition) {10714 MarkVTableUsed(TemplateNameLoc, Specialization, true);10715 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());10716 }10717 10718 // Instantiate the members of this class template specialization.10719 Def = cast_or_null<ClassTemplateSpecializationDecl>(10720 Specialization->getDefinition());10721 if (Def) {10722 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();10723 // Fix a TSK_ExplicitInstantiationDeclaration followed by a10724 // TSK_ExplicitInstantiationDefinition10725 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&10726 (TSK == TSK_ExplicitInstantiationDefinition ||10727 DLLImportExplicitInstantiationDef)) {10728 // FIXME: Need to notify the ASTMutationListener that we did this.10729 Def->setTemplateSpecializationKind(TSK);10730 10731 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&10732 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {10733 // An explicit instantiation definition can add a dll attribute to a10734 // template with a previous instantiation declaration. MinGW doesn't10735 // allow this.10736 auto *A = cast<InheritableAttr>(10737 getDLLAttr(Specialization)->clone(getASTContext()));10738 A->setInherited(true);10739 Def->addAttr(A);10740 dllExportImportClassTemplateSpecialization(*this, Def);10741 }10742 }10743 10744 // Fix a TSK_ImplicitInstantiation followed by a10745 // TSK_ExplicitInstantiationDefinition10746 bool NewlyDLLExported =10747 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();10748 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&10749 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {10750 // An explicit instantiation definition can add a dll attribute to a10751 // template with a previous implicit instantiation. MinGW doesn't allow10752 // this. We limit clang to only adding dllexport, to avoid potentially10753 // strange codegen behavior. For example, if we extend this conditional10754 // to dllimport, and we have a source file calling a method on an10755 // implicitly instantiated template class instance and then declaring a10756 // dllimport explicit instantiation definition for the same template10757 // class, the codegen for the method call will not respect the dllimport,10758 // while it will with cl. The Def will already have the DLL attribute,10759 // since the Def and Specialization will be the same in the case of10760 // Old_TSK == TSK_ImplicitInstantiation, and we already added the10761 // attribute to the Specialization; we just need to make it take effect.10762 assert(Def == Specialization &&10763 "Def and Specialization should match for implicit instantiation");10764 dllExportImportClassTemplateSpecialization(*this, Def);10765 }10766 10767 // In MinGW mode, export the template instantiation if the declaration10768 // was marked dllexport.10769 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&10770 Context.getTargetInfo().getTriple().isOSCygMing() &&10771 PrevDecl->hasAttr<DLLExportAttr>()) {10772 dllExportImportClassTemplateSpecialization(*this, Def);10773 }10774 10775 // Set the template specialization kind. Make sure it is set before10776 // instantiating the members which will trigger ASTConsumer callbacks.10777 Specialization->setTemplateSpecializationKind(TSK);10778 InstantiateClassTemplateSpecializationMembers(TemplateNameLoc, Def, TSK);10779 } else {10780 10781 // Set the template specialization kind.10782 Specialization->setTemplateSpecializationKind(TSK);10783 }10784 10785 return Specialization;10786}10787 10788DeclResult10789Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,10790 SourceLocation TemplateLoc, unsigned TagSpec,10791 SourceLocation KWLoc, CXXScopeSpec &SS,10792 IdentifierInfo *Name, SourceLocation NameLoc,10793 const ParsedAttributesView &Attr) {10794 10795 bool Owned = false;10796 bool IsDependent = false;10797 Decl *TagD =10798 ActOnTag(S, TagSpec, TagUseKind::Reference, KWLoc, SS, Name, NameLoc,10799 Attr, AS_none, /*ModulePrivateLoc=*/SourceLocation(),10800 MultiTemplateParamsArg(), Owned, IsDependent, SourceLocation(),10801 false, TypeResult(), /*IsTypeSpecifier*/ false,10802 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)10803 .get();10804 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");10805 10806 if (!TagD)10807 return true;10808 10809 TagDecl *Tag = cast<TagDecl>(TagD);10810 assert(!Tag->isEnum() && "shouldn't see enumerations here");10811 10812 if (Tag->isInvalidDecl())10813 return true;10814 10815 CXXRecordDecl *Record = cast<CXXRecordDecl>(Tag);10816 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();10817 if (!Pattern) {10818 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)10819 << Context.getCanonicalTagType(Record);10820 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);10821 return true;10822 }10823 10824 // C++0x [temp.explicit]p2:10825 // If the explicit instantiation is for a class or member class, the10826 // elaborated-type-specifier in the declaration shall include a10827 // simple-template-id.10828 //10829 // C++98 has the same restriction, just worded differently.10830 if (!ScopeSpecifierHasTemplateId(SS))10831 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)10832 << Record << SS.getRange();10833 10834 // C++0x [temp.explicit]p2:10835 // There are two forms of explicit instantiation: an explicit instantiation10836 // definition and an explicit instantiation declaration. An explicit10837 // instantiation declaration begins with the extern keyword. [...]10838 TemplateSpecializationKind TSK10839 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition10840 : TSK_ExplicitInstantiationDeclaration;10841 10842 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);10843 10844 // Verify that it is okay to explicitly instantiate here.10845 CXXRecordDecl *PrevDecl10846 = cast_or_null<CXXRecordDecl>(Record->getPreviousDecl());10847 if (!PrevDecl && Record->getDefinition())10848 PrevDecl = Record;10849 if (PrevDecl) {10850 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();10851 bool HasNoEffect = false;10852 assert(MSInfo && "No member specialization information?");10853 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,10854 PrevDecl,10855 MSInfo->getTemplateSpecializationKind(),10856 MSInfo->getPointOfInstantiation(),10857 HasNoEffect))10858 return true;10859 if (HasNoEffect)10860 return TagD;10861 }10862 10863 CXXRecordDecl *RecordDef10864 = cast_or_null<CXXRecordDecl>(Record->getDefinition());10865 if (!RecordDef) {10866 // C++ [temp.explicit]p3:10867 // A definition of a member class of a class template shall be in scope10868 // at the point of an explicit instantiation of the member class.10869 CXXRecordDecl *Def10870 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());10871 if (!Def) {10872 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)10873 << 0 << Record->getDeclName() << Record->getDeclContext();10874 Diag(Pattern->getLocation(), diag::note_forward_declaration)10875 << Pattern;10876 return true;10877 } else {10878 if (InstantiateClass(NameLoc, Record, Def,10879 getTemplateInstantiationArgs(Record),10880 TSK))10881 return true;10882 10883 RecordDef = cast_or_null<CXXRecordDecl>(Record->getDefinition());10884 if (!RecordDef)10885 return true;10886 }10887 }10888 10889 // Instantiate all of the members of the class.10890 InstantiateClassMembers(NameLoc, RecordDef,10891 getTemplateInstantiationArgs(Record), TSK);10892 10893 if (TSK == TSK_ExplicitInstantiationDefinition)10894 MarkVTableUsed(NameLoc, RecordDef, true);10895 10896 // FIXME: We don't have any representation for explicit instantiations of10897 // member classes. Such a representation is not needed for compilation, but it10898 // should be available for clients that want to see all of the declarations in10899 // the source code.10900 return TagD;10901}10902 10903DeclResult Sema::ActOnExplicitInstantiation(Scope *S,10904 SourceLocation ExternLoc,10905 SourceLocation TemplateLoc,10906 Declarator &D) {10907 // Explicit instantiations always require a name.10908 // TODO: check if/when DNInfo should replace Name.10909 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);10910 DeclarationName Name = NameInfo.getName();10911 if (!Name) {10912 if (!D.isInvalidType())10913 Diag(D.getDeclSpec().getBeginLoc(),10914 diag::err_explicit_instantiation_requires_name)10915 << D.getDeclSpec().getSourceRange() << D.getSourceRange();10916 10917 return true;10918 }10919 10920 // Get the innermost enclosing declaration scope.10921 S = S->getDeclParent();10922 10923 // Determine the type of the declaration.10924 TypeSourceInfo *T = GetTypeForDeclarator(D);10925 QualType R = T->getType();10926 if (R.isNull())10927 return true;10928 10929 // C++ [dcl.stc]p1:10930 // A storage-class-specifier shall not be specified in [...] an explicit10931 // instantiation (14.7.2) directive.10932 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {10933 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)10934 << Name;10935 return true;10936 } else if (D.getDeclSpec().getStorageClassSpec()10937 != DeclSpec::SCS_unspecified) {10938 // Complain about then remove the storage class specifier.10939 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)10940 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());10941 10942 D.getMutableDeclSpec().ClearStorageClassSpecs();10943 }10944 10945 // C++0x [temp.explicit]p1:10946 // [...] An explicit instantiation of a function template shall not use the10947 // inline or constexpr specifiers.10948 // Presumably, this also applies to member functions of class templates as10949 // well.10950 if (D.getDeclSpec().isInlineSpecified())10951 Diag(D.getDeclSpec().getInlineSpecLoc(),10952 getLangOpts().CPlusPlus11 ?10953 diag::err_explicit_instantiation_inline :10954 diag::warn_explicit_instantiation_inline_0x)10955 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());10956 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())10957 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is10958 // not already specified.10959 Diag(D.getDeclSpec().getConstexprSpecLoc(),10960 diag::err_explicit_instantiation_constexpr);10961 10962 // A deduction guide is not on the list of entities that can be explicitly10963 // instantiated.10964 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {10965 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)10966 << /*explicit instantiation*/ 0;10967 return true;10968 }10969 10970 // C++0x [temp.explicit]p2:10971 // There are two forms of explicit instantiation: an explicit instantiation10972 // definition and an explicit instantiation declaration. An explicit10973 // instantiation declaration begins with the extern keyword. [...]10974 TemplateSpecializationKind TSK10975 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition10976 : TSK_ExplicitInstantiationDeclaration;10977 10978 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);10979 LookupParsedName(Previous, S, &D.getCXXScopeSpec(),10980 /*ObjectType=*/QualType());10981 10982 if (!R->isFunctionType()) {10983 // C++ [temp.explicit]p1:10984 // A [...] static data member of a class template can be explicitly10985 // instantiated from the member definition associated with its class10986 // template.10987 // C++1y [temp.explicit]p1:10988 // A [...] variable [...] template specialization can be explicitly10989 // instantiated from its template.10990 if (Previous.isAmbiguous())10991 return true;10992 10993 VarDecl *Prev = Previous.getAsSingle<VarDecl>();10994 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();10995 10996 if (!PrevTemplate) {10997 if (!Prev || !Prev->isStaticDataMember()) {10998 // We expect to see a static data member here.10999 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)11000 << Name;11001 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();11002 P != PEnd; ++P)11003 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);11004 return true;11005 }11006 11007 if (!Prev->getInstantiatedFromStaticDataMember()) {11008 // FIXME: Check for explicit specialization?11009 Diag(D.getIdentifierLoc(),11010 diag::err_explicit_instantiation_data_member_not_instantiated)11011 << Prev;11012 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);11013 // FIXME: Can we provide a note showing where this was declared?11014 return true;11015 }11016 } else {11017 // Explicitly instantiate a variable template.11018 11019 // C++1y [dcl.spec.auto]p6:11020 // ... A program that uses auto or decltype(auto) in a context not11021 // explicitly allowed in this section is ill-formed.11022 //11023 // This includes auto-typed variable template instantiations.11024 if (R->isUndeducedType()) {11025 Diag(T->getTypeLoc().getBeginLoc(),11026 diag::err_auto_not_allowed_var_inst);11027 return true;11028 }11029 11030 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {11031 // C++1y [temp.explicit]p3:11032 // If the explicit instantiation is for a variable, the unqualified-id11033 // in the declaration shall be a template-id.11034 Diag(D.getIdentifierLoc(),11035 diag::err_explicit_instantiation_without_template_id)11036 << PrevTemplate;11037 Diag(PrevTemplate->getLocation(),11038 diag::note_explicit_instantiation_here);11039 return true;11040 }11041 11042 // Translate the parser's template argument list into our AST format.11043 TemplateArgumentListInfo TemplateArgs =11044 makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);11045 11046 DeclResult Res =11047 CheckVarTemplateId(PrevTemplate, TemplateLoc, D.getIdentifierLoc(),11048 TemplateArgs, /*SetWrittenArgs=*/true);11049 if (Res.isInvalid())11050 return true;11051 11052 if (!Res.isUsable()) {11053 // We somehow specified dependent template arguments in an explicit11054 // instantiation. This should probably only happen during error11055 // recovery.11056 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);11057 return true;11058 }11059 11060 // Ignore access control bits, we don't need them for redeclaration11061 // checking.11062 Prev = cast<VarDecl>(Res.get());11063 }11064 11065 // C++0x [temp.explicit]p2:11066 // If the explicit instantiation is for a member function, a member class11067 // or a static data member of a class template specialization, the name of11068 // the class template specialization in the qualified-id for the member11069 // name shall be a simple-template-id.11070 //11071 // C++98 has the same restriction, just worded differently.11072 //11073 // This does not apply to variable template specializations, where the11074 // template-id is in the unqualified-id instead.11075 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)11076 Diag(D.getIdentifierLoc(),11077 diag::ext_explicit_instantiation_without_qualified_id)11078 << Prev << D.getCXXScopeSpec().getRange();11079 11080 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);11081 11082 // Verify that it is okay to explicitly instantiate here.11083 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();11084 SourceLocation POI = Prev->getPointOfInstantiation();11085 bool HasNoEffect = false;11086 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,11087 PrevTSK, POI, HasNoEffect))11088 return true;11089 11090 if (!HasNoEffect) {11091 // Instantiate static data member or variable template.11092 Prev->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());11093 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Prev)) {11094 VTSD->setExternKeywordLoc(ExternLoc);11095 VTSD->setTemplateKeywordLoc(TemplateLoc);11096 }11097 11098 // Merge attributes.11099 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());11100 if (PrevTemplate)11101 ProcessAPINotes(Prev);11102 11103 if (TSK == TSK_ExplicitInstantiationDefinition)11104 InstantiateVariableDefinition(D.getIdentifierLoc(), Prev);11105 }11106 11107 // Check the new variable specialization against the parsed input.11108 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {11109 Diag(T->getTypeLoc().getBeginLoc(),11110 diag::err_invalid_var_template_spec_type)11111 << 0 << PrevTemplate << R << Prev->getType();11112 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)11113 << 2 << PrevTemplate->getDeclName();11114 return true;11115 }11116 11117 // FIXME: Create an ExplicitInstantiation node?11118 return (Decl*) nullptr;11119 }11120 11121 // If the declarator is a template-id, translate the parser's template11122 // argument list into our AST format.11123 bool HasExplicitTemplateArgs = false;11124 TemplateArgumentListInfo TemplateArgs;11125 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {11126 TemplateArgs = makeTemplateArgumentListInfo(*this, *D.getName().TemplateId);11127 HasExplicitTemplateArgs = true;11128 }11129 11130 // C++ [temp.explicit]p1:11131 // A [...] function [...] can be explicitly instantiated from its template.11132 // A member function [...] of a class template can be explicitly11133 // instantiated from the member definition associated with its class11134 // template.11135 UnresolvedSet<8> TemplateMatches;11136 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),11137 OverloadCandidateSet::CSK_Normal);11138 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());11139 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();11140 P != PEnd; ++P) {11141 NamedDecl *Prev = *P;11142 if (!HasExplicitTemplateArgs) {11143 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Prev)) {11144 QualType Adjusted = adjustCCAndNoReturn(R, Method->getType(),11145 /*AdjustExceptionSpec*/true);11146 if (Context.hasSameUnqualifiedType(Method->getType(), Adjusted)) {11147 if (Method->getPrimaryTemplate()) {11148 TemplateMatches.addDecl(Method, P.getAccess());11149 } else {11150 OverloadCandidate &C = NonTemplateMatches.addCandidate();11151 C.FoundDecl = P.getPair();11152 C.Function = Method;11153 C.Viable = true;11154 ConstraintSatisfaction S;11155 if (Method->getTrailingRequiresClause() &&11156 (CheckFunctionConstraints(Method, S, D.getIdentifierLoc(),11157 /*ForOverloadResolution=*/true) ||11158 !S.IsSatisfied)) {11159 C.Viable = false;11160 C.FailureKind = ovl_fail_constraints_not_satisfied;11161 }11162 }11163 }11164 }11165 }11166 11167 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Prev);11168 if (!FunTmpl)11169 continue;11170 11171 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());11172 FunctionDecl *Specialization = nullptr;11173 if (TemplateDeductionResult TDK = DeduceTemplateArguments(11174 FunTmpl, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), R,11175 Specialization, Info);11176 TDK != TemplateDeductionResult::Success) {11177 // Keep track of almost-matches.11178 FailedTemplateCandidates.addCandidate().set(11179 P.getPair(), FunTmpl->getTemplatedDecl(),11180 MakeDeductionFailureInfo(Context, TDK, Info));11181 (void)TDK;11182 continue;11183 }11184 11185 // Target attributes are part of the cuda function signature, so11186 // the cuda target of the instantiated function must match that of its11187 // template. Given that C++ template deduction does not take11188 // target attributes into account, we reject candidates here that11189 // have a different target.11190 if (LangOpts.CUDA &&11191 CUDA().IdentifyTarget(Specialization,11192 /* IgnoreImplicitHDAttr = */ true) !=11193 CUDA().IdentifyTarget(D.getDeclSpec().getAttributes())) {11194 FailedTemplateCandidates.addCandidate().set(11195 P.getPair(), FunTmpl->getTemplatedDecl(),11196 MakeDeductionFailureInfo(11197 Context, TemplateDeductionResult::CUDATargetMismatch, Info));11198 continue;11199 }11200 11201 TemplateMatches.addDecl(Specialization, P.getAccess());11202 }11203 11204 FunctionDecl *Specialization = nullptr;11205 if (!NonTemplateMatches.empty()) {11206 unsigned Msg = 0;11207 OverloadCandidateDisplayKind DisplayKind;11208 OverloadCandidateSet::iterator Best;11209 switch (NonTemplateMatches.BestViableFunction(*this, D.getIdentifierLoc(),11210 Best)) {11211 case OR_Success:11212 case OR_Deleted:11213 Specialization = cast<FunctionDecl>(Best->Function);11214 break;11215 case OR_Ambiguous:11216 Msg = diag::err_explicit_instantiation_ambiguous;11217 DisplayKind = OCD_AmbiguousCandidates;11218 break;11219 case OR_No_Viable_Function:11220 Msg = diag::err_explicit_instantiation_no_candidate;11221 DisplayKind = OCD_AllCandidates;11222 break;11223 }11224 if (Msg) {11225 PartialDiagnostic Diag = PDiag(Msg) << Name;11226 NonTemplateMatches.NoteCandidates(11227 PartialDiagnosticAt(D.getIdentifierLoc(), Diag), *this, DisplayKind,11228 {});11229 return true;11230 }11231 }11232 11233 if (!Specialization) {11234 // Find the most specialized function template specialization.11235 UnresolvedSetIterator Result = getMostSpecialized(11236 TemplateMatches.begin(), TemplateMatches.end(),11237 FailedTemplateCandidates, D.getIdentifierLoc(),11238 PDiag(diag::err_explicit_instantiation_not_known) << Name,11239 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,11240 PDiag(diag::note_explicit_instantiation_candidate));11241 11242 if (Result == TemplateMatches.end())11243 return true;11244 11245 // Ignore access control bits, we don't need them for redeclaration checking.11246 Specialization = cast<FunctionDecl>(*Result);11247 }11248 11249 // C++11 [except.spec]p411250 // In an explicit instantiation an exception-specification may be specified,11251 // but is not required.11252 // If an exception-specification is specified in an explicit instantiation11253 // directive, it shall be compatible with the exception-specifications of11254 // other declarations of that function.11255 if (auto *FPT = R->getAs<FunctionProtoType>())11256 if (FPT->hasExceptionSpec()) {11257 unsigned DiagID =11258 diag::err_mismatched_exception_spec_explicit_instantiation;11259 if (getLangOpts().MicrosoftExt)11260 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;11261 bool Result = CheckEquivalentExceptionSpec(11262 PDiag(DiagID) << Specialization->getType(),11263 PDiag(diag::note_explicit_instantiation_here),11264 Specialization->getType()->getAs<FunctionProtoType>(),11265 Specialization->getLocation(), FPT, D.getBeginLoc());11266 // In Microsoft mode, mismatching exception specifications just cause a11267 // warning.11268 if (!getLangOpts().MicrosoftExt && Result)11269 return true;11270 }11271 11272 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {11273 Diag(D.getIdentifierLoc(),11274 diag::err_explicit_instantiation_member_function_not_instantiated)11275 << Specialization11276 << (Specialization->getTemplateSpecializationKind() ==11277 TSK_ExplicitSpecialization);11278 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);11279 return true;11280 }11281 11282 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();11283 if (!PrevDecl && Specialization->isThisDeclarationADefinition())11284 PrevDecl = Specialization;11285 11286 if (PrevDecl) {11287 bool HasNoEffect = false;11288 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,11289 PrevDecl,11290 PrevDecl->getTemplateSpecializationKind(),11291 PrevDecl->getPointOfInstantiation(),11292 HasNoEffect))11293 return true;11294 11295 // FIXME: We may still want to build some representation of this11296 // explicit specialization.11297 if (HasNoEffect)11298 return (Decl*) nullptr;11299 }11300 11301 // HACK: libc++ has a bug where it attempts to explicitly instantiate the11302 // functions11303 // valarray<size_t>::valarray(size_t) and11304 // valarray<size_t>::~valarray()11305 // that it declared to have internal linkage with the internal_linkage11306 // attribute. Ignore the explicit instantiation declaration in this case.11307 if (Specialization->hasAttr<InternalLinkageAttr>() &&11308 TSK == TSK_ExplicitInstantiationDeclaration) {11309 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))11310 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&11311 RD->isInStdNamespace())11312 return (Decl*) nullptr;11313 }11314 11315 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());11316 ProcessAPINotes(Specialization);11317 11318 // In MSVC mode, dllimported explicit instantiation definitions are treated as11319 // instantiation declarations.11320 if (TSK == TSK_ExplicitInstantiationDefinition &&11321 Specialization->hasAttr<DLLImportAttr>() &&11322 Context.getTargetInfo().getCXXABI().isMicrosoft())11323 TSK = TSK_ExplicitInstantiationDeclaration;11324 11325 Specialization->setTemplateSpecializationKind(TSK, D.getIdentifierLoc());11326 11327 if (Specialization->isDefined()) {11328 // Let the ASTConsumer know that this function has been explicitly11329 // instantiated now, and its linkage might have changed.11330 Consumer.HandleTopLevelDecl(DeclGroupRef(Specialization));11331 } else if (TSK == TSK_ExplicitInstantiationDefinition)11332 InstantiateFunctionDefinition(D.getIdentifierLoc(), Specialization);11333 11334 // C++0x [temp.explicit]p2:11335 // If the explicit instantiation is for a member function, a member class11336 // or a static data member of a class template specialization, the name of11337 // the class template specialization in the qualified-id for the member11338 // name shall be a simple-template-id.11339 //11340 // C++98 has the same restriction, just worded differently.11341 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();11342 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&11343 D.getCXXScopeSpec().isSet() &&11344 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))11345 Diag(D.getIdentifierLoc(),11346 diag::ext_explicit_instantiation_without_qualified_id)11347 << Specialization << D.getCXXScopeSpec().getRange();11348 11349 CheckExplicitInstantiation(11350 *this,11351 FunTmpl ? (NamedDecl *)FunTmpl11352 : Specialization->getInstantiatedFromMemberFunction(),11353 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);11354 11355 // FIXME: Create some kind of ExplicitInstantiationDecl here.11356 return (Decl*) nullptr;11357}11358 11359TypeResult Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,11360 const CXXScopeSpec &SS,11361 const IdentifierInfo *Name,11362 SourceLocation TagLoc,11363 SourceLocation NameLoc) {11364 // This has to hold, because SS is expected to be defined.11365 assert(Name && "Expected a name in a dependent tag");11366 11367 NestedNameSpecifier NNS = SS.getScopeRep();11368 if (!NNS)11369 return true;11370 11371 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);11372 11373 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {11374 Diag(NameLoc, diag::err_dependent_tag_decl)11375 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();11376 return true;11377 }11378 11379 // Create the resulting type.11380 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Kind);11381 QualType Result = Context.getDependentNameType(Kwd, NNS, Name);11382 11383 // Create type-source location information for this type.11384 TypeLocBuilder TLB;11385 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(Result);11386 TL.setElaboratedKeywordLoc(TagLoc);11387 TL.setQualifierLoc(SS.getWithLocInContext(Context));11388 TL.setNameLoc(NameLoc);11389 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));11390}11391 11392TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,11393 const CXXScopeSpec &SS,11394 const IdentifierInfo &II,11395 SourceLocation IdLoc,11396 ImplicitTypenameContext IsImplicitTypename) {11397 if (SS.isInvalid())11398 return true;11399 11400 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())11401 DiagCompat(TypenameLoc, diag_compat::typename_outside_of_template)11402 << FixItHint::CreateRemoval(TypenameLoc);11403 11404 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);11405 TypeSourceInfo *TSI = nullptr;11406 QualType T =11407 CheckTypenameType(TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename11408 : ElaboratedTypeKeyword::None,11409 TypenameLoc, QualifierLoc, II, IdLoc, &TSI,11410 /*DeducedTSTContext=*/true);11411 if (T.isNull())11412 return true;11413 return CreateParsedType(T, TSI);11414}11415 11416TypeResult11417Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,11418 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,11419 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,11420 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,11421 ASTTemplateArgsPtr TemplateArgsIn,11422 SourceLocation RAngleLoc) {11423 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())11424 Diag(TypenameLoc, getLangOpts().CPlusPlus1111425 ? diag::compat_cxx11_typename_outside_of_template11426 : diag::compat_pre_cxx11_typename_outside_of_template)11427 << FixItHint::CreateRemoval(TypenameLoc);11428 11429 // Strangely, non-type results are not ignored by this lookup, so the11430 // program is ill-formed if it finds an injected-class-name.11431 if (TypenameLoc.isValid()) {11432 auto *LookupRD =11433 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, false));11434 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {11435 Diag(TemplateIILoc,11436 diag::ext_out_of_line_qualified_id_type_names_constructor)11437 << TemplateII << 0 /*injected-class-name used as template name*/11438 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);11439 }11440 }11441 11442 // Translate the parser's template argument list in our AST format.11443 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);11444 translateTemplateArguments(TemplateArgsIn, TemplateArgs);11445 11446 QualType T = CheckTemplateIdType(11447 TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename11448 : ElaboratedTypeKeyword::None,11449 TemplateIn.get(), TemplateIILoc, TemplateArgs,11450 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);11451 if (T.isNull())11452 return true;11453 11454 // Provide source-location information for the template specialization type.11455 TypeLocBuilder Builder;11456 TemplateSpecializationTypeLoc SpecTL11457 = Builder.push<TemplateSpecializationTypeLoc>(T);11458 SpecTL.set(TypenameLoc, SS.getWithLocInContext(Context), TemplateKWLoc,11459 TemplateIILoc, TemplateArgs);11460 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);11461 return CreateParsedType(T, TSI);11462}11463 11464/// Determine whether this failed name lookup should be treated as being11465/// disabled by a usage of std::enable_if.11466static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,11467 SourceRange &CondRange, Expr *&Cond) {11468 // We must be looking for a ::type...11469 if (!II.isStr("type"))11470 return false;11471 11472 // ... within an explicitly-written template specialization...11473 if (NNS.getNestedNameSpecifier().getKind() != NestedNameSpecifier::Kind::Type)11474 return false;11475 11476 // FIXME: Look through sugar.11477 auto EnableIfTSTLoc =11478 NNS.castAsTypeLoc().getAs<TemplateSpecializationTypeLoc>();11479 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)11480 return false;11481 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();11482 11483 // ... which names a complete class template declaration...11484 const TemplateDecl *EnableIfDecl =11485 EnableIfTST->getTemplateName().getAsTemplateDecl();11486 if (!EnableIfDecl || EnableIfTST->isIncompleteType())11487 return false;11488 11489 // ... called "enable_if".11490 const IdentifierInfo *EnableIfII =11491 EnableIfDecl->getDeclName().getAsIdentifierInfo();11492 if (!EnableIfII || !EnableIfII->isStr("enable_if"))11493 return false;11494 11495 // Assume the first template argument is the condition.11496 CondRange = EnableIfTSTLoc.getArgLoc(0).getSourceRange();11497 11498 // Dig out the condition.11499 Cond = nullptr;11500 if (EnableIfTSTLoc.getArgLoc(0).getArgument().getKind()11501 != TemplateArgument::Expression)11502 return true;11503 11504 Cond = EnableIfTSTLoc.getArgLoc(0).getSourceExpression();11505 11506 // Ignore Boolean literals; they add no value.11507 if (isa<CXXBoolLiteralExpr>(Cond->IgnoreParenCasts()))11508 Cond = nullptr;11509 11510 return true;11511}11512 11513QualType11514Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,11515 SourceLocation KeywordLoc,11516 NestedNameSpecifierLoc QualifierLoc,11517 const IdentifierInfo &II,11518 SourceLocation IILoc,11519 TypeSourceInfo **TSI,11520 bool DeducedTSTContext) {11521 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,11522 DeducedTSTContext);11523 if (T.isNull())11524 return QualType();11525 11526 TypeLocBuilder TLB;11527 if (isa<DependentNameType>(T)) {11528 auto TL = TLB.push<DependentNameTypeLoc>(T);11529 TL.setElaboratedKeywordLoc(KeywordLoc);11530 TL.setQualifierLoc(QualifierLoc);11531 TL.setNameLoc(IILoc);11532 } else if (isa<DeducedTemplateSpecializationType>(T)) {11533 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);11534 TL.setElaboratedKeywordLoc(KeywordLoc);11535 TL.setQualifierLoc(QualifierLoc);11536 TL.setNameLoc(IILoc);11537 } else if (isa<TemplateTypeParmType>(T)) {11538 // FIXME: There might be a 'typename' keyword here, but we just drop it11539 // as it can't be represented.11540 assert(!QualifierLoc);11541 TLB.pushTypeSpec(T).setNameLoc(IILoc);11542 } else if (isa<TagType>(T)) {11543 auto TL = TLB.push<TagTypeLoc>(T);11544 TL.setElaboratedKeywordLoc(KeywordLoc);11545 TL.setQualifierLoc(QualifierLoc);11546 TL.setNameLoc(IILoc);11547 } else if (isa<TypedefType>(T)) {11548 TLB.push<TypedefTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);11549 } else {11550 TLB.push<UnresolvedUsingTypeLoc>(T).set(KeywordLoc, QualifierLoc, IILoc);11551 }11552 *TSI = TLB.getTypeSourceInfo(Context, T);11553 return T;11554}11555 11556/// Build the type that describes a C++ typename specifier,11557/// e.g., "typename T::type".11558QualType11559Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,11560 SourceLocation KeywordLoc,11561 NestedNameSpecifierLoc QualifierLoc,11562 const IdentifierInfo &II,11563 SourceLocation IILoc, bool DeducedTSTContext) {11564 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());11565 11566 CXXScopeSpec SS;11567 SS.Adopt(QualifierLoc);11568 11569 DeclContext *Ctx = nullptr;11570 if (QualifierLoc) {11571 Ctx = computeDeclContext(SS);11572 if (!Ctx) {11573 // If the nested-name-specifier is dependent and couldn't be11574 // resolved to a type, build a typename type.11575 assert(QualifierLoc.getNestedNameSpecifier().isDependent());11576 return Context.getDependentNameType(Keyword,11577 QualifierLoc.getNestedNameSpecifier(),11578 &II);11579 }11580 11581 // If the nested-name-specifier refers to the current instantiation,11582 // the "typename" keyword itself is superfluous. In C++03, the11583 // program is actually ill-formed. However, DR 382 (in C++0x CD1)11584 // allows such extraneous "typename" keywords, and we retroactively11585 // apply this DR to C++03 code with only a warning. In any case we continue.11586 11587 if (RequireCompleteDeclContext(SS, Ctx))11588 return QualType();11589 }11590 11591 DeclarationName Name(&II);11592 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);11593 if (Ctx)11594 LookupQualifiedName(Result, Ctx, SS);11595 else11596 LookupName(Result, CurScope);11597 unsigned DiagID = 0;11598 Decl *Referenced = nullptr;11599 switch (Result.getResultKind()) {11600 case LookupResultKind::NotFound: {11601 // If we're looking up 'type' within a template named 'enable_if', produce11602 // a more specific diagnostic.11603 SourceRange CondRange;11604 Expr *Cond = nullptr;11605 if (Ctx && isEnableIf(QualifierLoc, II, CondRange, Cond)) {11606 // If we have a condition, narrow it down to the specific failed11607 // condition.11608 if (Cond) {11609 Expr *FailedCond;11610 std::string FailedDescription;11611 std::tie(FailedCond, FailedDescription) =11612 findFailedBooleanCondition(Cond);11613 11614 Diag(FailedCond->getExprLoc(),11615 diag::err_typename_nested_not_found_requirement)11616 << FailedDescription11617 << FailedCond->getSourceRange();11618 return QualType();11619 }11620 11621 Diag(CondRange.getBegin(),11622 diag::err_typename_nested_not_found_enable_if)11623 << Ctx << CondRange;11624 return QualType();11625 }11626 11627 DiagID = Ctx ? diag::err_typename_nested_not_found11628 : diag::err_unknown_typename;11629 break;11630 }11631 11632 case LookupResultKind::FoundUnresolvedValue: {11633 // We found a using declaration that is a value. Most likely, the using11634 // declaration itself is meant to have the 'typename' keyword.11635 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),11636 IILoc);11637 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)11638 << Name << Ctx << FullRange;11639 if (UnresolvedUsingValueDecl *Using11640 = dyn_cast<UnresolvedUsingValueDecl>(Result.getRepresentativeDecl())){11641 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();11642 Diag(Loc, diag::note_using_value_decl_missing_typename)11643 << FixItHint::CreateInsertion(Loc, "typename ");11644 }11645 }11646 // Fall through to create a dependent typename type, from which we can11647 // recover better.11648 [[fallthrough]];11649 11650 case LookupResultKind::NotFoundInCurrentInstantiation:11651 // Okay, it's a member of an unknown instantiation.11652 return Context.getDependentNameType(Keyword,11653 QualifierLoc.getNestedNameSpecifier(),11654 &II);11655 11656 case LookupResultKind::Found:11657 // FXIME: Missing support for UsingShadowDecl on this path?11658 if (TypeDecl *Type = dyn_cast<TypeDecl>(Result.getFoundDecl())) {11659 // C++ [class.qual]p2:11660 // In a lookup in which function names are not ignored and the11661 // nested-name-specifier nominates a class C, if the name specified11662 // after the nested-name-specifier, when looked up in C, is the11663 // injected-class-name of C [...] then the name is instead considered11664 // to name the constructor of class C.11665 //11666 // Unlike in an elaborated-type-specifier, function names are not ignored11667 // in typename-specifier lookup. However, they are ignored in all the11668 // contexts where we form a typename type with no keyword (that is, in11669 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).11670 //11671 // FIXME: That's not strictly true: mem-initializer-id lookup does not11672 // ignore functions, but that appears to be an oversight.11673 checkTypeDeclType(Ctx,11674 Keyword == ElaboratedTypeKeyword::Typename11675 ? DiagCtorKind::Typename11676 : DiagCtorKind::None,11677 Type, IILoc);11678 // FIXME: This appears to be the only case where a template type parameter11679 // can have an elaborated keyword. We should preserve it somehow.11680 if (isa<TemplateTypeParmDecl>(Type)) {11681 assert(Keyword == ElaboratedTypeKeyword::Typename);11682 assert(!QualifierLoc);11683 Keyword = ElaboratedTypeKeyword::None;11684 }11685 return Context.getTypeDeclType(11686 Keyword, QualifierLoc.getNestedNameSpecifier(), Type);11687 }11688 11689 // C++ [dcl.type.simple]p2:11690 // A type-specifier of the form11691 // typename[opt] nested-name-specifier[opt] template-name11692 // is a placeholder for a deduced class type [...].11693 if (getLangOpts().CPlusPlus17) {11694 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {11695 if (!DeducedTSTContext) {11696 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();11697 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)11698 Diag(IILoc, diag::err_dependent_deduced_tst)11699 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD))11700 << QualType(Qualifier.getAsType(), 0);11701 else11702 Diag(IILoc, diag::err_deduced_tst)11703 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD));11704 NoteTemplateLocation(*TD);11705 return QualType();11706 }11707 TemplateName Name = Context.getQualifiedTemplateName(11708 QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,11709 TemplateName(TD));11710 return Context.getDeducedTemplateSpecializationType(11711 Keyword, Name, /*DeducedType=*/QualType(), /*IsDependent=*/false);11712 }11713 }11714 11715 DiagID = Ctx ? diag::err_typename_nested_not_type11716 : diag::err_typename_not_type;11717 Referenced = Result.getFoundDecl();11718 break;11719 11720 case LookupResultKind::FoundOverloaded:11721 DiagID = Ctx ? diag::err_typename_nested_not_type11722 : diag::err_typename_not_type;11723 Referenced = *Result.begin();11724 break;11725 11726 case LookupResultKind::Ambiguous:11727 return QualType();11728 }11729 11730 // If we get here, it's because name lookup did not find a11731 // type. Emit an appropriate diagnostic and return an error.11732 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),11733 IILoc);11734 if (Ctx)11735 Diag(IILoc, DiagID) << FullRange << Name << Ctx;11736 else11737 Diag(IILoc, DiagID) << FullRange << Name;11738 if (Referenced)11739 Diag(Referenced->getLocation(),11740 Ctx ? diag::note_typename_member_refers_here11741 : diag::note_typename_refers_here)11742 << Name;11743 return QualType();11744}11745 11746namespace {11747 // See Sema::RebuildTypeInCurrentInstantiation11748 class CurrentInstantiationRebuilder11749 : public TreeTransform<CurrentInstantiationRebuilder> {11750 SourceLocation Loc;11751 DeclarationName Entity;11752 11753 public:11754 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;11755 11756 CurrentInstantiationRebuilder(Sema &SemaRef,11757 SourceLocation Loc,11758 DeclarationName Entity)11759 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),11760 Loc(Loc), Entity(Entity) { }11761 11762 /// Determine whether the given type \p T has already been11763 /// transformed.11764 ///11765 /// For the purposes of type reconstruction, a type has already been11766 /// transformed if it is NULL or if it is not dependent.11767 bool AlreadyTransformed(QualType T) {11768 return T.isNull() || !T->isInstantiationDependentType();11769 }11770 11771 /// Returns the location of the entity whose type is being11772 /// rebuilt.11773 SourceLocation getBaseLocation() { return Loc; }11774 11775 /// Returns the name of the entity whose type is being rebuilt.11776 DeclarationName getBaseEntity() { return Entity; }11777 11778 /// Sets the "base" location and entity when that11779 /// information is known based on another transformation.11780 void setBase(SourceLocation Loc, DeclarationName Entity) {11781 this->Loc = Loc;11782 this->Entity = Entity;11783 }11784 11785 ExprResult TransformLambdaExpr(LambdaExpr *E) {11786 // Lambdas never need to be transformed.11787 return E;11788 }11789 };11790} // end anonymous namespace11791 11792TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,11793 SourceLocation Loc,11794 DeclarationName Name) {11795 if (!T || !T->getType()->isInstantiationDependentType())11796 return T;11797 11798 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);11799 return Rebuilder.TransformType(T);11800}11801 11802ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {11803 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),11804 DeclarationName());11805 return Rebuilder.TransformExpr(E);11806}11807 11808bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {11809 if (SS.isInvalid())11810 return true;11811 11812 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);11813 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),11814 DeclarationName());11815 NestedNameSpecifierLoc Rebuilt11816 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);11817 if (!Rebuilt)11818 return true;11819 11820 SS.Adopt(Rebuilt);11821 return false;11822}11823 11824bool Sema::RebuildTemplateParamsInCurrentInstantiation(11825 TemplateParameterList *Params) {11826 for (unsigned I = 0, N = Params->size(); I != N; ++I) {11827 Decl *Param = Params->getParam(I);11828 11829 // There is nothing to rebuild in a type parameter.11830 if (isa<TemplateTypeParmDecl>(Param))11831 continue;11832 11833 // Rebuild the template parameter list of a template template parameter.11834 if (TemplateTemplateParmDecl *TTP11835 = dyn_cast<TemplateTemplateParmDecl>(Param)) {11836 if (RebuildTemplateParamsInCurrentInstantiation(11837 TTP->getTemplateParameters()))11838 return true;11839 11840 continue;11841 }11842 11843 // Rebuild the type of a non-type template parameter.11844 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Param);11845 TypeSourceInfo *NewTSI11846 = RebuildTypeInCurrentInstantiation(NTTP->getTypeSourceInfo(),11847 NTTP->getLocation(),11848 NTTP->getDeclName());11849 if (!NewTSI)11850 return true;11851 11852 if (NewTSI->getType()->isUndeducedType()) {11853 // C++17 [temp.dep.expr]p3:11854 // An id-expression is type-dependent if it contains11855 // - an identifier associated by name lookup with a non-type11856 // template-parameter declared with a type that contains a11857 // placeholder type (7.1.7.4),11858 NewTSI = SubstAutoTypeSourceInfoDependent(NewTSI);11859 }11860 11861 if (NewTSI != NTTP->getTypeSourceInfo()) {11862 NTTP->setTypeSourceInfo(NewTSI);11863 NTTP->setType(NewTSI->getType());11864 }11865 }11866 11867 return false;11868}11869 11870std::string11871Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,11872 const TemplateArgumentList &Args) {11873 return getTemplateArgumentBindingsText(Params, Args.data(), Args.size());11874}11875 11876std::string11877Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,11878 const TemplateArgument *Args,11879 unsigned NumArgs) {11880 SmallString<128> Str;11881 llvm::raw_svector_ostream Out(Str);11882 11883 if (!Params || Params->size() == 0 || NumArgs == 0)11884 return std::string();11885 11886 for (unsigned I = 0, N = Params->size(); I != N; ++I) {11887 if (I >= NumArgs)11888 break;11889 11890 if (I == 0)11891 Out << "[with ";11892 else11893 Out << ", ";11894 11895 if (const IdentifierInfo *Id = Params->getParam(I)->getIdentifier()) {11896 Out << Id->getName();11897 } else {11898 Out << '$' << I;11899 }11900 11901 Out << " = ";11902 Args[I].print(getPrintingPolicy(), Out,11903 TemplateParameterList::shouldIncludeTypeForArgument(11904 getPrintingPolicy(), Params, I));11905 }11906 11907 Out << ']';11908 return std::string(Out.str());11909}11910 11911void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,11912 CachedTokens &Toks) {11913 if (!FD)11914 return;11915 11916 auto LPT = std::make_unique<LateParsedTemplate>();11917 11918 // Take tokens to avoid allocations11919 LPT->Toks.swap(Toks);11920 LPT->D = FnD;11921 LPT->FPO = getCurFPFeatures();11922 LateParsedTemplateMap.insert(std::make_pair(FD, std::move(LPT)));11923 11924 FD->setLateTemplateParsed(true);11925}11926 11927void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {11928 if (!FD)11929 return;11930 FD->setLateTemplateParsed(false);11931}11932 11933bool Sema::IsInsideALocalClassWithinATemplateFunction() {11934 DeclContext *DC = CurContext;11935 11936 while (DC) {11937 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(CurContext)) {11938 const FunctionDecl *FD = RD->isLocalClass();11939 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);11940 } else if (DC->isTranslationUnit() || DC->isNamespace())11941 return false;11942 11943 DC = DC->getParent();11944 }11945 return false;11946}11947 11948namespace {11949/// Walk the path from which a declaration was instantiated, and check11950/// that every explicit specialization along that path is visible. This enforces11951/// C++ [temp.expl.spec]/6:11952///11953/// If a template, a member template or a member of a class template is11954/// explicitly specialized then that specialization shall be declared before11955/// the first use of that specialization that would cause an implicit11956/// instantiation to take place, in every translation unit in which such a11957/// use occurs; no diagnostic is required.11958///11959/// and also C++ [temp.class.spec]/1:11960///11961/// A partial specialization shall be declared before the first use of a11962/// class template specialization that would make use of the partial11963/// specialization as the result of an implicit or explicit instantiation11964/// in every translation unit in which such a use occurs; no diagnostic is11965/// required.11966class ExplicitSpecializationVisibilityChecker {11967 Sema &S;11968 SourceLocation Loc;11969 llvm::SmallVector<Module *, 8> Modules;11970 Sema::AcceptableKind Kind;11971 11972public:11973 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,11974 Sema::AcceptableKind Kind)11975 : S(S), Loc(Loc), Kind(Kind) {}11976 11977 void check(NamedDecl *ND) {11978 if (auto *FD = dyn_cast<FunctionDecl>(ND))11979 return checkImpl(FD);11980 if (auto *RD = dyn_cast<CXXRecordDecl>(ND))11981 return checkImpl(RD);11982 if (auto *VD = dyn_cast<VarDecl>(ND))11983 return checkImpl(VD);11984 if (auto *ED = dyn_cast<EnumDecl>(ND))11985 return checkImpl(ED);11986 }11987 11988private:11989 void diagnose(NamedDecl *D, bool IsPartialSpec) {11990 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization11991 : Sema::MissingImportKind::ExplicitSpecialization;11992 const bool Recover = true;11993 11994 // If we got a custom set of modules (because only a subset of the11995 // declarations are interesting), use them, otherwise let11996 // diagnoseMissingImport intelligently pick some.11997 if (Modules.empty())11998 S.diagnoseMissingImport(Loc, D, Kind, Recover);11999 else12000 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);12001 }12002 12003 bool CheckMemberSpecialization(const NamedDecl *D) {12004 return Kind == Sema::AcceptableKind::Visible12005 ? S.hasVisibleMemberSpecialization(D)12006 : S.hasReachableMemberSpecialization(D);12007 }12008 12009 bool CheckExplicitSpecialization(const NamedDecl *D) {12010 return Kind == Sema::AcceptableKind::Visible12011 ? S.hasVisibleExplicitSpecialization(D)12012 : S.hasReachableExplicitSpecialization(D);12013 }12014 12015 bool CheckDeclaration(const NamedDecl *D) {12016 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)12017 : S.hasReachableDeclaration(D);12018 }12019 12020 // Check a specific declaration. There are three problematic cases:12021 //12022 // 1) The declaration is an explicit specialization of a template12023 // specialization.12024 // 2) The declaration is an explicit specialization of a member of an12025 // templated class.12026 // 3) The declaration is an instantiation of a template, and that template12027 // is an explicit specialization of a member of a templated class.12028 //12029 // We don't need to go any deeper than that, as the instantiation of the12030 // surrounding class / etc is not triggered by whatever triggered this12031 // instantiation, and thus should be checked elsewhere.12032 template<typename SpecDecl>12033 void checkImpl(SpecDecl *Spec) {12034 bool IsHiddenExplicitSpecialization = false;12035 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();12036 // Some invalid friend declarations are written as specializations but are12037 // instantiated implicitly.12038 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)12039 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();12040 if (SpecKind == TSK_ExplicitSpecialization) {12041 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()12042 ? !CheckMemberSpecialization(Spec)12043 : !CheckExplicitSpecialization(Spec);12044 } else {12045 checkInstantiated(Spec);12046 }12047 12048 if (IsHiddenExplicitSpecialization)12049 diagnose(Spec->getMostRecentDecl(), false);12050 }12051 12052 void checkInstantiated(FunctionDecl *FD) {12053 if (auto *TD = FD->getPrimaryTemplate())12054 checkTemplate(TD);12055 }12056 12057 void checkInstantiated(CXXRecordDecl *RD) {12058 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(RD);12059 if (!SD)12060 return;12061 12062 auto From = SD->getSpecializedTemplateOrPartial();12063 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())12064 checkTemplate(TD);12065 else if (auto *TD =12066 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {12067 if (!CheckDeclaration(TD))12068 diagnose(TD, true);12069 checkTemplate(TD);12070 }12071 }12072 12073 void checkInstantiated(VarDecl *RD) {12074 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(RD);12075 if (!SD)12076 return;12077 12078 auto From = SD->getSpecializedTemplateOrPartial();12079 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())12080 checkTemplate(TD);12081 else if (auto *TD =12082 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {12083 if (!CheckDeclaration(TD))12084 diagnose(TD, true);12085 checkTemplate(TD);12086 }12087 }12088 12089 void checkInstantiated(EnumDecl *FD) {}12090 12091 template<typename TemplDecl>12092 void checkTemplate(TemplDecl *TD) {12093 if (TD->isMemberSpecialization()) {12094 if (!CheckMemberSpecialization(TD))12095 diagnose(TD->getMostRecentDecl(), false);12096 }12097 }12098};12099} // end anonymous namespace12100 12101void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {12102 if (!getLangOpts().Modules)12103 return;12104 12105 ExplicitSpecializationVisibilityChecker(*this, Loc,12106 Sema::AcceptableKind::Visible)12107 .check(Spec);12108}12109 12110void Sema::checkSpecializationReachability(SourceLocation Loc,12111 NamedDecl *Spec) {12112 if (!getLangOpts().CPlusPlusModules)12113 return checkSpecializationVisibility(Loc, Spec);12114 12115 ExplicitSpecializationVisibilityChecker(*this, Loc,12116 Sema::AcceptableKind::Reachable)12117 .check(Spec);12118}12119 12120SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {12121 if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())12122 return N->getLocation();12123 if (const auto *FD = dyn_cast<FunctionDecl>(N)) {12124 if (!FD->isFunctionTemplateSpecialization())12125 return FD->getLocation();12126 } else if (!isa<ClassTemplateSpecializationDecl,12127 VarTemplateSpecializationDecl>(N)) {12128 return N->getLocation();12129 }12130 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {12131 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())12132 continue;12133 return CSC.PointOfInstantiation;12134 }12135 return N->getLocation();12136}12137