1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements semantic analysis for C++ templates.
9//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
12#include "clang/AST/ASTConcept.h"
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/Decl.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclFriend.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/DynamicRecursiveASTVisitor.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/TemplateName.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeOrdering.h"
25#include "clang/AST/TypeVisitor.h"
26#include "clang/Basic/Builtins.h"
27#include "clang/Basic/DiagnosticSema.h"
28#include "clang/Basic/LangOptions.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceLocation.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Sema/DeclSpec.h"
33#include "clang/Sema/EnterExpressionEvaluationContext.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/Overload.h"
37#include "clang/Sema/ParsedTemplate.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/SemaCUDA.h"
40#include "clang/Sema/SemaInternal.h"
41#include "clang/Sema/Template.h"
42#include "clang/Sema/TemplateDeduction.h"
43#include "llvm/ADT/SmallBitVector.h"
44#include "llvm/ADT/StringExtras.h"
45#include "llvm/Support/Casting.h"
46#include "llvm/Support/SaveAndRestore.h"
47
48#include <optional>
49using namespace clang;
50using namespace sema;
51
52// Exported for use by Parser.
53SourceRange
54clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
55 unsigned N) {
56 if (!N) return SourceRange();
57 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
58}
59
60unsigned Sema::getTemplateDepth(Scope *S) const {
61 unsigned Depth = 0;
62
63 // Each template parameter scope represents one level of template parameter
64 // depth.
65 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
66 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
67 ++Depth;
68 }
69
70 // Note that there are template parameters with the given depth.
71 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(a: Depth, b: D + 1); };
72
73 // Look for parameters of an enclosing generic lambda. We don't create a
74 // template parameter scope for these.
75 for (FunctionScopeInfo *FSI : getFunctionScopes()) {
76 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FSI)) {
77 if (!LSI->TemplateParams.empty()) {
78 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
79 break;
80 }
81 if (LSI->GLTemplateParameterList) {
82 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
83 break;
84 }
85 }
86 }
87
88 // Look for parameters of an enclosing terse function template. We don't
89 // create a template parameter scope for these either.
90 for (const InventedTemplateParameterInfo &Info :
91 getInventedParameterInfos()) {
92 if (!Info.TemplateParams.empty()) {
93 ParamsAtDepth(Info.AutoTemplateParameterDepth);
94 break;
95 }
96 }
97
98 return Depth;
99}
100
101/// \brief Determine whether the declaration found is acceptable as the name
102/// of a template and, if so, return that template declaration. Otherwise,
103/// returns null.
104///
105/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
106/// is true. In all other cases it will return a TemplateDecl (or null).
107NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
108 bool AllowFunctionTemplates,
109 bool AllowDependent) {
110 D = D->getUnderlyingDecl();
111
112 if (isa<TemplateDecl>(Val: D)) {
113 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(Val: D))
114 return nullptr;
115
116 return D;
117 }
118
119 if (const auto *Record = dyn_cast<CXXRecordDecl>(Val: D)) {
120 // C++ [temp.local]p1:
121 // Like normal (non-template) classes, class templates have an
122 // injected-class-name (Clause 9). The injected-class-name
123 // can be used with or without a template-argument-list. When
124 // it is used without a template-argument-list, it is
125 // equivalent to the injected-class-name followed by the
126 // template-parameters of the class template enclosed in
127 // <>. When it is used with a template-argument-list, it
128 // refers to the specified class template specialization,
129 // which could be the current specialization or another
130 // specialization.
131 if (Record->isInjectedClassName()) {
132 Record = cast<CXXRecordDecl>(Val: Record->getDeclContext());
133 if (Record->getDescribedClassTemplate())
134 return Record->getDescribedClassTemplate();
135
136 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record))
137 return Spec->getSpecializedTemplate();
138 }
139
140 return nullptr;
141 }
142
143 // 'using Dependent::foo;' can resolve to a template name.
144 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
145 // injected-class-name).
146 if (AllowDependent && isa<UnresolvedUsingValueDecl>(Val: D))
147 return D;
148
149 return nullptr;
150}
151
152void Sema::FilterAcceptableTemplateNames(LookupResult &R,
153 bool AllowFunctionTemplates,
154 bool AllowDependent) {
155 LookupResult::Filter filter = R.makeFilter();
156 while (filter.hasNext()) {
157 NamedDecl *Orig = filter.next();
158 if (!getAsTemplateNameDecl(D: Orig, AllowFunctionTemplates, AllowDependent))
159 filter.erase();
160 }
161 filter.done();
162}
163
164bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
165 bool AllowFunctionTemplates,
166 bool AllowDependent,
167 bool AllowNonTemplateFunctions) {
168 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
169 if (getAsTemplateNameDecl(D: *I, AllowFunctionTemplates, AllowDependent))
170 return true;
171 if (AllowNonTemplateFunctions &&
172 isa<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
173 return true;
174 }
175
176 return false;
177}
178
179TemplateNameKind
180Sema::isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword,
181 const UnqualifiedId &Name, ParsedType ObjectTypePtr,
182 bool EnteringContext, TemplateTy &TemplateResult,
183 bool &MemberOfUnknownSpecialization,
184 bool AllowTypoCorrection) {
185 assert(getLangOpts().CPlusPlus && "No template names in C!");
186
187 DeclarationName TName;
188 MemberOfUnknownSpecialization = false;
189
190 switch (Name.getKind()) {
191 case UnqualifiedIdKind::IK_Identifier:
192 TName = DeclarationName(Name.Identifier);
193 break;
194
195 case UnqualifiedIdKind::IK_OperatorFunctionId:
196 TName = Context.DeclarationNames.getCXXOperatorName(
197 Op: Name.OperatorFunctionId.Operator);
198 break;
199
200 case UnqualifiedIdKind::IK_LiteralOperatorId:
201 TName = Context.DeclarationNames.getCXXLiteralOperatorName(II: Name.Identifier);
202 break;
203
204 default:
205 return TNK_Non_template;
206 }
207
208 QualType ObjectType = ObjectTypePtr.get();
209
210 AssumedTemplateKind AssumedTemplate;
211 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
212 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
213 /*RequiredTemplate=*/SourceLocation(),
214 ATK: &AssumedTemplate, AllowTypoCorrection))
215 return TNK_Non_template;
216 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
217
218 if (AssumedTemplate != AssumedTemplateKind::None) {
219 TemplateResult = TemplateTy::make(P: Context.getAssumedTemplateName(Name: TName));
220 // Let the parser know whether we found nothing or found functions; if we
221 // found nothing, we want to more carefully check whether this is actually
222 // a function template name versus some other kind of undeclared identifier.
223 return AssumedTemplate == AssumedTemplateKind::FoundNothing
224 ? TNK_Undeclared_template
225 : TNK_Function_template;
226 }
227
228 if (R.empty())
229 return TNK_Non_template;
230
231 NamedDecl *D = nullptr;
232 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *R.begin());
233 if (R.isAmbiguous()) {
234 // If we got an ambiguity involving a non-function template, treat this
235 // as a template name, and pick an arbitrary template for error recovery.
236 bool AnyFunctionTemplates = false;
237 for (NamedDecl *FoundD : R) {
238 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(D: FoundD)) {
239 if (isa<FunctionTemplateDecl>(Val: FoundTemplate))
240 AnyFunctionTemplates = true;
241 else {
242 D = FoundTemplate;
243 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: FoundD);
244 break;
245 }
246 }
247 }
248
249 // If we didn't find any templates at all, this isn't a template name.
250 // Leave the ambiguity for a later lookup to diagnose.
251 if (!D && !AnyFunctionTemplates) {
252 R.suppressDiagnostics();
253 return TNK_Non_template;
254 }
255
256 // If the only templates were function templates, filter out the rest.
257 // We'll diagnose the ambiguity later.
258 if (!D)
259 FilterAcceptableTemplateNames(R);
260 }
261
262 // At this point, we have either picked a single template name declaration D
263 // or we have a non-empty set of results R containing either one template name
264 // declaration or a set of function templates.
265
266 TemplateName Template;
267 TemplateNameKind TemplateKind;
268
269 unsigned ResultCount = R.end() - R.begin();
270 if (!D && ResultCount > 1) {
271 // We assume that we'll preserve the qualifier from a function
272 // template name in other ways.
273 Template = Context.getOverloadedTemplateName(Begin: R.begin(), End: R.end());
274 TemplateKind = TNK_Function_template;
275
276 // We'll do this lookup again later.
277 R.suppressDiagnostics();
278 } else {
279 if (!D) {
280 D = getAsTemplateNameDecl(D: *R.begin());
281 assert(D && "unambiguous result is not a template name");
282 }
283
284 if (isa<UnresolvedUsingValueDecl>(Val: D)) {
285 // We don't yet know whether this is a template-name or not.
286 MemberOfUnknownSpecialization = true;
287 return TNK_Non_template;
288 }
289
290 TemplateDecl *TD = cast<TemplateDecl>(Val: D);
291 Template =
292 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
293 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
294 if (!SS.isInvalid()) {
295 NestedNameSpecifier Qualifier = SS.getScopeRep();
296 Template = Context.getQualifiedTemplateName(Qualifier, TemplateKeyword: hasTemplateKeyword,
297 Template);
298 }
299
300 if (isa<FunctionTemplateDecl>(Val: TD)) {
301 TemplateKind = TNK_Function_template;
302
303 // We'll do this lookup again later.
304 R.suppressDiagnostics();
305 } else {
306 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
307 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
308 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
309 TemplateKind =
310 isa<TemplateTemplateParmDecl>(Val: TD)
311 ? dyn_cast<TemplateTemplateParmDecl>(Val: TD)->templateParameterKind()
312 : isa<VarTemplateDecl>(Val: TD) ? TNK_Var_template
313 : isa<ConceptDecl>(Val: TD) ? TNK_Concept_template
314 : TNK_Type_template;
315 }
316 }
317
318 if (isPackProducingBuiltinTemplateName(N: Template) && S &&
319 S->getTemplateParamParent() == nullptr)
320 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_builtin_pack_outside_template) << TName;
321 // Recover by returning the template, even though we would never be able to
322 // substitute it.
323
324 TemplateResult = TemplateTy::make(P: Template);
325 return TemplateKind;
326}
327
328bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
329 SourceLocation NameLoc, CXXScopeSpec &SS,
330 ParsedTemplateTy *Template /*=nullptr*/) {
331 // We could use redeclaration lookup here, but we don't need to: the
332 // syntactic form of a deduction guide is enough to identify it even
333 // if we can't look up the template name at all.
334 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
335 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
336 /*EnteringContext*/ false))
337 return false;
338
339 if (R.empty()) return false;
340 if (R.isAmbiguous()) {
341 // FIXME: Diagnose an ambiguity if we find at least one template.
342 R.suppressDiagnostics();
343 return false;
344 }
345
346 // We only treat template-names that name type templates as valid deduction
347 // guide names.
348 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
349 if (!TD || !getAsTypeTemplateDecl(D: TD))
350 return false;
351
352 if (Template) {
353 TemplateName Name = Context.getQualifiedTemplateName(
354 Qualifier: SS.getScopeRep(), /*TemplateKeyword=*/false, Template: TemplateName(TD));
355 *Template = TemplateTy::make(P: Name);
356 }
357 return true;
358}
359
360bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
361 SourceLocation IILoc,
362 Scope *S,
363 const CXXScopeSpec *SS,
364 TemplateTy &SuggestedTemplate,
365 TemplateNameKind &SuggestedKind) {
366 // We can't recover unless there's a dependent scope specifier preceding the
367 // template name.
368 // FIXME: Typo correction?
369 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(SS: *SS) ||
370 computeDeclContext(SS: *SS))
371 return false;
372
373 // The code is missing a 'template' keyword prior to the dependent template
374 // name.
375 SuggestedTemplate = TemplateTy::make(P: Context.getDependentTemplateName(
376 Name: {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
377 Diag(Loc: IILoc, DiagID: diag::err_template_kw_missing)
378 << SuggestedTemplate.get()
379 << FixItHint::CreateInsertion(InsertionLoc: IILoc, Code: "template ");
380 SuggestedKind = TNK_Dependent_template_name;
381 return true;
382}
383
384bool Sema::LookupTemplateName(LookupResult &Found, Scope *S, CXXScopeSpec &SS,
385 QualType ObjectType, bool EnteringContext,
386 RequiredTemplateKind RequiredTemplate,
387 AssumedTemplateKind *ATK,
388 bool AllowTypoCorrection) {
389 if (ATK)
390 *ATK = AssumedTemplateKind::None;
391
392 if (SS.isInvalid())
393 return true;
394
395 Found.setTemplateNameLookup(true);
396
397 // Determine where to perform name lookup
398 DeclContext *LookupCtx = nullptr;
399 bool IsDependent = false;
400 if (!ObjectType.isNull()) {
401 // This nested-name-specifier occurs in a member access expression, e.g.,
402 // x->B::f, and we are looking into the type of the object.
403 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
404 LookupCtx = computeDeclContext(T: ObjectType);
405 IsDependent = !LookupCtx && ObjectType->isDependentType();
406 assert((IsDependent || !ObjectType->isIncompleteType() ||
407 !ObjectType->getAs<TagType>() ||
408 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&
409 "Caller should have completed object type");
410
411 // Template names cannot appear inside an Objective-C class or object type
412 // or a vector type.
413 //
414 // FIXME: This is wrong. For example:
415 //
416 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
417 // Vec<int> vi;
418 // vi.Vec<int>::~Vec<int>();
419 //
420 // ... should be accepted but we will not treat 'Vec' as a template name
421 // here. The right thing to do would be to check if the name is a valid
422 // vector component name, and look up a template name if not. And similarly
423 // for lookups into Objective-C class and object types, where the same
424 // problem can arise.
425 if (ObjectType->isObjCObjectOrInterfaceType() ||
426 ObjectType->isVectorType()) {
427 Found.clear();
428 return false;
429 }
430 } else if (SS.isNotEmpty()) {
431 // This nested-name-specifier occurs after another nested-name-specifier,
432 // so long into the context associated with the prior nested-name-specifier.
433 LookupCtx = computeDeclContext(SS, EnteringContext);
434 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
435
436 // The declaration context must be complete.
437 if (LookupCtx && RequireCompleteDeclContext(SS, DC: LookupCtx))
438 return true;
439 }
440
441 bool ObjectTypeSearchedInScope = false;
442 bool AllowFunctionTemplatesInLookup = true;
443 if (LookupCtx) {
444 // Perform "qualified" name lookup into the declaration context we
445 // computed, which is either the type of the base of a member access
446 // expression or the declaration context associated with a prior
447 // nested-name-specifier.
448 LookupQualifiedName(R&: Found, LookupCtx);
449
450 // FIXME: The C++ standard does not clearly specify what happens in the
451 // case where the object type is dependent, and implementations vary. In
452 // Clang, we treat a name after a . or -> as a template-name if lookup
453 // finds a non-dependent member or member of the current instantiation that
454 // is a type template, or finds no such members and lookup in the context
455 // of the postfix-expression finds a type template. In the latter case, the
456 // name is nonetheless dependent, and we may resolve it to a member of an
457 // unknown specialization when we come to instantiate the template.
458 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
459 }
460
461 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
462 // C++ [basic.lookup.classref]p1:
463 // In a class member access expression (5.2.5), if the . or -> token is
464 // immediately followed by an identifier followed by a <, the
465 // identifier must be looked up to determine whether the < is the
466 // beginning of a template argument list (14.2) or a less-than operator.
467 // The identifier is first looked up in the class of the object
468 // expression. If the identifier is not found, it is then looked up in
469 // the context of the entire postfix-expression and shall name a class
470 // template.
471 if (S)
472 LookupName(R&: Found, S);
473
474 if (!ObjectType.isNull()) {
475 // FIXME: We should filter out all non-type templates here, particularly
476 // variable templates and concepts. But the exclusion of alias templates
477 // and template template parameters is a wording defect.
478 AllowFunctionTemplatesInLookup = false;
479 ObjectTypeSearchedInScope = true;
480 }
481
482 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
483 }
484
485 if (Found.isAmbiguous())
486 return false;
487
488 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
489 !RequiredTemplate.hasTemplateKeyword()) {
490 // C++2a [temp.names]p2:
491 // A name is also considered to refer to a template if it is an
492 // unqualified-id followed by a < and name lookup finds either one or more
493 // functions or finds nothing.
494 //
495 // To keep our behavior consistent, we apply the "finds nothing" part in
496 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
497 // successfully form a call to an undeclared template-id.
498 bool AllFunctions =
499 getLangOpts().CPlusPlus20 && llvm::all_of(Range&: Found, P: [](NamedDecl *ND) {
500 return isa<FunctionDecl>(Val: ND->getUnderlyingDecl());
501 });
502 if (AllFunctions || (Found.empty() && !IsDependent)) {
503 // If lookup found any functions, or if this is a name that can only be
504 // used for a function, then strongly assume this is a function
505 // template-id.
506 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
507 ? AssumedTemplateKind::FoundNothing
508 : AssumedTemplateKind::FoundFunctions;
509 Found.clear();
510 return false;
511 }
512 }
513
514 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
515 // If we did not find any names, and this is not a disambiguation, attempt
516 // to correct any typos.
517 DeclarationName Name = Found.getLookupName();
518 Found.clear();
519
520 class TemplateNameLookupValidatorCCC final
521 : public QualifiedLookupValidatorCCC {
522 public:
523 using QualifiedLookupValidatorCCC::QualifiedLookupValidatorCCC;
524
525 bool ValidateCandidate(const TypoCorrection &Candidate) final {
526 if (const NamedDecl *ND = Candidate.getCorrectionDecl();
527 !ND || !isa<TemplateDecl>(Val: ND))
528 return false;
529 return QualifiedLookupValidatorCCC::ValidateCandidate(Candidate);
530 }
531
532 std::unique_ptr<CorrectionCandidateCallback> clone() final {
533 return std::make_unique<TemplateNameLookupValidatorCCC>(args&: *this);
534 }
535 };
536
537 TemplateNameLookupValidatorCCC FilterCCC(!SS.isEmpty());
538 FilterCCC.WantTypeSpecifiers = false;
539 FilterCCC.WantExpressionKeywords = false;
540 FilterCCC.WantRemainingKeywords = false;
541 FilterCCC.WantCXXNamedCasts = true;
542 if (TypoCorrection Corrected = CorrectTypo(
543 Typo: Found.getLookupNameInfo(), LookupKind: Found.getLookupKind(), S, SS: &SS, CCC&: FilterCCC,
544 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
545 if (auto *ND = Corrected.getFoundDecl())
546 Found.addDecl(D: ND);
547 FilterAcceptableTemplateNames(R&: Found);
548 if (Found.isAmbiguous()) {
549 Found.clear();
550 } else if (!Found.empty()) {
551 // Do not erase the typo-corrected result to avoid duplicated
552 // diagnostics.
553 AllowFunctionTemplatesInLookup = true;
554 Found.setLookupName(Corrected.getCorrection());
555 if (LookupCtx) {
556 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
557 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
558 Name.getAsString() == CorrectedStr;
559 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_template_suggest)
560 << Name << LookupCtx << DroppedSpecifier
561 << SS.getRange());
562 } else {
563 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_template_suggest) << Name);
564 }
565
566 if (Corrected.WillReplaceSpecifier()) {
567 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
568 // In order to be valid, a non-empty CXXScopeSpec needs a source
569 // range.
570 SS.MakeTrivial(Context, Qualifier: NNS,
571 R: NNS ? Found.getNameLoc() : SourceRange());
572 }
573 }
574 }
575 }
576
577 NamedDecl *ExampleLookupResult =
578 Found.empty() ? nullptr : Found.getRepresentativeDecl();
579 FilterAcceptableTemplateNames(R&: Found, AllowFunctionTemplates: AllowFunctionTemplatesInLookup);
580 if (Found.empty()) {
581 if (IsDependent) {
582 Found.setNotFoundInCurrentInstantiation();
583 return false;
584 }
585
586 // If a 'template' keyword was used, a lookup that finds only non-template
587 // names is an error.
588 if (ExampleLookupResult && RequiredTemplate) {
589 Diag(Loc: Found.getNameLoc(), DiagID: diag::err_template_kw_refers_to_non_template)
590 << Found.getLookupName() << SS.getRange()
591 << RequiredTemplate.hasTemplateKeyword()
592 << RequiredTemplate.getTemplateKeywordLoc();
593 Diag(Loc: ExampleLookupResult->getUnderlyingDecl()->getLocation(),
594 DiagID: diag::note_template_kw_refers_to_non_template)
595 << Found.getLookupName();
596 return true;
597 }
598
599 return false;
600 }
601
602 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
603 !getLangOpts().CPlusPlus11) {
604 // C++03 [basic.lookup.classref]p1:
605 // [...] If the lookup in the class of the object expression finds a
606 // template, the name is also looked up in the context of the entire
607 // postfix-expression and [...]
608 //
609 // Note: C++11 does not perform this second lookup.
610 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
611 LookupOrdinaryName);
612 FoundOuter.setTemplateNameLookup(true);
613 LookupName(R&: FoundOuter, S);
614 // FIXME: We silently accept an ambiguous lookup here, in violation of
615 // [basic.lookup]/1.
616 FilterAcceptableTemplateNames(R&: FoundOuter, /*AllowFunctionTemplates=*/false);
617
618 NamedDecl *OuterTemplate;
619 if (FoundOuter.empty()) {
620 // - if the name is not found, the name found in the class of the
621 // object expression is used, otherwise
622 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
623 !(OuterTemplate =
624 getAsTemplateNameDecl(D: FoundOuter.getFoundDecl()))) {
625 // - if the name is found in the context of the entire
626 // postfix-expression and does not name a class template, the name
627 // found in the class of the object expression is used, otherwise
628 FoundOuter.clear();
629 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
630 // - if the name found is a class template, it must refer to the same
631 // entity as the one found in the class of the object expression,
632 // otherwise the program is ill-formed.
633 if (!Found.isSingleResult() ||
634 getAsTemplateNameDecl(D: Found.getFoundDecl())->getCanonicalDecl() !=
635 OuterTemplate->getCanonicalDecl()) {
636 Diag(Loc: Found.getNameLoc(),
637 DiagID: diag::ext_nested_name_member_ref_lookup_ambiguous)
638 << Found.getLookupName()
639 << ObjectType;
640 Diag(Loc: Found.getRepresentativeDecl()->getLocation(),
641 DiagID: diag::note_ambig_member_ref_object_type)
642 << ObjectType;
643 Diag(Loc: FoundOuter.getFoundDecl()->getLocation(),
644 DiagID: diag::note_ambig_member_ref_scope);
645
646 // Recover by taking the template that we found in the object
647 // expression's type.
648 }
649 }
650 }
651
652 return false;
653}
654
655void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
656 SourceLocation Less,
657 SourceLocation Greater) {
658 if (TemplateName.isInvalid())
659 return;
660
661 DeclarationNameInfo NameInfo;
662 CXXScopeSpec SS;
663 LookupNameKind LookupKind;
664
665 DeclContext *LookupCtx = nullptr;
666 NamedDecl *Found = nullptr;
667 bool MissingTemplateKeyword = false;
668
669 // Figure out what name we looked up.
670 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: TemplateName.get())) {
671 NameInfo = DRE->getNameInfo();
672 SS.Adopt(Other: DRE->getQualifierLoc());
673 LookupKind = LookupOrdinaryName;
674 Found = DRE->getFoundDecl();
675 } else if (auto *ME = dyn_cast<MemberExpr>(Val: TemplateName.get())) {
676 NameInfo = ME->getMemberNameInfo();
677 SS.Adopt(Other: ME->getQualifierLoc());
678 LookupKind = LookupMemberName;
679 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
680 Found = ME->getMemberDecl();
681 } else if (auto *DSDRE =
682 dyn_cast<DependentScopeDeclRefExpr>(Val: TemplateName.get())) {
683 NameInfo = DSDRE->getNameInfo();
684 SS.Adopt(Other: DSDRE->getQualifierLoc());
685 MissingTemplateKeyword = true;
686 } else if (auto *DSME =
687 dyn_cast<CXXDependentScopeMemberExpr>(Val: TemplateName.get())) {
688 NameInfo = DSME->getMemberNameInfo();
689 SS.Adopt(Other: DSME->getQualifierLoc());
690 MissingTemplateKeyword = true;
691 } else {
692 llvm_unreachable("unexpected kind of potential template name");
693 }
694
695 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
696 // was missing.
697 if (MissingTemplateKeyword) {
698 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_template_kw_missing)
699 << NameInfo.getName() << SourceRange(Less, Greater);
700 return;
701 }
702
703 // Try to correct the name by looking for templates and C++ named casts.
704 struct TemplateCandidateFilter : CorrectionCandidateCallback {
705 Sema &S;
706 TemplateCandidateFilter(Sema &S) : S(S) {
707 WantTypeSpecifiers = false;
708 WantExpressionKeywords = false;
709 WantRemainingKeywords = false;
710 WantCXXNamedCasts = true;
711 };
712 bool ValidateCandidate(const TypoCorrection &Candidate) override {
713 if (auto *ND = Candidate.getCorrectionDecl())
714 return S.getAsTemplateNameDecl(D: ND);
715 return Candidate.isKeyword();
716 }
717
718 std::unique_ptr<CorrectionCandidateCallback> clone() override {
719 return std::make_unique<TemplateCandidateFilter>(args&: *this);
720 }
721 };
722
723 DeclarationName Name = NameInfo.getName();
724 TemplateCandidateFilter CCC(*this);
725 if (TypoCorrection Corrected =
726 CorrectTypo(Typo: NameInfo, LookupKind, S, SS: &SS, CCC,
727 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
728 auto *ND = Corrected.getFoundDecl();
729 if (ND)
730 ND = getAsTemplateNameDecl(D: ND);
731 if (ND || Corrected.isKeyword()) {
732 if (LookupCtx) {
733 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
734 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
735 Name.getAsString() == CorrectedStr;
736 diagnoseTypo(Correction: Corrected,
737 TypoDiag: PDiag(DiagID: diag::err_non_template_in_member_template_id_suggest)
738 << Name << LookupCtx << DroppedSpecifier
739 << SS.getRange(), ErrorRecovery: false);
740 } else {
741 diagnoseTypo(Correction: Corrected,
742 TypoDiag: PDiag(DiagID: diag::err_non_template_in_template_id_suggest)
743 << Name, ErrorRecovery: false);
744 }
745 if (Found)
746 Diag(Loc: Found->getLocation(),
747 DiagID: diag::note_non_template_in_template_id_found);
748 return;
749 }
750 }
751
752 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_non_template_in_template_id)
753 << Name << SourceRange(Less, Greater);
754 if (Found)
755 Diag(Loc: Found->getLocation(), DiagID: diag::note_non_template_in_template_id_found);
756}
757
758ExprResult
759Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
760 SourceLocation TemplateKWLoc,
761 const DeclarationNameInfo &NameInfo,
762 bool isAddressOfOperand,
763 const TemplateArgumentListInfo *TemplateArgs) {
764 if (SS.isEmpty()) {
765 // FIXME: This codepath is only used by dependent unqualified names
766 // (e.g. a dependent conversion-function-id, or operator= once we support
767 // it). It doesn't quite do the right thing, and it will silently fail if
768 // getCurrentThisType() returns null.
769 QualType ThisType = getCurrentThisType();
770 if (ThisType.isNull())
771 return ExprError();
772
773 return CXXDependentScopeMemberExpr::Create(
774 Ctx: Context, /*Base=*/nullptr, BaseType: ThisType,
775 /*IsArrow=*/!Context.getLangOpts().HLSL,
776 /*OperatorLoc=*/SourceLocation(),
777 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
778 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
779 }
780 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
781}
782
783ExprResult
784Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
785 SourceLocation TemplateKWLoc,
786 const DeclarationNameInfo &NameInfo,
787 const TemplateArgumentListInfo *TemplateArgs) {
788 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
789 if (!SS.isValid())
790 return CreateRecoveryExpr(
791 Begin: SS.getBeginLoc(),
792 End: TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), SubExprs: {});
793
794 return DependentScopeDeclRefExpr::Create(
795 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
796 TemplateArgs);
797}
798
799ExprResult
800Sema::BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
801 QualType ParamType, SourceLocation Loc,
802 TemplateArgument Arg,
803 UnsignedOrNone PackIndex, bool Final) {
804 // The template argument itself might be an expression, in which case we just
805 // return that expression. This happens when substituting into an alias
806 // template.
807 Expr *Replacement;
808 if (Arg.getKind() == TemplateArgument::Expression) {
809 Replacement = Arg.getAsExpr();
810 } else {
811 ExprResult result =
812 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
813 if (result.isInvalid())
814 return ExprError();
815 Replacement = result.get();
816 }
817 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
818 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
819 AssociatedDecl, ParamType, Index, PackIndex, Final);
820}
821
822bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
823 NamedDecl *Instantiation,
824 bool InstantiatedFromMember,
825 const NamedDecl *Pattern,
826 const NamedDecl *PatternDef,
827 TemplateSpecializationKind TSK,
828 bool Complain, bool *Unreachable) {
829 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
830 isa<VarDecl>(Instantiation));
831
832 bool IsEntityBeingDefined = false;
833 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(Val: PatternDef))
834 IsEntityBeingDefined = TD->isBeingDefined();
835
836 if (PatternDef && !IsEntityBeingDefined) {
837 NamedDecl *SuggestedDef = nullptr;
838 if (!hasReachableDefinition(D: const_cast<NamedDecl *>(PatternDef),
839 Suggested: &SuggestedDef,
840 /*OnlyNeedComplete*/ false)) {
841 if (Unreachable)
842 *Unreachable = true;
843 // If we're allowed to diagnose this and recover, do so.
844 bool Recover = Complain && !isSFINAEContext();
845 if (Complain)
846 diagnoseMissingImport(Loc: PointOfInstantiation, Decl: SuggestedDef,
847 MIK: Sema::MissingImportKind::Definition, Recover);
848 return !Recover;
849 }
850 return false;
851 }
852
853 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
854 return true;
855
856 CanQualType InstantiationTy;
857 if (TagDecl *TD = dyn_cast<TagDecl>(Val: Instantiation))
858 InstantiationTy = Context.getCanonicalTagType(TD);
859 if (PatternDef) {
860 Diag(Loc: PointOfInstantiation,
861 DiagID: diag::err_template_instantiate_within_definition)
862 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
863 << InstantiationTy;
864 // Not much point in noting the template declaration here, since
865 // we're lexically inside it.
866 Instantiation->setInvalidDecl();
867 } else if (InstantiatedFromMember) {
868 if (isa<FunctionDecl>(Val: Instantiation)) {
869 Diag(Loc: PointOfInstantiation,
870 DiagID: diag::err_explicit_instantiation_undefined_member)
871 << /*member function*/ 1 << Instantiation->getDeclName()
872 << Instantiation->getDeclContext();
873 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
874 } else {
875 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
876 Diag(Loc: PointOfInstantiation,
877 DiagID: diag::err_implicit_instantiate_member_undefined)
878 << InstantiationTy;
879 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_member_declared_at);
880 }
881 } else {
882 if (isa<FunctionDecl>(Val: Instantiation)) {
883 Diag(Loc: PointOfInstantiation,
884 DiagID: diag::err_explicit_instantiation_undefined_func_template)
885 << Pattern;
886 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
887 } else if (isa<TagDecl>(Val: Instantiation)) {
888 Diag(Loc: PointOfInstantiation, DiagID: diag::err_template_instantiate_undefined)
889 << (TSK != TSK_ImplicitInstantiation)
890 << InstantiationTy;
891 NoteTemplateLocation(Decl: *Pattern);
892 } else {
893 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
894 if (isa<VarTemplateSpecializationDecl>(Val: Instantiation)) {
895 Diag(Loc: PointOfInstantiation,
896 DiagID: diag::err_explicit_instantiation_undefined_var_template)
897 << Instantiation;
898 Instantiation->setInvalidDecl();
899 } else
900 Diag(Loc: PointOfInstantiation,
901 DiagID: diag::err_explicit_instantiation_undefined_member)
902 << /*static data member*/ 2 << Instantiation->getDeclName()
903 << Instantiation->getDeclContext();
904 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
905 }
906 }
907
908 // In general, Instantiation isn't marked invalid to get more than one
909 // error for multiple undefined instantiations. But the code that does
910 // explicit declaration -> explicit definition conversion can't handle
911 // invalid declarations, so mark as invalid in that case.
912 if (TSK == TSK_ExplicitInstantiationDeclaration)
913 Instantiation->setInvalidDecl();
914 return true;
915}
916
917void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
918 bool SupportedForCompatibility) {
919 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
920
921 // C++23 [temp.local]p6:
922 // The name of a template-parameter shall not be bound to any following.
923 // declaration whose locus is contained by the scope to which the
924 // template-parameter belongs.
925 //
926 // When MSVC compatibility is enabled, the diagnostic is always a warning
927 // by default. Otherwise, it an error unless SupportedForCompatibility is
928 // true, in which case it is a default-to-error warning.
929 unsigned DiagId =
930 getLangOpts().MSVCCompat
931 ? diag::ext_template_param_shadow
932 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
933 : diag::err_template_param_shadow);
934 const auto *ND = cast<NamedDecl>(Val: PrevDecl);
935 Diag(Loc, DiagID: DiagId) << ND->getDeclName();
936 NoteTemplateParameterLocation(Decl: *ND);
937}
938
939TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
940 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(Val: D)) {
941 D = Temp->getTemplatedDecl();
942 return Temp;
943 }
944 return nullptr;
945}
946
947ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
948 SourceLocation EllipsisLoc) const {
949 assert(Kind == Template &&
950 "Only template template arguments can be pack expansions here");
951 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
952 "Template template argument pack expansion without packs");
953 ParsedTemplateArgument Result(*this);
954 Result.EllipsisLoc = EllipsisLoc;
955 return Result;
956}
957
958static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
959 const ParsedTemplateArgument &Arg) {
960
961 switch (Arg.getKind()) {
962 case ParsedTemplateArgument::Type: {
963 TypeSourceInfo *TSI;
964 QualType T = SemaRef.GetTypeFromParser(Ty: Arg.getAsType(), TInfo: &TSI);
965 if (!TSI)
966 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc: Arg.getNameLoc());
967 return TemplateArgumentLoc(TemplateArgument(T), TSI);
968 }
969
970 case ParsedTemplateArgument::NonType: {
971 Expr *E = Arg.getAsExpr();
972 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
973 }
974
975 case ParsedTemplateArgument::Template: {
976 TemplateName Template = Arg.getAsTemplate().get();
977 TemplateArgument TArg;
978 if (Arg.getEllipsisLoc().isValid())
979 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
980 else
981 TArg = Template;
982 return TemplateArgumentLoc(
983 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
984 Arg.getScopeSpec().getWithLocInContext(Context&: SemaRef.Context),
985 Arg.getNameLoc(), Arg.getEllipsisLoc());
986 }
987 }
988
989 llvm_unreachable("Unhandled parsed template argument");
990}
991
992void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
993 TemplateArgumentListInfo &TemplateArgs) {
994 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
995 TemplateArgs.addArgument(Loc: translateTemplateArgument(SemaRef&: *this,
996 Arg: TemplateArgsIn[I]));
997}
998
999static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
1000 SourceLocation Loc,
1001 const IdentifierInfo *Name) {
1002 NamedDecl *PrevDecl =
1003 SemaRef.LookupSingleName(S, Name, Loc, NameKind: Sema::LookupOrdinaryName,
1004 Redecl: RedeclarationKind::ForVisibleRedeclaration);
1005 if (PrevDecl && PrevDecl->isTemplateParameter())
1006 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
1007}
1008
1009ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
1010 TypeSourceInfo *TInfo;
1011 QualType T = GetTypeFromParser(Ty: ParsedType.get(), TInfo: &TInfo);
1012 if (T.isNull())
1013 return ParsedTemplateArgument();
1014 assert(TInfo && "template argument with no location");
1015
1016 // If we might have formed a deduced template specialization type, convert
1017 // it to a template template argument.
1018 if (getLangOpts().CPlusPlus17) {
1019 TypeLoc TL = TInfo->getTypeLoc();
1020 SourceLocation EllipsisLoc;
1021 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1022 EllipsisLoc = PET.getEllipsisLoc();
1023 TL = PET.getPatternLoc();
1024 }
1025
1026 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1027 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1028 CXXScopeSpec SS;
1029 SS.Adopt(Other: DTST.getQualifierLoc());
1030 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1031 TemplateTy::make(P: Name),
1032 DTST.getTemplateNameLoc());
1033 if (EllipsisLoc.isValid())
1034 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1035 return Result;
1036 }
1037 }
1038
1039 // This is a normal type template argument. Note, if the type template
1040 // argument is an injected-class-name for a template, it has a dual nature
1041 // and can be used as either a type or a template. We handle that in
1042 // convertTypeTemplateArgumentToTemplate.
1043 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1044 ParsedType.get().getAsOpaquePtr(),
1045 TInfo->getTypeLoc().getBeginLoc());
1046}
1047
1048NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
1049 SourceLocation EllipsisLoc,
1050 SourceLocation KeyLoc,
1051 IdentifierInfo *ParamName,
1052 SourceLocation ParamNameLoc,
1053 unsigned Depth, unsigned Position,
1054 SourceLocation EqualLoc,
1055 ParsedType DefaultArg,
1056 bool HasTypeConstraint) {
1057 assert(S->isTemplateParamScope() &&
1058 "Template type parameter not in template parameter scope!");
1059
1060 bool IsParameterPack = EllipsisLoc.isValid();
1061 TemplateTypeParmDecl *Param
1062 = TemplateTypeParmDecl::Create(C: Context, DC: Context.getTranslationUnitDecl(),
1063 KeyLoc, NameLoc: ParamNameLoc, D: Depth, P: Position,
1064 Id: ParamName, Typename, ParameterPack: IsParameterPack,
1065 HasTypeConstraint);
1066 Param->setAccess(AS_public);
1067
1068 if (Param->isParameterPack())
1069 if (auto *CSI = getEnclosingLambdaOrBlock())
1070 CSI->LocalPacks.push_back(Elt: Param);
1071
1072 if (ParamName) {
1073 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: ParamNameLoc, Name: ParamName);
1074
1075 // Add the template parameter into the current scope.
1076 S->AddDecl(D: Param);
1077 IdResolver.AddDecl(D: Param);
1078 }
1079
1080 // C++0x [temp.param]p9:
1081 // A default template-argument may be specified for any kind of
1082 // template-parameter that is not a template parameter pack.
1083 if (DefaultArg && IsParameterPack) {
1084 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1085 DefaultArg = nullptr;
1086 }
1087
1088 // Handle the default argument, if provided.
1089 if (DefaultArg) {
1090 TypeSourceInfo *DefaultTInfo;
1091 GetTypeFromParser(Ty: DefaultArg, TInfo: &DefaultTInfo);
1092
1093 assert(DefaultTInfo && "expected source information for type");
1094
1095 // Check for unexpanded parameter packs.
1096 if (DiagnoseUnexpandedParameterPack(Loc: ParamNameLoc, T: DefaultTInfo,
1097 UPPC: UPPC_DefaultArgument))
1098 return Param;
1099
1100 // Check the template argument itself.
1101 if (CheckTemplateArgument(Arg: DefaultTInfo)) {
1102 Param->setInvalidDecl();
1103 return Param;
1104 }
1105
1106 Param->setDefaultArgument(
1107 C: Context, DefArg: TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1108 }
1109
1110 return Param;
1111}
1112
1113/// Convert the parser's template argument list representation into our form.
1114static TemplateArgumentListInfo
1115makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1116 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1117 TemplateId.RAngleLoc);
1118 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1119 TemplateId.NumArgs);
1120 S.translateTemplateArguments(TemplateArgsIn: TemplateArgsPtr, TemplateArgs);
1121 return TemplateArgs;
1122}
1123
1124bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {
1125
1126 TemplateName TN = TypeConstr->Template.get();
1127 NamedDecl *CD = nullptr;
1128 bool IsTypeConcept = false;
1129 bool RequiresArguments = false;
1130 if (auto *TTP = TN.getAsTemplateTemplateParmDecl()) {
1131 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1132 RequiresArguments =
1133 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1134 CD = TTP;
1135 } else {
1136 CD = TN.getAsTemplateDecl();
1137 IsTypeConcept = cast<ConceptDecl>(Val: CD)->isTypeConcept();
1138 RequiresArguments = cast<ConceptDecl>(Val: CD)
1139 ->getTemplateParameters()
1140 ->getMinRequiredArguments() > 1;
1141 }
1142
1143 // C++2a [temp.param]p4:
1144 // [...] The concept designated by a type-constraint shall be a type
1145 // concept ([temp.concept]).
1146 if (!IsTypeConcept) {
1147 Diag(Loc: TypeConstr->TemplateNameLoc,
1148 DiagID: diag::err_type_constraint_non_type_concept);
1149 return true;
1150 }
1151
1152 if (CheckConceptUseInDefinition(Concept: CD, Loc: TypeConstr->TemplateNameLoc))
1153 return true;
1154
1155 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1156
1157 if (!WereArgsSpecified && RequiresArguments) {
1158 Diag(Loc: TypeConstr->TemplateNameLoc,
1159 DiagID: diag::err_type_constraint_missing_arguments)
1160 << CD;
1161 return true;
1162 }
1163 return false;
1164}
1165
1166bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1167 TemplateIdAnnotation *TypeConstr,
1168 TemplateTypeParmDecl *ConstrainedParameter,
1169 SourceLocation EllipsisLoc) {
1170 return BuildTypeConstraint(SS, TypeConstraint: TypeConstr, ConstrainedParameter, EllipsisLoc,
1171 AllowUnexpandedPack: false);
1172}
1173
1174bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1175 TemplateIdAnnotation *TypeConstr,
1176 TemplateTypeParmDecl *ConstrainedParameter,
1177 SourceLocation EllipsisLoc,
1178 bool AllowUnexpandedPack) {
1179
1180 if (CheckTypeConstraint(TypeConstr))
1181 return true;
1182
1183 TemplateName TN = TypeConstr->Template.get();
1184 UsingShadowDecl *USD = TN.getAsUsingShadowDecl();
1185 TemplateDecl *CD = TN.getAsTemplateDecl();
1186
1187 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1188 TypeConstr->TemplateNameLoc);
1189
1190 TemplateArgumentListInfo TemplateArgs;
1191 if (TypeConstr->LAngleLoc.isValid()) {
1192 TemplateArgs =
1193 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TypeConstr);
1194
1195 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1196 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1197 if (DiagnoseUnexpandedParameterPack(Arg, UPPC: UPPC_TypeConstraint))
1198 return true;
1199 }
1200 }
1201 }
1202 return AttachTypeConstraint(
1203 NS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1204 NameInfo: ConceptName, NamedConcept: TN,
1205 /*FoundDecl=*/USD ? cast<NamedDecl>(Val: USD) : cast_if_present<NamedDecl>(Val: CD),
1206 TemplateArgs: TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1207 ConstrainedParameter, EllipsisLoc);
1208}
1209
1210template <typename ArgumentLocAppender>
1211static ExprResult formImmediatelyDeclaredConstraint(
1212 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1213 TemplateName NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1214 SourceLocation RAngleLoc, QualType ConstrainedType,
1215 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1216 SourceLocation EllipsisLoc) {
1217
1218 TemplateArgumentListInfo ConstraintArgs;
1219 ConstraintArgs.addArgument(
1220 Loc: S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(ConstrainedType),
1221 /*NTTPType=*/QualType(), Loc: ParamNameLoc));
1222
1223 ConstraintArgs.setRAngleLoc(RAngleLoc);
1224 ConstraintArgs.setLAngleLoc(LAngleLoc);
1225 Appender(ConstraintArgs);
1226
1227 // C++2a [temp.param]p4:
1228 // [...] This constraint-expression E is called the immediately-declared
1229 // constraint of T. [...]
1230 CXXScopeSpec SS;
1231 SS.Adopt(Other: NS);
1232 ExprResult ImmediatelyDeclaredConstraint;
1233 if (auto *CD =
1234 dyn_cast_if_present<ConceptDecl>(Val: NamedConcept.getAsTemplateDecl())) {
1235 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1236 SS, /*TemplateKWLoc=*/SourceLocation(), ConceptNameInfo: NameInfo,
1237 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, NamedConcept: CD, TemplateArgs: &ConstraintArgs,
1238 /*DoCheckConstraintSatisfaction=*/
1239 !S.inParameterMappingSubstitution());
1240 }
1241 // We have a template template parameter
1242 else {
1243 assert(SS.isEmpty() && "template parameter with a scope specifier?");
1244 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1245 NameInfo, Template: NamedConcept, TemplateArgs: &ConstraintArgs);
1246 }
1247 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1248 return ImmediatelyDeclaredConstraint;
1249
1250 // C++2a [temp.param]p4:
1251 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1252 //
1253 // We have the following case:
1254 //
1255 // template<typename T> concept C1 = true;
1256 // template<C1... T> struct s1;
1257 //
1258 // The constraint: (C1<T> && ...)
1259 //
1260 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1261 // any unqualified lookups for 'operator&&' here.
1262 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/Callee: nullptr,
1263 /*LParenLoc=*/SourceLocation(),
1264 LHS: ImmediatelyDeclaredConstraint.get(), Operator: BO_LAnd,
1265 EllipsisLoc, /*RHS=*/nullptr,
1266 /*RParenLoc=*/SourceLocation(),
1267 /*NumExpansions=*/std::nullopt);
1268}
1269
1270bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1271 DeclarationNameInfo NameInfo,
1272 TemplateName NamedConcept, NamedDecl *FoundDecl,
1273 const TemplateArgumentListInfo *TemplateArgs,
1274 TemplateTypeParmDecl *ConstrainedParameter,
1275 SourceLocation EllipsisLoc) {
1276 // C++2a [temp.param]p4:
1277 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1278 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1279 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1280 TemplateArgs ? ASTTemplateArgumentListInfo::Create(C: Context,
1281 List: *TemplateArgs) : nullptr;
1282
1283 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1284
1285 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1286 S&: *this, NS, NameInfo, NamedConcept, FoundDecl,
1287 LAngleLoc: TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1288 RAngleLoc: TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1289 ConstrainedType: ParamAsArgument, ParamNameLoc: ConstrainedParameter->getLocation(),
1290 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1291 if (TemplateArgs)
1292 for (const auto &ArgLoc : TemplateArgs->arguments())
1293 ConstraintArgs.addArgument(Loc: ArgLoc);
1294 },
1295 EllipsisLoc);
1296 if (ImmediatelyDeclaredConstraint.isInvalid())
1297 return true;
1298
1299 auto *CL = ConceptReference::Create(C: Context, /*NNS=*/NS,
1300 /*TemplateKWLoc=*/SourceLocation{},
1301 /*ConceptNameInfo=*/NameInfo,
1302 /*FoundDecl=*/FoundDecl,
1303 /*NamedConcept=*/NamedConcept,
1304 /*ArgsWritten=*/ArgsAsWritten);
1305 ConstrainedParameter->setTypeConstraint(
1306 CR: CL, ImmediatelyDeclaredConstraint: ImmediatelyDeclaredConstraint.get(), ArgPackSubstIndex: std::nullopt);
1307 return false;
1308}
1309
1310bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
1311 NonTypeTemplateParmDecl *NewConstrainedParm,
1312 NonTypeTemplateParmDecl *OrigConstrainedParm,
1313 SourceLocation EllipsisLoc) {
1314 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1315 TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1316 Diag(Loc: NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1317 DiagID: diag::err_unsupported_placeholder_constraint)
1318 << NewConstrainedParm->getTypeSourceInfo()
1319 ->getTypeLoc()
1320 .getSourceRange();
1321 NewConstrainedParm->setType(TL.getType());
1322 return true;
1323 }
1324 // FIXME: Concepts: This should be the type of the placeholder, but this is
1325 // unclear in the wording right now.
1326 DeclRefExpr *Ref =
1327 BuildDeclRefExpr(D: OrigConstrainedParm, Ty: OrigConstrainedParm->getType(),
1328 VK: VK_PRValue, Loc: OrigConstrainedParm->getLocation());
1329 if (!Ref)
1330 return true;
1331 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1332 S&: *this, NS: TL.getNestedNameSpecifierLoc(), NameInfo: TL.getConceptNameInfo(),
1333 NamedConcept: TL.getNamedConcept(),
1334 /*FoundDecl=*/TL.getFoundDecl(), LAngleLoc: TL.getLAngleLoc(), RAngleLoc: TL.getRAngleLoc(),
1335 ConstrainedType: BuildDecltypeType(E: Ref), ParamNameLoc: OrigConstrainedParm->getLocation(),
1336 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1337 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1338 ConstraintArgs.addArgument(Loc: TL.getArgLoc(i: I));
1339 },
1340 EllipsisLoc);
1341 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1342 !ImmediatelyDeclaredConstraint.isUsable())
1343 return true;
1344
1345 NewConstrainedParm->setPlaceholderTypeConstraint(
1346 ImmediatelyDeclaredConstraint.get());
1347 return false;
1348}
1349
1350QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1351 SourceLocation Loc) {
1352 if (TSI->getType()->isUndeducedType()) {
1353 // C++17 [temp.dep.expr]p3:
1354 // An id-expression is type-dependent if it contains
1355 // - an identifier associated by name lookup with a non-type
1356 // template-parameter declared with a type that contains a
1357 // placeholder type (7.1.7.4),
1358 TypeSourceInfo *NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSI);
1359 if (!NewTSI)
1360 return QualType();
1361 TSI = NewTSI;
1362 }
1363
1364 return CheckNonTypeTemplateParameterType(T: TSI->getType(), Loc);
1365}
1366
1367bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1368 if (T->isDependentType())
1369 return false;
1370
1371 if (RequireCompleteType(Loc, T, DiagID: diag::err_template_nontype_parm_incomplete))
1372 return true;
1373
1374 if (T->isStructuralType())
1375 return false;
1376
1377 // Structural types are required to be object types or lvalue references.
1378 if (T->isRValueReferenceType()) {
1379 Diag(Loc, DiagID: diag::err_template_nontype_parm_rvalue_ref) << T;
1380 return true;
1381 }
1382
1383 // Don't mention structural types in our diagnostic prior to C++20. Also,
1384 // there's not much more we can say about non-scalar non-class types --
1385 // because we can't see functions or arrays here, those can only be language
1386 // extensions.
1387 if (!getLangOpts().CPlusPlus20 ||
1388 (!T->isScalarType() && !T->isRecordType())) {
1389 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_type) << T;
1390 return true;
1391 }
1392
1393 // Structural types are required to be literal types.
1394 if (RequireLiteralType(Loc, T, DiagID: diag::err_template_nontype_parm_not_literal))
1395 return true;
1396
1397 Diag(Loc, DiagID: diag::err_template_nontype_parm_not_structural) << T;
1398
1399 // Drill down into the reason why the class is non-structural.
1400 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1401 // All members are required to be public and non-mutable, and can't be of
1402 // rvalue reference type. Check these conditions first to prefer a "local"
1403 // reason over a more distant one.
1404 for (const FieldDecl *FD : RD->fields()) {
1405 if (FD->getAccess() != AS_public) {
1406 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_non_public) << T << 0;
1407 return true;
1408 }
1409 if (FD->isMutable()) {
1410 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_mutable_field) << T;
1411 return true;
1412 }
1413 if (FD->getType()->isRValueReferenceType()) {
1414 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_rvalue_ref_field)
1415 << T;
1416 return true;
1417 }
1418 }
1419
1420 // All bases are required to be public.
1421 for (const auto &BaseSpec : RD->bases()) {
1422 if (BaseSpec.getAccessSpecifier() != AS_public) {
1423 Diag(Loc: BaseSpec.getBaseTypeLoc(), DiagID: diag::note_not_structural_non_public)
1424 << T << 1;
1425 return true;
1426 }
1427 }
1428
1429 // All subobjects are required to be of structural types.
1430 SourceLocation SubLoc;
1431 QualType SubType;
1432 int Kind = -1;
1433
1434 for (const FieldDecl *FD : RD->fields()) {
1435 QualType T = Context.getBaseElementType(QT: FD->getType());
1436 if (!T->isStructuralType()) {
1437 SubLoc = FD->getLocation();
1438 SubType = T;
1439 Kind = 0;
1440 break;
1441 }
1442 }
1443
1444 if (Kind == -1) {
1445 for (const auto &BaseSpec : RD->bases()) {
1446 QualType T = BaseSpec.getType();
1447 if (!T->isStructuralType()) {
1448 SubLoc = BaseSpec.getBaseTypeLoc();
1449 SubType = T;
1450 Kind = 1;
1451 break;
1452 }
1453 }
1454 }
1455
1456 assert(Kind != -1 && "couldn't find reason why type is not structural");
1457 Diag(Loc: SubLoc, DiagID: diag::note_not_structural_subobject)
1458 << T << Kind << SubType;
1459 T = SubType;
1460 RD = T->getAsCXXRecordDecl();
1461 }
1462
1463 return true;
1464}
1465
1466QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1467 SourceLocation Loc) {
1468 // We don't allow variably-modified types as the type of non-type template
1469 // parameters.
1470 if (T->isVariablyModifiedType()) {
1471 Diag(Loc, DiagID: diag::err_variably_modified_nontype_template_param)
1472 << T;
1473 return QualType();
1474 }
1475
1476 if (T->isBlockPointerType()) {
1477 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_type) << T;
1478 return QualType();
1479 }
1480
1481 // C++ [temp.param]p4:
1482 //
1483 // A non-type template-parameter shall have one of the following
1484 // (optionally cv-qualified) types:
1485 //
1486 // -- integral or enumeration type,
1487 if (T->isIntegralOrEnumerationType() ||
1488 // -- pointer to object or pointer to function,
1489 T->isPointerType() ||
1490 // -- lvalue reference to object or lvalue reference to function,
1491 T->isLValueReferenceType() ||
1492 // -- pointer to member,
1493 T->isMemberPointerType() ||
1494 // -- std::nullptr_t, or
1495 T->isNullPtrType() ||
1496 // -- a type that contains a placeholder type.
1497 T->isUndeducedType()) {
1498 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1499 // are ignored when determining its type.
1500 return T.getUnqualifiedType();
1501 }
1502
1503 // C++ [temp.param]p8:
1504 //
1505 // A non-type template-parameter of type "array of T" or
1506 // "function returning T" is adjusted to be of type "pointer to
1507 // T" or "pointer to function returning T", respectively.
1508 if (T->isArrayType() || T->isFunctionType())
1509 return Context.getDecayedType(T);
1510
1511 // If T is a dependent type, we can't do the check now, so we
1512 // assume that it is well-formed. Note that stripping off the
1513 // qualifiers here is not really correct if T turns out to be
1514 // an array type, but we'll recompute the type everywhere it's
1515 // used during instantiation, so that should be OK. (Using the
1516 // qualified type is equally wrong.)
1517 if (T->isDependentType())
1518 return T.getUnqualifiedType();
1519
1520 // C++20 [temp.param]p6:
1521 // -- a structural type
1522 if (RequireStructuralType(T, Loc))
1523 return QualType();
1524
1525 if (!getLangOpts().CPlusPlus20) {
1526 // FIXME: Consider allowing structural types as an extension in C++17. (In
1527 // earlier language modes, the template argument evaluation rules are too
1528 // inflexible.)
1529 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_structural_type) << T;
1530 return QualType();
1531 }
1532
1533 Diag(Loc, DiagID: diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1534 return T.getUnqualifiedType();
1535}
1536
1537NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1538 unsigned Depth,
1539 unsigned Position,
1540 SourceLocation EqualLoc,
1541 Expr *Default) {
1542 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
1543
1544 // Check that we have valid decl-specifiers specified.
1545 auto CheckValidDeclSpecifiers = [this, &D] {
1546 // C++ [temp.param]
1547 // p1
1548 // template-parameter:
1549 // ...
1550 // parameter-declaration
1551 // p2
1552 // ... A storage class shall not be specified in a template-parameter
1553 // declaration.
1554 // [dcl.typedef]p1:
1555 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1556 // of a parameter-declaration
1557 const DeclSpec &DS = D.getDeclSpec();
1558 auto EmitDiag = [this](SourceLocation Loc) {
1559 Diag(Loc, DiagID: diag::err_invalid_decl_specifier_in_nontype_parm)
1560 << FixItHint::CreateRemoval(RemoveRange: Loc);
1561 };
1562 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1563 EmitDiag(DS.getStorageClassSpecLoc());
1564
1565 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1566 EmitDiag(DS.getThreadStorageClassSpecLoc());
1567
1568 // [dcl.inline]p1:
1569 // The inline specifier can be applied only to the declaration or
1570 // definition of a variable or function.
1571
1572 if (DS.isInlineSpecified())
1573 EmitDiag(DS.getInlineSpecLoc());
1574
1575 // [dcl.constexpr]p1:
1576 // The constexpr specifier shall be applied only to the definition of a
1577 // variable or variable template or the declaration of a function or
1578 // function template.
1579
1580 if (DS.hasConstexprSpecifier())
1581 EmitDiag(DS.getConstexprSpecLoc());
1582
1583 // [dcl.fct.spec]p1:
1584 // Function-specifiers can be used only in function declarations.
1585
1586 if (DS.isVirtualSpecified())
1587 EmitDiag(DS.getVirtualSpecLoc());
1588
1589 if (DS.hasExplicitSpecifier())
1590 EmitDiag(DS.getExplicitSpecLoc());
1591
1592 if (DS.isNoreturnSpecified())
1593 EmitDiag(DS.getNoreturnSpecLoc());
1594 };
1595
1596 CheckValidDeclSpecifiers();
1597
1598 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1599 if (isa<AutoType>(Val: T))
1600 Diag(Loc: D.getIdentifierLoc(),
1601 DiagID: diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1602 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1603
1604 assert(S->isTemplateParamScope() &&
1605 "Non-type template parameter not in template parameter scope!");
1606 bool Invalid = false;
1607
1608 QualType T = CheckNonTypeTemplateParameterType(TSI&: TInfo, Loc: D.getIdentifierLoc());
1609 if (T.isNull()) {
1610 T = Context.IntTy; // Recover with an 'int' type.
1611 Invalid = true;
1612 }
1613
1614 CheckFunctionOrTemplateParamDeclarator(S, D);
1615
1616 const IdentifierInfo *ParamName = D.getIdentifier();
1617 bool IsParameterPack = D.hasEllipsis();
1618 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1619 C: Context, DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
1620 IdLoc: D.getIdentifierLoc(), D: Depth, P: Position, Id: ParamName, T, ParameterPack: IsParameterPack,
1621 TInfo);
1622 Param->setAccess(AS_public);
1623
1624 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1625 if (TL.isConstrained()) {
1626 if (D.getEllipsisLoc().isInvalid() &&
1627 T->containsUnexpandedParameterPack()) {
1628 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1629 for (auto &Loc :
1630 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1631 Invalid |= DiagnoseUnexpandedParameterPack(
1632 Arg: Loc, UPPC: UnexpandedParameterPackContext::UPPC_TypeConstraint);
1633 }
1634 if (!Invalid &&
1635 AttachTypeConstraint(TL, NewConstrainedParm: Param, OrigConstrainedParm: Param, EllipsisLoc: D.getEllipsisLoc()))
1636 Invalid = true;
1637 }
1638
1639 if (Invalid)
1640 Param->setInvalidDecl();
1641
1642 if (Param->isParameterPack())
1643 if (auto *CSI = getEnclosingLambdaOrBlock())
1644 CSI->LocalPacks.push_back(Elt: Param);
1645
1646 if (ParamName) {
1647 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: D.getIdentifierLoc(),
1648 Name: ParamName);
1649
1650 // Add the template parameter into the current scope.
1651 S->AddDecl(D: Param);
1652 IdResolver.AddDecl(D: Param);
1653 }
1654
1655 // C++0x [temp.param]p9:
1656 // A default template-argument may be specified for any kind of
1657 // template-parameter that is not a template parameter pack.
1658 if (Default && IsParameterPack) {
1659 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1660 Default = nullptr;
1661 }
1662
1663 // Check the well-formedness of the default template argument, if provided.
1664 if (Default) {
1665 // Check for unexpanded parameter packs.
1666 if (DiagnoseUnexpandedParameterPack(E: Default, UPPC: UPPC_DefaultArgument))
1667 return Param;
1668
1669 Param->setDefaultArgument(
1670 C: Context, DefArg: getTrivialTemplateArgumentLoc(
1671 Arg: TemplateArgument(Default, /*IsCanonical=*/false),
1672 NTTPType: QualType(), Loc: SourceLocation()));
1673 }
1674
1675 return Param;
1676}
1677
1678/// ActOnTemplateTemplateParameter - Called when a C++ template template
1679/// parameter (e.g. T in template <template \<typename> class T> class array)
1680/// has been parsed. S is the current scope.
1681NamedDecl *Sema::ActOnTemplateTemplateParameter(
1682 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1683 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1684 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1685 unsigned Position, SourceLocation EqualLoc,
1686 ParsedTemplateArgument Default) {
1687 assert(S->isTemplateParamScope() &&
1688 "Template template parameter not in template parameter scope!");
1689
1690 bool IsParameterPack = EllipsisLoc.isValid();
1691
1692 SourceLocation Loc = NameLoc.isInvalid() ? TmpLoc : NameLoc;
1693 if (Params->size() == 0) {
1694 Diag(Loc, DiagID: diag::err_template_template_parm_no_parms)
1695 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1696
1697 // Recover as if there was a type template parameter pack.
1698 SmallVector<NamedDecl *, 4> ParamDecls;
1699 ParamDecls.push_back(Elt: TemplateTypeParmDecl::Create(
1700 C: Context, DC: Context.getTranslationUnitDecl(), KeyLoc: Loc, NameLoc: SourceLocation(),
1701 D: Depth + 1, P: 0, /*Id=*/nullptr,
1702 /*Typename=*/false, /*ParameterPack=*/true));
1703 Params = TemplateParameterList::Create(
1704 C: Context, TemplateLoc: Params->getTemplateLoc(), LAngleLoc: Params->getLAngleLoc(), Params: ParamDecls,
1705 RAngleLoc: Params->getRAngleLoc(), RequiresClause: Params->getRequiresClause());
1706 }
1707
1708 bool Invalid = false;
1709 if (CheckTemplateParameterList(
1710 NewParams: Params,
1711 /*OldParams=*/nullptr,
1712 TPC: IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1713 Invalid = true;
1714
1715 // Construct the parameter object.
1716 TemplateTemplateParmDecl *Param = TemplateTemplateParmDecl::Create(
1717 C: Context, DC: Context.getTranslationUnitDecl(), L: Loc, D: Depth, P: Position,
1718 ParameterPack: IsParameterPack, Id: Name, ParameterKind: Kind, Typename, Params);
1719 Param->setAccess(AS_public);
1720
1721 if (Param->isParameterPack())
1722 if (auto *LSI = getEnclosingLambdaOrBlock())
1723 LSI->LocalPacks.push_back(Elt: Param);
1724
1725 // If the template template parameter has a name, then link the identifier
1726 // into the scope and lookup mechanisms.
1727 if (Name) {
1728 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: NameLoc, Name);
1729
1730 S->AddDecl(D: Param);
1731 IdResolver.AddDecl(D: Param);
1732 }
1733
1734 if (Invalid)
1735 Param->setInvalidDecl();
1736
1737 // C++0x [temp.param]p9:
1738 // A default template-argument may be specified for any kind of
1739 // template-parameter that is not a template parameter pack.
1740 if (IsParameterPack && !Default.isInvalid()) {
1741 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1742 Default = ParsedTemplateArgument();
1743 }
1744
1745 if (!Default.isInvalid()) {
1746 // Check only that we have a template template argument. We don't want to
1747 // try to check well-formedness now, because our template template parameter
1748 // might have dependent types in its template parameters, which we wouldn't
1749 // be able to match now.
1750 //
1751 // If none of the template template parameter's template arguments mention
1752 // other template parameters, we could actually perform more checking here.
1753 // However, it isn't worth doing.
1754 TemplateArgumentLoc DefaultArg = translateTemplateArgument(SemaRef&: *this, Arg: Default);
1755 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1756 Diag(Loc: DefaultArg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
1757 << DefaultArg.getSourceRange();
1758 return Param;
1759 }
1760
1761 TemplateName Name =
1762 DefaultArg.getArgument().getAsTemplateOrTemplatePattern();
1763 TemplateDecl *Template = Name.getAsTemplateDecl();
1764 if (Template &&
1765 !CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg: DefaultArg)) {
1766 return Param;
1767 }
1768
1769 // Check for unexpanded parameter packs.
1770 if (DiagnoseUnexpandedParameterPack(Loc: DefaultArg.getLocation(),
1771 Template: DefaultArg.getArgument().getAsTemplate(),
1772 UPPC: UPPC_DefaultArgument))
1773 return Param;
1774
1775 Param->setDefaultArgument(C: Context, DefArg: DefaultArg);
1776 }
1777
1778 return Param;
1779}
1780
1781namespace {
1782class ConstraintRefersToContainingTemplateChecker
1783 : public ConstDynamicRecursiveASTVisitor {
1784 using inherited = ConstDynamicRecursiveASTVisitor;
1785 bool Result = false;
1786 const FunctionDecl *Friend = nullptr;
1787 unsigned TemplateDepth = 0;
1788
1789 // Check a record-decl that we've seen to see if it is a lexical parent of the
1790 // Friend, likely because it was referred to without its template arguments.
1791 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1792 CheckingRD = CheckingRD->getMostRecentDecl();
1793 if (!CheckingRD->isTemplated())
1794 return true;
1795
1796 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1797 DC && !DC->isFileContext(); DC = DC->getParent())
1798 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
1799 if (CheckingRD == RD->getMostRecentDecl()) {
1800 Result = true;
1801 return false;
1802 }
1803
1804 return true;
1805 }
1806
1807 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1808 if (D->getDepth() < TemplateDepth)
1809 Result = true;
1810
1811 // Necessary because the type of the NTTP might be what refers to the parent
1812 // constriant.
1813 return TraverseType(T: D->getType());
1814 }
1815
1816public:
1817 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1818 unsigned TemplateDepth)
1819 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1820
1821 bool getResult() const { return Result; }
1822
1823 // This should be the only template parm type that we have to deal with.
1824 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1825 // FunctionParmPackExpr are all partially substituted, which cannot happen
1826 // with concepts at this point in translation.
1827 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1828 if (Type->getDecl()->getDepth() < TemplateDepth) {
1829 Result = true;
1830 return false;
1831 }
1832 return true;
1833 }
1834
1835 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1836 return TraverseDecl(D: E->getDecl());
1837 }
1838
1839 bool TraverseTypedefType(const TypedefType *TT,
1840 bool /*TraverseQualifier*/) override {
1841 return TraverseType(T: TT->desugar());
1842 }
1843
1844 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1845 // We don't care about TypeLocs. So traverse Types instead.
1846 return TraverseType(T: TL.getType(), TraverseQualifier);
1847 }
1848
1849 bool VisitTagType(const TagType *T) override {
1850 return TraverseDecl(D: T->getDecl());
1851 }
1852
1853 bool TraverseDecl(const Decl *D) override {
1854 assert(D);
1855 // FIXME : This is possibly an incomplete list, but it is unclear what other
1856 // Decl kinds could be used to refer to the template parameters. This is a
1857 // best guess so far based on examples currently available, but the
1858 // unreachable should catch future instances/cases.
1859 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
1860 return TraverseType(T: TD->getUnderlyingType());
1861 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Val: D))
1862 return CheckNonTypeTemplateParmDecl(D: NTTPD);
1863 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
1864 return TraverseType(T: VD->getType());
1865 if (isa<TemplateDecl>(Val: D))
1866 return true;
1867 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1868 return CheckIfContainingRecord(CheckingRD: RD);
1869
1870 if (isa<NamedDecl, RequiresExprBodyDecl>(Val: D)) {
1871 // No direct types to visit here I believe.
1872 } else
1873 llvm_unreachable("Don't know how to handle this declaration type yet");
1874 return true;
1875 }
1876};
1877} // namespace
1878
1879bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1880 const FunctionDecl *Friend, unsigned TemplateDepth,
1881 const Expr *Constraint) {
1882 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1883 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1884 Checker.TraverseStmt(S: Constraint);
1885 return Checker.getResult();
1886}
1887
1888TemplateParameterList *
1889Sema::ActOnTemplateParameterList(unsigned Depth,
1890 SourceLocation ExportLoc,
1891 SourceLocation TemplateLoc,
1892 SourceLocation LAngleLoc,
1893 ArrayRef<NamedDecl *> Params,
1894 SourceLocation RAngleLoc,
1895 Expr *RequiresClause) {
1896 if (ExportLoc.isValid())
1897 Diag(Loc: ExportLoc, DiagID: diag::warn_template_export_unsupported);
1898
1899 for (NamedDecl *P : Params)
1900 warnOnReservedIdentifier(D: P);
1901
1902 return TemplateParameterList::Create(C: Context, TemplateLoc, LAngleLoc,
1903 Params: llvm::ArrayRef(Params), RAngleLoc,
1904 RequiresClause);
1905}
1906
1907static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1908 const CXXScopeSpec &SS) {
1909 if (SS.isSet())
1910 T->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
1911}
1912
1913// Returns the template parameter list with all default template argument
1914// information.
1915TemplateParameterList *Sema::GetTemplateParameterList(TemplateDecl *TD) {
1916 // Make sure we get the template parameter list from the most
1917 // recent declaration, since that is the only one that is guaranteed to
1918 // have all the default template argument information.
1919 Decl *D = TD->getMostRecentDecl();
1920 // C++11 N3337 [temp.param]p12:
1921 // A default template argument shall not be specified in a friend class
1922 // template declaration.
1923 //
1924 // Skip past friend *declarations* because they are not supposed to contain
1925 // default template arguments. Moreover, these declarations may introduce
1926 // template parameters living in different template depths than the
1927 // corresponding template parameters in TD, causing unmatched constraint
1928 // substitution.
1929 //
1930 // FIXME: Diagnose such cases within a class template:
1931 // template <class T>
1932 // struct S {
1933 // template <class = void> friend struct C;
1934 // };
1935 // template struct S<int>;
1936 while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
1937 D->getPreviousDecl())
1938 D = D->getPreviousDecl();
1939 return cast<TemplateDecl>(Val: D)->getTemplateParameters();
1940}
1941
1942DeclResult Sema::CheckClassTemplate(
1943 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1944 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1945 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1946 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1947 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1948 TemplateParameterList **OuterTemplateParamLists,
1949 bool IsMemberSpecialization, SkipBodyInfo *SkipBody) {
1950 assert(TemplateParams && TemplateParams->size() > 0 &&
1951 "No template parameters");
1952 assert(TUK != TagUseKind::Reference &&
1953 "Can only declare or define class templates");
1954 bool Invalid = false;
1955
1956 // Check that we can declare a template here.
1957 if (CheckTemplateDeclScope(S, TemplateParams))
1958 return true;
1959
1960 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
1961 assert(Kind != TagTypeKind::Enum &&
1962 "can't build template of enumerated type");
1963
1964 // There is no such thing as an unnamed class template.
1965 if (!Name) {
1966 Diag(Loc: KWLoc, DiagID: diag::err_template_unnamed_class);
1967 return true;
1968 }
1969
1970 // Find any previous declaration with this name. For a friend with no
1971 // scope explicitly specified, we only look for tag declarations (per
1972 // C++11 [basic.lookup.elab]p2).
1973 DeclContext *SemanticContext;
1974 LookupResult Previous(*this, Name, NameLoc,
1975 (SS.isEmpty() && TUK == TagUseKind::Friend)
1976 ? LookupTagName
1977 : LookupOrdinaryName,
1978 forRedeclarationInCurContext());
1979 if (SS.isNotEmpty() && !SS.isInvalid()) {
1980 SemanticContext = computeDeclContext(SS, EnteringContext: true);
1981 if (!SemanticContext) {
1982 Diag(Loc: NameLoc, DiagID: diag::err_template_qualified_declarator_no_match)
1983 << SS.getScopeRep() << SS.getRange();
1984 return true;
1985 }
1986
1987 if (RequireCompleteDeclContext(SS, DC: SemanticContext))
1988 return true;
1989
1990 // If we're adding a template to a dependent context, we may need to
1991 // rebuilding some of the types used within the template parameter list,
1992 // now that we know what the current instantiation is.
1993 if (SemanticContext->isDependentContext()) {
1994 ContextRAII SavedContext(*this, SemanticContext);
1995 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
1996 Invalid = true;
1997 }
1998
1999 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference &&
2000 diagnoseQualifiedDeclaration(SS, DC: SemanticContext, Name, Loc: NameLoc,
2001 /*TemplateId=*/nullptr,
2002 IsMemberSpecialization))
2003 return true;
2004
2005 LookupQualifiedName(R&: Previous, LookupCtx: SemanticContext);
2006 } else {
2007 SemanticContext = CurContext;
2008
2009 // C++14 [class.mem]p14:
2010 // If T is the name of a class, then each of the following shall have a
2011 // name different from T:
2012 // -- every member template of class T
2013 if (TUK != TagUseKind::Friend &&
2014 DiagnoseClassNameShadow(DC: SemanticContext,
2015 Info: DeclarationNameInfo(Name, NameLoc)))
2016 return true;
2017
2018 LookupName(R&: Previous, S);
2019 }
2020
2021 if (Previous.isAmbiguous())
2022 return true;
2023
2024 // Let the template parameter scope enter the lookup chain of the current
2025 // class template. For example, given
2026 //
2027 // namespace ns {
2028 // template <class> bool Param = false;
2029 // template <class T> struct N;
2030 // }
2031 //
2032 // template <class Param> struct ns::N { void foo(Param); };
2033 //
2034 // When we reference Param inside the function parameter list, our name lookup
2035 // chain for it should be like:
2036 // FunctionScope foo
2037 // -> RecordScope N
2038 // -> TemplateParamScope (where we will find Param)
2039 // -> NamespaceScope ns
2040 //
2041 // See also CppLookupName().
2042 if (S->isTemplateParamScope())
2043 EnterTemplatedContext(S, DC: SemanticContext);
2044
2045 NamedDecl *PrevDecl = nullptr;
2046 if (Previous.begin() != Previous.end())
2047 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2048
2049 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2050 // Maybe we will complain about the shadowed template parameter.
2051 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl);
2052 // Just pretend that we didn't see the previous declaration.
2053 PrevDecl = nullptr;
2054 }
2055
2056 // If there is a previous declaration with the same name, check
2057 // whether this is a valid redeclaration.
2058 ClassTemplateDecl *PrevClassTemplate =
2059 dyn_cast_or_null<ClassTemplateDecl>(Val: PrevDecl);
2060
2061 // We may have found the injected-class-name of a class template,
2062 // class template partial specialization, or class template specialization.
2063 // In these cases, grab the template that is being defined or specialized.
2064 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(Val: PrevDecl) &&
2065 cast<CXXRecordDecl>(Val: PrevDecl)->isInjectedClassName()) {
2066 PrevDecl = cast<CXXRecordDecl>(Val: PrevDecl->getDeclContext());
2067 PrevClassTemplate
2068 = cast<CXXRecordDecl>(Val: PrevDecl)->getDescribedClassTemplate();
2069 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(Val: PrevDecl)) {
2070 PrevClassTemplate
2071 = cast<ClassTemplateSpecializationDecl>(Val: PrevDecl)
2072 ->getSpecializedTemplate();
2073 }
2074 }
2075
2076 if (TUK == TagUseKind::Friend) {
2077 // C++ [namespace.memdef]p3:
2078 // [...] When looking for a prior declaration of a class or a function
2079 // declared as a friend, and when the name of the friend class or
2080 // function is neither a qualified name nor a template-id, scopes outside
2081 // the innermost enclosing namespace scope are not considered.
2082 if (!SS.isSet()) {
2083 DeclContext *OutermostContext = CurContext;
2084 while (!OutermostContext->isFileContext())
2085 OutermostContext = OutermostContext->getLookupParent();
2086
2087 if (PrevDecl &&
2088 (OutermostContext->Equals(DC: PrevDecl->getDeclContext()) ||
2089 OutermostContext->Encloses(DC: PrevDecl->getDeclContext()))) {
2090 SemanticContext = PrevDecl->getDeclContext();
2091 } else {
2092 // Declarations in outer scopes don't matter. However, the outermost
2093 // context we computed is the semantic context for our new
2094 // declaration.
2095 PrevDecl = PrevClassTemplate = nullptr;
2096 SemanticContext = OutermostContext;
2097
2098 // Check that the chosen semantic context doesn't already contain a
2099 // declaration of this name as a non-tag type.
2100 Previous.clear(Kind: LookupOrdinaryName);
2101 DeclContext *LookupContext = SemanticContext;
2102 while (LookupContext->isTransparentContext())
2103 LookupContext = LookupContext->getLookupParent();
2104 LookupQualifiedName(R&: Previous, LookupCtx: LookupContext);
2105
2106 if (Previous.isAmbiguous())
2107 return true;
2108
2109 if (Previous.begin() != Previous.end())
2110 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2111 }
2112 }
2113 } else if (PrevDecl && !isDeclInScope(D: Previous.getRepresentativeDecl(),
2114 Ctx: SemanticContext, S, AllowInlineNamespace: SS.isValid()))
2115 PrevDecl = PrevClassTemplate = nullptr;
2116
2117 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2118 Val: PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2119 if (SS.isEmpty() &&
2120 !(PrevClassTemplate &&
2121 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2122 DC: SemanticContext->getRedeclContext()))) {
2123 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
2124 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
2125 DiagID: diag::note_using_decl_target);
2126 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
2127 // Recover by ignoring the old declaration.
2128 PrevDecl = PrevClassTemplate = nullptr;
2129 }
2130 }
2131
2132 if (PrevClassTemplate) {
2133 // Ensure that the template parameter lists are compatible. Skip this check
2134 // for a friend in a dependent context: the template parameter list itself
2135 // could be dependent.
2136 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2137 !TemplateParameterListsAreEqual(
2138 NewInstFrom: TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2139 : CurContext,
2140 CurContext, KWLoc),
2141 New: TemplateParams, OldInstFrom: PrevClassTemplate,
2142 Old: PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2143 Kind: TPL_TemplateMatch))
2144 return true;
2145
2146 // C++ [temp.class]p4:
2147 // In a redeclaration, partial specialization, explicit
2148 // specialization or explicit instantiation of a class template,
2149 // the class-key shall agree in kind with the original class
2150 // template declaration (7.1.5.3).
2151 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2152 if (!isAcceptableTagRedeclaration(
2153 Previous: PrevRecordDecl, NewTag: Kind, isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc, Name)) {
2154 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
2155 << Name
2156 << FixItHint::CreateReplacement(RemoveRange: KWLoc, Code: PrevRecordDecl->getKindName());
2157 Diag(Loc: PrevRecordDecl->getLocation(), DiagID: diag::note_previous_use);
2158 Kind = PrevRecordDecl->getTagKind();
2159 }
2160
2161 // Check for redefinition of this class template.
2162 if (TUK == TagUseKind::Definition) {
2163 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2164 // If we have a prior definition that is not visible, treat this as
2165 // simply making that previous definition visible.
2166 NamedDecl *Hidden = nullptr;
2167 bool HiddenDefVisible = false;
2168 if (SkipBody &&
2169 isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible)) {
2170 SkipBody->ShouldSkip = true;
2171 SkipBody->Previous = Def;
2172 if (!HiddenDefVisible && Hidden) {
2173 auto *Tmpl =
2174 cast<CXXRecordDecl>(Val: Hidden)->getDescribedClassTemplate();
2175 assert(Tmpl && "original definition of a class template is not a "
2176 "class template?");
2177 makeMergedDefinitionVisible(ND: Hidden);
2178 makeMergedDefinitionVisible(ND: Tmpl);
2179 }
2180 } else {
2181 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
2182 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
2183 // FIXME: Would it make sense to try to "forget" the previous
2184 // definition, as part of error recovery?
2185 return true;
2186 }
2187 }
2188 }
2189 } else if (PrevDecl) {
2190 // C++ [temp]p5:
2191 // A class template shall not have the same name as any other
2192 // template, class, function, object, enumeration, enumerator,
2193 // namespace, or type in the same scope (3.3), except as specified
2194 // in (14.5.4).
2195 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
2196 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
2197 return true;
2198 }
2199
2200 // Check the template parameter list of this declaration, possibly
2201 // merging in the template parameter list from the previous class
2202 // template declaration. Skip this check for a friend in a dependent
2203 // context, because the template parameter list might be dependent.
2204 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2205 CheckTemplateParameterList(
2206 NewParams: TemplateParams,
2207 OldParams: PrevClassTemplate ? GetTemplateParameterList(TD: PrevClassTemplate)
2208 : nullptr,
2209 TPC: (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2210 SemanticContext->isDependentContext())
2211 ? TPC_ClassTemplateMember
2212 : TUK == TagUseKind::Friend ? TPC_FriendClassTemplate
2213 : TPC_Other,
2214 SkipBody))
2215 Invalid = true;
2216
2217 if (SS.isSet()) {
2218 // If the name of the template was qualified, we must be defining the
2219 // template out-of-line.
2220 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate)
2221 return Diag(Loc: NameLoc, DiagID: TUK == TagUseKind::Friend
2222 ? diag::err_friend_decl_does_not_match
2223 : diag::err_member_decl_does_not_match)
2224 << Name << SemanticContext << /*IsDefinition*/ true
2225 << SS.getRange();
2226 }
2227
2228 // If this is a templated friend in a dependent context we should not put it
2229 // on the redecl chain. In some cases, the templated friend can be the most
2230 // recent declaration tricking the template instantiator to make substitutions
2231 // there.
2232 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2233 bool ShouldAddRedecl =
2234 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2235
2236 CXXRecordDecl *NewClass = CXXRecordDecl::Create(
2237 C: Context, TK: Kind, DC: SemanticContext, StartLoc: KWLoc, IdLoc: NameLoc, Id: Name,
2238 PrevDecl: PrevClassTemplate && ShouldAddRedecl
2239 ? PrevClassTemplate->getTemplatedDecl()
2240 : nullptr);
2241 SetNestedNameSpecifier(S&: *this, T: NewClass, SS);
2242 if (NumOuterTemplateParamLists > 0)
2243 NewClass->setTemplateParameterListsInfo(
2244 Context,
2245 TPLists: llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2246
2247 // Add alignment attributes if necessary; these attributes are checked when
2248 // the ASTContext lays out the structure.
2249 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2250 if (LangOpts.HLSL)
2251 NewClass->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
2252 AddAlignmentAttributesForRecord(RD: NewClass);
2253 AddMsStructLayoutForRecord(RD: NewClass);
2254 }
2255
2256 ClassTemplateDecl *NewTemplate
2257 = ClassTemplateDecl::Create(C&: Context, DC: SemanticContext, L: NameLoc,
2258 Name: DeclarationName(Name), Params: TemplateParams,
2259 Decl: NewClass);
2260
2261 if (ShouldAddRedecl)
2262 NewTemplate->setPreviousDecl(PrevClassTemplate);
2263
2264 NewClass->setDescribedClassTemplate(NewTemplate);
2265
2266 if (ModulePrivateLoc.isValid())
2267 NewTemplate->setModulePrivate();
2268
2269 if (IsMemberSpecialization) {
2270 assert(PrevClassTemplate &&
2271 "Member specialization without a primary template?");
2272 NewTemplate->setMemberSpecialization();
2273 }
2274
2275 // Set the access specifier.
2276 if (!Invalid && TUK != TagUseKind::Friend &&
2277 NewTemplate->getDeclContext()->isRecord())
2278 SetMemberAccessSpecifier(MemberDecl: NewTemplate, PrevMemberDecl: PrevClassTemplate, LexicalAS: AS);
2279
2280 // Set the lexical context of these templates
2281 NewClass->setLexicalDeclContext(CurContext);
2282 NewTemplate->setLexicalDeclContext(CurContext);
2283
2284 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2285 NewClass->startDefinition();
2286
2287 ProcessDeclAttributeList(S, D: NewClass, AttrList: Attr);
2288
2289 if (PrevClassTemplate) {
2290 mergeDeclAttributes(New: NewTemplate, Old: PrevClassTemplate);
2291 mergeDeclAttributes(New: NewClass, Old: PrevClassTemplate->getTemplatedDecl());
2292 }
2293
2294 AddPushedVisibilityAttribute(RD: NewClass);
2295 inferGslOwnerPointerAttribute(Record: NewClass);
2296 inferNullableClassAttribute(CRD: NewClass);
2297
2298 if (TUK != TagUseKind::Friend) {
2299 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2300 Scope *Outer = S;
2301 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2302 Outer = Outer->getParent();
2303 PushOnScopeChains(D: NewTemplate, S: Outer);
2304 } else {
2305 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2306 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2307 NewClass->setAccess(PrevClassTemplate->getAccess());
2308 }
2309
2310 NewTemplate->setObjectOfFriendDecl();
2311
2312 // Friend templates are visible in fairly strange ways.
2313 if (!CurContext->isDependentContext()) {
2314 DeclContext *DC = SemanticContext->getRedeclContext();
2315 DC->makeDeclVisibleInContext(D: NewTemplate);
2316 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2317 PushOnScopeChains(D: NewTemplate, S: EnclosingScope,
2318 /* AddToContext = */ false);
2319 }
2320
2321 FriendDecl *Friend = FriendDecl::Create(
2322 C&: Context, DC: CurContext, L: NewClass->getLocation(), Friend: NewTemplate, FriendL: FriendLoc);
2323 Friend->setAccess(AS_public);
2324 CurContext->addDecl(D: Friend);
2325 }
2326
2327 if (PrevClassTemplate)
2328 CheckRedeclarationInModule(New: NewTemplate, Old: PrevClassTemplate);
2329
2330 if (Invalid) {
2331 NewTemplate->setInvalidDecl();
2332 NewClass->setInvalidDecl();
2333 }
2334
2335 ActOnDocumentableDecl(D: NewTemplate);
2336
2337 if (SkipBody && SkipBody->ShouldSkip)
2338 return SkipBody->Previous;
2339
2340 return NewTemplate;
2341}
2342
2343/// Diagnose the presence of a default template argument on a
2344/// template parameter, which is ill-formed in certain contexts.
2345///
2346/// \returns true if the default template argument should be dropped.
2347static bool DiagnoseDefaultTemplateArgument(Sema &S,
2348 Sema::TemplateParamListContext TPC,
2349 SourceLocation ParamLoc,
2350 SourceRange DefArgRange) {
2351 switch (TPC) {
2352 case Sema::TPC_Other:
2353 case Sema::TPC_TemplateTemplateParameterPack:
2354 return false;
2355
2356 case Sema::TPC_FunctionTemplate:
2357 case Sema::TPC_FriendFunctionTemplateDefinition:
2358 // C++ [temp.param]p9:
2359 // A default template-argument shall not be specified in a
2360 // function template declaration or a function template
2361 // definition [...]
2362 // If a friend function template declaration specifies a default
2363 // template-argument, that declaration shall be a definition and shall be
2364 // the only declaration of the function template in the translation unit.
2365 // (C++98/03 doesn't have this wording; see DR226).
2366 S.DiagCompat(Loc: ParamLoc, CompatDiagId: diag_compat::templ_default_in_function_templ)
2367 << DefArgRange;
2368 return false;
2369
2370 case Sema::TPC_ClassTemplateMember:
2371 // C++0x [temp.param]p9:
2372 // A default template-argument shall not be specified in the
2373 // template-parameter-lists of the definition of a member of a
2374 // class template that appears outside of the member's class.
2375 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_template_member)
2376 << DefArgRange;
2377 return true;
2378
2379 case Sema::TPC_FriendClassTemplate:
2380 case Sema::TPC_FriendFunctionTemplate:
2381 // C++ [temp.param]p9:
2382 // A default template-argument shall not be specified in a
2383 // friend template declaration.
2384 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_friend_template)
2385 << DefArgRange;
2386 return true;
2387
2388 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2389 // for friend function templates if there is only a single
2390 // declaration (and it is a definition). Strange!
2391 }
2392
2393 llvm_unreachable("Invalid TemplateParamListContext!");
2394}
2395
2396/// Check for unexpanded parameter packs within the template parameters
2397/// of a template template parameter, recursively.
2398static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2399 TemplateTemplateParmDecl *TTP) {
2400 // A template template parameter which is a parameter pack is also a pack
2401 // expansion.
2402 if (TTP->isParameterPack())
2403 return false;
2404
2405 TemplateParameterList *Params = TTP->getTemplateParameters();
2406 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2407 NamedDecl *P = Params->getParam(Idx: I);
2408 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: P)) {
2409 if (!TTP->isParameterPack())
2410 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2411 if (TC->hasExplicitTemplateArgs())
2412 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2413 if (S.DiagnoseUnexpandedParameterPack(Arg: ArgLoc,
2414 UPPC: Sema::UPPC_TypeConstraint))
2415 return true;
2416 continue;
2417 }
2418
2419 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: P)) {
2420 if (!NTTP->isParameterPack() &&
2421 S.DiagnoseUnexpandedParameterPack(Loc: NTTP->getLocation(),
2422 T: NTTP->getTypeSourceInfo(),
2423 UPPC: Sema::UPPC_NonTypeTemplateParameterType))
2424 return true;
2425
2426 continue;
2427 }
2428
2429 if (TemplateTemplateParmDecl *InnerTTP
2430 = dyn_cast<TemplateTemplateParmDecl>(Val: P))
2431 if (DiagnoseUnexpandedParameterPacks(S, TTP: InnerTTP))
2432 return true;
2433 }
2434
2435 return false;
2436}
2437
2438bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2439 TemplateParameterList *OldParams,
2440 TemplateParamListContext TPC,
2441 SkipBodyInfo *SkipBody) {
2442 bool Invalid = false;
2443
2444 // C++ [temp.param]p10:
2445 // The set of default template-arguments available for use with a
2446 // template declaration or definition is obtained by merging the
2447 // default arguments from the definition (if in scope) and all
2448 // declarations in scope in the same way default function
2449 // arguments are (8.3.6).
2450 bool SawDefaultArgument = false;
2451 SourceLocation PreviousDefaultArgLoc;
2452
2453 // Dummy initialization to avoid warnings.
2454 TemplateParameterList::iterator OldParam = NewParams->end();
2455 if (OldParams)
2456 OldParam = OldParams->begin();
2457
2458 bool RemoveDefaultArguments = false;
2459 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2460 NewParamEnd = NewParams->end();
2461 NewParam != NewParamEnd; ++NewParam) {
2462 // Whether we've seen a duplicate default argument in the same translation
2463 // unit.
2464 bool RedundantDefaultArg = false;
2465 // Whether we've found inconsis inconsitent default arguments in different
2466 // translation unit.
2467 bool InconsistentDefaultArg = false;
2468 // The name of the module which contains the inconsistent default argument.
2469 std::string PrevModuleName;
2470
2471 SourceLocation OldDefaultLoc;
2472 SourceLocation NewDefaultLoc;
2473
2474 // Variable used to diagnose missing default arguments
2475 bool MissingDefaultArg = false;
2476
2477 // Variable used to diagnose non-final parameter packs
2478 bool SawParameterPack = false;
2479
2480 if (TemplateTypeParmDecl *NewTypeParm
2481 = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam)) {
2482 // Check the presence of a default argument here.
2483 if (NewTypeParm->hasDefaultArgument() &&
2484 DiagnoseDefaultTemplateArgument(
2485 S&: *this, TPC, ParamLoc: NewTypeParm->getLocation(),
2486 DefArgRange: NewTypeParm->getDefaultArgument().getSourceRange()))
2487 NewTypeParm->removeDefaultArgument();
2488
2489 // Merge default arguments for template type parameters.
2490 TemplateTypeParmDecl *OldTypeParm
2491 = OldParams? cast<TemplateTypeParmDecl>(Val: *OldParam) : nullptr;
2492 if (NewTypeParm->isParameterPack()) {
2493 assert(!NewTypeParm->hasDefaultArgument() &&
2494 "Parameter packs can't have a default argument!");
2495 SawParameterPack = true;
2496 } else if (OldTypeParm && hasVisibleDefaultArgument(D: OldTypeParm) &&
2497 NewTypeParm->hasDefaultArgument() &&
2498 (!SkipBody || !SkipBody->ShouldSkip)) {
2499 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2500 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2501 SawDefaultArgument = true;
2502
2503 if (!OldTypeParm->getOwningModule())
2504 RedundantDefaultArg = true;
2505 else if (!getASTContext().isSameDefaultTemplateArgument(X: OldTypeParm,
2506 Y: NewTypeParm)) {
2507 InconsistentDefaultArg = true;
2508 PrevModuleName =
2509 OldTypeParm->getImportedOwningModule()->getFullModuleName();
2510 }
2511 PreviousDefaultArgLoc = NewDefaultLoc;
2512 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2513 // Merge the default argument from the old declaration to the
2514 // new declaration.
2515 NewTypeParm->setInheritedDefaultArgument(C: Context, Prev: OldTypeParm);
2516 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2517 } else if (NewTypeParm->hasDefaultArgument()) {
2518 SawDefaultArgument = true;
2519 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2520 } else if (SawDefaultArgument)
2521 MissingDefaultArg = true;
2522 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2523 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam)) {
2524 // Check for unexpanded parameter packs, except in a template template
2525 // parameter pack, as in those any unexpanded packs should be expanded
2526 // along with the parameter itself.
2527 if (TPC != TPC_TemplateTemplateParameterPack &&
2528 !NewNonTypeParm->isParameterPack() &&
2529 DiagnoseUnexpandedParameterPack(Loc: NewNonTypeParm->getLocation(),
2530 T: NewNonTypeParm->getTypeSourceInfo(),
2531 UPPC: UPPC_NonTypeTemplateParameterType)) {
2532 Invalid = true;
2533 continue;
2534 }
2535
2536 // Check the presence of a default argument here.
2537 if (NewNonTypeParm->hasDefaultArgument() &&
2538 DiagnoseDefaultTemplateArgument(
2539 S&: *this, TPC, ParamLoc: NewNonTypeParm->getLocation(),
2540 DefArgRange: NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2541 NewNonTypeParm->removeDefaultArgument();
2542 }
2543
2544 // Merge default arguments for non-type template parameters
2545 NonTypeTemplateParmDecl *OldNonTypeParm
2546 = OldParams? cast<NonTypeTemplateParmDecl>(Val: *OldParam) : nullptr;
2547 if (NewNonTypeParm->isParameterPack()) {
2548 assert(!NewNonTypeParm->hasDefaultArgument() &&
2549 "Parameter packs can't have a default argument!");
2550 if (!NewNonTypeParm->isPackExpansion())
2551 SawParameterPack = true;
2552 } else if (OldNonTypeParm && hasVisibleDefaultArgument(D: OldNonTypeParm) &&
2553 NewNonTypeParm->hasDefaultArgument() &&
2554 (!SkipBody || !SkipBody->ShouldSkip)) {
2555 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2556 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2557 SawDefaultArgument = true;
2558 if (!OldNonTypeParm->getOwningModule())
2559 RedundantDefaultArg = true;
2560 else if (!getASTContext().isSameDefaultTemplateArgument(
2561 X: OldNonTypeParm, Y: NewNonTypeParm)) {
2562 InconsistentDefaultArg = true;
2563 PrevModuleName =
2564 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2565 }
2566 PreviousDefaultArgLoc = NewDefaultLoc;
2567 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2568 // Merge the default argument from the old declaration to the
2569 // new declaration.
2570 NewNonTypeParm->setInheritedDefaultArgument(C: Context, Parm: OldNonTypeParm);
2571 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2572 } else if (NewNonTypeParm->hasDefaultArgument()) {
2573 SawDefaultArgument = true;
2574 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2575 } else if (SawDefaultArgument)
2576 MissingDefaultArg = true;
2577 } else {
2578 TemplateTemplateParmDecl *NewTemplateParm
2579 = cast<TemplateTemplateParmDecl>(Val: *NewParam);
2580
2581 // Check for unexpanded parameter packs, recursively.
2582 if (::DiagnoseUnexpandedParameterPacks(S&: *this, TTP: NewTemplateParm)) {
2583 Invalid = true;
2584 continue;
2585 }
2586
2587 // Check the presence of a default argument here.
2588 if (NewTemplateParm->hasDefaultArgument() &&
2589 DiagnoseDefaultTemplateArgument(S&: *this, TPC,
2590 ParamLoc: NewTemplateParm->getLocation(),
2591 DefArgRange: NewTemplateParm->getDefaultArgument().getSourceRange()))
2592 NewTemplateParm->removeDefaultArgument();
2593
2594 // Merge default arguments for template template parameters
2595 TemplateTemplateParmDecl *OldTemplateParm
2596 = OldParams? cast<TemplateTemplateParmDecl>(Val: *OldParam) : nullptr;
2597 if (NewTemplateParm->isParameterPack()) {
2598 assert(!NewTemplateParm->hasDefaultArgument() &&
2599 "Parameter packs can't have a default argument!");
2600 if (!NewTemplateParm->isPackExpansion())
2601 SawParameterPack = true;
2602 } else if (OldTemplateParm &&
2603 hasVisibleDefaultArgument(D: OldTemplateParm) &&
2604 NewTemplateParm->hasDefaultArgument() &&
2605 (!SkipBody || !SkipBody->ShouldSkip)) {
2606 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2607 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2608 SawDefaultArgument = true;
2609 if (!OldTemplateParm->getOwningModule())
2610 RedundantDefaultArg = true;
2611 else if (!getASTContext().isSameDefaultTemplateArgument(
2612 X: OldTemplateParm, Y: NewTemplateParm)) {
2613 InconsistentDefaultArg = true;
2614 PrevModuleName =
2615 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2616 }
2617 PreviousDefaultArgLoc = NewDefaultLoc;
2618 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2619 // Merge the default argument from the old declaration to the
2620 // new declaration.
2621 NewTemplateParm->setInheritedDefaultArgument(C: Context, Prev: OldTemplateParm);
2622 PreviousDefaultArgLoc
2623 = OldTemplateParm->getDefaultArgument().getLocation();
2624 } else if (NewTemplateParm->hasDefaultArgument()) {
2625 SawDefaultArgument = true;
2626 PreviousDefaultArgLoc
2627 = NewTemplateParm->getDefaultArgument().getLocation();
2628 } else if (SawDefaultArgument)
2629 MissingDefaultArg = true;
2630 }
2631
2632 // C++11 [temp.param]p11:
2633 // If a template parameter of a primary class template or alias template
2634 // is a template parameter pack, it shall be the last template parameter.
2635 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2636 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2637 Diag(Loc: (*NewParam)->getLocation(),
2638 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
2639 Invalid = true;
2640 }
2641
2642 // [basic.def.odr]/13:
2643 // There can be more than one definition of a
2644 // ...
2645 // default template argument
2646 // ...
2647 // in a program provided that each definition appears in a different
2648 // translation unit and the definitions satisfy the [same-meaning
2649 // criteria of the ODR].
2650 //
2651 // Simply, the design of modules allows the definition of template default
2652 // argument to be repeated across translation unit. Note that the ODR is
2653 // checked elsewhere. But it is still not allowed to repeat template default
2654 // argument in the same translation unit.
2655 if (RedundantDefaultArg) {
2656 Diag(Loc: NewDefaultLoc, DiagID: diag::err_template_param_default_arg_redefinition);
2657 Diag(Loc: OldDefaultLoc, DiagID: diag::note_template_param_prev_default_arg);
2658 Invalid = true;
2659 } else if (InconsistentDefaultArg) {
2660 // We could only diagnose about the case that the OldParam is imported.
2661 // The case NewParam is imported should be handled in ASTReader.
2662 Diag(Loc: NewDefaultLoc,
2663 DiagID: diag::err_template_param_default_arg_inconsistent_redefinition);
2664 Diag(Loc: OldDefaultLoc,
2665 DiagID: diag::note_template_param_prev_default_arg_in_other_module)
2666 << PrevModuleName;
2667 Invalid = true;
2668 } else if (MissingDefaultArg &&
2669 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2670 TPC == TPC_FriendClassTemplate)) {
2671 // C++ 23[temp.param]p14:
2672 // If a template-parameter of a class template, variable template, or
2673 // alias template has a default template argument, each subsequent
2674 // template-parameter shall either have a default template argument
2675 // supplied or be a template parameter pack.
2676 Diag(Loc: (*NewParam)->getLocation(),
2677 DiagID: diag::err_template_param_default_arg_missing);
2678 Diag(Loc: PreviousDefaultArgLoc, DiagID: diag::note_template_param_prev_default_arg);
2679 Invalid = true;
2680 RemoveDefaultArguments = true;
2681 }
2682
2683 // If we have an old template parameter list that we're merging
2684 // in, move on to the next parameter.
2685 if (OldParams)
2686 ++OldParam;
2687 }
2688
2689 // We were missing some default arguments at the end of the list, so remove
2690 // all of the default arguments.
2691 if (RemoveDefaultArguments) {
2692 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2693 NewParamEnd = NewParams->end();
2694 NewParam != NewParamEnd; ++NewParam) {
2695 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam))
2696 TTP->removeDefaultArgument();
2697 else if (NonTypeTemplateParmDecl *NTTP
2698 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam))
2699 NTTP->removeDefaultArgument();
2700 else
2701 cast<TemplateTemplateParmDecl>(Val: *NewParam)->removeDefaultArgument();
2702 }
2703 }
2704
2705 return Invalid;
2706}
2707
2708namespace {
2709
2710/// A class which looks for a use of a certain level of template
2711/// parameter.
2712struct DependencyChecker : DynamicRecursiveASTVisitor {
2713 unsigned Depth;
2714
2715 // Whether we're looking for a use of a template parameter that makes the
2716 // overall construct type-dependent / a dependent type. This is strictly
2717 // best-effort for now; we may fail to match at all for a dependent type
2718 // in some cases if this is set.
2719 bool IgnoreNonTypeDependent;
2720
2721 bool Match;
2722 SourceLocation MatchLoc;
2723
2724 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2725 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2726 Match(false) {}
2727
2728 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2729 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2730 NamedDecl *ND = Params->getParam(Idx: 0);
2731 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(Val: ND)) {
2732 Depth = PD->getDepth();
2733 } else if (NonTypeTemplateParmDecl *PD =
2734 dyn_cast<NonTypeTemplateParmDecl>(Val: ND)) {
2735 Depth = PD->getDepth();
2736 } else {
2737 Depth = cast<TemplateTemplateParmDecl>(Val: ND)->getDepth();
2738 }
2739 }
2740
2741 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2742 if (ParmDepth >= Depth) {
2743 Match = true;
2744 MatchLoc = Loc;
2745 return true;
2746 }
2747 return false;
2748 }
2749
2750 bool TraverseStmt(Stmt *S) override {
2751 // Prune out non-type-dependent expressions if requested. This can
2752 // sometimes result in us failing to find a template parameter reference
2753 // (if a value-dependent expression creates a dependent type), but this
2754 // mode is best-effort only.
2755 if (auto *E = dyn_cast_or_null<Expr>(Val: S))
2756 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2757 return true;
2758 return DynamicRecursiveASTVisitor::TraverseStmt(S);
2759 }
2760
2761 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2762 if (IgnoreNonTypeDependent && !TL.isNull() &&
2763 !TL.getType()->isDependentType())
2764 return true;
2765 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2766 }
2767
2768 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2769 return !Matches(ParmDepth: TL.getTypePtr()->getDepth(), Loc: TL.getNameLoc());
2770 }
2771
2772 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2773 // For a best-effort search, keep looking until we find a location.
2774 return IgnoreNonTypeDependent || !Matches(ParmDepth: T->getDepth());
2775 }
2776
2777 bool TraverseTemplateName(TemplateName N, bool TraverseQualifier) override {
2778 if (TemplateTemplateParmDecl *PD =
2779 dyn_cast_or_null<TemplateTemplateParmDecl>(Val: N.getAsTemplateDecl()))
2780 if (Matches(ParmDepth: PD->getDepth()))
2781 return false;
2782 return DynamicRecursiveASTVisitor::TraverseTemplateName(Template: N,
2783 TraverseQualifier);
2784 }
2785
2786 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2787 if (NonTypeTemplateParmDecl *PD =
2788 dyn_cast<NonTypeTemplateParmDecl>(Val: E->getDecl()))
2789 if (Matches(ParmDepth: PD->getDepth(), Loc: E->getExprLoc()))
2790 return false;
2791 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(S: E);
2792 }
2793
2794 bool VisitDependentTemplateIdExpr(DependentTemplateIdExpr *E) override {
2795 if (Matches(ParmDepth: E->getParameter()->getDepth(), Loc: E->getExprLoc()))
2796 return false;
2797 return DynamicRecursiveASTVisitor::VisitDependentTemplateIdExpr(S: E);
2798 }
2799
2800 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2801 return TraverseType(T: T->getReplacementType());
2802 }
2803
2804 bool VisitSubstTemplateTypeParmPackType(
2805 SubstTemplateTypeParmPackType *T) override {
2806 return TraverseTemplateArgument(Arg: T->getArgumentPack());
2807 }
2808
2809 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2810 bool TraverseQualifier) override {
2811 // An InjectedClassNameType will never have a dependent template name,
2812 // so no need to traverse it.
2813 return TraverseTemplateArguments(
2814 Args: T->getTemplateArgs(Ctx: T->getDecl()->getASTContext()));
2815 }
2816};
2817} // end anonymous namespace
2818
2819/// Determines whether a given type depends on the given parameter
2820/// list.
2821static bool
2822DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2823 if (!Params->size())
2824 return false;
2825
2826 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2827 Checker.TraverseType(T);
2828 return Checker.Match;
2829}
2830
2831// Find the source range corresponding to the named type in the given
2832// nested-name-specifier, if any.
2833static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2834 QualType T,
2835 const CXXScopeSpec &SS) {
2836 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2837 for (;;) {
2838 NestedNameSpecifier NNS = NNSLoc.getNestedNameSpecifier();
2839 if (NNS.getKind() != NestedNameSpecifier::Kind::Type)
2840 break;
2841 if (Context.hasSameUnqualifiedType(T1: T, T2: QualType(NNS.getAsType(), 0)))
2842 return NNSLoc.castAsTypeLoc().getSourceRange();
2843 // FIXME: This will always be empty.
2844 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2845 }
2846
2847 return SourceRange();
2848}
2849
2850TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2851 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2852 TemplateIdAnnotation *TemplateId,
2853 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2854 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2855 IsMemberSpecialization = false;
2856 Invalid = false;
2857
2858 // The sequence of nested types to which we will match up the template
2859 // parameter lists. We first build this list by starting with the type named
2860 // by the nested-name-specifier and walking out until we run out of types.
2861 SmallVector<QualType, 4> NestedTypes;
2862 QualType T;
2863 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2864 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2865 if (CXXRecordDecl *Record =
2866 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: true)))
2867 T = Context.getCanonicalTagType(TD: Record);
2868 else
2869 T = QualType(Qualifier.getAsType(), 0);
2870 }
2871
2872 // If we found an explicit specialization that prevents us from needing
2873 // 'template<>' headers, this will be set to the location of that
2874 // explicit specialization.
2875 SourceLocation ExplicitSpecLoc;
2876
2877 while (!T.isNull()) {
2878 NestedTypes.push_back(Elt: T);
2879
2880 // Retrieve the parent of a record type.
2881 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2882 // If this type is an explicit specialization, we're done.
2883 if (ClassTemplateSpecializationDecl *Spec
2884 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
2885 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Spec) &&
2886 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2887 ExplicitSpecLoc = Spec->getLocation();
2888 break;
2889 }
2890 } else if (Record->getTemplateSpecializationKind()
2891 == TSK_ExplicitSpecialization) {
2892 ExplicitSpecLoc = Record->getLocation();
2893 break;
2894 }
2895
2896 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Record->getParent()))
2897 T = Context.getTypeDeclType(Decl: Parent);
2898 else
2899 T = QualType();
2900 continue;
2901 }
2902
2903 if (const TemplateSpecializationType *TST
2904 = T->getAs<TemplateSpecializationType>()) {
2905 TemplateName Name = TST->getTemplateName();
2906 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2907 // Look one step prior in a dependent template specialization type.
2908 if (NestedNameSpecifier NNS = DTS->getQualifier();
2909 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2910 T = QualType(NNS.getAsType(), 0);
2911 else
2912 T = QualType();
2913 continue;
2914 }
2915 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2916 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Template->getDeclContext()))
2917 T = Context.getTypeDeclType(Decl: Parent);
2918 else
2919 T = QualType();
2920 continue;
2921 }
2922 }
2923
2924 // Look one step prior in a dependent name type.
2925 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2926 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2927 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2928 T = QualType(NNS.getAsType(), 0);
2929 else
2930 T = QualType();
2931 continue;
2932 }
2933
2934 // Retrieve the parent of an enumeration type.
2935 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2936 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2937 // check here.
2938 EnumDecl *Enum = EnumT->getDecl();
2939
2940 // Get to the parent type.
2941 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Enum->getParent()))
2942 T = Context.getCanonicalTypeDeclType(TD: Parent);
2943 else
2944 T = QualType();
2945 continue;
2946 }
2947
2948 T = QualType();
2949 }
2950 // Reverse the nested types list, since we want to traverse from the outermost
2951 // to the innermost while checking template-parameter-lists.
2952 std::reverse(first: NestedTypes.begin(), last: NestedTypes.end());
2953
2954 // C++0x [temp.expl.spec]p17:
2955 // A member or a member template may be nested within many
2956 // enclosing class templates. In an explicit specialization for
2957 // such a member, the member declaration shall be preceded by a
2958 // template<> for each enclosing class template that is
2959 // explicitly specialized.
2960 bool SawNonEmptyTemplateParameterList = false;
2961
2962 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2963 if (SawNonEmptyTemplateParameterList) {
2964 if (!SuppressDiagnostic)
2965 Diag(Loc: DeclLoc, DiagID: diag::err_specialize_member_of_template)
2966 << !Recovery << Range;
2967 Invalid = true;
2968 IsMemberSpecialization = false;
2969 return true;
2970 }
2971
2972 return false;
2973 };
2974
2975 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2976 // Check that we can have an explicit specialization here.
2977 if (CheckExplicitSpecialization(Range, true))
2978 return true;
2979
2980 // We don't have a template header, but we should.
2981 SourceLocation ExpectedTemplateLoc;
2982 if (!ParamLists.empty())
2983 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2984 else
2985 ExpectedTemplateLoc = DeclStartLoc;
2986
2987 if (!SuppressDiagnostic)
2988 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_header)
2989 << Range
2990 << FixItHint::CreateInsertion(InsertionLoc: ExpectedTemplateLoc, Code: "template<> ");
2991 return false;
2992 };
2993
2994 unsigned ParamIdx = 0;
2995 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2996 ++TypeIdx) {
2997 T = NestedTypes[TypeIdx];
2998
2999 // Whether we expect a 'template<>' header.
3000 bool NeedEmptyTemplateHeader = false;
3001
3002 // Whether we expect a template header with parameters.
3003 bool NeedNonemptyTemplateHeader = false;
3004
3005 // For a dependent type, the set of template parameters that we
3006 // expect to see.
3007 TemplateParameterList *ExpectedTemplateParams = nullptr;
3008
3009 // C++0x [temp.expl.spec]p15:
3010 // A member or a member template may be nested within many enclosing
3011 // class templates. In an explicit specialization for such a member, the
3012 // member declaration shall be preceded by a template<> for each
3013 // enclosing class template that is explicitly specialized.
3014 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3015 if (ClassTemplatePartialSpecializationDecl *Partial
3016 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Record)) {
3017 ExpectedTemplateParams = Partial->getTemplateParameters();
3018 NeedNonemptyTemplateHeader = true;
3019 } else if (Record->isDependentType()) {
3020 if (Record->getDescribedClassTemplate()) {
3021 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3022 ->getTemplateParameters();
3023 NeedNonemptyTemplateHeader = true;
3024 }
3025 } else if (ClassTemplateSpecializationDecl *Spec
3026 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
3027 // C++0x [temp.expl.spec]p4:
3028 // Members of an explicitly specialized class template are defined
3029 // in the same manner as members of normal classes, and not using
3030 // the template<> syntax.
3031 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3032 NeedEmptyTemplateHeader = true;
3033 else
3034 continue;
3035 } else if (Record->getTemplateSpecializationKind()) {
3036 if (Record->getTemplateSpecializationKind()
3037 != TSK_ExplicitSpecialization &&
3038 TypeIdx == NumTypes - 1)
3039 IsMemberSpecialization = true;
3040
3041 continue;
3042 }
3043 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3044 TemplateName Name = TST->getTemplateName();
3045 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3046 ExpectedTemplateParams = Template->getTemplateParameters();
3047 NeedNonemptyTemplateHeader = true;
3048 } else if (Name.getAsDependentTemplateName()) {
3049 NeedNonemptyTemplateHeader = true;
3050 } else if (Name.getAsDeducedTemplateName()) {
3051 // FIXME: We actually could/should check the template arguments here
3052 // against the corresponding template parameter list.
3053 NeedNonemptyTemplateHeader = false;
3054 }
3055 }
3056
3057 // C++ [temp.expl.spec]p16:
3058 // In an explicit specialization declaration for a member of a class
3059 // template or a member template that appears in namespace scope, the
3060 // member template and some of its enclosing class templates may remain
3061 // unspecialized, except that the declaration shall not explicitly
3062 // specialize a class member template if its enclosing class templates
3063 // are not explicitly specialized as well.
3064 if (ParamIdx < ParamLists.size()) {
3065 if (ParamLists[ParamIdx]->size() == 0) {
3066 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3067 false))
3068 return nullptr;
3069 } else
3070 SawNonEmptyTemplateParameterList = true;
3071 }
3072
3073 if (NeedEmptyTemplateHeader) {
3074 // If we're on the last of the types, and we need a 'template<>' header
3075 // here, then it's a member specialization.
3076 if (TypeIdx == NumTypes - 1)
3077 IsMemberSpecialization = true;
3078
3079 if (ParamIdx < ParamLists.size()) {
3080 if (ParamLists[ParamIdx]->size() > 0) {
3081 // The header has template parameters when it shouldn't. Complain.
3082 if (!SuppressDiagnostic)
3083 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3084 DiagID: diag::err_template_param_list_matches_nontemplate)
3085 << T
3086 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3087 ParamLists[ParamIdx]->getRAngleLoc())
3088 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3089 Invalid = true;
3090 return nullptr;
3091 }
3092
3093 // Consume this template header.
3094 ++ParamIdx;
3095 continue;
3096 }
3097
3098 if (!IsFriend)
3099 if (DiagnoseMissingExplicitSpecialization(
3100 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3101 return nullptr;
3102
3103 continue;
3104 }
3105
3106 if (NeedNonemptyTemplateHeader) {
3107 // In friend declarations we can have template-ids which don't
3108 // depend on the corresponding template parameter lists. But
3109 // assume that empty parameter lists are supposed to match this
3110 // template-id.
3111 if (IsFriend && T->isDependentType()) {
3112 if (ParamIdx < ParamLists.size() &&
3113 DependsOnTemplateParameters(T, Params: ParamLists[ParamIdx]))
3114 ExpectedTemplateParams = nullptr;
3115 else
3116 continue;
3117 }
3118
3119 if (ParamIdx < ParamLists.size()) {
3120 // Check the template parameter list, if we can.
3121 if (ExpectedTemplateParams &&
3122 !TemplateParameterListsAreEqual(New: ParamLists[ParamIdx],
3123 Old: ExpectedTemplateParams,
3124 Complain: !SuppressDiagnostic, Kind: TPL_TemplateMatch))
3125 Invalid = true;
3126
3127 if (!Invalid &&
3128 CheckTemplateParameterList(NewParams: ParamLists[ParamIdx], OldParams: nullptr,
3129 TPC: TPC_ClassTemplateMember))
3130 Invalid = true;
3131
3132 ++ParamIdx;
3133 continue;
3134 }
3135
3136 if (!SuppressDiagnostic)
3137 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_template_parameters)
3138 << T
3139 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3140 Invalid = true;
3141 continue;
3142 }
3143 }
3144
3145 // If there were at least as many template-ids as there were template
3146 // parameter lists, then there are no template parameter lists remaining for
3147 // the declaration itself.
3148 if (ParamIdx >= ParamLists.size()) {
3149 if (TemplateId && !IsFriend) {
3150 // We don't have a template header for the declaration itself, but we
3151 // should.
3152 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3153 TemplateId->RAngleLoc));
3154
3155 // Fabricate an empty template parameter list for the invented header.
3156 return TemplateParameterList::Create(C: Context, TemplateLoc: SourceLocation(),
3157 LAngleLoc: SourceLocation(), Params: {},
3158 RAngleLoc: SourceLocation(), RequiresClause: nullptr);
3159 }
3160
3161 return nullptr;
3162 }
3163
3164 // If there were too many template parameter lists, complain about that now.
3165 if (ParamIdx < ParamLists.size() - 1) {
3166 bool HasAnyExplicitSpecHeader = false;
3167 bool AllExplicitSpecHeaders = true;
3168 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3169 if (ParamLists[I]->size() == 0)
3170 HasAnyExplicitSpecHeader = true;
3171 else
3172 AllExplicitSpecHeaders = false;
3173 }
3174
3175 if (!SuppressDiagnostic)
3176 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3177 DiagID: AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3178 : diag::err_template_spec_extra_headers)
3179 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3180 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3181
3182 // If there was a specialization somewhere, such that 'template<>' is
3183 // not required, and there were any 'template<>' headers, note where the
3184 // specialization occurred.
3185 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3186 !SuppressDiagnostic)
3187 Diag(Loc: ExplicitSpecLoc,
3188 DiagID: diag::note_explicit_template_spec_does_not_need_header)
3189 << NestedTypes.back();
3190
3191 // We have a template parameter list with no corresponding scope, which
3192 // means that the resulting template declaration can't be instantiated
3193 // properly (we'll end up with dependent nodes when we shouldn't).
3194 if (!AllExplicitSpecHeaders)
3195 Invalid = true;
3196 }
3197
3198 // C++ [temp.expl.spec]p16:
3199 // In an explicit specialization declaration for a member of a class
3200 // template or a member template that ap- pears in namespace scope, the
3201 // member template and some of its enclosing class templates may remain
3202 // unspecialized, except that the declaration shall not explicitly
3203 // specialize a class member template if its en- closing class templates
3204 // are not explicitly specialized as well.
3205 if (ParamLists.back()->size() == 0 &&
3206 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3207 false))
3208 return nullptr;
3209
3210 // Return the last template parameter list, which corresponds to the
3211 // entity being declared.
3212 return ParamLists.back();
3213}
3214
3215void Sema::NoteAllFoundTemplates(TemplateName Name) {
3216 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3217 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_declared_here)
3218 << (isa<FunctionTemplateDecl>(Val: Template)
3219 ? 0
3220 : isa<ClassTemplateDecl>(Val: Template)
3221 ? 1
3222 : isa<VarTemplateDecl>(Val: Template)
3223 ? 2
3224 : isa<TypeAliasTemplateDecl>(Val: Template) ? 3 : 4)
3225 << Template->getDeclName();
3226 return;
3227 }
3228
3229 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3230 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3231 IEnd = OST->end();
3232 I != IEnd; ++I)
3233 Diag(Loc: (*I)->getLocation(), DiagID: diag::note_template_declared_here)
3234 << 0 << (*I)->getDeclName();
3235
3236 return;
3237 }
3238}
3239
3240static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword,
3241 TemplateName BaseTemplate,
3242 SourceLocation TemplateLoc,
3243 ArrayRef<TemplateArgument> Ts) {
3244 auto lookUpCommonType = [&](TemplateArgument T1,
3245 TemplateArgument T2) -> QualType {
3246 // Don't bother looking for other specializations if both types are
3247 // builtins - users aren't allowed to specialize for them
3248 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3249 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3250 Ts: {T1, T2});
3251
3252 TemplateArgumentListInfo Args;
3253 Args.addArgument(Loc: TemplateArgumentLoc(
3254 T1, S.Context.getTrivialTypeSourceInfo(T: T1.getAsType())));
3255 Args.addArgument(Loc: TemplateArgumentLoc(
3256 T2, S.Context.getTrivialTypeSourceInfo(T: T2.getAsType())));
3257
3258 EnterExpressionEvaluationContext UnevaluatedContext(
3259 S, Sema::ExpressionEvaluationContext::Unevaluated);
3260 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3261 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3262
3263 QualType BaseTemplateInst = S.CheckTemplateIdType(
3264 Keyword, Template: BaseTemplate, TemplateLoc, TemplateArgs&: Args,
3265 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3266
3267 if (SFINAE.hasErrorOccurred())
3268 return QualType();
3269
3270 return BaseTemplateInst;
3271 };
3272
3273 // Note A: For the common_type trait applied to a template parameter pack T of
3274 // types, the member type shall be either defined or not present as follows:
3275 switch (Ts.size()) {
3276
3277 // If sizeof...(T) is zero, there shall be no member type.
3278 case 0:
3279 return QualType();
3280
3281 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3282 // pack T. The member typedef-name type shall denote the same type, if any, as
3283 // common_type_t<T0, T0>; otherwise there shall be no member type.
3284 case 1:
3285 return lookUpCommonType(Ts[0], Ts[0]);
3286
3287 // If sizeof...(T) is two, let the first and second types constituting T be
3288 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3289 // as decay_t<T1> and decay_t<T2>, respectively.
3290 case 2: {
3291 QualType T1 = Ts[0].getAsType();
3292 QualType T2 = Ts[1].getAsType();
3293 QualType D1 = S.BuiltinDecay(BaseType: T1, Loc: {});
3294 QualType D2 = S.BuiltinDecay(BaseType: T2, Loc: {});
3295
3296 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3297 // the same type, if any, as common_type_t<D1, D2>.
3298 if (!S.Context.hasSameType(T1, T2: D1) || !S.Context.hasSameType(T1: T2, T2: D2))
3299 return lookUpCommonType(D1, D2);
3300
3301 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3302 // denotes a valid type, let C denote that type.
3303 {
3304 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3305 EnterExpressionEvaluationContext UnevaluatedContext(
3306 S, Sema::ExpressionEvaluationContext::Unevaluated);
3307 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3308 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3309
3310 // false
3311 OpaqueValueExpr CondExpr(SourceLocation(), S.Context.BoolTy,
3312 VK_PRValue);
3313 ExprResult Cond = &CondExpr;
3314
3315 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3316 if (ConstRefQual) {
3317 D1.addConst();
3318 D2.addConst();
3319 }
3320
3321 // declval<D1>()
3322 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3323 ExprResult LHS = &LHSExpr;
3324
3325 // declval<D2>()
3326 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3327 ExprResult RHS = &RHSExpr;
3328
3329 ExprValueKind VK = VK_PRValue;
3330 ExprObjectKind OK = OK_Ordinary;
3331
3332 // decltype(false ? declval<D1>() : declval<D2>())
3333 QualType Result =
3334 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc: TemplateLoc);
3335
3336 if (Result.isNull() || SFINAE.hasErrorOccurred())
3337 return QualType();
3338
3339 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3340 return S.BuiltinDecay(BaseType: Result, Loc: TemplateLoc);
3341 };
3342
3343 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3344 return Res;
3345
3346 // Let:
3347 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3348 // COND-RES(X, Y) be
3349 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3350
3351 // C++20 only
3352 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3353 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3354 if (!S.Context.getLangOpts().CPlusPlus20)
3355 return QualType();
3356 return CheckConditionalOperands(true);
3357 }
3358 }
3359
3360 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3361 // denote the first, second, and (pack of) remaining types constituting T. Let
3362 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3363 // a type C, the member typedef-name type shall denote the same type, if any,
3364 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3365 default: {
3366 QualType Result = Ts.front().getAsType();
3367 for (auto T : llvm::drop_begin(RangeOrContainer&: Ts)) {
3368 Result = lookUpCommonType(Result, T.getAsType());
3369 if (Result.isNull())
3370 return QualType();
3371 }
3372 return Result;
3373 }
3374 }
3375}
3376
3377static bool isInVkNamespace(const RecordType *RT) {
3378 DeclContext *DC = RT->getDecl()->getDeclContext();
3379 if (!DC)
3380 return false;
3381
3382 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Val: DC);
3383 if (!ND)
3384 return false;
3385
3386 return ND->getQualifiedNameAsString() == "hlsl::vk";
3387}
3388
3389static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3390 QualType OperandArg,
3391 SourceLocation Loc) {
3392 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3393 bool Literal = false;
3394 SourceLocation LiteralLoc;
3395 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3396 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3397 assert(SpecDecl);
3398
3399 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3400 QualType ConstantType = LiteralArgs[0].getAsType();
3401 RT = ConstantType->getAsCanonical<RecordType>();
3402 Literal = true;
3403 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3404 }
3405
3406 if (RT && isInVkNamespace(RT) &&
3407 RT->getDecl()->getName() == "integral_constant") {
3408 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3409 assert(SpecDecl);
3410
3411 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3412
3413 QualType ConstantType = ConstantArgs[0].getAsType();
3414 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3415
3416 if (Literal)
3417 return SpirvOperand::createLiteral(Val: Value);
3418 return SpirvOperand::createConstant(ResultType: ConstantType, Val: Value);
3419 } else if (Literal) {
3420 SemaRef.Diag(Loc: LiteralLoc, DiagID: diag::err_hlsl_vk_literal_must_contain_constant);
3421 return SpirvOperand();
3422 }
3423 }
3424 if (SemaRef.RequireCompleteType(Loc, T: OperandArg,
3425 DiagID: diag::err_call_incomplete_argument))
3426 return SpirvOperand();
3427 return SpirvOperand::createType(T: OperandArg);
3428}
3429
3430static QualType checkBuiltinTemplateIdType(
3431 Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD,
3432 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3433 TemplateArgumentListInfo &TemplateArgs) {
3434 ASTContext &Context = SemaRef.getASTContext();
3435
3436 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3437 "Builtin template arguments do not match its parameters");
3438
3439 switch (BTD->getBuiltinTemplateKind()) {
3440 case BTK__make_integer_seq: {
3441 // Specializations of __make_integer_seq<S, T, N> are treated like
3442 // S<T, 0, ..., N-1>.
3443
3444 QualType OrigType = Converted[1].getAsType();
3445 // C++14 [inteseq.intseq]p1:
3446 // T shall be an integer type.
3447 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Ctx: Context)) {
3448 SemaRef.Diag(Loc: TemplateArgs[1].getLocation(),
3449 DiagID: diag::err_integer_sequence_integral_element_type);
3450 return QualType();
3451 }
3452
3453 TemplateArgument NumArgsArg = Converted[2];
3454 if (NumArgsArg.isDependent())
3455 return QualType();
3456
3457 TemplateArgumentListInfo SyntheticTemplateArgs;
3458 // The type argument, wrapped in substitution sugar, gets reused as the
3459 // first template argument in the synthetic template argument list.
3460 SyntheticTemplateArgs.addArgument(
3461 Loc: TemplateArgumentLoc(TemplateArgument(OrigType),
3462 SemaRef.Context.getTrivialTypeSourceInfo(
3463 T: OrigType, Loc: TemplateArgs[1].getLocation())));
3464
3465 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3466 // Expand N into 0 ... N-1.
3467 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3468 I < NumArgs; ++I) {
3469 TemplateArgument TA(Context, I, OrigType);
3470 SyntheticTemplateArgs.addArgument(Loc: SemaRef.getTrivialTemplateArgumentLoc(
3471 Arg: TA, NTTPType: OrigType, Loc: TemplateArgs[2].getLocation()));
3472 }
3473 } else {
3474 // C++14 [inteseq.make]p1:
3475 // If N is negative the program is ill-formed.
3476 SemaRef.Diag(Loc: TemplateArgs[2].getLocation(),
3477 DiagID: diag::err_integer_sequence_negative_length);
3478 return QualType();
3479 }
3480
3481 // The first template argument will be reused as the template decl that
3482 // our synthetic template arguments will be applied to.
3483 return SemaRef.CheckTemplateIdType(Keyword, Template: Converted[0].getAsTemplate(),
3484 TemplateLoc, TemplateArgs&: SyntheticTemplateArgs,
3485 /*Scope=*/nullptr,
3486 /*ForNestedNameSpecifier=*/false);
3487 }
3488
3489 case BTK__type_pack_element: {
3490 // Specializations of
3491 // __type_pack_element<Index, T_1, ..., T_N>
3492 // are treated like T_Index.
3493 assert(Converted.size() == 2 &&
3494 "__type_pack_element should be given an index and a parameter pack");
3495
3496 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3497 if (IndexArg.isDependent() || Ts.isDependent())
3498 return QualType();
3499
3500 llvm::APSInt Index = IndexArg.getAsIntegral();
3501 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3502 "type std::size_t, and hence be non-negative");
3503 // If the Index is out of bounds, the program is ill-formed.
3504 if (Index >= Ts.pack_size()) {
3505 SemaRef.Diag(Loc: TemplateArgs[0].getLocation(),
3506 DiagID: diag::err_type_pack_element_out_of_bounds);
3507 return QualType();
3508 }
3509
3510 // We simply return the type at index `Index`.
3511 int64_t N = Index.getExtValue();
3512 return Ts.getPackAsArray()[N].getAsType();
3513 }
3514
3515 case BTK__builtin_common_type: {
3516 assert(Converted.size() == 4);
3517 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3518 return QualType();
3519
3520 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3521 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3522 if (auto CT = builtinCommonTypeImpl(S&: SemaRef, Keyword, BaseTemplate,
3523 TemplateLoc, Ts);
3524 !CT.isNull()) {
3525 TemplateArgumentListInfo TAs;
3526 TAs.addArgument(Loc: TemplateArgumentLoc(
3527 TemplateArgument(CT), SemaRef.Context.getTrivialTypeSourceInfo(
3528 T: CT, Loc: TemplateArgs[1].getLocation())));
3529 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3530 return SemaRef.CheckTemplateIdType(Keyword, Template: HasTypeMember, TemplateLoc,
3531 TemplateArgs&: TAs, /*Scope=*/nullptr,
3532 /*ForNestedNameSpecifier=*/false);
3533 }
3534 QualType HasNoTypeMember = Converted[2].getAsType();
3535 return HasNoTypeMember;
3536 }
3537
3538 case BTK__hlsl_spirv_type: {
3539 assert(Converted.size() == 4);
3540
3541 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3542 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_hlsl_spirv_only) << BTD;
3543 }
3544
3545 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3546 return QualType();
3547
3548 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3549 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3550 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3551
3552 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3553
3554 llvm::SmallVector<SpirvOperand> Operands;
3555
3556 for (auto &OperandTA : OperandArgs) {
3557 QualType OperandArg = OperandTA.getAsType();
3558 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3559 Loc: TemplateArgs[3].getLocation());
3560 if (!Operand.isValid())
3561 return QualType();
3562 Operands.push_back(Elt: Operand);
3563 }
3564
3565 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3566 }
3567 case BTK__builtin_dedup_pack: {
3568 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3569 "a parameter pack");
3570 TemplateArgument Ts = Converted[0];
3571 // Delay the computation until we can compute the final result. We choose
3572 // not to remove the duplicates upfront before substitution to keep the code
3573 // simple.
3574 if (Ts.isDependent())
3575 return QualType();
3576 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3577 llvm::SmallVector<TemplateArgument> OutArgs;
3578 llvm::SmallDenseSet<QualType> Seen;
3579 // Synthesize a new template argument list, removing duplicates.
3580 for (auto T : Ts.getPackAsArray()) {
3581 assert(T.getKind() == clang::TemplateArgument::Type);
3582 if (!Seen.insert(V: T.getAsType().getCanonicalType()).second)
3583 continue;
3584 OutArgs.push_back(Elt: T);
3585 }
3586 return Context.getSubstBuiltinTemplatePack(
3587 ArgPack: TemplateArgument::CreatePackCopy(Context, Args: OutArgs));
3588 }
3589 }
3590 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3591}
3592
3593/// Determine whether this alias template is "enable_if_t".
3594/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3595static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3596 return AliasTemplate->getName() == "enable_if_t" ||
3597 AliasTemplate->getName() == "__enable_if_t";
3598}
3599
3600/// Collect all of the separable terms in the given condition, which
3601/// might be a conjunction.
3602///
3603/// FIXME: The right answer is to convert the logical expression into
3604/// disjunctive normal form, so we can find the first failed term
3605/// within each possible clause.
3606static void collectConjunctionTerms(Expr *Clause,
3607 SmallVectorImpl<Expr *> &Terms) {
3608 if (auto BinOp = dyn_cast<BinaryOperator>(Val: Clause->IgnoreParenImpCasts())) {
3609 if (BinOp->getOpcode() == BO_LAnd) {
3610 collectConjunctionTerms(Clause: BinOp->getLHS(), Terms);
3611 collectConjunctionTerms(Clause: BinOp->getRHS(), Terms);
3612 return;
3613 }
3614 }
3615
3616 Terms.push_back(Elt: Clause);
3617}
3618
3619// The ranges-v3 library uses an odd pattern of a top-level "||" with
3620// a left-hand side that is value-dependent but never true. Identify
3621// the idiom and ignore that term.
3622static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3623 // Top-level '||'.
3624 auto *BinOp = dyn_cast<BinaryOperator>(Val: Cond->IgnoreParenImpCasts());
3625 if (!BinOp) return Cond;
3626
3627 if (BinOp->getOpcode() != BO_LOr) return Cond;
3628
3629 // With an inner '==' that has a literal on the right-hand side.
3630 Expr *LHS = BinOp->getLHS();
3631 auto *InnerBinOp = dyn_cast<BinaryOperator>(Val: LHS->IgnoreParenImpCasts());
3632 if (!InnerBinOp) return Cond;
3633
3634 if (InnerBinOp->getOpcode() != BO_EQ ||
3635 !isa<IntegerLiteral>(Val: InnerBinOp->getRHS()))
3636 return Cond;
3637
3638 // If the inner binary operation came from a macro expansion named
3639 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3640 // of the '||', which is the real, user-provided condition.
3641 SourceLocation Loc = InnerBinOp->getExprLoc();
3642 if (!Loc.isMacroID()) return Cond;
3643
3644 StringRef MacroName = PP.getImmediateMacroName(Loc);
3645 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3646 return BinOp->getRHS();
3647
3648 return Cond;
3649}
3650
3651namespace {
3652
3653// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3654// within failing boolean expression, such as substituting template parameters
3655// for actual types.
3656class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3657public:
3658 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3659 : Policy(P) {}
3660
3661 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3662 const auto *DR = dyn_cast<DeclRefExpr>(Val: E);
3663 if (DR && DR->getQualifier()) {
3664 // If this is a qualified name, expand the template arguments in nested
3665 // qualifiers.
3666 DR->getQualifier().print(OS, Policy, ResolveTemplateArguments: true);
3667 // Then print the decl itself.
3668 const ValueDecl *VD = DR->getDecl();
3669 OS << *VD;
3670 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) {
3671 // This is a template variable, print the expanded template arguments.
3672 printTemplateArgumentList(
3673 OS, Args: IV->getTemplateArgs().asArray(), Policy,
3674 TPL: IV->getSpecializedTemplate()->getTemplateParameters());
3675 }
3676 return true;
3677 }
3678 return false;
3679 }
3680
3681private:
3682 const PrintingPolicy Policy;
3683};
3684
3685} // end anonymous namespace
3686
3687std::pair<Expr *, std::string>
3688Sema::findFailedBooleanCondition(Expr *Cond) {
3689 Cond = lookThroughRangesV3Condition(PP, Cond);
3690
3691 // Separate out all of the terms in a conjunction.
3692 SmallVector<Expr *, 4> Terms;
3693 collectConjunctionTerms(Clause: Cond, Terms);
3694
3695 // Determine which term failed.
3696 Expr *FailedCond = nullptr;
3697 for (Expr *Term : Terms) {
3698 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3699
3700 // Literals are uninteresting.
3701 if (isa<CXXBoolLiteralExpr>(Val: TermAsWritten) ||
3702 isa<IntegerLiteral>(Val: TermAsWritten))
3703 continue;
3704
3705 // The initialization of the parameter from the argument is
3706 // a constant-evaluated context.
3707 EnterExpressionEvaluationContext ConstantEvaluated(
3708 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3709
3710 bool Succeeded;
3711 if (Term->EvaluateAsBooleanCondition(Result&: Succeeded, Ctx: Context) &&
3712 !Succeeded) {
3713 FailedCond = TermAsWritten;
3714 break;
3715 }
3716 }
3717 if (!FailedCond)
3718 FailedCond = Cond->IgnoreParenImpCasts();
3719
3720 std::string Description;
3721 {
3722 llvm::raw_string_ostream Out(Description);
3723 PrintingPolicy Policy = getPrintingPolicy();
3724 Policy.PrintAsCanonical = true;
3725 FailedBooleanConditionPrinterHelper Helper(Policy);
3726 FailedCond->printPretty(OS&: Out, Helper: &Helper, Policy, Indentation: 0, NewlineSymbol: "\n", Context: nullptr);
3727 }
3728 return { FailedCond, Description };
3729}
3730
3731static TemplateName
3732resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope,
3733 const AssumedTemplateStorage *ATN,
3734 SourceLocation NameLoc) {
3735 // We assumed this undeclared identifier to be an (ADL-only) function
3736 // template name, but it was used in a context where a type was required.
3737 // Try to typo-correct it now.
3738 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3739 struct CandidateCallback : CorrectionCandidateCallback {
3740 bool ValidateCandidate(const TypoCorrection &TC) override {
3741 return TC.getCorrectionDecl() &&
3742 getAsTypeTemplateDecl(D: TC.getCorrectionDecl());
3743 }
3744 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3745 return std::make_unique<CandidateCallback>(args&: *this);
3746 }
3747 } FilterCCC;
3748
3749 TypoCorrection Corrected =
3750 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Scope,
3751 /*SS=*/nullptr, CCC&: FilterCCC, Mode: CorrectTypoKind::ErrorRecovery);
3752 if (Corrected && Corrected.getFoundDecl()) {
3753 S.diagnoseTypo(Correction: Corrected, TypoDiag: S.PDiag(DiagID: diag::err_no_template_suggest)
3754 << ATN->getDeclName());
3755 return S.Context.getQualifiedTemplateName(
3756 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3757 Template: TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()));
3758 }
3759
3760 return TemplateName();
3761}
3762
3763QualType Sema::CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
3764 TemplateName Name,
3765 SourceLocation TemplateLoc,
3766 TemplateArgumentListInfo &TemplateArgs,
3767 Scope *Scope, bool ForNestedNameSpecifier) {
3768 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3769
3770 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3771 if (!Template) {
3772 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3773 Template = S->getParameterPack();
3774 } else if (const auto *PI = UnderlyingName.getAsPackIndexingTemplate()) {
3775 Template = PI->getParameterPack();
3776 if (!Template)
3777 Template = PI->getPattern().getAsTemplateDecl();
3778 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3779 if (DTN->getName().getIdentifier())
3780 // When building a template-id where the template-name is dependent,
3781 // assume the template is a type template. Either our assumption is
3782 // correct, or the code is ill-formed and will be diagnosed when the
3783 // dependent name is substituted.
3784 return Context.getTemplateSpecializationType(Keyword, T: Name,
3785 SpecifiedArgs: TemplateArgs.arguments(),
3786 /*CanonicalArgs=*/{});
3787 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3788 if (TemplateName CorrectedName = ::resolveAssumedTemplateNameAsType(
3789 S&: *this, Scope, ATN, NameLoc: TemplateLoc);
3790 CorrectedName.isNull()) {
3791 Diag(Loc: TemplateLoc, DiagID: diag::err_no_template) << ATN->getDeclName();
3792 return QualType();
3793 } else {
3794 Name = CorrectedName;
3795 Template = Name.getAsTemplateDecl();
3796 }
3797 }
3798 }
3799 if (!Template ||
3800 isa<FunctionTemplateDecl, VarTemplateDecl, ConceptDecl>(Val: Template)) {
3801 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3802 if (ForNestedNameSpecifier)
3803 Diag(Loc: TemplateLoc, DiagID: diag::err_non_type_template_in_nested_name_specifier)
3804 << isa_and_nonnull<VarTemplateDecl>(Val: Template) << Name << R;
3805 else
3806 Diag(Loc: TemplateLoc, DiagID: diag::err_template_id_not_a_type) << Name << R;
3807 NoteAllFoundTemplates(Name);
3808 return QualType();
3809 }
3810
3811 // Check that the template argument list is well-formed for this
3812 // template.
3813 CheckTemplateArgumentInfo CTAI;
3814 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3815 DefaultArgs, /*PartialTemplateArgs=*/false,
3816 CTAI,
3817 /*UpdateArgsWithConversions=*/true))
3818 return QualType();
3819
3820 // FIXME: Diagnose uses of this template. DiagnoseUseOfDecl is quite slow,
3821 // and there are no diagnsotics currently implemented for TemplateDecls,
3822 // so avoid doing it for now.
3823 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Template, /*OdrUse=*/MightBeOdrUse: false);
3824
3825 QualType CanonType;
3826
3827 if (isa<TemplateTemplateParmDecl>(Val: Template)) {
3828 // We might have a substituted template template parameter pack. If so,
3829 // build a template specialization type for it.
3830 } else if (TypeAliasTemplateDecl *AliasTemplate =
3831 dyn_cast<TypeAliasTemplateDecl>(Val: Template)) {
3832
3833 // C++0x [dcl.type.elab]p2:
3834 // If the identifier resolves to a typedef-name or the simple-template-id
3835 // resolves to an alias template specialization, the
3836 // elaborated-type-specifier is ill-formed.
3837 if (Keyword != ElaboratedTypeKeyword::None &&
3838 Keyword != ElaboratedTypeKeyword::Typename) {
3839 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_tag_reference_non_tag)
3840 << AliasTemplate << NonTagKind::TypeAliasTemplate
3841 << KeywordHelpers::getTagTypeKindForKeyword(Keyword);
3842 SemaRef.Diag(Loc: AliasTemplate->getLocation(), DiagID: diag::note_declared_at);
3843 }
3844
3845 // Find the canonical type for this type alias template specialization.
3846 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3847
3848 // Diagnose uses of the pattern of this template.
3849 (void)DiagnoseUseOfDecl(D: Pattern, Locs: TemplateLoc);
3850 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Pattern, /*OdrUse=*/MightBeOdrUse: false);
3851
3852 if (Pattern->isInvalidDecl())
3853 return QualType();
3854
3855 // Only substitute for the innermost template argument list.
3856 MultiLevelTemplateArgumentList TemplateArgLists;
3857 TemplateArgLists.addOuterTemplateArguments(AssociatedDecl: Template, Args: CTAI.SugaredConverted,
3858 /*Final=*/true);
3859 TemplateArgLists.addOuterRetainedLevels(
3860 Num: AliasTemplate->getTemplateParameters()->getDepth());
3861
3862 LocalInstantiationScope Scope(*this);
3863
3864 // FIXME: The TemplateArgs passed here are not used for the context note,
3865 // nor they should, because this note will be pointing to the specialization
3866 // anyway. These arguments are needed for a hack for instantiating lambdas
3867 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3868 // arguments will be used for collating the template arguments needed to
3869 // instantiate the lambda.
3870 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3871 /*Entity=*/AliasTemplate,
3872 /*TemplateArgs=*/CTAI.SugaredConverted);
3873 if (Inst.isInvalid())
3874 return QualType();
3875
3876 std::optional<ContextRAII> SavedContext;
3877 if (!AliasTemplate->getDeclContext()->isFileContext())
3878 SavedContext.emplace(args&: *this, args: AliasTemplate->getDeclContext());
3879
3880 CanonType =
3881 SubstType(T: Pattern->getUnderlyingType(), TemplateArgs: TemplateArgLists,
3882 Loc: AliasTemplate->getLocation(), Entity: AliasTemplate->getDeclName());
3883 if (CanonType.isNull()) {
3884 // If this was enable_if and we failed to find the nested type
3885 // within enable_if in a SFINAE context, dig out the specific
3886 // enable_if condition that failed and present that instead.
3887 if (isEnableIfAliasTemplate(AliasTemplate)) {
3888 if (SFINAETrap *Trap = getSFINAEContext();
3889 TemplateDeductionInfo *DeductionInfo =
3890 Trap ? Trap->getDeductionInfo() : nullptr) {
3891 if (DeductionInfo->hasSFINAEDiagnostic() &&
3892 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3893 diag::err_typename_nested_not_found_enable_if &&
3894 TemplateArgs[0].getArgument().getKind() ==
3895 TemplateArgument::Expression) {
3896 Expr *FailedCond;
3897 std::string FailedDescription;
3898 std::tie(args&: FailedCond, args&: FailedDescription) =
3899 findFailedBooleanCondition(Cond: TemplateArgs[0].getSourceExpression());
3900
3901 // Remove the old SFINAE diagnostic.
3902 PartialDiagnosticAt OldDiag =
3903 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3904 DeductionInfo->takeSFINAEDiagnostic(PD&: OldDiag);
3905
3906 // Add a new SFINAE diagnostic specifying which condition
3907 // failed.
3908 DeductionInfo->addSFINAEDiagnostic(
3909 Loc: OldDiag.first,
3910 PD: PDiag(DiagID: diag::err_typename_nested_not_found_requirement)
3911 << FailedDescription << FailedCond->getSourceRange());
3912 }
3913 }
3914 }
3915
3916 return QualType();
3917 }
3918 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Val: Template)) {
3919 CanonType = checkBuiltinTemplateIdType(
3920 SemaRef&: *this, Keyword, BTD, Converted: CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3921 } else if (Name.isDependent() ||
3922 TemplateSpecializationType::anyDependentTemplateArguments(
3923 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
3924 // This class template specialization is a dependent
3925 // type. Therefore, its canonical type is another class template
3926 // specialization type that contains all of the converted
3927 // arguments in canonical form. This ensures that, e.g., A<T> and
3928 // A<T, T> have identical types when A is declared as:
3929 //
3930 // template<typename T, typename U = T> struct A;
3931 CanonType = Context.getCanonicalTemplateSpecializationType(
3932 Keyword: ElaboratedTypeKeyword::None,
3933 T: Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3934 CanonicalArgs: CTAI.CanonicalConverted);
3935 assert(CanonType->isCanonicalUnqualified());
3936
3937 // This might work out to be a current instantiation, in which
3938 // case the canonical type needs to be the InjectedClassNameType.
3939 //
3940 // TODO: in theory this could be a simple hashtable lookup; most
3941 // changes to CurContext don't change the set of current
3942 // instantiations.
3943 if (isa<ClassTemplateDecl>(Val: Template)) {
3944 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3945 // If we get out to a namespace, we're done.
3946 if (Ctx->isFileContext()) break;
3947
3948 // If this isn't a record, keep looking.
3949 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Ctx);
3950 if (!Record) continue;
3951
3952 // Look for one of the two cases with InjectedClassNameTypes
3953 // and check whether it's the same template.
3954 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Record) &&
3955 !Record->getDescribedClassTemplate())
3956 continue;
3957
3958 // Fetch the injected class name type and check whether its
3959 // injected type is equal to the type we just built.
3960 CanQualType ICNT = Context.getCanonicalTagType(TD: Record);
3961 CanQualType Injected =
3962 Record->getCanonicalTemplateSpecializationType(Ctx: Context);
3963
3964 if (CanonType != Injected)
3965 continue;
3966
3967 (void)DiagnoseUseOfDecl(D: Record, Locs: TemplateLoc);
3968 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Record, /*OdrUse=*/MightBeOdrUse: false);
3969
3970 // If so, the canonical type of this TST is the injected
3971 // class name type of the record we just found.
3972 CanonType = ICNT;
3973 break;
3974 }
3975 }
3976 } else if (ClassTemplateDecl *ClassTemplate =
3977 dyn_cast<ClassTemplateDecl>(Val: Template)) {
3978 // Find the class template specialization declaration that
3979 // corresponds to these arguments.
3980 void *InsertPos = nullptr;
3981 ClassTemplateSpecializationDecl *Decl =
3982 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
3983 if (!Decl) {
3984 // This is the first time we have referenced this class template
3985 // specialization. Create the canonical declaration and add it to
3986 // the set of specializations.
3987 Decl = ClassTemplateSpecializationDecl::Create(
3988 Context, TK: ClassTemplate->getTemplatedDecl()->getTagKind(),
3989 DC: ClassTemplate->getDeclContext(),
3990 StartLoc: ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3991 IdLoc: ClassTemplate->getLocation(), SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted,
3992 StrictPackMatch: CTAI.StrictPackMatch, PrevDecl: nullptr);
3993 ClassTemplate->AddSpecialization(D: Decl, InsertPos);
3994 if (ClassTemplate->isOutOfLine())
3995 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3996 }
3997
3998 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3999 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4000 NonSFINAEContext _(*this);
4001 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4002 if (!Inst.isInvalid()) {
4003 MultiLevelTemplateArgumentList TemplateArgLists(Template,
4004 CTAI.CanonicalConverted,
4005 /*Final=*/false);
4006 InstantiateAttrsForDecl(TemplateArgs: TemplateArgLists,
4007 Pattern: ClassTemplate->getTemplatedDecl(), Inst: Decl);
4008 }
4009 }
4010
4011 // Diagnose uses of this specialization.
4012 (void)DiagnoseUseOfDecl(D: Decl, Locs: TemplateLoc);
4013 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Decl, /*OdrUse=*/MightBeOdrUse: false);
4014
4015 CanonType = Context.getCanonicalTagType(TD: Decl);
4016 assert(isa<RecordType>(CanonType) &&
4017 "type of non-dependent specialization is not a RecordType");
4018 } else {
4019 llvm_unreachable("Unhandled template kind");
4020 }
4021
4022 // Build the fully-sugared type for this class template
4023 // specialization, which refers back to the class template
4024 // specialization we created or found.
4025 return Context.getTemplateSpecializationType(
4026 Keyword, T: Name, SpecifiedArgs: TemplateArgs.arguments(), CanonicalArgs: CTAI.CanonicalConverted,
4027 Canon: CanonType);
4028}
4029
4030void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
4031 TemplateNameKind &TNK,
4032 SourceLocation NameLoc,
4033 IdentifierInfo *&II) {
4034 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4035
4036 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4037 assert(ATN && "not an assumed template name");
4038 II = ATN->getDeclName().getAsIdentifierInfo();
4039
4040 if (TemplateName Name =
4041 ::resolveAssumedTemplateNameAsType(S&: *this, Scope: S, ATN, NameLoc);
4042 !Name.isNull()) {
4043 // Resolved to a type template name.
4044 ParsedName = TemplateTy::make(P: Name);
4045 TNK = TNK_Type_template;
4046 }
4047}
4048
4049TypeResult Sema::ActOnTemplateIdType(
4050 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4051 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4052 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4053 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4054 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4055 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4056 ImplicitTypenameContext AllowImplicitTypename) {
4057 if (SS.isInvalid())
4058 return true;
4059
4060 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4061 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4062
4063 // C++ [temp.res]p3:
4064 // A qualified-id that refers to a type and in which the
4065 // nested-name-specifier depends on a template-parameter (14.6.2)
4066 // shall be prefixed by the keyword typename to indicate that the
4067 // qualified-id denotes a type, forming an
4068 // elaborated-type-specifier (7.1.5.3).
4069 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4070 // C++2a relaxes some of those restrictions in [temp.res]p5.
4071 QualType DNT = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
4072 NNS: SS.getScopeRep(), Name: TemplateII);
4073 NestedNameSpecifier NNS(DNT.getTypePtr());
4074 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4075 auto DB = DiagCompat(Loc: SS.getBeginLoc(), CompatDiagId: diag_compat::implicit_typename)
4076 << NNS;
4077 if (!getLangOpts().CPlusPlus20)
4078 DB << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "typename ");
4079 } else
4080 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_typename_missing_template) << NNS;
4081
4082 // FIXME: This is not quite correct recovery as we don't transform SS
4083 // into the corresponding dependent form (and we don't diagnose missing
4084 // 'template' keywords within SS as a result).
4085 return ActOnTypenameType(S: nullptr, TypenameLoc: SourceLocation(), SS, TemplateLoc: TemplateKWLoc,
4086 TemplateName: TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4087 TemplateArgs: TemplateArgsIn, RAngleLoc);
4088 }
4089
4090 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4091 // it's not actually allowed to be used as a type in most cases. Because
4092 // we annotate it before we know whether it's valid, we have to check for
4093 // this case here.
4094 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
4095 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4096 Diag(Loc: TemplateIILoc,
4097 DiagID: TemplateKWLoc.isInvalid()
4098 ? diag::err_out_of_line_qualified_id_type_names_constructor
4099 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4100 << TemplateII << 0 /*injected-class-name used as template name*/
4101 << 1 /*if any keyword was present, it was 'template'*/;
4102 }
4103 }
4104
4105 // Translate the parser's template argument list in our AST format.
4106 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4107 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4108
4109 QualType SpecTy = CheckTemplateIdType(
4110 Keyword: ElaboratedKeyword, Name: TemplateD.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
4111 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4112 if (SpecTy.isNull())
4113 return true;
4114
4115 // Build type-source information.
4116 TypeLocBuilder TLB;
4117 TLB.push<TemplateSpecializationTypeLoc>(T: SpecTy).set(
4118 ElaboratedKeywordLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
4119 NameLoc: TemplateIILoc, TAL: TemplateArgs);
4120 return CreateParsedType(T: SpecTy, TInfo: TLB.getTypeSourceInfo(Context, T: SpecTy));
4121}
4122
4123TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
4124 TypeSpecifierType TagSpec,
4125 SourceLocation TagLoc,
4126 CXXScopeSpec &SS,
4127 SourceLocation TemplateKWLoc,
4128 TemplateTy TemplateD,
4129 SourceLocation TemplateLoc,
4130 SourceLocation LAngleLoc,
4131 ASTTemplateArgsPtr TemplateArgsIn,
4132 SourceLocation RAngleLoc) {
4133 if (SS.isInvalid())
4134 return TypeResult(true);
4135
4136 // Translate the parser's template argument list in our AST format.
4137 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4138 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4139
4140 // Determine the tag kind
4141 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
4142 ElaboratedTypeKeyword Keyword
4143 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
4144
4145 QualType Result =
4146 CheckTemplateIdType(Keyword, Name: TemplateD.get(), TemplateLoc, TemplateArgs,
4147 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4148 if (Result.isNull())
4149 return TypeResult(true);
4150
4151 // Check the tag kind
4152 if (const RecordType *RT = Result->getAs<RecordType>()) {
4153 RecordDecl *D = RT->getDecl();
4154
4155 IdentifierInfo *Id = D->getIdentifier();
4156 assert(Id && "templated class must have an identifier");
4157
4158 if (!isAcceptableTagRedeclaration(Previous: D, NewTag: TagKind, isDefinition: TUK == TagUseKind::Definition,
4159 NewTagLoc: TagLoc, Name: Id)) {
4160 Diag(Loc: TagLoc, DiagID: diag::err_use_with_wrong_tag)
4161 << Result
4162 << FixItHint::CreateReplacement(RemoveRange: SourceRange(TagLoc), Code: D->getKindName());
4163 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_use);
4164 }
4165 }
4166
4167 // Provide source-location information for the template specialization.
4168 TypeLocBuilder TLB;
4169 TLB.push<TemplateSpecializationTypeLoc>(T: Result).set(
4170 ElaboratedKeywordLoc: TagLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc, NameLoc: TemplateLoc,
4171 TAL: TemplateArgs);
4172 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
4173}
4174
4175static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4176 NamedDecl *PrevDecl,
4177 SourceLocation Loc,
4178 bool IsPartialSpecialization);
4179
4180static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4181
4182static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg,
4183 unsigned Depth,
4184 unsigned Index) {
4185 switch (Arg.getKind()) {
4186 case TemplateArgument::Null:
4187 case TemplateArgument::NullPtr:
4188 case TemplateArgument::Integral:
4189 case TemplateArgument::Declaration:
4190 case TemplateArgument::StructuralValue:
4191 case TemplateArgument::Pack:
4192 case TemplateArgument::TemplateExpansion:
4193 return false;
4194
4195 case TemplateArgument::Type: {
4196 QualType Type = Arg.getAsType();
4197 const TemplateTypeParmType *TPT =
4198 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4199 return TPT && !Type.hasQualifiers() &&
4200 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4201 }
4202
4203 case TemplateArgument::Expression: {
4204 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg.getAsExpr());
4205 if (!DRE || !DRE->getDecl())
4206 return false;
4207 const NonTypeTemplateParmDecl *NTTP =
4208 dyn_cast<NonTypeTemplateParmDecl>(Val: DRE->getDecl());
4209 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4210 }
4211
4212 case TemplateArgument::Template:
4213 const TemplateTemplateParmDecl *TTP =
4214 dyn_cast_or_null<TemplateTemplateParmDecl>(
4215 Val: Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4216 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4217 }
4218 llvm_unreachable("unexpected kind of template argument");
4219}
4220
4221static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4222 TemplateParameterList *SpecParams,
4223 ArrayRef<TemplateArgument> Args) {
4224 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4225 return false;
4226
4227 unsigned Depth = Params->getDepth();
4228
4229 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4230 TemplateArgument Arg = Args[I];
4231
4232 // If the parameter is a pack expansion, the argument must be a pack
4233 // whose only element is a pack expansion.
4234 if (Params->getParam(Idx: I)->isParameterPack()) {
4235 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4236 !Arg.pack_begin()->isPackExpansion())
4237 return false;
4238 Arg = Arg.pack_begin()->getPackExpansionPattern();
4239 }
4240
4241 if (!isTemplateArgumentTemplateParameter(Arg, Depth, Index: I))
4242 return false;
4243
4244 // For NTTPs further specialization is allowed via deduced types, so
4245 // we need to make sure to only reject here if primary template and
4246 // specialization use the same type for the NTTP.
4247 if (auto *SpecNTTP =
4248 dyn_cast<NonTypeTemplateParmDecl>(Val: SpecParams->getParam(Idx: I))) {
4249 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: I));
4250 if (!NTTP || NTTP->getType().getCanonicalType() !=
4251 SpecNTTP->getType().getCanonicalType())
4252 return false;
4253 }
4254 }
4255
4256 return true;
4257}
4258
4259template<typename PartialSpecDecl>
4260static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4261 if (Partial->getDeclContext()->isDependentContext())
4262 return;
4263
4264 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4265 // for non-substitution-failure issues?
4266 TemplateDeductionInfo Info(Partial->getLocation());
4267 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4268 return;
4269
4270 auto *Template = Partial->getSpecializedTemplate();
4271 S.Diag(Partial->getLocation(),
4272 diag::ext_partial_spec_not_more_specialized_than_primary)
4273 << isa<VarTemplateDecl>(Template);
4274
4275 if (Info.hasSFINAEDiagnostic()) {
4276 PartialDiagnosticAt Diag = {SourceLocation(),
4277 PartialDiagnostic::NullDiagnostic()};
4278 Info.takeSFINAEDiagnostic(PD&: Diag);
4279 SmallString<128> SFINAEArgString;
4280 Diag.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
4281 S.Diag(Loc: Diag.first,
4282 DiagID: diag::note_partial_spec_not_more_specialized_than_primary)
4283 << SFINAEArgString;
4284 }
4285
4286 S.NoteTemplateLocation(Decl: *Template);
4287 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4288 Template->getAssociatedConstraints(TemplateAC);
4289 Partial->getAssociatedConstraints(PartialAC);
4290 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Partial, AC1: PartialAC, D2: Template,
4291 AC2: TemplateAC);
4292}
4293
4294static void
4295noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4296 const llvm::SmallBitVector &DeducibleParams) {
4297 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4298 if (!DeducibleParams[I]) {
4299 NamedDecl *Param = TemplateParams->getParam(Idx: I);
4300 if (Param->getDeclName())
4301 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4302 << Param->getDeclName();
4303 else
4304 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4305 << "(anonymous)";
4306 }
4307 }
4308}
4309
4310
4311template<typename PartialSpecDecl>
4312static void checkTemplatePartialSpecialization(Sema &S,
4313 PartialSpecDecl *Partial) {
4314 // C++1z [temp.class.spec]p8: (DR1495)
4315 // - The specialization shall be more specialized than the primary
4316 // template (14.5.5.2).
4317 checkMoreSpecializedThanPrimary(S, Partial);
4318
4319 // C++ [temp.class.spec]p8: (DR1315)
4320 // - Each template-parameter shall appear at least once in the
4321 // template-id outside a non-deduced context.
4322 // C++1z [temp.class.spec.match]p3 (P0127R2)
4323 // If the template arguments of a partial specialization cannot be
4324 // deduced because of the structure of its template-parameter-list
4325 // and the template-id, the program is ill-formed.
4326 auto *TemplateParams = Partial->getTemplateParameters();
4327 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4328 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4329 TemplateParams->getDepth(), DeducibleParams);
4330
4331 if (!DeducibleParams.all()) {
4332 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4333 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4334 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4335 << (NumNonDeducible > 1)
4336 << SourceRange(Partial->getLocation(),
4337 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4338 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4339 }
4340}
4341
4342void Sema::CheckTemplatePartialSpecialization(
4343 ClassTemplatePartialSpecializationDecl *Partial) {
4344 checkTemplatePartialSpecialization(S&: *this, Partial);
4345}
4346
4347void Sema::CheckTemplatePartialSpecialization(
4348 VarTemplatePartialSpecializationDecl *Partial) {
4349 checkTemplatePartialSpecialization(S&: *this, Partial);
4350}
4351
4352void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4353 // C++1z [temp.param]p11:
4354 // A template parameter of a deduction guide template that does not have a
4355 // default-argument shall be deducible from the parameter-type-list of the
4356 // deduction guide template.
4357 auto *TemplateParams = TD->getTemplateParameters();
4358 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4359 MarkDeducedTemplateParameters(FunctionTemplate: TD, Deduced&: DeducibleParams);
4360 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4361 // A parameter pack is deducible (to an empty pack).
4362 auto *Param = TemplateParams->getParam(Idx: I);
4363 if (Param->isParameterPack() || hasVisibleDefaultArgument(D: Param))
4364 DeducibleParams[I] = true;
4365 }
4366
4367 if (!DeducibleParams.all()) {
4368 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4369 Diag(Loc: TD->getLocation(), DiagID: diag::err_deduction_guide_template_not_deducible)
4370 << (NumNonDeducible > 1);
4371 noteNonDeducibleParameters(S&: *this, TemplateParams, DeducibleParams);
4372 }
4373}
4374
4375DeclResult Sema::ActOnVarTemplateSpecialization(
4376 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
4377 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4378 StorageClass SC, bool IsPartialSpecialization) {
4379 // D must be variable template id.
4380 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4381 "Variable template specialization is declared with a template id.");
4382
4383 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4384 TemplateArgumentListInfo TemplateArgs =
4385 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TemplateId);
4386 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4387 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4388 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4389
4390 TemplateName Name = TemplateId->Template.get();
4391
4392 // The template-id must name a variable template.
4393 VarTemplateDecl *VarTemplate =
4394 dyn_cast_or_null<VarTemplateDecl>(Val: Name.getAsTemplateDecl());
4395 if (!VarTemplate) {
4396 NamedDecl *FnTemplate;
4397 if (auto *OTS = Name.getAsOverloadedTemplate())
4398 FnTemplate = *OTS->begin();
4399 else
4400 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Val: Name.getAsTemplateDecl());
4401 if (FnTemplate)
4402 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template_but_method)
4403 << FnTemplate->getDeclName();
4404 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template)
4405 << IsPartialSpecialization;
4406 }
4407
4408 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4409 auto Message = DSA->getMessage();
4410 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
4411 << VarTemplate << !Message.empty() << Message;
4412 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
4413 }
4414
4415 // Check for unexpanded parameter packs in any of the template arguments.
4416 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4417 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
4418 UPPC: IsPartialSpecialization
4419 ? UPPC_PartialSpecialization
4420 : UPPC_ExplicitSpecialization))
4421 return true;
4422
4423 // Check that the template argument list is well-formed for this
4424 // template.
4425 CheckTemplateArgumentInfo CTAI;
4426 if (CheckTemplateArgumentList(Template: VarTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
4427 /*DefaultArgs=*/{},
4428 /*PartialTemplateArgs=*/false, CTAI,
4429 /*UpdateArgsWithConversions=*/true))
4430 return true;
4431
4432 // Find the variable template (partial) specialization declaration that
4433 // corresponds to these arguments.
4434 if (IsPartialSpecialization) {
4435 if (CheckTemplatePartialSpecializationArgs(Loc: TemplateNameLoc, PrimaryTemplate: VarTemplate,
4436 NumExplicitArgs: TemplateArgs.size(),
4437 Args: CTAI.CanonicalConverted))
4438 return true;
4439
4440 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4441 // we also do them during instantiation.
4442 if (!Name.isDependent() &&
4443 !TemplateSpecializationType::anyDependentTemplateArguments(
4444 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4445 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
4446 << VarTemplate->getDeclName();
4447 IsPartialSpecialization = false;
4448 }
4449
4450 if (isSameAsPrimaryTemplate(Params: VarTemplate->getTemplateParameters(),
4451 SpecParams: TemplateParams, Args: CTAI.CanonicalConverted) &&
4452 (!Context.getLangOpts().CPlusPlus20 ||
4453 !TemplateParams->hasAssociatedConstraints())) {
4454 // C++ [temp.class.spec]p9b3:
4455 //
4456 // -- The argument list of the specialization shall not be identical
4457 // to the implicit argument list of the primary template.
4458 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
4459 << /*variable template*/ 1
4460 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4461 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
4462 // FIXME: Recover from this by treating the declaration as a
4463 // redeclaration of the primary template.
4464 return true;
4465 }
4466 }
4467
4468 void *InsertPos = nullptr;
4469 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4470
4471 if (IsPartialSpecialization)
4472 PrevDecl = VarTemplate->findPartialSpecialization(
4473 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertPos);
4474 else
4475 PrevDecl =
4476 VarTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
4477
4478 VarTemplateSpecializationDecl *Specialization = nullptr;
4479
4480 // Check whether we can declare a variable template specialization in
4481 // the current scope.
4482 if (CheckTemplateSpecializationScope(S&: *this, Specialized: VarTemplate, PrevDecl,
4483 Loc: TemplateNameLoc,
4484 IsPartialSpecialization))
4485 return true;
4486
4487 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4488 // Since the only prior variable template specialization with these
4489 // arguments was referenced but not declared, reuse that
4490 // declaration node as our own, updating its source location and
4491 // the list of outer template parameters to reflect our new declaration.
4492 Specialization = PrevDecl;
4493 Specialization->setLocation(TemplateNameLoc);
4494 PrevDecl = nullptr;
4495 } else if (IsPartialSpecialization) {
4496 // Create a new class template partial specialization declaration node.
4497 VarTemplatePartialSpecializationDecl *PrevPartial =
4498 cast_or_null<VarTemplatePartialSpecializationDecl>(Val: PrevDecl);
4499 VarTemplatePartialSpecializationDecl *Partial =
4500 VarTemplatePartialSpecializationDecl::Create(
4501 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc,
4502 IdLoc: TemplateNameLoc, Params: TemplateParams, SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI,
4503 S: SC, Args: CTAI.CanonicalConverted);
4504 Partial->setTemplateArgsAsWritten(TemplateArgs);
4505
4506 if (!PrevPartial)
4507 VarTemplate->AddPartialSpecialization(D: Partial, InsertPos);
4508 Specialization = Partial;
4509
4510 CheckTemplatePartialSpecialization(Partial);
4511 } else {
4512 // Create a new class template specialization declaration node for
4513 // this explicit specialization or friend declaration.
4514 Specialization = VarTemplateSpecializationDecl::Create(
4515 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc, IdLoc: TemplateNameLoc,
4516 SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI, S: SC, Args: CTAI.CanonicalConverted);
4517 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4518
4519 if (!PrevDecl)
4520 VarTemplate->AddSpecialization(D: Specialization, InsertPos);
4521 }
4522
4523 // C++ [temp.expl.spec]p6:
4524 // If a template, a member template or the member of a class template is
4525 // explicitly specialized then that specialization shall be declared
4526 // before the first use of that specialization that would cause an implicit
4527 // instantiation to take place, in every translation unit in which such a
4528 // use occurs; no diagnostic is required.
4529 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4530 bool Okay = false;
4531 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4532 // Is there any previous explicit specialization declaration?
4533 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
4534 Okay = true;
4535 break;
4536 }
4537 }
4538
4539 if (!Okay) {
4540 SourceRange Range(TemplateNameLoc, RAngleLoc);
4541 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
4542 << Name << Range;
4543
4544 Diag(Loc: PrevDecl->getPointOfInstantiation(),
4545 DiagID: diag::note_instantiation_required_here)
4546 << (PrevDecl->getTemplateSpecializationKind() !=
4547 TSK_ImplicitInstantiation);
4548 return true;
4549 }
4550 }
4551
4552 Specialization->setLexicalDeclContext(CurContext);
4553
4554 // Add the specialization into its lexical context, so that it can
4555 // be seen when iterating through the list of declarations in that
4556 // context. However, specializations are not found by name lookup.
4557 CurContext->addDecl(D: Specialization);
4558
4559 // Note that this is an explicit specialization.
4560 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4561
4562 Previous.clear();
4563 if (PrevDecl)
4564 Previous.addDecl(D: PrevDecl);
4565 else if (Specialization->isStaticDataMember() &&
4566 Specialization->isOutOfLine())
4567 Specialization->setAccess(VarTemplate->getAccess());
4568
4569 return Specialization;
4570}
4571
4572namespace {
4573/// A partial specialization whose template arguments have matched
4574/// a given template-id.
4575struct PartialSpecMatchResult {
4576 VarTemplatePartialSpecializationDecl *Partial;
4577 TemplateArgumentList *Args;
4578};
4579
4580// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4581// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4582static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4583 if (Var->getName() != "format_kind" ||
4584 !Var->getDeclContext()->isStdNamespace())
4585 return false;
4586
4587 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4588 // release in which users can access std::format_kind.
4589 // We can use 20250520 as the final date, see the following commits.
4590 // GCC releases/gcc-15 branch:
4591 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4592 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4593 // GCC master branch:
4594 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4595 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4596 return PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2025'05'20);
4597}
4598} // end anonymous namespace
4599
4600DeclResult
4601Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4602 SourceLocation TemplateNameLoc,
4603 const TemplateArgumentListInfo &TemplateArgs,
4604 bool SetWrittenArgs) {
4605 assert(Template && "A variable template id without template?");
4606
4607 // Check that the template argument list is well-formed for this template.
4608 CheckTemplateArgumentInfo CTAI;
4609 if (CheckTemplateArgumentList(
4610 Template, TemplateLoc: TemplateNameLoc,
4611 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4612 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4613 /*UpdateArgsWithConversions=*/true))
4614 return true;
4615
4616 // Produce a placeholder value if the specialization is dependent.
4617 if (Template->getDeclContext()->isDependentContext() ||
4618 TemplateSpecializationType::anyDependentTemplateArguments(
4619 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4620 if (ParsingInitForAutoVars.empty())
4621 return DeclResult();
4622
4623 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4624 const TemplateArgument &Arg2) {
4625 return Context.isSameTemplateArgument(Arg1, Arg2);
4626 };
4627
4628 if (VarDecl *Var = Template->getTemplatedDecl();
4629 ParsingInitForAutoVars.count(Ptr: Var) &&
4630 // See comments on this function definition
4631 !IsLibstdcxxStdFormatKind(PP, Var) &&
4632 llvm::equal(
4633 LRange&: CTAI.CanonicalConverted,
4634 RRange: Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4635 P: IsSameTemplateArg)) {
4636 Diag(Loc: TemplateNameLoc,
4637 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4638 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4639 return true;
4640 }
4641
4642 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4643 Template->getPartialSpecializations(PS&: PartialSpecs);
4644 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4645 if (ParsingInitForAutoVars.count(Ptr: Partial) &&
4646 llvm::equal(LRange&: CTAI.CanonicalConverted,
4647 RRange: Partial->getTemplateArgs().asArray(),
4648 P: IsSameTemplateArg)) {
4649 Diag(Loc: TemplateNameLoc,
4650 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4651 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4652 << Partial->getType();
4653 return true;
4654 }
4655
4656 return DeclResult();
4657 }
4658
4659 // Find the variable template specialization declaration that
4660 // corresponds to these arguments.
4661 void *InsertPos = nullptr;
4662 if (VarTemplateSpecializationDecl *Spec =
4663 Template->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos)) {
4664 checkSpecializationReachability(Loc: TemplateNameLoc, Spec);
4665 if (Spec->getType()->isUndeducedType()) {
4666 if (ParsingInitForAutoVars.count(Ptr: Spec))
4667 Diag(Loc: TemplateNameLoc,
4668 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4669 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4670 << Spec->getType();
4671 else
4672 // We are substituting the initializer of this variable template
4673 // specialization.
4674 Diag(Loc: TemplateNameLoc, DiagID: diag::err_var_template_spec_type_depends_on_self)
4675 << Spec << Spec->getType();
4676
4677 return true;
4678 }
4679 // If we already have a variable template specialization, return it.
4680 return Spec;
4681 }
4682
4683 // This is the first time we have referenced this variable template
4684 // specialization. Create the canonical declaration and add it to
4685 // the set of specializations, based on the closest partial specialization
4686 // that it represents. That is,
4687 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4688 const TemplateArgumentList *PartialSpecArgs = nullptr;
4689 bool AmbiguousPartialSpec = false;
4690 typedef PartialSpecMatchResult MatchResult;
4691 SmallVector<MatchResult, 4> Matched;
4692 SourceLocation PointOfInstantiation = TemplateNameLoc;
4693 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4694 /*ForTakingAddress=*/false);
4695
4696 // 1. Attempt to find the closest partial specialization that this
4697 // specializes, if any.
4698 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4699 // Perhaps better after unification of DeduceTemplateArguments() and
4700 // getMoreSpecializedPartialSpecialization().
4701 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4702 Template->getPartialSpecializations(PS&: PartialSpecs);
4703
4704 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4705 // C++ [temp.spec.partial.member]p2:
4706 // If the primary member template is explicitly specialized for a given
4707 // (implicit) specialization of the enclosing class template, the partial
4708 // specializations of the member template are ignored for this
4709 // specialization of the enclosing class template. If a partial
4710 // specialization of the member template is explicitly specialized for a
4711 // given (implicit) specialization of the enclosing class template, the
4712 // primary member template and its other partial specializations are still
4713 // considered for this specialization of the enclosing class template.
4714 if (Template->isMemberSpecialization() &&
4715 !Partial->isMemberSpecialization())
4716 continue;
4717
4718 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4719
4720 if (TemplateDeductionResult Result =
4721 DeduceTemplateArguments(Partial, TemplateArgs: CTAI.SugaredConverted, Info);
4722 Result != TemplateDeductionResult::Success) {
4723 // Store the failed-deduction information for use in diagnostics, later.
4724 // TODO: Actually use the failed-deduction info?
4725 FailedCandidates.addCandidate().set(
4726 Found: DeclAccessPair::make(D: Template, AS: AS_public), Spec: Partial,
4727 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
4728 (void)Result;
4729 } else {
4730 Matched.push_back(Elt: PartialSpecMatchResult());
4731 Matched.back().Partial = Partial;
4732 Matched.back().Args = Info.takeSugared();
4733 }
4734 }
4735
4736 if (Matched.size() >= 1) {
4737 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4738 if (Matched.size() == 1) {
4739 // -- If exactly one matching specialization is found, the
4740 // instantiation is generated from that specialization.
4741 // We don't need to do anything for this.
4742 } else {
4743 // -- If more than one matching specialization is found, the
4744 // partial order rules (14.5.4.2) are used to determine
4745 // whether one of the specializations is more specialized
4746 // than the others. If none of the specializations is more
4747 // specialized than all of the other matching
4748 // specializations, then the use of the variable template is
4749 // ambiguous and the program is ill-formed.
4750 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4751 PEnd = Matched.end();
4752 P != PEnd; ++P) {
4753 if (getMoreSpecializedPartialSpecialization(PS1: P->Partial, PS2: Best->Partial,
4754 Loc: PointOfInstantiation) ==
4755 P->Partial)
4756 Best = P;
4757 }
4758
4759 // Determine if the best partial specialization is more specialized than
4760 // the others.
4761 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4762 PEnd = Matched.end();
4763 P != PEnd; ++P) {
4764 if (P != Best && getMoreSpecializedPartialSpecialization(
4765 PS1: P->Partial, PS2: Best->Partial,
4766 Loc: PointOfInstantiation) != Best->Partial) {
4767 AmbiguousPartialSpec = true;
4768 break;
4769 }
4770 }
4771 }
4772
4773 // Instantiate using the best variable template partial specialization.
4774 InstantiationPattern = Best->Partial;
4775 PartialSpecArgs = Best->Args;
4776 } else {
4777 // -- If no match is found, the instantiation is generated
4778 // from the primary template.
4779 // InstantiationPattern = Template->getTemplatedDecl();
4780 }
4781
4782 // 2. Create the canonical declaration.
4783 // Note that we do not instantiate a definition until we see an odr-use
4784 // in DoMarkVarDeclReferenced().
4785 // FIXME: LateAttrs et al.?
4786 if (AmbiguousPartialSpec) {
4787 // Partial ordering did not produce a clear winner. Complain.
4788 Diag(Loc: PointOfInstantiation, DiagID: diag::err_partial_spec_ordering_ambiguous)
4789 << Template;
4790 // Print the matching partial specializations.
4791 for (MatchResult P : Matched)
4792 Diag(Loc: P.Partial->getLocation(), DiagID: diag::note_partial_spec_match)
4793 << getTemplateArgumentBindingsText(Params: P.Partial->getTemplateParameters(),
4794 Args: *P.Args);
4795 return true;
4796 }
4797
4798 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4799 VarTemplate: Template, FromVar: InstantiationPattern, PartialSpecArgs, Converted&: CTAI.CanonicalConverted,
4800 PointOfInstantiation: TemplateNameLoc /*, LateAttrs, StartingScope*/);
4801 if (!Decl)
4802 return true;
4803 if (SetWrittenArgs)
4804 Decl->setTemplateArgsAsWritten(TemplateArgs);
4805
4806 if (VarTemplatePartialSpecializationDecl *D =
4807 dyn_cast<VarTemplatePartialSpecializationDecl>(Val: InstantiationPattern))
4808 Decl->setInstantiationOf(PartialSpec: D, TemplateArgs: PartialSpecArgs);
4809
4810 checkSpecializationReachability(Loc: TemplateNameLoc, Spec: Decl);
4811
4812 assert(Decl && "No variable template specialization?");
4813 return Decl;
4814}
4815
4816ExprResult Sema::CheckVarTemplateId(
4817 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4818 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4819 const TemplateArgumentListInfo *TemplateArgs) {
4820
4821 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, TemplateNameLoc: NameInfo.getLoc(),
4822 TemplateArgs: *TemplateArgs, /*SetWrittenArgs=*/false);
4823 if (Decl.isInvalid())
4824 return ExprError();
4825
4826 if (!Decl.get())
4827 return ExprResult();
4828
4829 VarDecl *Var = cast<VarDecl>(Val: Decl.get());
4830 if (!Var->getTemplateSpecializationKind())
4831 Var->setTemplateSpecializationKind(TSK: TSK_ImplicitInstantiation,
4832 PointOfInstantiation: NameInfo.getLoc());
4833
4834 // Build an ordinary singleton decl ref.
4835 return BuildDeclarationNameExpr(SS, NameInfo, D: Var, FoundD, TemplateArgs);
4836}
4837
4838ExprResult Sema::CheckVarOrConceptTemplateTemplateId(
4839 const DeclarationNameInfo &NameInfo, TemplateName Template,
4840 const TemplateArgumentListInfo *TemplateArgs) {
4841 TemplateTemplateParmDecl *Parameter =
4842 Template.getAsTemplateTemplateParmDecl();
4843 assert(Parameter && "A variable template id without template?");
4844
4845 if (Parameter->templateParameterKind() !=
4846 TemplateNameKind::TNK_Var_template &&
4847 Parameter->templateParameterKind() !=
4848 TemplateNameKind::TNK_Concept_template)
4849 return ExprResult();
4850
4851 // Check that the template argument list is well-formed for this template.
4852 CheckTemplateArgumentInfo CTAI;
4853 if (CheckTemplateArgumentList(
4854 Template: Parameter, /*Template kw loc=*/TemplateLoc: {},
4855 // FIXME: TemplateArgs will not be modified because
4856 // UpdateArgsWithConversions is false, however, we should
4857 // CheckTemplateArgumentList to be const-correct.
4858 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4859 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4860 /*UpdateArgsWithConversions=*/false))
4861 return true;
4862
4863 return DependentTemplateIdExpr::Create(Context: getASTContext(), NameInfo, Name: Template,
4864 TemplateArgs: *TemplateArgs);
4865}
4866
4867void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4868 SourceLocation Loc) {
4869 Diag(Loc, DiagID: diag::err_template_missing_args)
4870 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4871 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4872 NoteTemplateLocation(Decl: *TD, ParamRange: TD->getTemplateParameters()->getSourceRange());
4873 }
4874}
4875
4876void Sema::diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
4877 bool TemplateKeyword,
4878 TemplateDecl *TD,
4879 SourceLocation Loc) {
4880 TemplateName Name = Context.getQualifiedTemplateName(
4881 Qualifier: SS.getScopeRep(), TemplateKeyword, Template: TemplateName(TD));
4882 diagnoseMissingTemplateArguments(Name, Loc);
4883}
4884
4885ExprResult Sema::CheckConceptTemplateId(
4886 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4887 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4888 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4889 bool DoCheckConstraintSatisfaction) {
4890 assert(NamedConcept && "A concept template id without a template?");
4891
4892 if (NamedConcept->isInvalidDecl())
4893 return ExprError();
4894
4895 CheckTemplateArgumentInfo CTAI;
4896 if (CheckTemplateArgumentList(
4897 Template: NamedConcept, TemplateLoc: ConceptNameInfo.getLoc(),
4898 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4899 /*DefaultArgs=*/{},
4900 /*PartialTemplateArgs=*/false, CTAI,
4901 /*UpdateArgsWithConversions=*/false))
4902 return ExprError();
4903
4904 DiagnoseUseOfDecl(D: NamedConcept, Locs: ConceptNameInfo.getLoc());
4905
4906 // There's a bug with CTAI.CanonicalConverted.
4907 // If the template argument contains a DependentDecltypeType that includes a
4908 // TypeAliasType, and the same written type had occurred previously in the
4909 // source, then the DependentDecltypeType would be canonicalized to that
4910 // previous type which would mess up the substitution.
4911 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4912 auto *CSD = ImplicitConceptSpecializationDecl::Create(
4913 C: Context, DC: NamedConcept->getDeclContext(), SL: NamedConcept->getLocation(),
4914 ConvertedArgs: CTAI.SugaredConverted);
4915 ConstraintSatisfaction Satisfaction;
4916 bool AreArgsDependent =
4917 TemplateSpecializationType::anyDependentTemplateArguments(
4918 *TemplateArgs, Converted: CTAI.SugaredConverted);
4919 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4920 /*Final=*/false);
4921 auto *CL = ConceptReference::Create(
4922 C: Context,
4923 NNS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4924 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept: TemplateName(NamedConcept),
4925 ArgsAsWritten: ASTTemplateArgumentListInfo::Create(C: Context, List: *TemplateArgs));
4926
4927 bool Error = false;
4928 if (const auto *Concept = dyn_cast<ConceptDecl>(Val: NamedConcept);
4929 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4930 DoCheckConstraintSatisfaction) {
4931
4932 LocalInstantiationScope Scope(*this);
4933
4934 EnterExpressionEvaluationContext EECtx{
4935 *this, ExpressionEvaluationContext::Unevaluated};
4936
4937 Error = CheckConstraintSatisfaction(
4938 Entity: NamedConcept, AssociatedConstraints: AssociatedConstraint(Concept->getConstraintExpr()), TemplateArgLists: MLTAL,
4939 TemplateIDRange: SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4940 TemplateArgs->getRAngleLoc()),
4941 Satisfaction, TopLevelConceptId: CL);
4942 Satisfaction.ContainsErrors = Error;
4943 }
4944
4945 if (Error)
4946 return ExprError();
4947
4948 return ConceptSpecializationExpr::Create(
4949 C: Context, ConceptRef: CL, SpecDecl: CSD, Satisfaction: AreArgsDependent ? nullptr : &Satisfaction);
4950}
4951
4952ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4953 SourceLocation TemplateKWLoc,
4954 LookupResult &R,
4955 bool RequiresADL,
4956 const TemplateArgumentListInfo *TemplateArgs) {
4957 // FIXME: Can we do any checking at this point? I guess we could check the
4958 // template arguments that we have against the template name, if the template
4959 // name refers to a single template. That's not a terribly common case,
4960 // though.
4961 // foo<int> could identify a single function unambiguously
4962 // This approach does NOT work, since f<int>(1);
4963 // gets resolved prior to resorting to overload resolution
4964 // i.e., template<class T> void f(double);
4965 // vs template<class T, class U> void f(U);
4966
4967 // These should be filtered out by our callers.
4968 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4969
4970 // Non-function templates require a template argument list.
4971 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4972 if (!TemplateArgs && !isa<FunctionTemplateDecl>(Val: TD)) {
4973 diagnoseMissingTemplateArguments(
4974 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, Loc: R.getNameLoc());
4975 return ExprError();
4976 }
4977 }
4978 bool KnownDependent = false;
4979 // In C++1y, check variable template ids.
4980 if (R.getAsSingle<VarTemplateDecl>()) {
4981 ExprResult Res = CheckVarTemplateId(
4982 SS, NameInfo: R.getLookupNameInfo(), Template: R.getAsSingle<VarTemplateDecl>(),
4983 FoundD: R.getRepresentativeDecl(), TemplateLoc: TemplateKWLoc, TemplateArgs);
4984 if (Res.isInvalid() || Res.isUsable())
4985 return Res;
4986 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4987 KnownDependent = true;
4988 }
4989
4990 // We don't want lookup warnings at this point.
4991 R.suppressDiagnostics();
4992
4993 if (R.getAsSingle<ConceptDecl>()) {
4994 assert(TemplateKWLoc.isInvalid() &&
4995 "template keyword in front of a concept id?");
4996 return CheckConceptTemplateId(SS, TemplateKWLoc, ConceptNameInfo: R.getLookupNameInfo(),
4997 FoundDecl: R.getRepresentativeDecl(),
4998 NamedConcept: R.getAsSingle<ConceptDecl>(), TemplateArgs);
4999 }
5000
5001 // Check variable template ids (C++17) and concept template parameters
5002 // (C++26).
5003 UnresolvedLookupExpr *ULE;
5004 if (R.getAsSingle<TemplateTemplateParmDecl>()) {
5005 assert(SS.isEmpty() && "template parameter with a scope specifier?");
5006 assert(TemplateKWLoc.isInvalid() &&
5007 "template keyword in front of a template parameter?");
5008 return CheckVarOrConceptTemplateTemplateId(
5009 NameInfo: R.getLookupNameInfo(),
5010 Template: TemplateName(R.getAsSingle<TemplateTemplateParmDecl>()), TemplateArgs);
5011 }
5012
5013 // Function templates
5014 ULE = UnresolvedLookupExpr::Create(
5015 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
5016 TemplateKWLoc, NameInfo: R.getLookupNameInfo(), RequiresADL, Args: TemplateArgs,
5017 Begin: R.begin(), End: R.end(), KnownDependent,
5018 /*KnownInstantiationDependent=*/false);
5019 // Model the templates with UnresolvedTemplateTy. The expression should then
5020 // either be transformed in an instantiation or be diagnosed in
5021 // CheckPlaceholderExpr.
5022 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5023 !R.getFoundDecl()->getAsFunction())
5024 ULE->setType(Context.UnresolvedTemplateTy);
5025
5026 return ULE;
5027}
5028
5029ExprResult Sema::BuildQualifiedTemplateIdExpr(
5030 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5031 const DeclarationNameInfo &NameInfo,
5032 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5033 assert(TemplateArgs || TemplateKWLoc.isValid());
5034
5035 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5036 if (LookupTemplateName(Found&: R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5037 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc))
5038 return ExprError();
5039
5040 if (R.isAmbiguous())
5041 return ExprError();
5042
5043 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5044 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5045
5046 if (R.empty()) {
5047 DeclContext *DC = computeDeclContext(SS);
5048 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
5049 << NameInfo.getName() << DC << SS.getRange();
5050 return ExprError();
5051 }
5052
5053 // If necessary, build an implicit class member access.
5054 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5055 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5056 /*S=*/nullptr);
5057
5058 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/RequiresADL: false, TemplateArgs);
5059}
5060
5061TemplateNameKind Sema::ActOnTemplateName(Scope *S,
5062 CXXScopeSpec &SS,
5063 SourceLocation TemplateKWLoc,
5064 const UnqualifiedId &Name,
5065 ParsedType ObjectType,
5066 bool EnteringContext,
5067 TemplateTy &Result,
5068 bool AllowInjectedClassName) {
5069 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5070 Diag(Loc: TemplateKWLoc,
5071 DiagID: getLangOpts().CPlusPlus11 ?
5072 diag::warn_cxx98_compat_template_outside_of_template :
5073 diag::ext_template_outside_of_template)
5074 << FixItHint::CreateRemoval(RemoveRange: TemplateKWLoc);
5075
5076 if (SS.isInvalid())
5077 return TNK_Non_template;
5078
5079 // Figure out where isTemplateName is going to look.
5080 DeclContext *LookupCtx = nullptr;
5081 if (SS.isNotEmpty())
5082 LookupCtx = computeDeclContext(SS, EnteringContext);
5083 else if (ObjectType)
5084 LookupCtx = computeDeclContext(T: GetTypeFromParser(Ty: ObjectType));
5085
5086 // C++0x [temp.names]p5:
5087 // If a name prefixed by the keyword template is not the name of
5088 // a template, the program is ill-formed. [Note: the keyword
5089 // template may not be applied to non-template members of class
5090 // templates. -end note ] [ Note: as is the case with the
5091 // typename prefix, the template prefix is allowed in cases
5092 // where it is not strictly necessary; i.e., when the
5093 // nested-name-specifier or the expression on the left of the ->
5094 // or . is not dependent on a template-parameter, or the use
5095 // does not appear in the scope of a template. -end note]
5096 //
5097 // Note: C++03 was more strict here, because it banned the use of
5098 // the "template" keyword prior to a template-name that was not a
5099 // dependent name. C++ DR468 relaxed this requirement (the
5100 // "template" keyword is now permitted). We follow the C++0x
5101 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5102 bool MemberOfUnknownSpecialization;
5103 TemplateNameKind TNK = isTemplateName(S, SS, hasTemplateKeyword: TemplateKWLoc.isValid(), Name,
5104 ObjectTypePtr: ObjectType, EnteringContext, TemplateResult&: Result,
5105 MemberOfUnknownSpecialization);
5106 if (TNK != TNK_Non_template) {
5107 // We resolved this to a (non-dependent) template name. Return it.
5108 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
5109 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5110 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5111 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5112 // C++14 [class.qual]p2:
5113 // In a lookup in which function names are not ignored and the
5114 // nested-name-specifier nominates a class C, if the name specified
5115 // [...] is the injected-class-name of C, [...] the name is instead
5116 // considered to name the constructor
5117 //
5118 // We don't get here if naming the constructor would be valid, so we
5119 // just reject immediately and recover by treating the
5120 // injected-class-name as naming the template.
5121 Diag(Loc: Name.getBeginLoc(),
5122 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
5123 << Name.Identifier
5124 << 0 /*injected-class-name used as template name*/
5125 << TemplateKWLoc.isValid();
5126 }
5127 return TNK;
5128 }
5129
5130 if (!MemberOfUnknownSpecialization) {
5131 // Didn't find a template name, and the lookup wasn't dependent.
5132 // Do the lookup again to determine if this is a "nothing found" case or
5133 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5134 // need to do this.
5135 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
5136 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5137 LookupOrdinaryName);
5138 // Tell LookupTemplateName that we require a template so that it diagnoses
5139 // cases where it finds a non-template.
5140 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5141 ? RequiredTemplateKind(TemplateKWLoc)
5142 : TemplateNameIsRequired;
5143 if (!LookupTemplateName(Found&: R, S, SS, ObjectType: ObjectType.get(), EnteringContext, RequiredTemplate: RTK,
5144 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5145 !R.isAmbiguous()) {
5146 if (LookupCtx)
5147 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_no_member)
5148 << DNI.getName() << LookupCtx << SS.getRange();
5149 else
5150 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_undeclared_use)
5151 << DNI.getName() << SS.getRange();
5152 }
5153 return TNK_Non_template;
5154 }
5155
5156 NestedNameSpecifier Qualifier = SS.getScopeRep();
5157
5158 switch (Name.getKind()) {
5159 case UnqualifiedIdKind::IK_Identifier:
5160 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5161 Name: {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5162 return TNK_Dependent_template_name;
5163
5164 case UnqualifiedIdKind::IK_OperatorFunctionId:
5165 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5166 Name: {Qualifier, Name.OperatorFunctionId.Operator,
5167 TemplateKWLoc.isValid()}));
5168 return TNK_Function_template;
5169
5170 case UnqualifiedIdKind::IK_LiteralOperatorId:
5171 // This is a kind of template name, but can never occur in a dependent
5172 // scope (literal operators can only be declared at namespace scope).
5173 break;
5174
5175 default:
5176 break;
5177 }
5178
5179 // This name cannot possibly name a dependent template. Diagnose this now
5180 // rather than building a dependent template name that can never be valid.
5181 Diag(Loc: Name.getBeginLoc(),
5182 DiagID: diag::err_template_kw_refers_to_dependent_non_template)
5183 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5184 << TemplateKWLoc.isValid() << TemplateKWLoc;
5185 return TNK_Non_template;
5186}
5187
5188bool Sema::CheckTemplateTypeArgument(
5189 TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
5190 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5191 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5192 const TemplateArgument &Arg = AL.getArgument();
5193 QualType ArgType;
5194 TypeSourceInfo *TSI = nullptr;
5195
5196 // Check template type parameter.
5197 switch(Arg.getKind()) {
5198 case TemplateArgument::Type:
5199 // C++ [temp.arg.type]p1:
5200 // A template-argument for a template-parameter which is a
5201 // type shall be a type-id.
5202 ArgType = Arg.getAsType();
5203 TSI = AL.getTypeSourceInfo();
5204 break;
5205 case TemplateArgument::Template:
5206 case TemplateArgument::TemplateExpansion: {
5207 // We have a template type parameter but the template argument
5208 // is a template without any arguments.
5209 SourceRange SR = AL.getSourceRange();
5210 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
5211 diagnoseMissingTemplateArguments(Name, Loc: SR.getEnd());
5212 return true;
5213 }
5214 case TemplateArgument::Expression: {
5215 // We have a template type parameter but the template argument is an
5216 // expression; see if maybe it is missing the "typename" keyword.
5217 CXXScopeSpec SS;
5218 DeclarationNameInfo NameInfo;
5219
5220 if (DependentScopeDeclRefExpr *ArgExpr =
5221 dyn_cast<DependentScopeDeclRefExpr>(Val: Arg.getAsExpr())) {
5222 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5223 NameInfo = ArgExpr->getNameInfo();
5224 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5225 dyn_cast<CXXDependentScopeMemberExpr>(Val: Arg.getAsExpr())) {
5226 if (ArgExpr->isImplicitAccess()) {
5227 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5228 NameInfo = ArgExpr->getMemberNameInfo();
5229 }
5230 }
5231
5232 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5233 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5234 LookupParsedName(R&: Result, S: CurScope, SS: &SS, /*ObjectType=*/QualType());
5235
5236 if (Result.getAsSingle<TypeDecl>() ||
5237 Result.wasNotFoundInCurrentInstantiation()) {
5238 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5239 // Suggest that the user add 'typename' before the NNS.
5240 SourceLocation Loc = AL.getSourceRange().getBegin();
5241 Diag(Loc, DiagID: getLangOpts().MSVCCompat
5242 ? diag::ext_ms_template_type_arg_missing_typename
5243 : diag::err_template_arg_must_be_type_suggest)
5244 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
5245 NoteTemplateParameterLocation(Decl: *Param);
5246
5247 // Recover by synthesizing a type using the location information that we
5248 // already have.
5249 ArgType = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
5250 NNS: SS.getScopeRep(), Name: II);
5251 TypeLocBuilder TLB;
5252 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: ArgType);
5253 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5254 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5255 TL.setNameLoc(NameInfo.getLoc());
5256 TSI = TLB.getTypeSourceInfo(Context, T: ArgType);
5257
5258 // Overwrite our input TemplateArgumentLoc so that we can recover
5259 // properly.
5260 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5261 TemplateArgumentLocInfo(TSI));
5262
5263 break;
5264 }
5265 }
5266 // fallthrough
5267 [[fallthrough]];
5268 }
5269 default: {
5270 // We allow instantiating a template with template argument packs when
5271 // building deduction guides or mapping constraint template parameters.
5272 if (Arg.getKind() == TemplateArgument::Pack &&
5273 (CodeSynthesisContexts.back().Kind ==
5274 Sema::CodeSynthesisContext::BuildingDeductionGuides ||
5275 inParameterMappingSubstitution())) {
5276 SugaredConverted.push_back(Elt: Arg);
5277 CanonicalConverted.push_back(Elt: Arg);
5278 return false;
5279 }
5280 // We have a template type parameter but the template argument
5281 // is not a type.
5282 SourceRange SR = AL.getSourceRange();
5283 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_type) << SR;
5284 NoteTemplateParameterLocation(Decl: *Param);
5285
5286 return true;
5287 }
5288 }
5289
5290 if (CheckTemplateArgument(Arg: TSI))
5291 return true;
5292
5293 // Objective-C ARC:
5294 // If an explicitly-specified template argument type is a lifetime type
5295 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5296 if (getLangOpts().ObjCAutoRefCount &&
5297 ArgType->isObjCLifetimeType() &&
5298 !ArgType.getObjCLifetime()) {
5299 Qualifiers Qs;
5300 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5301 ArgType = Context.getQualifiedType(T: ArgType, Qs);
5302 }
5303
5304 SugaredConverted.push_back(Elt: TemplateArgument(ArgType));
5305 CanonicalConverted.push_back(
5306 Elt: TemplateArgument(Context.getCanonicalType(T: ArgType)));
5307 return false;
5308}
5309
5310/// Substitute template arguments into the default template argument for
5311/// the given template type parameter.
5312///
5313/// \param SemaRef the semantic analysis object for which we are performing
5314/// the substitution.
5315///
5316/// \param Template the template that we are synthesizing template arguments
5317/// for.
5318///
5319/// \param TemplateLoc the location of the template name that started the
5320/// template-id we are checking.
5321///
5322/// \param RAngleLoc the location of the right angle bracket ('>') that
5323/// terminates the template-id.
5324///
5325/// \param Param the template template parameter whose default we are
5326/// substituting into.
5327///
5328/// \param Converted the list of template arguments provided for template
5329/// parameters that precede \p Param in the template parameter list.
5330///
5331/// \param Output the resulting substituted template argument.
5332///
5333/// \returns true if an error occurred.
5334static bool SubstDefaultTemplateArgument(
5335 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5336 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5337 ArrayRef<TemplateArgument> SugaredConverted,
5338 ArrayRef<TemplateArgument> CanonicalConverted,
5339 TemplateArgumentLoc &Output) {
5340 Output = Param->getDefaultArgument();
5341
5342 // If the argument type is dependent, instantiate it now based
5343 // on the previously-computed template arguments.
5344 if (Output.getArgument().isInstantiationDependent()) {
5345 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5346 SugaredConverted,
5347 SourceRange(TemplateLoc, RAngleLoc));
5348 if (Inst.isInvalid())
5349 return true;
5350
5351 // Only substitute for the innermost template argument list.
5352 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5353 /*Final=*/true);
5354 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5355 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5356
5357 bool ForLambdaCallOperator = false;
5358 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Val: Template->getDeclContext()))
5359 ForLambdaCallOperator = Rec->isLambda();
5360 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5361 !ForLambdaCallOperator);
5362
5363 if (SemaRef.SubstTemplateArgument(Input: Output, TemplateArgs: TemplateArgLists, Output,
5364 Loc: Param->getDefaultArgumentLoc(),
5365 Entity: Param->getDeclName()))
5366 return true;
5367 }
5368
5369 return false;
5370}
5371
5372/// Substitute template arguments into the default template argument for
5373/// the given non-type template parameter.
5374///
5375/// \param SemaRef the semantic analysis object for which we are performing
5376/// the substitution.
5377///
5378/// \param Template the template that we are synthesizing template arguments
5379/// for.
5380///
5381/// \param TemplateLoc the location of the template name that started the
5382/// template-id we are checking.
5383///
5384/// \param RAngleLoc the location of the right angle bracket ('>') that
5385/// terminates the template-id.
5386///
5387/// \param Param the non-type template parameter whose default we are
5388/// substituting into.
5389///
5390/// \param Converted the list of template arguments provided for template
5391/// parameters that precede \p Param in the template parameter list.
5392///
5393/// \returns the substituted template argument, or NULL if an error occurred.
5394static bool SubstDefaultTemplateArgument(
5395 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5396 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5397 ArrayRef<TemplateArgument> SugaredConverted,
5398 ArrayRef<TemplateArgument> CanonicalConverted,
5399 TemplateArgumentLoc &Output) {
5400 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5401 SugaredConverted,
5402 SourceRange(TemplateLoc, RAngleLoc));
5403 if (Inst.isInvalid())
5404 return true;
5405
5406 // Only substitute for the innermost template argument list.
5407 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5408 /*Final=*/true);
5409 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5410 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5411
5412 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5413 EnterExpressionEvaluationContext ConstantEvaluated(
5414 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5415 return SemaRef.SubstTemplateArgument(Input: Param->getDefaultArgument(),
5416 TemplateArgs: TemplateArgLists, Output);
5417}
5418
5419/// Substitute template arguments into the default template argument for
5420/// the given template template parameter.
5421///
5422/// \param SemaRef the semantic analysis object for which we are performing
5423/// the substitution.
5424///
5425/// \param Template the template that we are synthesizing template arguments
5426/// for.
5427///
5428/// \param TemplateLoc the location of the template name that started the
5429/// template-id we are checking.
5430///
5431/// \param RAngleLoc the location of the right angle bracket ('>') that
5432/// terminates the template-id.
5433///
5434/// \param Param the template template parameter whose default we are
5435/// substituting into.
5436///
5437/// \param Converted the list of template arguments provided for template
5438/// parameters that precede \p Param in the template parameter list.
5439///
5440/// \param QualifierLoc Will be set to the nested-name-specifier (with
5441/// source-location information) that precedes the template name.
5442///
5443/// \returns the substituted template argument, or NULL if an error occurred.
5444static TemplateName SubstDefaultTemplateArgument(
5445 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5446 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5447 TemplateTemplateParmDecl *Param,
5448 ArrayRef<TemplateArgument> SugaredConverted,
5449 ArrayRef<TemplateArgument> CanonicalConverted,
5450 NestedNameSpecifierLoc &QualifierLoc) {
5451 Sema::InstantiatingTemplate Inst(
5452 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5453 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5454 if (Inst.isInvalid())
5455 return TemplateName();
5456
5457 // Only substitute for the innermost template argument list.
5458 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5459 /*Final=*/true);
5460 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5461 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5462
5463 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5464
5465 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5466 QualifierLoc = A.getTemplateQualifierLoc();
5467 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5468 Name: A.getArgument().getAsTemplate(),
5469 NameLoc: A.getTemplateNameLoc(), TemplateArgs: TemplateArgLists);
5470}
5471
5472TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
5473 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5474 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5475 ArrayRef<TemplateArgument> SugaredConverted,
5476 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5477 HasDefaultArg = false;
5478
5479 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
5480 if (!hasReachableDefaultArgument(D: TypeParm))
5481 return TemplateArgumentLoc();
5482
5483 HasDefaultArg = true;
5484 TemplateArgumentLoc Output;
5485 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5486 RAngleLoc, Param: TypeParm, SugaredConverted,
5487 CanonicalConverted, Output))
5488 return TemplateArgumentLoc();
5489 return Output;
5490 }
5491
5492 if (NonTypeTemplateParmDecl *NonTypeParm
5493 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5494 if (!hasReachableDefaultArgument(D: NonTypeParm))
5495 return TemplateArgumentLoc();
5496
5497 HasDefaultArg = true;
5498 TemplateArgumentLoc Output;
5499 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5500 RAngleLoc, Param: NonTypeParm, SugaredConverted,
5501 CanonicalConverted, Output))
5502 return TemplateArgumentLoc();
5503 return Output;
5504 }
5505
5506 TemplateTemplateParmDecl *TempTempParm
5507 = cast<TemplateTemplateParmDecl>(Val: Param);
5508 if (!hasReachableDefaultArgument(D: TempTempParm))
5509 return TemplateArgumentLoc();
5510
5511 HasDefaultArg = true;
5512 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5513 NestedNameSpecifierLoc QualifierLoc;
5514 TemplateName TName = SubstDefaultTemplateArgument(
5515 SemaRef&: *this, Template, TemplateKWLoc, TemplateLoc: TemplateNameLoc, RAngleLoc, Param: TempTempParm,
5516 SugaredConverted, CanonicalConverted, QualifierLoc);
5517 if (TName.isNull())
5518 return TemplateArgumentLoc();
5519
5520 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5521 QualifierLoc, A.getTemplateNameLoc());
5522}
5523
5524/// Convert a template-argument that we parsed as a type into a template, if
5525/// possible. C++ permits injected-class-names to perform dual service as
5526/// template template arguments and as template type arguments.
5527static TemplateArgumentLoc
5528convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5529 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5530 if (!TagLoc)
5531 return TemplateArgumentLoc();
5532
5533 // If this type was written as an injected-class-name, it can be used as a
5534 // template template argument.
5535 // If this type was written as an injected-class-name, it may have been
5536 // converted to a RecordType during instantiation. If the RecordType is
5537 // *not* wrapped in a TemplateSpecializationType and denotes a class
5538 // template specialization, it must have come from an injected-class-name.
5539
5540 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Ctx: Context);
5541 if (Name.isNull())
5542 return TemplateArgumentLoc();
5543
5544 return TemplateArgumentLoc(Context, Name,
5545 /*TemplateKWLoc=*/SourceLocation(),
5546 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5547}
5548
5549bool Sema::CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &ArgLoc,
5550 NamedDecl *Template,
5551 SourceLocation TemplateLoc,
5552 SourceLocation RAngleLoc,
5553 unsigned ArgumentPackIndex,
5554 CheckTemplateArgumentInfo &CTAI,
5555 CheckTemplateArgumentKind CTAK) {
5556 // Check template type parameters.
5557 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param))
5558 return CheckTemplateTypeArgument(Param: TTP, AL&: ArgLoc, SugaredConverted&: CTAI.SugaredConverted,
5559 CanonicalConverted&: CTAI.CanonicalConverted);
5560
5561 const TemplateArgument &Arg = ArgLoc.getArgument();
5562 // Check non-type template parameters.
5563 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5564 // Do substitution on the type of the non-type template parameter
5565 // with the template arguments we've seen thus far. But if the
5566 // template has a dependent context then we cannot substitute yet.
5567 QualType NTTPType = NTTP->getType();
5568 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5569 NTTPType = NTTP->getExpansionType(I: ArgumentPackIndex);
5570
5571 if (NTTPType->isInstantiationDependentType()) {
5572 // Do substitution on the type of the non-type template parameter.
5573 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5574 CTAI.SugaredConverted,
5575 SourceRange(TemplateLoc, RAngleLoc));
5576 if (Inst.isInvalid())
5577 return true;
5578
5579 MultiLevelTemplateArgumentList MLTAL(Template, CTAI.SugaredConverted,
5580 /*Final=*/true);
5581 MLTAL.addOuterRetainedLevels(Num: NTTP->getDepth());
5582 // If the parameter is a pack expansion, expand this slice of the pack.
5583 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5584 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5585 NTTPType = SubstType(T: PET->getPattern(), TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5586 Entity: NTTP->getDeclName());
5587 } else {
5588 NTTPType = SubstType(T: NTTPType, TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5589 Entity: NTTP->getDeclName());
5590 }
5591
5592 // If that worked, check the non-type template parameter type
5593 // for validity.
5594 if (!NTTPType.isNull())
5595 NTTPType = CheckNonTypeTemplateParameterType(T: NTTPType,
5596 Loc: NTTP->getLocation());
5597 if (NTTPType.isNull())
5598 return true;
5599 }
5600
5601 auto checkExpr = [&](Expr *E) -> Expr * {
5602 TemplateArgument SugaredResult, CanonicalResult;
5603 ExprResult Res = CheckTemplateArgument(
5604 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E, SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5605 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5606 // If the current template argument causes an error, give up now.
5607 if (Res.isInvalid())
5608 return nullptr;
5609 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5610 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5611 return Res.get();
5612 };
5613
5614 switch (Arg.getKind()) {
5615 case TemplateArgument::Null:
5616 llvm_unreachable("Should never see a NULL template argument here");
5617
5618 case TemplateArgument::Expression: {
5619 Expr *E = Arg.getAsExpr();
5620 Expr *R = checkExpr(E);
5621 if (!R)
5622 return true;
5623 // If the resulting expression is new, then use it in place of the
5624 // old expression in the template argument.
5625 if (R != E) {
5626 TemplateArgument TA(R, /*IsCanonical=*/false);
5627 ArgLoc = TemplateArgumentLoc(TA, R);
5628 }
5629 break;
5630 }
5631
5632 // As for the converted NTTP kinds, they still might need another
5633 // conversion, as the new corresponding parameter might be different.
5634 // Ideally, we would always perform substitution starting with sugared types
5635 // and never need these, as we would still have expressions. Since these are
5636 // needed so rarely, it's probably a better tradeoff to just convert them
5637 // back to expressions.
5638 case TemplateArgument::Integral:
5639 case TemplateArgument::Declaration:
5640 case TemplateArgument::NullPtr:
5641 case TemplateArgument::StructuralValue: {
5642 // FIXME: StructuralValue is untested here.
5643 ExprResult R =
5644 BuildExpressionFromNonTypeTemplateArgument(Arg, Loc: SourceLocation());
5645 assert(R.isUsable());
5646 if (!checkExpr(R.get()))
5647 return true;
5648 break;
5649 }
5650
5651 case TemplateArgument::Template:
5652 case TemplateArgument::TemplateExpansion:
5653 // We were given a template template argument. It may not be ill-formed;
5654 // see below.
5655 if (DependentTemplateName *DTN = Arg.getAsTemplateOrTemplatePattern()
5656 .getAsDependentTemplateName()) {
5657 // We have a template argument such as \c T::template X, which we
5658 // parsed as a template template argument. However, since we now
5659 // know that we need a non-type template argument, convert this
5660 // template name into an expression.
5661
5662 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5663 ArgLoc.getTemplateNameLoc());
5664
5665 CXXScopeSpec SS;
5666 SS.Adopt(Other: ArgLoc.getTemplateQualifierLoc());
5667 // FIXME: the template-template arg was a DependentTemplateName,
5668 // so it was provided with a template keyword. However, its source
5669 // location is not stored in the template argument structure.
5670 SourceLocation TemplateKWLoc;
5671 ExprResult E = DependentScopeDeclRefExpr::Create(
5672 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5673 TemplateArgs: nullptr);
5674
5675 // If we parsed the template argument as a pack expansion, create a
5676 // pack expansion expression.
5677 if (Arg.getKind() == TemplateArgument::TemplateExpansion) {
5678 E = ActOnPackExpansion(Pattern: E.get(), EllipsisLoc: ArgLoc.getTemplateEllipsisLoc());
5679 if (E.isInvalid())
5680 return true;
5681 }
5682
5683 TemplateArgument SugaredResult, CanonicalResult;
5684 E = CheckTemplateArgument(
5685 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E.get(), SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5686 /*StrictCheck=*/CTAI.PartialOrdering, CTAK: CTAK_Specified);
5687 if (E.isInvalid())
5688 return true;
5689
5690 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5691 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5692 break;
5693 }
5694
5695 // We have a template argument that actually does refer to a class
5696 // template, alias template, or template template parameter, and
5697 // therefore cannot be a non-type template argument.
5698 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_expr)
5699 << ArgLoc.getSourceRange();
5700 NoteTemplateParameterLocation(Decl: *Param);
5701
5702 return true;
5703
5704 case TemplateArgument::Type: {
5705 // We have a non-type template parameter but the template
5706 // argument is a type.
5707
5708 // C++ [temp.arg]p2:
5709 // In a template-argument, an ambiguity between a type-id and
5710 // an expression is resolved to a type-id, regardless of the
5711 // form of the corresponding template-parameter.
5712 //
5713 // We warn specifically about this case, since it can be rather
5714 // confusing for users.
5715 QualType T = Arg.getAsType();
5716 SourceRange SR = ArgLoc.getSourceRange();
5717 if (T->isFunctionType())
5718 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_nontype_ambig) << SR << T;
5719 else
5720 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_expr) << SR;
5721 NoteTemplateParameterLocation(Decl: *Param);
5722 return true;
5723 }
5724
5725 case TemplateArgument::Pack:
5726 llvm_unreachable("Caller must expand template argument packs");
5727 }
5728
5729 return false;
5730 }
5731
5732
5733 // Check template template parameters.
5734 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Val: Param);
5735
5736 TemplateParameterList *Params = TempParm->getTemplateParameters();
5737 if (TempParm->isExpandedParameterPack())
5738 Params = TempParm->getExpansionTemplateParameters(I: ArgumentPackIndex);
5739
5740 // Substitute into the template parameter list of the template
5741 // template parameter, since previously-supplied template arguments
5742 // may appear within the template template parameter.
5743 //
5744 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5745 {
5746 // Set up a template instantiation context.
5747 LocalInstantiationScope Scope(*this);
5748 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5749 CTAI.SugaredConverted,
5750 SourceRange(TemplateLoc, RAngleLoc));
5751 if (Inst.isInvalid())
5752 return true;
5753
5754 Params = SubstTemplateParams(
5755 Params, Owner: CurContext,
5756 TemplateArgs: MultiLevelTemplateArgumentList(Template, CTAI.SugaredConverted,
5757 /*Final=*/true),
5758 /*EvaluateConstraints=*/false);
5759 if (!Params)
5760 return true;
5761 }
5762
5763 // C++1z [temp.local]p1: (DR1004)
5764 // When [the injected-class-name] is used [...] as a template-argument for
5765 // a template template-parameter [...] it refers to the class template
5766 // itself.
5767 if (Arg.getKind() == TemplateArgument::Type) {
5768 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5769 Context, TLoc: ArgLoc.getTypeSourceInfo()->getTypeLoc());
5770 if (!ConvertedArg.getArgument().isNull())
5771 ArgLoc = ConvertedArg;
5772 }
5773
5774 switch (Arg.getKind()) {
5775 case TemplateArgument::Null:
5776 llvm_unreachable("Should never see a NULL template argument here");
5777
5778 case TemplateArgument::Template:
5779 case TemplateArgument::TemplateExpansion:
5780 if (CheckTemplateTemplateArgument(Param: TempParm, Params, Arg&: ArgLoc,
5781 PartialOrdering: CTAI.PartialOrdering,
5782 StrictPackMatch: &CTAI.StrictPackMatch))
5783 return true;
5784
5785 CTAI.SugaredConverted.push_back(Elt: Arg);
5786 CTAI.CanonicalConverted.push_back(
5787 Elt: Context.getCanonicalTemplateArgument(Arg));
5788 break;
5789
5790 case TemplateArgument::Expression:
5791 case TemplateArgument::Type: {
5792 auto Kind = 0;
5793 switch (TempParm->templateParameterKind()) {
5794 case TemplateNameKind::TNK_Var_template:
5795 Kind = 1;
5796 break;
5797 case TemplateNameKind::TNK_Concept_template:
5798 Kind = 2;
5799 break;
5800 default:
5801 break;
5802 }
5803
5804 // We have a template template parameter but the template
5805 // argument does not refer to a template.
5806 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_template)
5807 << Kind << getLangOpts().CPlusPlus11;
5808 return true;
5809 }
5810
5811 case TemplateArgument::Declaration:
5812 case TemplateArgument::Integral:
5813 case TemplateArgument::StructuralValue:
5814 case TemplateArgument::NullPtr:
5815 llvm_unreachable("non-type argument with template template parameter");
5816
5817 case TemplateArgument::Pack:
5818 llvm_unreachable("Caller must expand template argument packs");
5819 }
5820
5821 return false;
5822}
5823
5824/// Diagnose a missing template argument.
5825template<typename TemplateParmDecl>
5826static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5827 TemplateDecl *TD,
5828 const TemplateParmDecl *D,
5829 TemplateArgumentListInfo &Args) {
5830 // Dig out the most recent declaration of the template parameter; there may be
5831 // declarations of the template that are more recent than TD.
5832 D = cast<TemplateParmDecl>(cast<TemplateDecl>(Val: TD->getMostRecentDecl())
5833 ->getTemplateParameters()
5834 ->getParam(D->getIndex()));
5835
5836 // If there's a default argument that's not reachable, diagnose that we're
5837 // missing a module import.
5838 llvm::SmallVector<Module*, 8> Modules;
5839 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, Modules: &Modules)) {
5840 S.diagnoseMissingImport(Loc, cast<NamedDecl>(Val: TD),
5841 D->getDefaultArgumentLoc(), Modules,
5842 Sema::MissingImportKind::DefaultArgument,
5843 /*Recover*/true);
5844 return true;
5845 }
5846
5847 // FIXME: If there's a more recent default argument that *is* visible,
5848 // diagnose that it was declared too late.
5849
5850 TemplateParameterList *Params = TD->getTemplateParameters();
5851
5852 S.Diag(Loc, DiagID: diag::err_template_arg_list_different_arity)
5853 << /*not enough args*/0
5854 << (int)S.getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
5855 << TD;
5856 S.NoteTemplateLocation(Decl: *TD, ParamRange: Params->getSourceRange());
5857 return true;
5858}
5859
5860/// Check that the given template argument list is well-formed
5861/// for specializing the given template.
5862bool Sema::CheckTemplateArgumentList(
5863 TemplateDecl *Template, SourceLocation TemplateLoc,
5864 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5865 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5866 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5867 return CheckTemplateArgumentList(
5868 Template, Params: GetTemplateParameterList(TD: Template), TemplateLoc, TemplateArgs,
5869 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5870 ConstraintsNotSatisfied);
5871}
5872
5873/// Check that the given template argument list is well-formed
5874/// for specializing the given template.
5875bool Sema::CheckTemplateArgumentList(
5876 TemplateDecl *Template, TemplateParameterList *Params,
5877 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5878 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5879 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5880 bool *ConstraintsNotSatisfied) {
5881
5882 if (ConstraintsNotSatisfied)
5883 *ConstraintsNotSatisfied = false;
5884
5885 // Make a copy of the template arguments for processing. Only make the
5886 // changes at the end when successful in matching the arguments to the
5887 // template.
5888 TemplateArgumentListInfo NewArgs = TemplateArgs;
5889
5890 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5891
5892 // C++23 [temp.arg.general]p1:
5893 // [...] The type and form of each template-argument specified in
5894 // a template-id shall match the type and form specified for the
5895 // corresponding parameter declared by the template in its
5896 // template-parameter-list.
5897 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Val: Template);
5898 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5899 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5900 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5901 LocalInstantiationScope InstScope(*this, true);
5902 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5903 ParamEnd = Params->end(),
5904 Param = ParamBegin;
5905 Param != ParamEnd;
5906 /* increment in loop */) {
5907 if (size_t ParamIdx = Param - ParamBegin;
5908 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5909 // All written arguments should have been consumed by this point.
5910 assert(ArgIdx == NumArgs && "bad default argument deduction");
5911 if (ParamIdx == DefaultArgs.StartPos) {
5912 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5913 // Default arguments from a DeducedTemplateName are already converted.
5914 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5915 CTAI.SugaredConverted.push_back(Elt: DefArg);
5916 CTAI.CanonicalConverted.push_back(
5917 Elt: Context.getCanonicalTemplateArgument(Arg: DefArg));
5918 ++Param;
5919 }
5920 continue;
5921 }
5922 }
5923
5924 // If we have an expanded parameter pack, make sure we don't have too
5925 // many arguments.
5926 if (UnsignedOrNone Expansions = getExpandedPackSize(Param: *Param)) {
5927 if (*Expansions == SugaredArgumentPack.size()) {
5928 // We're done with this parameter pack. Pack up its arguments and add
5929 // them to the list.
5930 CTAI.SugaredConverted.push_back(
5931 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
5932 SugaredArgumentPack.clear();
5933
5934 CTAI.CanonicalConverted.push_back(
5935 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
5936 CanonicalArgumentPack.clear();
5937
5938 // This argument is assigned to the next parameter.
5939 ++Param;
5940 continue;
5941 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5942 // Not enough arguments for this parameter pack.
5943 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
5944 << /*not enough args*/0
5945 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
5946 << Template;
5947 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
5948 return true;
5949 }
5950 }
5951
5952 // Check for builtins producing template packs in this context, we do not
5953 // support them yet.
5954 if (const NonTypeTemplateParmDecl *NTTP =
5955 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param);
5956 NTTP && NTTP->isPackExpansion()) {
5957 auto TL = NTTP->getTypeSourceInfo()
5958 ->getTypeLoc()
5959 .castAs<PackExpansionTypeLoc>();
5960 llvm::SmallVector<UnexpandedParameterPack> Unexpanded;
5961 collectUnexpandedParameterPacks(TL: TL.getPatternLoc(), Unexpanded);
5962 for (const auto &UPP : Unexpanded) {
5963 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5964 if (!TST)
5965 continue;
5966 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5967 // Expanding a built-in pack in this context is not yet supported.
5968 Diag(Loc: TL.getEllipsisLoc(),
5969 DiagID: diag::err_unsupported_builtin_template_pack_expansion)
5970 << TST->getTemplateName();
5971 return true;
5972 }
5973 }
5974
5975 if (ArgIdx < NumArgs) {
5976 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5977 bool NonPackParameter =
5978 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(Param: *Param);
5979 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5980
5981 if (ArgIsExpansion && CTAI.MatchingTTP) {
5982 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5983 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5984 ++Param) {
5985 TemplateArgument &Arg = Args[Param - First];
5986 Arg = ArgLoc.getArgument();
5987 if (!(*Param)->isTemplateParameterPack() ||
5988 getExpandedPackSize(Param: *Param))
5989 Arg = Arg.getPackExpansionPattern();
5990 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5991 SaveAndRestore _1(CTAI.PartialOrdering, false);
5992 SaveAndRestore _2(CTAI.MatchingTTP, true);
5993 if (CheckTemplateArgument(Param: *Param, ArgLoc&: NewArgLoc, Template, TemplateLoc,
5994 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
5995 CTAK: CTAK_Specified))
5996 return true;
5997 Arg = NewArgLoc.getArgument();
5998 CTAI.CanonicalConverted.back().setIsDefaulted(
5999 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg, Param: *Param,
6000 Args: CTAI.CanonicalConverted,
6001 Depth: Params->getDepth()));
6002 }
6003 ArgLoc = TemplateArgumentLoc(
6004 TemplateArgument::CreatePackCopy(Context, Args),
6005 TemplateArgumentLocInfo(Context, ArgLoc.getLocation()));
6006 } else {
6007 SaveAndRestore _1(CTAI.PartialOrdering, false);
6008 if (CheckTemplateArgument(Param: *Param, ArgLoc, Template, TemplateLoc,
6009 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
6010 CTAK: CTAK_Specified))
6011 return true;
6012 CTAI.CanonicalConverted.back().setIsDefaulted(
6013 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg: ArgLoc.getArgument(),
6014 Param: *Param, Args: CTAI.CanonicalConverted,
6015 Depth: Params->getDepth()));
6016 if (ArgIsExpansion && NonPackParameter) {
6017 // CWG1430/CWG2686: we have a pack expansion as an argument to an
6018 // alias template, builtin template, or concept, and it's not part of
6019 // a parameter pack. This can't be canonicalized, so reject it now.
6020 if (isa<TypeAliasTemplateDecl, ConceptDecl, BuiltinTemplateDecl>(
6021 Val: Template)) {
6022 unsigned DiagSelect = isa<ConceptDecl>(Val: Template) ? 1
6023 : isa<BuiltinTemplateDecl>(Val: Template) ? 2
6024 : 0;
6025 Diag(Loc: ArgLoc.getLocation(),
6026 DiagID: diag::err_template_expansion_into_fixed_list)
6027 << DiagSelect << ArgLoc.getSourceRange();
6028 NoteTemplateParameterLocation(Decl: **Param);
6029 return true;
6030 }
6031 }
6032 }
6033
6034 // We're now done with this argument.
6035 ++ArgIdx;
6036
6037 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6038 // Directly convert the remaining arguments, because we don't know what
6039 // parameters they'll match up with.
6040
6041 if (!SugaredArgumentPack.empty()) {
6042 // If we were part way through filling in an expanded parameter pack,
6043 // fall back to just producing individual arguments.
6044 CTAI.SugaredConverted.insert(I: CTAI.SugaredConverted.end(),
6045 From: SugaredArgumentPack.begin(),
6046 To: SugaredArgumentPack.end());
6047 SugaredArgumentPack.clear();
6048
6049 CTAI.CanonicalConverted.insert(I: CTAI.CanonicalConverted.end(),
6050 From: CanonicalArgumentPack.begin(),
6051 To: CanonicalArgumentPack.end());
6052 CanonicalArgumentPack.clear();
6053 }
6054
6055 while (ArgIdx < NumArgs) {
6056 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6057 CTAI.SugaredConverted.push_back(Elt: Arg);
6058 CTAI.CanonicalConverted.push_back(
6059 Elt: Context.getCanonicalTemplateArgument(Arg));
6060 ++ArgIdx;
6061 }
6062
6063 return false;
6064 }
6065
6066 if ((*Param)->isTemplateParameterPack()) {
6067 // The template parameter was a template parameter pack, so take the
6068 // deduced argument and place it on the argument pack. Note that we
6069 // stay on the same template parameter so that we can deduce more
6070 // arguments.
6071 SugaredArgumentPack.push_back(Elt: CTAI.SugaredConverted.pop_back_val());
6072 CanonicalArgumentPack.push_back(Elt: CTAI.CanonicalConverted.pop_back_val());
6073 } else {
6074 // Move to the next template parameter.
6075 ++Param;
6076 }
6077 continue;
6078 }
6079
6080 // If we're checking a partial template argument list, we're done.
6081 if (PartialTemplateArgs) {
6082 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6083 CTAI.SugaredConverted.push_back(
6084 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6085 CTAI.CanonicalConverted.push_back(
6086 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6087 }
6088 return false;
6089 }
6090
6091 // If we have a template parameter pack with no more corresponding
6092 // arguments, just break out now and we'll fill in the argument pack below.
6093 if ((*Param)->isTemplateParameterPack()) {
6094 assert(!getExpandedPackSize(*Param) &&
6095 "Should have dealt with this already");
6096
6097 // A non-expanded parameter pack before the end of the parameter list
6098 // only occurs for an ill-formed template parameter list, unless we've
6099 // got a partial argument list for a function template, so just bail out.
6100 if (Param + 1 != ParamEnd) {
6101 assert(
6102 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6103 "Concept templates must have parameter packs at the end.");
6104 return true;
6105 }
6106
6107 CTAI.SugaredConverted.push_back(
6108 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6109 SugaredArgumentPack.clear();
6110
6111 CTAI.CanonicalConverted.push_back(
6112 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6113 CanonicalArgumentPack.clear();
6114
6115 ++Param;
6116 continue;
6117 }
6118
6119 // Check whether we have a default argument.
6120 bool HasDefaultArg;
6121
6122 // Retrieve the default template argument from the template
6123 // parameter. For each kind of template parameter, we substitute the
6124 // template arguments provided thus far and any "outer" template arguments
6125 // (when the template parameter was part of a nested template) into
6126 // the default argument.
6127 TemplateArgumentLoc Arg = SubstDefaultTemplateArgumentIfAvailable(
6128 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateNameLoc: TemplateLoc, RAngleLoc,
6129 Param: *Param, SugaredConverted: CTAI.SugaredConverted, CanonicalConverted: CTAI.CanonicalConverted, HasDefaultArg);
6130
6131 if (Arg.getArgument().isNull()) {
6132 if (!HasDefaultArg) {
6133 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *Param))
6134 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: TTP,
6135 Args&: NewArgs);
6136 if (NonTypeTemplateParmDecl *NTTP =
6137 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param))
6138 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: NTTP,
6139 Args&: NewArgs);
6140 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template,
6141 D: cast<TemplateTemplateParmDecl>(Val: *Param),
6142 Args&: NewArgs);
6143 }
6144 return true;
6145 }
6146
6147 // Introduce an instantiation record that describes where we are using
6148 // the default template argument. We're not actually instantiating a
6149 // template here, we just create this object to put a note into the
6150 // context stack.
6151 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6152 CTAI.SugaredConverted,
6153 SourceRange(TemplateLoc, RAngleLoc));
6154 if (Inst.isInvalid())
6155 return true;
6156
6157 SaveAndRestore _1(CTAI.PartialOrdering, false);
6158 SaveAndRestore _2(CTAI.MatchingTTP, false);
6159 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6160 // Check the default template argument.
6161 if (CheckTemplateArgument(Param: *Param, ArgLoc&: Arg, Template, TemplateLoc, RAngleLoc, ArgumentPackIndex: 0,
6162 CTAI, CTAK: CTAK_Specified))
6163 return true;
6164
6165 CTAI.SugaredConverted.back().setIsDefaulted(true);
6166 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6167
6168 // Core issue 150 (assumed resolution): if this is a template template
6169 // parameter, keep track of the default template arguments from the
6170 // template definition.
6171 if (isTemplateTemplateParameter)
6172 NewArgs.addArgument(Loc: Arg);
6173
6174 // Move to the next template parameter and argument.
6175 ++Param;
6176 ++ArgIdx;
6177 }
6178
6179 // If we're performing a partial argument substitution, allow any trailing
6180 // pack expansions; they might be empty. This can happen even if
6181 // PartialTemplateArgs is false (the list of arguments is complete but
6182 // still dependent).
6183 if (CTAI.MatchingTTP ||
6184 (CurrentInstantiationScope &&
6185 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6186 while (ArgIdx < NumArgs &&
6187 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6188 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6189 CTAI.SugaredConverted.push_back(Elt: Arg);
6190 CTAI.CanonicalConverted.push_back(
6191 Elt: Context.getCanonicalTemplateArgument(Arg));
6192 }
6193 }
6194
6195 // If we have any leftover arguments, then there were too many arguments.
6196 // Complain and fail.
6197 if (ArgIdx < NumArgs) {
6198 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
6199 << /*too many args*/1
6200 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
6201 << Template
6202 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6203 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
6204 return true;
6205 }
6206
6207 // No problems found with the new argument list, propagate changes back
6208 // to caller.
6209 if (UpdateArgsWithConversions)
6210 TemplateArgs = std::move(NewArgs);
6211
6212 if (!PartialTemplateArgs) {
6213 // Setup the context/ThisScope for the case where we are needing to
6214 // re-instantiate constraints outside of normal instantiation.
6215 DeclContext *NewContext = Template->getDeclContext();
6216
6217 // If this template is in a template, make sure we extract the templated
6218 // decl.
6219 if (auto *TD = dyn_cast<TemplateDecl>(Val: NewContext))
6220 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6221 auto *RD = dyn_cast<CXXRecordDecl>(Val: NewContext);
6222
6223 Qualifiers ThisQuals;
6224 if (const auto *Method =
6225 dyn_cast_or_null<CXXMethodDecl>(Val: Template->getTemplatedDecl()))
6226 ThisQuals = Method->getMethodQualifiers();
6227
6228 ContextRAII Context(*this, NewContext);
6229 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6230
6231 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
6232 D: Template, DC: NewContext, /*Final=*/true, Innermost: CTAI.SugaredConverted,
6233 /*RelativeToPrimary=*/true,
6234 /*Pattern=*/nullptr,
6235 /*ForConceptInstantiation=*/ForConstraintInstantiation: true);
6236 if (!isa<ConceptDecl>(Val: Template) &&
6237 EnsureTemplateArgumentListConstraints(
6238 Template, TemplateArgs: MLTAL,
6239 TemplateIDRange: SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6240 if (ConstraintsNotSatisfied)
6241 *ConstraintsNotSatisfied = true;
6242 return true;
6243 }
6244 }
6245
6246 return false;
6247}
6248
6249namespace {
6250 class UnnamedLocalNoLinkageFinder
6251 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6252 {
6253 Sema &S;
6254 SourceRange SR;
6255
6256 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
6257
6258 public:
6259 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6260
6261 bool Visit(QualType T) {
6262 return T.isNull() ? false : inherited::Visit(T: T.getTypePtr());
6263 }
6264
6265#define TYPE(Class, Parent) \
6266 bool Visit##Class##Type(const Class##Type *);
6267#define ABSTRACT_TYPE(Class, Parent) \
6268 bool Visit##Class##Type(const Class##Type *) { return false; }
6269#define NON_CANONICAL_TYPE(Class, Parent) \
6270 bool Visit##Class##Type(const Class##Type *) { return false; }
6271#include "clang/AST/TypeNodes.inc"
6272
6273 bool VisitTagDecl(const TagDecl *Tag);
6274 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6275 };
6276} // end anonymous namespace
6277
6278bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6279 return false;
6280}
6281
6282bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6283 return Visit(T: T->getElementType());
6284}
6285
6286bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6287 return Visit(T: T->getPointeeType());
6288}
6289
6290bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6291 const BlockPointerType* T) {
6292 return Visit(T: T->getPointeeType());
6293}
6294
6295bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6296 const LValueReferenceType* T) {
6297 return Visit(T: T->getPointeeType());
6298}
6299
6300bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6301 const RValueReferenceType* T) {
6302 return Visit(T: T->getPointeeType());
6303}
6304
6305bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6306 const MemberPointerType *T) {
6307 if (Visit(T: T->getPointeeType()))
6308 return true;
6309 if (auto *RD = T->getMostRecentCXXRecordDecl())
6310 return VisitTagDecl(Tag: RD);
6311 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6312}
6313
6314bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6315 const ConstantArrayType* T) {
6316 return Visit(T: T->getElementType());
6317}
6318
6319bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6320 const IncompleteArrayType* T) {
6321 return Visit(T: T->getElementType());
6322}
6323
6324bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6325 const VariableArrayType* T) {
6326 return Visit(T: T->getElementType());
6327}
6328
6329bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6330 const DependentSizedArrayType* T) {
6331 return Visit(T: T->getElementType());
6332}
6333
6334bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6335 const DependentSizedExtVectorType* T) {
6336 return Visit(T: T->getElementType());
6337}
6338
6339bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6340 const DependentSizedMatrixType *T) {
6341 return Visit(T: T->getElementType());
6342}
6343
6344bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6345 const DependentAddressSpaceType *T) {
6346 return Visit(T: T->getPointeeType());
6347}
6348
6349bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6350 return Visit(T: T->getElementType());
6351}
6352
6353bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6354 const DependentVectorType *T) {
6355 return Visit(T: T->getElementType());
6356}
6357
6358bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6359 return Visit(T: T->getElementType());
6360}
6361
6362bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6363 const ConstantMatrixType *T) {
6364 return Visit(T: T->getElementType());
6365}
6366
6367bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6368 const FunctionProtoType* T) {
6369 for (const auto &A : T->param_types()) {
6370 if (Visit(T: A))
6371 return true;
6372 }
6373
6374 return Visit(T: T->getReturnType());
6375}
6376
6377bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6378 const FunctionNoProtoType* T) {
6379 return Visit(T: T->getReturnType());
6380}
6381
6382bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6383 const UnresolvedUsingType*) {
6384 return false;
6385}
6386
6387bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6388 return false;
6389}
6390
6391bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6392 return Visit(T: T->getUnmodifiedType());
6393}
6394
6395bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6396 return false;
6397}
6398
6399bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6400 const PackIndexingType *) {
6401 return false;
6402}
6403
6404bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6405 const UnaryTransformType*) {
6406 return false;
6407}
6408
6409bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6410 return Visit(T: T->getDeducedType());
6411}
6412
6413bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6414 const DeducedTemplateSpecializationType *T) {
6415 return Visit(T: T->getDeducedType());
6416}
6417
6418bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6419 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6420}
6421
6422bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6423 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6424}
6425
6426bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6427 const TemplateTypeParmType*) {
6428 return false;
6429}
6430
6431bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6432 const SubstTemplateTypeParmPackType *) {
6433 return false;
6434}
6435
6436bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6437 const SubstBuiltinTemplatePackType *) {
6438 return false;
6439}
6440
6441bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6442 const TemplateSpecializationType*) {
6443 return false;
6444}
6445
6446bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6447 const InjectedClassNameType* T) {
6448 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6449}
6450
6451bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6452 const DependentNameType* T) {
6453 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6454}
6455
6456bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6457 const PackExpansionType* T) {
6458 return Visit(T: T->getPattern());
6459}
6460
6461bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6462 return false;
6463}
6464
6465bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6466 const ObjCInterfaceType *) {
6467 return false;
6468}
6469
6470bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6471 const ObjCObjectPointerType *) {
6472 return false;
6473}
6474
6475bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6476 return Visit(T: T->getValueType());
6477}
6478
6479bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6480 const OverflowBehaviorType *T) {
6481 return Visit(T: T->getUnderlyingType());
6482}
6483
6484bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6485 return false;
6486}
6487
6488bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6489 return false;
6490}
6491
6492bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6493 const ArrayParameterType *T) {
6494 return VisitConstantArrayType(T);
6495}
6496
6497bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6498 const DependentBitIntType *T) {
6499 return false;
6500}
6501
6502bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6503 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6504 S.Diag(Loc: SR.getBegin(), DiagID: S.getLangOpts().CPlusPlus11
6505 ? diag::warn_cxx98_compat_template_arg_local_type
6506 : diag::ext_template_arg_local_type)
6507 << S.Context.getCanonicalTagType(TD: Tag) << SR;
6508 return true;
6509 }
6510
6511 if (!Tag->hasNameForLinkage()) {
6512 S.Diag(Loc: SR.getBegin(),
6513 DiagID: S.getLangOpts().CPlusPlus11 ?
6514 diag::warn_cxx98_compat_template_arg_unnamed_type :
6515 diag::ext_template_arg_unnamed_type) << SR;
6516 S.Diag(Loc: Tag->getLocation(), DiagID: diag::note_template_unnamed_type_here);
6517 return true;
6518 }
6519
6520 return false;
6521}
6522
6523bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6524 NestedNameSpecifier NNS) {
6525 switch (NNS.getKind()) {
6526 case NestedNameSpecifier::Kind::Null:
6527 case NestedNameSpecifier::Kind::Namespace:
6528 case NestedNameSpecifier::Kind::Global:
6529 case NestedNameSpecifier::Kind::MicrosoftSuper:
6530 return false;
6531 case NestedNameSpecifier::Kind::Type:
6532 return Visit(T: QualType(NNS.getAsType(), 0));
6533 }
6534 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6535}
6536
6537bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6538 const HLSLAttributedResourceType *T) {
6539 if (T->hasContainedType() && Visit(T: T->getContainedType()))
6540 return true;
6541 return Visit(T: T->getWrappedType());
6542}
6543
6544bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6545 const HLSLInlineSpirvType *T) {
6546 for (auto &Operand : T->getOperands())
6547 if (Operand.isConstant() && Operand.isLiteral())
6548 if (Visit(T: Operand.getResultType()))
6549 return true;
6550 return false;
6551}
6552
6553bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6554 assert(ArgInfo && "invalid TypeSourceInfo");
6555 QualType Arg = ArgInfo->getType();
6556 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6557 QualType CanonArg = Context.getCanonicalType(T: Arg);
6558
6559 if (CanonArg->isVariablyModifiedType()) {
6560 return Diag(Loc: SR.getBegin(), DiagID: diag::err_variably_modified_template_arg) << Arg;
6561 } else if (Context.hasSameUnqualifiedType(T1: Arg, T2: Context.OverloadTy)) {
6562 return Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_overload_type) << SR;
6563 }
6564
6565 // C++03 [temp.arg.type]p2:
6566 // A local type, a type with no linkage, an unnamed type or a type
6567 // compounded from any of these types shall not be used as a
6568 // template-argument for a template type-parameter.
6569 //
6570 // C++11 allows these, and even in C++03 we allow them as an extension with
6571 // a warning.
6572 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6573 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6574 (void)Finder.Visit(T: CanonArg);
6575 }
6576
6577 return false;
6578}
6579
6580enum NullPointerValueKind {
6581 NPV_NotNullPointer,
6582 NPV_NullPointer,
6583 NPV_Error
6584};
6585
6586/// Determine whether the given template argument is a null pointer
6587/// value of the appropriate type.
6588static NullPointerValueKind
6589isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param,
6590 QualType ParamType, Expr *Arg,
6591 Decl *Entity = nullptr) {
6592 if (Arg->isValueDependent() || Arg->isTypeDependent())
6593 return NPV_NotNullPointer;
6594
6595 // dllimport'd entities aren't constant but are available inside of template
6596 // arguments.
6597 if (Entity && Entity->hasAttr<DLLImportAttr>())
6598 return NPV_NotNullPointer;
6599
6600 if (!S.isCompleteType(Loc: Arg->getExprLoc(), T: ParamType))
6601 llvm_unreachable(
6602 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6603
6604 if (!S.getLangOpts().CPlusPlus11)
6605 return NPV_NotNullPointer;
6606
6607 // Determine whether we have a constant expression.
6608 ExprResult ArgRV = S.DefaultFunctionArrayConversion(E: Arg);
6609 if (ArgRV.isInvalid())
6610 return NPV_Error;
6611 Arg = ArgRV.get();
6612
6613 Expr::EvalResult EvalResult;
6614 SmallVector<PartialDiagnosticAt, 8> Notes;
6615 EvalResult.Diag = &Notes;
6616 if (!Arg->EvaluateAsRValue(Result&: EvalResult, Ctx: S.Context) ||
6617 EvalResult.HasSideEffects) {
6618 SourceLocation DiagLoc = Arg->getExprLoc();
6619
6620 // If our only note is the usual "invalid subexpression" note, just point
6621 // the caret at its location rather than producing an essentially
6622 // redundant note.
6623 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6624 diag::note_invalid_subexpr_in_const_expr) {
6625 DiagLoc = Notes[0].first;
6626 Notes.clear();
6627 }
6628
6629 S.Diag(Loc: DiagLoc, DiagID: diag::err_template_arg_not_address_constant)
6630 << Arg->getType() << Arg->getSourceRange();
6631 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6632 S.Diag(Loc: Notes[I].first, PD: Notes[I].second);
6633
6634 S.NoteTemplateParameterLocation(Decl: *Param);
6635 return NPV_Error;
6636 }
6637
6638 // C++11 [temp.arg.nontype]p1:
6639 // - an address constant expression of type std::nullptr_t
6640 if (Arg->getType()->isNullPtrType())
6641 return NPV_NullPointer;
6642
6643 // - a constant expression that evaluates to a null pointer value (4.10); or
6644 // - a constant expression that evaluates to a null member pointer value
6645 // (4.11); or
6646 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6647 (EvalResult.Val.isMemberPointer() &&
6648 !EvalResult.Val.getMemberPointerDecl())) {
6649 // If our expression has an appropriate type, we've succeeded.
6650 bool ObjCLifetimeConversion;
6651 if (S.Context.hasSameUnqualifiedType(T1: Arg->getType(), T2: ParamType) ||
6652 S.IsQualificationConversion(FromType: Arg->getType(), ToType: ParamType, CStyle: false,
6653 ObjCLifetimeConversion))
6654 return NPV_NullPointer;
6655
6656 // The types didn't match, but we know we got a null pointer; complain,
6657 // then recover as if the types were correct.
6658 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_wrongtype_null_constant)
6659 << Arg->getType() << ParamType << Arg->getSourceRange();
6660 S.NoteTemplateParameterLocation(Decl: *Param);
6661 return NPV_NullPointer;
6662 }
6663
6664 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6665 // We found a pointer that isn't null, but doesn't refer to an object.
6666 // We could just return NPV_NotNullPointer, but we can print a better
6667 // message with the information we have here.
6668 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_invalid)
6669 << EvalResult.Val.getAsString(Ctx: S.Context, Ty: ParamType);
6670 S.NoteTemplateParameterLocation(Decl: *Param);
6671 return NPV_Error;
6672 }
6673
6674 // If we don't have a null pointer value, but we do have a NULL pointer
6675 // constant, suggest a cast to the appropriate type.
6676 if (Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_NeverValueDependent)) {
6677 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6678 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_untyped_null_constant)
6679 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code)
6680 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: Arg->getEndLoc()),
6681 Code: ")");
6682 S.NoteTemplateParameterLocation(Decl: *Param);
6683 return NPV_NullPointer;
6684 }
6685
6686 // FIXME: If we ever want to support general, address-constant expressions
6687 // as non-type template arguments, we should return the ExprResult here to
6688 // be interpreted by the caller.
6689 return NPV_NotNullPointer;
6690}
6691
6692/// Checks whether the given template argument is compatible with its
6693/// template parameter.
6694static bool
6695CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param,
6696 QualType ParamType, Expr *ArgIn,
6697 Expr *Arg, QualType ArgType) {
6698 bool ObjCLifetimeConversion;
6699 if (ParamType->isPointerType() &&
6700 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6701 S.IsQualificationConversion(FromType: ArgType, ToType: ParamType, CStyle: false,
6702 ObjCLifetimeConversion)) {
6703 // For pointer-to-object types, qualification conversions are
6704 // permitted.
6705 } else {
6706 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6707 if (!ParamRef->getPointeeType()->isFunctionType()) {
6708 // C++ [temp.arg.nontype]p5b3:
6709 // For a non-type template-parameter of type reference to
6710 // object, no conversions apply. The type referred to by the
6711 // reference may be more cv-qualified than the (otherwise
6712 // identical) type of the template- argument. The
6713 // template-parameter is bound directly to the
6714 // template-argument, which shall be an lvalue.
6715
6716 // FIXME: Other qualifiers?
6717 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6718 unsigned ArgQuals = ArgType.getCVRQualifiers();
6719
6720 if ((ParamQuals | ArgQuals) != ParamQuals) {
6721 S.Diag(Loc: Arg->getBeginLoc(),
6722 DiagID: diag::err_template_arg_ref_bind_ignores_quals)
6723 << ParamType << Arg->getType() << Arg->getSourceRange();
6724 S.NoteTemplateParameterLocation(Decl: *Param);
6725 return true;
6726 }
6727 }
6728 }
6729
6730 // At this point, the template argument refers to an object or
6731 // function with external linkage. We now need to check whether the
6732 // argument and parameter types are compatible.
6733 if (!S.Context.hasSameUnqualifiedType(T1: ArgType,
6734 T2: ParamType.getNonReferenceType())) {
6735 // We can't perform this conversion or binding.
6736 if (ParamType->isReferenceType())
6737 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_no_ref_bind)
6738 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6739 else
6740 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
6741 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6742 S.NoteTemplateParameterLocation(Decl: *Param);
6743 return true;
6744 }
6745 }
6746
6747 return false;
6748}
6749
6750/// Checks whether the given template argument is the address
6751/// of an object or function according to C++ [temp.arg.nontype]p1.
6752static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6753 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6754 bool IsSpecified, TemplateArgument &SugaredConverted,
6755 TemplateArgument &CanonicalConverted) {
6756 Expr *Arg = ArgIn;
6757 QualType ArgType = Arg->getType();
6758
6759 bool AddressTaken = false;
6760 SourceLocation AddrOpLoc;
6761 if (S.getLangOpts().MicrosoftExt) {
6762 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6763 // dereference and address-of operators.
6764 Arg = Arg->IgnoreParenCasts();
6765
6766 bool ExtWarnMSTemplateArg = false;
6767 UnaryOperatorKind FirstOpKind;
6768 SourceLocation FirstOpLoc;
6769 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6770 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6771 if (UnOpKind == UO_Deref)
6772 ExtWarnMSTemplateArg = true;
6773 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6774 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6775 if (!AddrOpLoc.isValid()) {
6776 FirstOpKind = UnOpKind;
6777 FirstOpLoc = UnOp->getOperatorLoc();
6778 }
6779 } else
6780 break;
6781 }
6782 if (FirstOpLoc.isValid()) {
6783 if (ExtWarnMSTemplateArg)
6784 S.Diag(Loc: ArgIn->getBeginLoc(), DiagID: diag::ext_ms_deref_template_argument)
6785 << ArgIn->getSourceRange();
6786
6787 if (FirstOpKind == UO_AddrOf)
6788 AddressTaken = true;
6789 else if (Arg->getType()->isPointerType()) {
6790 // We cannot let pointers get dereferenced here, that is obviously not a
6791 // constant expression.
6792 assert(FirstOpKind == UO_Deref);
6793 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6794 << Arg->getSourceRange();
6795 }
6796 }
6797 } else {
6798 // See through any implicit casts we added to fix the type.
6799 // Also ignore parentheses for deduced template arguments.
6800 Arg = IsSpecified ? Arg->IgnoreImpCasts() : Arg->IgnoreParenImpCasts();
6801
6802 // C++ [temp.arg.nontype]p1:
6803 //
6804 // A template-argument for a non-type, non-template
6805 // template-parameter shall be one of: [...]
6806 //
6807 // -- the address of an object or function with external
6808 // linkage, including function templates and function
6809 // template-ids but excluding non-static class members,
6810 // expressed as & id-expression where the & is optional if
6811 // the name refers to a function or array, or if the
6812 // corresponding template-parameter is a reference; or
6813
6814 // In C++98/03 mode, give an extension warning on any extra parentheses.
6815 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6816 if (IsSpecified) {
6817 bool ExtraParens = false;
6818 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
6819 if (!ExtraParens) {
6820 S.DiagCompat(Loc: Arg->getBeginLoc(),
6821 CompatDiagId: diag_compat::template_arg_extra_parens)
6822 << Arg->getSourceRange();
6823 ExtraParens = true;
6824 }
6825
6826 Arg = Parens->getSubExpr();
6827 }
6828 }
6829
6830 while (SubstNonTypeTemplateParmExpr *subst =
6831 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6832 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6833
6834 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6835 if (UnOp->getOpcode() == UO_AddrOf) {
6836 Arg = UnOp->getSubExpr();
6837 AddressTaken = true;
6838 AddrOpLoc = UnOp->getOperatorLoc();
6839 }
6840 }
6841
6842 while (SubstNonTypeTemplateParmExpr *subst =
6843 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6844 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6845 }
6846
6847 ValueDecl *Entity = nullptr;
6848 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg))
6849 Entity = DRE->getDecl();
6850 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Val: Arg))
6851 Entity = CUE->getGuidDecl();
6852
6853 // If our parameter has pointer type, check for a null template value.
6854 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6855 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ArgIn,
6856 Entity)) {
6857 case NPV_NullPointer:
6858 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
6859 SugaredConverted = TemplateArgument(ParamType,
6860 /*isNullPtr=*/true);
6861 CanonicalConverted =
6862 TemplateArgument(S.Context.getCanonicalType(T: ParamType),
6863 /*isNullPtr=*/true);
6864 return false;
6865
6866 case NPV_Error:
6867 return true;
6868
6869 case NPV_NotNullPointer:
6870 break;
6871 }
6872 }
6873
6874 // Stop checking the precise nature of the argument if it is value dependent,
6875 // it should be checked when instantiated.
6876 if (Arg->isValueDependent()) {
6877 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6878 CanonicalConverted =
6879 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
6880 return false;
6881 }
6882
6883 if (!Entity) {
6884 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6885 << Arg->getSourceRange();
6886 S.NoteTemplateParameterLocation(Decl: *Param);
6887 return true;
6888 }
6889
6890 // Cannot refer to non-static data members
6891 if (isa<FieldDecl>(Val: Entity) || isa<IndirectFieldDecl>(Val: Entity)) {
6892 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_field)
6893 << Entity << Arg->getSourceRange();
6894 S.NoteTemplateParameterLocation(Decl: *Param);
6895 return true;
6896 }
6897
6898 // Cannot refer to non-static member functions
6899 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Entity)) {
6900 if (!Method->isStatic()) {
6901 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_method)
6902 << Method << Arg->getSourceRange();
6903 S.NoteTemplateParameterLocation(Decl: *Param);
6904 return true;
6905 }
6906 }
6907
6908 FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Entity);
6909 VarDecl *Var = dyn_cast<VarDecl>(Val: Entity);
6910 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Val: Entity);
6911
6912 // A non-type template argument must refer to an object or function.
6913 if (!Func && !Var && !Guid) {
6914 // We found something, but we don't know specifically what it is.
6915 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_object_or_func)
6916 << Arg->getSourceRange();
6917 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_refers_here);
6918 return true;
6919 }
6920
6921 // Address / reference template args must have external linkage in C++98.
6922 if (Entity->getFormalLinkage() == Linkage::Internal) {
6923 S.Diag(Loc: Arg->getBeginLoc(),
6924 DiagID: S.getLangOpts().CPlusPlus11
6925 ? diag::warn_cxx98_compat_template_arg_object_internal
6926 : diag::ext_template_arg_object_internal)
6927 << !Func << Entity << Arg->getSourceRange();
6928 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6929 << !Func;
6930 } else if (!Entity->hasLinkage()) {
6931 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_object_no_linkage)
6932 << !Func << Entity << Arg->getSourceRange();
6933 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6934 << !Func;
6935 return true;
6936 }
6937
6938 if (Var) {
6939 // A value of reference type is not an object.
6940 if (Var->getType()->isReferenceType()) {
6941 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_reference_var)
6942 << Var->getType() << Arg->getSourceRange();
6943 S.NoteTemplateParameterLocation(Decl: *Param);
6944 return true;
6945 }
6946
6947 // A template argument must have static storage duration.
6948 if (Var->getTLSKind()) {
6949 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_thread_local)
6950 << Arg->getSourceRange();
6951 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_template_arg_refers_here);
6952 return true;
6953 }
6954 }
6955
6956 if (AddressTaken && ParamType->isReferenceType()) {
6957 // If we originally had an address-of operator, but the
6958 // parameter has reference type, complain and (if things look
6959 // like they will work) drop the address-of operator.
6960 if (!S.Context.hasSameUnqualifiedType(T1: Entity->getType(),
6961 T2: ParamType.getNonReferenceType())) {
6962 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6963 << ParamType;
6964 S.NoteTemplateParameterLocation(Decl: *Param);
6965 return true;
6966 }
6967
6968 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6969 << ParamType
6970 << FixItHint::CreateRemoval(RemoveRange: AddrOpLoc);
6971 S.NoteTemplateParameterLocation(Decl: *Param);
6972
6973 ArgType = Entity->getType();
6974 }
6975
6976 // If the template parameter has pointer type, either we must have taken the
6977 // address or the argument must decay to a pointer.
6978 if (!AddressTaken && ParamType->isPointerType()) {
6979 if (Func) {
6980 // Function-to-pointer decay.
6981 ArgType = S.Context.getPointerType(T: Func->getType());
6982 } else if (Entity->getType()->isArrayType()) {
6983 // Array-to-pointer decay.
6984 ArgType = S.Context.getArrayDecayedType(T: Entity->getType());
6985 } else {
6986 // If the template parameter has pointer type but the address of
6987 // this object was not taken, complain and (possibly) recover by
6988 // taking the address of the entity.
6989 ArgType = S.Context.getPointerType(T: Entity->getType());
6990 if (!S.Context.hasSameUnqualifiedType(T1: ArgType, T2: ParamType)) {
6991 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
6992 << ParamType;
6993 S.NoteTemplateParameterLocation(Decl: *Param);
6994 return true;
6995 }
6996
6997 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
6998 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code: "&");
6999
7000 S.NoteTemplateParameterLocation(Decl: *Param);
7001 }
7002 }
7003
7004 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7005 Arg, ArgType))
7006 return true;
7007
7008 // Create the template argument.
7009 SugaredConverted = TemplateArgument(Entity, ParamType);
7010 CanonicalConverted =
7011 TemplateArgument(cast<ValueDecl>(Val: Entity->getCanonicalDecl()),
7012 S.Context.getCanonicalType(T: ParamType));
7013 S.MarkAnyDeclReferenced(Loc: Arg->getBeginLoc(), D: Entity, MightBeOdrUse: false);
7014 return false;
7015}
7016
7017/// Checks whether the given template argument is a pointer to
7018/// member constant according to C++ [temp.arg.nontype]p1.
7019static bool CheckTemplateArgumentPointerToMember(
7020 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7021 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7022 bool Invalid = false;
7023
7024 Expr *Arg = ResultArg;
7025 bool ObjCLifetimeConversion;
7026
7027 // C++ [temp.arg.nontype]p1:
7028 //
7029 // A template-argument for a non-type, non-template
7030 // template-parameter shall be one of: [...]
7031 //
7032 // -- a pointer to member expressed as described in 5.3.1.
7033 DeclRefExpr *DRE = nullptr;
7034
7035 // In C++98/03 mode, give an extension warning on any extra parentheses.
7036 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7037 bool ExtraParens = false;
7038 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
7039 if (!Invalid && !ExtraParens) {
7040 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_extra_parens)
7041 << Arg->getSourceRange();
7042 ExtraParens = true;
7043 }
7044
7045 Arg = Parens->getSubExpr();
7046 }
7047
7048 while (SubstNonTypeTemplateParmExpr *subst =
7049 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
7050 Arg = subst->getReplacement()->IgnoreImpCasts();
7051
7052 // A pointer-to-member constant written &Class::member.
7053 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
7054 if (UnOp->getOpcode() == UO_AddrOf) {
7055 DRE = dyn_cast<DeclRefExpr>(Val: UnOp->getSubExpr());
7056 if (DRE && !DRE->getQualifier())
7057 DRE = nullptr;
7058 }
7059 }
7060 // A constant of pointer-to-member type.
7061 else if ((DRE = dyn_cast<DeclRefExpr>(Val: Arg))) {
7062 ValueDecl *VD = DRE->getDecl();
7063 if (VD->getType()->isMemberPointerType()) {
7064 if (isa<NonTypeTemplateParmDecl>(Val: VD)) {
7065 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7066 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7067 CanonicalConverted =
7068 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7069 } else {
7070 SugaredConverted = TemplateArgument(VD, ParamType);
7071 CanonicalConverted =
7072 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7073 S.Context.getCanonicalType(T: ParamType));
7074 }
7075 return Invalid;
7076 }
7077 }
7078
7079 DRE = nullptr;
7080 }
7081
7082 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7083
7084 // Check for a null pointer value.
7085 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ResultArg,
7086 Entity)) {
7087 case NPV_Error:
7088 return true;
7089 case NPV_NullPointer:
7090 S.Diag(Loc: ResultArg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7091 SugaredConverted = TemplateArgument(ParamType,
7092 /*isNullPtr*/ true);
7093 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(T: ParamType),
7094 /*isNullPtr*/ true);
7095 return false;
7096 case NPV_NotNullPointer:
7097 break;
7098 }
7099
7100 if (S.IsQualificationConversion(FromType: ResultArg->getType(),
7101 ToType: ParamType.getNonReferenceType(), CStyle: false,
7102 ObjCLifetimeConversion)) {
7103 ResultArg = S.ImpCastExprToType(E: ResultArg, Type: ParamType, CK: CK_NoOp,
7104 VK: ResultArg->getValueKind())
7105 .get();
7106 } else if (!S.Context.hasSameUnqualifiedType(
7107 T1: ResultArg->getType(), T2: ParamType.getNonReferenceType())) {
7108 // We can't perform this conversion.
7109 S.Diag(Loc: ResultArg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
7110 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7111 S.NoteTemplateParameterLocation(Decl: *Param);
7112 return true;
7113 }
7114
7115 if (!DRE)
7116 return S.Diag(Loc: Arg->getBeginLoc(),
7117 DiagID: diag::err_template_arg_not_pointer_to_member_form)
7118 << Arg->getSourceRange();
7119
7120 if (isa<FieldDecl>(Val: DRE->getDecl()) ||
7121 isa<IndirectFieldDecl>(Val: DRE->getDecl()) ||
7122 isa<CXXMethodDecl>(Val: DRE->getDecl())) {
7123 assert((isa<FieldDecl>(DRE->getDecl()) ||
7124 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7125 cast<CXXMethodDecl>(DRE->getDecl())
7126 ->isImplicitObjectMemberFunction()) &&
7127 "Only non-static member pointers can make it here");
7128
7129 // Okay: this is the address of a non-static member, and therefore
7130 // a member pointer constant.
7131 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7132 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7133 CanonicalConverted =
7134 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7135 } else {
7136 ValueDecl *D = DRE->getDecl();
7137 SugaredConverted = TemplateArgument(D, ParamType);
7138 CanonicalConverted =
7139 TemplateArgument(cast<ValueDecl>(Val: D->getCanonicalDecl()),
7140 S.Context.getCanonicalType(T: ParamType));
7141 }
7142 return Invalid;
7143 }
7144
7145 // We found something else, but we don't know specifically what it is.
7146 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_pointer_to_member_form)
7147 << Arg->getSourceRange();
7148 S.Diag(Loc: DRE->getDecl()->getLocation(), DiagID: diag::note_template_arg_refers_here);
7149 return true;
7150}
7151
7152/// Check a template argument against its corresponding
7153/// non-type template parameter.
7154///
7155/// This routine implements the semantics of C++ [temp.arg.nontype].
7156/// If an error occurred, it returns ExprError(); otherwise, it
7157/// returns the converted template argument. \p ParamType is the
7158/// type of the non-type template parameter after it has been instantiated.
7159ExprResult Sema::CheckTemplateArgument(NamedDecl *Param, QualType ParamType,
7160 Expr *Arg,
7161 TemplateArgument &SugaredConverted,
7162 TemplateArgument &CanonicalConverted,
7163 bool StrictCheck,
7164 CheckTemplateArgumentKind CTAK) {
7165 SourceLocation StartLoc = Arg->getBeginLoc();
7166 auto *ArgPE = dyn_cast<PackExpansionExpr>(Val: Arg);
7167 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7168 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7169 DeductionArg = NewDeductionArg;
7170 if (ArgPE) {
7171 // Recreate a pack expansion if we unwrapped one.
7172 Arg = new (Context) PackExpansionExpr(
7173 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7174 } else {
7175 Arg = DeductionArg;
7176 }
7177 };
7178
7179 // If the parameter type somehow involves auto, deduce the type now.
7180 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7181 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7182 if (IsDeduced) {
7183 // When checking a deduced template argument, deduce from its type even if
7184 // the type is dependent, in order to check the types of non-type template
7185 // arguments line up properly in partial ordering.
7186 TypeSourceInfo *TSI =
7187 Context.getTrivialTypeSourceInfo(T: ParamType, Loc: Param->getLocation());
7188 if (isa<DeducedTemplateSpecializationType>(Val: DeducedT)) {
7189 InitializedEntity Entity =
7190 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7191 InitializationKind Kind = InitializationKind::CreateForInit(
7192 Loc: DeductionArg->getBeginLoc(), /*DirectInit*/false, Init: DeductionArg);
7193 Expr *Inits[1] = {DeductionArg};
7194 ParamType =
7195 DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind, Init: Inits);
7196 if (ParamType.isNull())
7197 return ExprError();
7198 } else {
7199 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7200 Param->getTemplateDepth() + 1);
7201 ParamType = QualType();
7202 TemplateDeductionResult Result =
7203 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeductionArg, Result&: ParamType, Info,
7204 /*DependentDeduction=*/true,
7205 // We do not check constraints right now because the
7206 // immediately-declared constraint of the auto type is
7207 // also an associated constraint, and will be checked
7208 // along with the other associated constraints after
7209 // checking the template argument list.
7210 /*IgnoreConstraints=*/true);
7211 if (Result != TemplateDeductionResult::Success) {
7212 ParamType = TSI->getType();
7213 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7214 if (Result == TemplateDeductionResult::AlreadyDiagnosed)
7215 return ExprError();
7216 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param))
7217 Diag(Loc: Arg->getExprLoc(),
7218 DiagID: diag::err_non_type_template_parm_type_deduction_failure)
7219 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7220 << Arg->getSourceRange();
7221 NoteTemplateParameterLocation(Decl: *Param);
7222 return ExprError();
7223 }
7224 ParamType = SubstAutoTypeDependent(TypeWithAuto: ParamType);
7225 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7226 }
7227 }
7228 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7229 // an error. The error message normally references the parameter
7230 // declaration, but here we'll pass the argument location because that's
7231 // where the parameter type is deduced.
7232 ParamType = CheckNonTypeTemplateParameterType(T: ParamType, Loc: Arg->getExprLoc());
7233 if (ParamType.isNull()) {
7234 NoteTemplateParameterLocation(Decl: *Param);
7235 return ExprError();
7236 }
7237 }
7238
7239 // We should have already dropped all cv-qualifiers by now.
7240 assert(!ParamType.hasQualifiers() &&
7241 "non-type template parameter type cannot be qualified");
7242
7243 // If either the parameter has a dependent type or the argument is
7244 // type-dependent, there's nothing we can check now.
7245 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7246 // Force the argument to the type of the parameter to maintain invariants.
7247 if (!IsDeduced) {
7248 ExprResult E = ImpCastExprToType(
7249 E: DeductionArg, Type: ParamType.getNonLValueExprType(Context), CK: CK_Dependent,
7250 VK: ParamType->isLValueReferenceType() ? VK_LValue
7251 : ParamType->isRValueReferenceType() ? VK_XValue
7252 : VK_PRValue);
7253 if (E.isInvalid())
7254 return ExprError();
7255 setDeductionArg(E.get());
7256 }
7257 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7258 CanonicalConverted = TemplateArgument(
7259 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7260 return Arg;
7261 }
7262
7263 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7264 if (CTAK == CTAK_Deduced && !StrictCheck &&
7265 (ParamType->isReferenceType()
7266 ? !Context.hasSameType(T1: ParamType.getNonReferenceType(),
7267 T2: DeductionArg->getType())
7268 : !Context.hasSameUnqualifiedType(T1: ParamType,
7269 T2: DeductionArg->getType()))) {
7270 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7271 // we should actually be checking the type of the template argument in P,
7272 // not the type of the template argument deduced from A, against the
7273 // template parameter type.
7274 Diag(Loc: StartLoc, DiagID: diag::err_deduced_non_type_template_arg_type_mismatch)
7275 << Arg->getType() << ParamType.getUnqualifiedType();
7276 NoteTemplateParameterLocation(Decl: *Param);
7277 return ExprError();
7278 }
7279
7280 // If the argument is a pack expansion, we don't know how many times it would
7281 // expand. If we continue checking the argument, this will make the template
7282 // definition ill-formed if it would be ill-formed for any number of
7283 // expansions during instantiation time. When partial ordering or matching
7284 // template template parameters, this is exactly what we want. Otherwise, the
7285 // normal template rules apply: we accept the template if it would be valid
7286 // for any number of expansions (i.e. none).
7287 if (ArgPE && !StrictCheck) {
7288 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7289 CanonicalConverted = TemplateArgument(
7290 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7291 return Arg;
7292 }
7293
7294 // Avoid making a copy when initializing a template parameter of class type
7295 // from a template parameter object of the same type. This is going beyond
7296 // the standard, but is required for soundness: in
7297 // template<A a> struct X { X *p; X<a> *q; };
7298 // ... we need p and q to have the same type.
7299 //
7300 // Similarly, don't inject a call to a copy constructor when initializing
7301 // from a template parameter of the same type.
7302 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7303 if (ParamType->isRecordType() && isa<DeclRefExpr>(Val: InnerArg) &&
7304 Context.hasSameUnqualifiedType(T1: ParamType, T2: InnerArg->getType())) {
7305 NamedDecl *ND = cast<DeclRefExpr>(Val: InnerArg)->getDecl();
7306 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(Val: ND)) {
7307
7308 SugaredConverted = TemplateArgument(TPO, ParamType);
7309 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7310 ParamType.getCanonicalType());
7311 return Arg;
7312 }
7313 if (isa<NonTypeTemplateParmDecl>(Val: ND)) {
7314 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7315 CanonicalConverted =
7316 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7317 return Arg;
7318 }
7319 }
7320
7321 // The initialization of the parameter from the argument is
7322 // a constant-evaluated context.
7323 EnterExpressionEvaluationContext ConstantEvaluated(
7324 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7325
7326 bool IsConvertedConstantExpression = true;
7327 if (isa<InitListExpr>(Val: DeductionArg) || ParamType->isRecordType()) {
7328 InitializationKind Kind = InitializationKind::CreateForInit(
7329 Loc: StartLoc, /*DirectInit=*/false, Init: DeductionArg);
7330 Expr *Inits[1] = {DeductionArg};
7331 InitializedEntity Entity =
7332 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7333 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7334 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Inits);
7335 if (Result.isInvalid() || !Result.get())
7336 return ExprError();
7337 Result = ActOnConstantExpression(Res: Result.get());
7338 if (Result.isInvalid() || !Result.get())
7339 return ExprError();
7340 setDeductionArg(ActOnFinishFullExpr(Expr: Result.get(), CC: Arg->getBeginLoc(),
7341 /*DiscardedValue=*/false,
7342 /*IsConstexpr=*/true,
7343 /*IsTemplateArgument=*/true)
7344 .get());
7345 IsConvertedConstantExpression = false;
7346 }
7347
7348 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7349 // C++17 [temp.arg.nontype]p1:
7350 // A template-argument for a non-type template parameter shall be
7351 // a converted constant expression of the type of the template-parameter.
7352 APValue Value;
7353 ExprResult ArgResult;
7354 if (IsConvertedConstantExpression) {
7355 ArgResult = BuildConvertedConstantExpression(
7356 From: DeductionArg, T: ParamType,
7357 CCE: StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Dest: Param);
7358 assert(!ArgResult.isUnset());
7359 if (ArgResult.isInvalid()) {
7360 NoteTemplateParameterLocation(Decl: *Param);
7361 return ExprError();
7362 }
7363 } else {
7364 ArgResult = DeductionArg;
7365 }
7366
7367 // For a value-dependent argument, CheckConvertedConstantExpression is
7368 // permitted (and expected) to be unable to determine a value.
7369 if (ArgResult.get()->isValueDependent()) {
7370 setDeductionArg(ArgResult.get());
7371 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7372 CanonicalConverted =
7373 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7374 return Arg;
7375 }
7376
7377 APValue PreNarrowingValue;
7378 ArgResult = EvaluateConvertedConstantExpression(
7379 E: ArgResult.get(), T: ParamType, Value, CCE: CCEKind::TemplateArg, /*RequireInt=*/
7380 false, PreNarrowingValue);
7381 if (ArgResult.isInvalid())
7382 return ExprError();
7383 setDeductionArg(ArgResult.get());
7384
7385 if (Value.isLValue()) {
7386 APValue::LValueBase Base = Value.getLValueBase();
7387 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7388 // For a non-type template-parameter of pointer or reference type,
7389 // the value of the constant expression shall not refer to
7390 assert(ParamType->isPointerOrReferenceType() ||
7391 ParamType->isNullPtrType());
7392 // -- a temporary object
7393 // -- a string literal
7394 // -- the result of a typeid expression, or
7395 // -- a predefined __func__ variable
7396 if (Base &&
7397 (!VD ||
7398 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(Val: VD))) {
7399 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
7400 << Arg->getSourceRange();
7401 return ExprError();
7402 }
7403
7404 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7405 VD->getType()->isArrayType() &&
7406 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7407 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7408 if (ArgPE) {
7409 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7410 CanonicalConverted =
7411 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7412 } else {
7413 SugaredConverted = TemplateArgument(VD, ParamType);
7414 CanonicalConverted =
7415 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7416 ParamType.getCanonicalType());
7417 }
7418 return Arg;
7419 }
7420
7421 // -- a subobject [until C++20]
7422 if (!getLangOpts().CPlusPlus20) {
7423 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7424 Value.isLValueOnePastTheEnd()) {
7425 Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_subobject)
7426 << Value.getAsString(Ctx: Context, Ty: ParamType);
7427 return ExprError();
7428 }
7429 assert((VD || !ParamType->isReferenceType()) &&
7430 "null reference should not be a constant expression");
7431 assert((!VD || !ParamType->isNullPtrType()) &&
7432 "non-null value of type nullptr_t?");
7433 }
7434 }
7435
7436 if (Value.isAddrLabelDiff())
7437 return Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_addr_label_diff);
7438
7439 if (ArgPE) {
7440 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7441 CanonicalConverted =
7442 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7443 } else {
7444 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7445 CanonicalConverted =
7446 TemplateArgument(Context, ParamType.getCanonicalType(), Value);
7447 }
7448 return Arg;
7449 }
7450
7451 // These should have all been handled above using the C++17 rules.
7452 assert(!ArgPE && !StrictCheck);
7453
7454 // C++ [temp.arg.nontype]p5:
7455 // The following conversions are performed on each expression used
7456 // as a non-type template-argument. If a non-type
7457 // template-argument cannot be converted to the type of the
7458 // corresponding template-parameter then the program is
7459 // ill-formed.
7460 if (ParamType->isIntegralOrEnumerationType()) {
7461 // C++11:
7462 // -- for a non-type template-parameter of integral or
7463 // enumeration type, conversions permitted in a converted
7464 // constant expression are applied.
7465 //
7466 // C++98:
7467 // -- for a non-type template-parameter of integral or
7468 // enumeration type, integral promotions (4.5) and integral
7469 // conversions (4.7) are applied.
7470
7471 if (getLangOpts().CPlusPlus11) {
7472 // C++ [temp.arg.nontype]p1:
7473 // A template-argument for a non-type, non-template template-parameter
7474 // shall be one of:
7475 //
7476 // -- for a non-type template-parameter of integral or enumeration
7477 // type, a converted constant expression of the type of the
7478 // template-parameter; or
7479 llvm::APSInt Value;
7480 ExprResult ArgResult = CheckConvertedConstantExpression(
7481 From: Arg, T: ParamType, Value, CCE: CCEKind::TemplateArg);
7482 if (ArgResult.isInvalid())
7483 return ExprError();
7484 Arg = ArgResult.get();
7485
7486 // We can't check arbitrary value-dependent arguments.
7487 if (Arg->isValueDependent()) {
7488 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7489 CanonicalConverted =
7490 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7491 return Arg;
7492 }
7493
7494 // Widen the argument value to sizeof(parameter type). This is almost
7495 // always a no-op, except when the parameter type is bool. In
7496 // that case, this may extend the argument from 1 bit to 8 bits.
7497 QualType IntegerType = ParamType;
7498 if (const auto *ED = IntegerType->getAsEnumDecl())
7499 IntegerType = ED->getIntegerType();
7500 Value = Value.extOrTrunc(width: IntegerType->isBitIntType()
7501 ? Context.getIntWidth(T: IntegerType)
7502 : Context.getTypeSize(T: IntegerType));
7503
7504 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7505 CanonicalConverted =
7506 TemplateArgument(Context, Value, Context.getCanonicalType(T: ParamType));
7507 return Arg;
7508 }
7509
7510 ExprResult ArgResult = DefaultLvalueConversion(E: Arg);
7511 if (ArgResult.isInvalid())
7512 return ExprError();
7513 Arg = ArgResult.get();
7514
7515 QualType ArgType = Arg->getType();
7516
7517 // C++ [temp.arg.nontype]p1:
7518 // A template-argument for a non-type, non-template
7519 // template-parameter shall be one of:
7520 //
7521 // -- an integral constant-expression of integral or enumeration
7522 // type; or
7523 // -- the name of a non-type template-parameter; or
7524 llvm::APSInt Value;
7525 if (!ArgType->isIntegralOrEnumerationType()) {
7526 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_integral_or_enumeral)
7527 << ArgType << Arg->getSourceRange();
7528 NoteTemplateParameterLocation(Decl: *Param);
7529 return ExprError();
7530 }
7531 if (!Arg->isValueDependent()) {
7532 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7533 QualType T;
7534
7535 public:
7536 TmplArgICEDiagnoser(QualType T) : T(T) { }
7537
7538 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7539 SourceLocation Loc) override {
7540 return S.Diag(Loc, DiagID: diag::err_template_arg_not_ice) << T;
7541 }
7542 } Diagnoser(ArgType);
7543
7544 Arg = VerifyIntegerConstantExpression(E: Arg, Result: &Value, Diagnoser).get();
7545 if (!Arg)
7546 return ExprError();
7547 }
7548
7549 // From here on out, all we care about is the unqualified form
7550 // of the argument type.
7551 ArgType = ArgType.getUnqualifiedType();
7552
7553 // Try to convert the argument to the parameter's type.
7554 if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
7555 // Okay: no conversion necessary
7556 } else if (ParamType->isBooleanType()) {
7557 // This is an integral-to-boolean conversion.
7558 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralToBoolean).get();
7559 } else if (IsIntegralPromotion(From: Arg, FromType: ArgType, ToType: ParamType) ||
7560 !ParamType->isEnumeralType()) {
7561 // This is an integral promotion or conversion.
7562 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralCast).get();
7563 } else {
7564 // We can't perform this conversion.
7565 Diag(Loc: StartLoc, DiagID: diag::err_template_arg_not_convertible)
7566 << Arg->getType() << ParamType << Arg->getSourceRange();
7567 NoteTemplateParameterLocation(Decl: *Param);
7568 return ExprError();
7569 }
7570
7571 // Add the value of this argument to the list of converted
7572 // arguments. We use the bitwidth and signedness of the template
7573 // parameter.
7574 if (Arg->isValueDependent()) {
7575 // The argument is value-dependent. Create a new
7576 // TemplateArgument with the converted expression.
7577 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7578 CanonicalConverted =
7579 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7580 return Arg;
7581 }
7582
7583 QualType IntegerType = ParamType;
7584 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7585 IntegerType = ED->getIntegerType();
7586 }
7587
7588 if (ParamType->isBooleanType()) {
7589 // Value must be zero or one.
7590 Value = Value != 0;
7591 unsigned AllowedBits = Context.getTypeSize(T: IntegerType);
7592 if (Value.getBitWidth() != AllowedBits)
7593 Value = Value.extOrTrunc(width: AllowedBits);
7594 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7595 } else {
7596 llvm::APSInt OldValue = Value;
7597
7598 // Coerce the template argument's value to the value it will have
7599 // based on the template parameter's type.
7600 unsigned AllowedBits = IntegerType->isBitIntType()
7601 ? Context.getIntWidth(T: IntegerType)
7602 : Context.getTypeSize(T: IntegerType);
7603 if (Value.getBitWidth() != AllowedBits)
7604 Value = Value.extOrTrunc(width: AllowedBits);
7605 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7606
7607 // Complain if an unsigned parameter received a negative value.
7608 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7609 (OldValue.isSigned() && OldValue.isNegative())) {
7610 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_negative)
7611 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7612 << Arg->getSourceRange();
7613 NoteTemplateParameterLocation(Decl: *Param);
7614 }
7615
7616 // Complain if we overflowed the template parameter's type.
7617 unsigned RequiredBits;
7618 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7619 RequiredBits = OldValue.getActiveBits();
7620 else if (OldValue.isUnsigned())
7621 RequiredBits = OldValue.getActiveBits() + 1;
7622 else
7623 RequiredBits = OldValue.getSignificantBits();
7624 if (RequiredBits > AllowedBits) {
7625 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_too_large)
7626 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7627 << Arg->getSourceRange();
7628 NoteTemplateParameterLocation(Decl: *Param);
7629 }
7630 }
7631
7632 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7633 SugaredConverted = TemplateArgument(Context, Value, T);
7634 CanonicalConverted =
7635 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7636 return Arg;
7637 }
7638
7639 QualType ArgType = Arg->getType();
7640 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7641 bool IsSpecified = CTAK == CTAK_Specified;
7642
7643 // Handle pointer-to-function, reference-to-function, and
7644 // pointer-to-member-function all in (roughly) the same way.
7645 if (// -- For a non-type template-parameter of type pointer to
7646 // function, only the function-to-pointer conversion (4.3) is
7647 // applied. If the template-argument represents a set of
7648 // overloaded functions (or a pointer to such), the matching
7649 // function is selected from the set (13.4).
7650 (ParamType->isPointerType() &&
7651 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7652 // -- For a non-type template-parameter of type reference to
7653 // function, no conversions apply. If the template-argument
7654 // represents a set of overloaded functions, the matching
7655 // function is selected from the set (13.4).
7656 (ParamType->isReferenceType() &&
7657 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7658 // -- For a non-type template-parameter of type pointer to
7659 // member function, no conversions apply. If the
7660 // template-argument represents a set of overloaded member
7661 // functions, the matching member function is selected from
7662 // the set (13.4).
7663 (ParamType->isMemberPointerType() &&
7664 ParamType->castAs<MemberPointerType>()->getPointeeType()
7665 ->isFunctionType())) {
7666
7667 if (Arg->getType() == Context.OverloadTy) {
7668 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg, TargetType: ParamType,
7669 Complain: true,
7670 Found&: FoundResult)) {
7671 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7672 return ExprError();
7673
7674 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7675 if (Res.isInvalid())
7676 return ExprError();
7677 Arg = Res.get();
7678 ArgType = Arg->getType();
7679 } else
7680 return ExprError();
7681 }
7682
7683 if (!ParamType->isMemberPointerType()) {
7684 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7685 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7686 CanonicalConverted))
7687 return ExprError();
7688 return Arg;
7689 }
7690
7691 if (CheckTemplateArgumentPointerToMember(
7692 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7693 return ExprError();
7694 return Arg;
7695 }
7696
7697 if (ParamType->isPointerType()) {
7698 // -- for a non-type template-parameter of type pointer to
7699 // object, qualification conversions (4.4) and the
7700 // array-to-pointer conversion (4.2) are applied.
7701 // C++0x also allows a value of std::nullptr_t.
7702 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7703 "Only object pointers allowed here");
7704
7705 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7706 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7707 CanonicalConverted))
7708 return ExprError();
7709 return Arg;
7710 }
7711
7712 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7713 // -- For a non-type template-parameter of type reference to
7714 // object, no conversions apply. The type referred to by the
7715 // reference may be more cv-qualified than the (otherwise
7716 // identical) type of the template-argument. The
7717 // template-parameter is bound directly to the
7718 // template-argument, which must be an lvalue.
7719 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7720 "Only object references allowed here");
7721
7722 if (Arg->getType() == Context.OverloadTy) {
7723 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg,
7724 TargetType: ParamRefType->getPointeeType(),
7725 Complain: true,
7726 Found&: FoundResult)) {
7727 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7728 return ExprError();
7729 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7730 if (Res.isInvalid())
7731 return ExprError();
7732 Arg = Res.get();
7733 ArgType = Arg->getType();
7734 } else
7735 return ExprError();
7736 }
7737
7738 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7739 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7740 CanonicalConverted))
7741 return ExprError();
7742 return Arg;
7743 }
7744
7745 // Deal with parameters of type std::nullptr_t.
7746 if (ParamType->isNullPtrType()) {
7747 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7748 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7749 CanonicalConverted =
7750 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7751 return Arg;
7752 }
7753
7754 switch (isNullPointerValueTemplateArgument(S&: *this, Param, ParamType, Arg)) {
7755 case NPV_NotNullPointer:
7756 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_not_convertible)
7757 << Arg->getType() << ParamType;
7758 NoteTemplateParameterLocation(Decl: *Param);
7759 return ExprError();
7760
7761 case NPV_Error:
7762 return ExprError();
7763
7764 case NPV_NullPointer:
7765 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7766 SugaredConverted = TemplateArgument(ParamType,
7767 /*isNullPtr=*/true);
7768 CanonicalConverted = TemplateArgument(Context.getCanonicalType(T: ParamType),
7769 /*isNullPtr=*/true);
7770 return Arg;
7771 }
7772 }
7773
7774 // -- For a non-type template-parameter of type pointer to data
7775 // member, qualification conversions (4.4) are applied.
7776 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7777
7778 if (CheckTemplateArgumentPointerToMember(
7779 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7780 return ExprError();
7781 return Arg;
7782}
7783
7784static void DiagnoseTemplateParameterListArityMismatch(
7785 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7786 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7787
7788bool Sema::CheckDeclCompatibleWithTemplateTemplate(
7789 TemplateDecl *Template, TemplateTemplateParmDecl *Param,
7790 const TemplateArgumentLoc &Arg) {
7791 // C++0x [temp.arg.template]p1:
7792 // A template-argument for a template template-parameter shall be
7793 // the name of a class template or an alias template, expressed as an
7794 // id-expression. When the template-argument names a class template, only
7795 // primary class templates are considered when matching the
7796 // template template argument with the corresponding parameter;
7797 // partial specializations are not considered even if their
7798 // parameter lists match that of the template template parameter.
7799 //
7800
7801 TemplateNameKind Kind = TNK_Non_template;
7802 unsigned DiagFoundKind = 0;
7803
7804 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Val: Template)) {
7805 switch (TTP->templateParameterKind()) {
7806 case TemplateNameKind::TNK_Concept_template:
7807 DiagFoundKind = 3;
7808 break;
7809 case TemplateNameKind::TNK_Var_template:
7810 DiagFoundKind = 2;
7811 break;
7812 default:
7813 DiagFoundKind = 1;
7814 break;
7815 }
7816 Kind = TTP->templateParameterKind();
7817 } else if (isa<ConceptDecl>(Val: Template)) {
7818 Kind = TemplateNameKind::TNK_Concept_template;
7819 DiagFoundKind = 3;
7820 } else if (isa<FunctionTemplateDecl>(Val: Template)) {
7821 Kind = TemplateNameKind::TNK_Function_template;
7822 DiagFoundKind = 0;
7823 } else if (isa<VarTemplateDecl>(Val: Template)) {
7824 Kind = TemplateNameKind::TNK_Var_template;
7825 DiagFoundKind = 2;
7826 } else if (isa<ClassTemplateDecl>(Val: Template) ||
7827 isa<TypeAliasTemplateDecl>(Val: Template) ||
7828 isa<BuiltinTemplateDecl>(Val: Template)) {
7829 Kind = TemplateNameKind::TNK_Type_template;
7830 DiagFoundKind = 1;
7831 } else {
7832 assert(false && "Unexpected Decl");
7833 }
7834
7835 if (Kind == Param->templateParameterKind()) {
7836 return true;
7837 }
7838
7839 unsigned DiagKind = 0;
7840 switch (Param->templateParameterKind()) {
7841 case TemplateNameKind::TNK_Concept_template:
7842 DiagKind = 2;
7843 break;
7844 case TemplateNameKind::TNK_Var_template:
7845 DiagKind = 1;
7846 break;
7847 default:
7848 DiagKind = 0;
7849 break;
7850 }
7851 Diag(Loc: Arg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
7852 << DiagKind;
7853 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_arg_refers_to_template_here)
7854 << DiagFoundKind << Template;
7855 return false;
7856}
7857
7858/// Check a template argument against its corresponding
7859/// template template parameter.
7860///
7861/// This routine implements the semantics of C++ [temp.arg.template].
7862/// It returns true if an error occurred, and false otherwise.
7863bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7864 TemplateParameterList *Params,
7865 TemplateArgumentLoc &Arg,
7866 bool PartialOrdering,
7867 bool *StrictPackMatch) {
7868 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7869 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7870 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7871 if (!Template) {
7872 // FIXME: Handle AssumedTemplateNames
7873 // Any dependent template name is fine.
7874 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7875 return false;
7876 }
7877
7878 if (Template->isInvalidDecl())
7879 return true;
7880
7881 if (!CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg)) {
7882 return true;
7883 }
7884
7885 // C++1z [temp.arg.template]p3: (DR 150)
7886 // A template-argument matches a template template-parameter P when P
7887 // is at least as specialized as the template-argument A.
7888 if (!isTemplateTemplateParameterAtLeastAsSpecializedAs(
7889 PParam: Params, PArg: Param, AArg: Template, DefaultArgs, ArgLoc: Arg.getLocation(),
7890 PartialOrdering, StrictPackMatch))
7891 return true;
7892 // P2113
7893 // C++20[temp.func.order]p2
7894 // [...] If both deductions succeed, the partial ordering selects the
7895 // more constrained template (if one exists) as determined below.
7896 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7897 Params->getAssociatedConstraints(AC&: ParamsAC);
7898 // C++20[temp.arg.template]p3
7899 // [...] In this comparison, if P is unconstrained, the constraints on A
7900 // are not considered.
7901 if (ParamsAC.empty())
7902 return false;
7903
7904 Template->getAssociatedConstraints(AC&: TemplateAC);
7905
7906 bool IsParamAtLeastAsConstrained;
7907 if (IsAtLeastAsConstrained(D1: Param, AC1: ParamsAC, D2: Template, AC2: TemplateAC,
7908 Result&: IsParamAtLeastAsConstrained))
7909 return true;
7910 if (!IsParamAtLeastAsConstrained) {
7911 Diag(Loc: Arg.getLocation(),
7912 DiagID: diag::err_template_template_parameter_not_at_least_as_constrained)
7913 << Template << Param << Arg.getSourceRange();
7914 Diag(Loc: Param->getLocation(), DiagID: diag::note_entity_declared_at) << Param;
7915 Diag(Loc: Template->getLocation(), DiagID: diag::note_entity_declared_at) << Template;
7916 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Param, AC1: ParamsAC, D2: Template,
7917 AC2: TemplateAC);
7918 return true;
7919 }
7920 return false;
7921}
7922
7923static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7924 unsigned HereDiagID,
7925 unsigned ExternalDiagID) {
7926 if (Decl.getLocation().isValid())
7927 return S.Diag(Loc: Decl.getLocation(), DiagID: HereDiagID);
7928
7929 SmallString<128> Str;
7930 llvm::raw_svector_ostream Out(Str);
7931 PrintingPolicy PP = S.getPrintingPolicy();
7932 PP.TerseOutput = 1;
7933 Decl.print(Out, Policy: PP);
7934 return S.Diag(Loc: Decl.getLocation(), DiagID: ExternalDiagID) << Out.str();
7935}
7936
7937void Sema::NoteTemplateLocation(const NamedDecl &Decl,
7938 std::optional<SourceRange> ParamRange) {
7939 SemaDiagnosticBuilder DB =
7940 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_decl_here,
7941 ExternalDiagID: diag::note_template_decl_external);
7942 if (ParamRange && ParamRange->isValid()) {
7943 assert(Decl.getLocation().isValid() &&
7944 "Parameter range has location when Decl does not");
7945 DB << *ParamRange;
7946 }
7947}
7948
7949void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
7950 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_param_here,
7951 ExternalDiagID: diag::note_template_param_external);
7952}
7953
7954/// Given a non-type template argument that refers to a
7955/// declaration and the type of its corresponding non-type template
7956/// parameter, produce an expression that properly refers to that
7957/// declaration.
7958ExprResult Sema::BuildExpressionFromDeclTemplateArgument(
7959 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc) {
7960 // C++ [temp.param]p8:
7961 //
7962 // A non-type template-parameter of type "array of T" or
7963 // "function returning T" is adjusted to be of type "pointer to
7964 // T" or "pointer to function returning T", respectively.
7965 if (ParamType->isArrayType())
7966 ParamType = Context.getArrayDecayedType(T: ParamType);
7967 else if (ParamType->isFunctionType())
7968 ParamType = Context.getPointerType(T: ParamType);
7969
7970 // For a NULL non-type template argument, return nullptr casted to the
7971 // parameter's type.
7972 if (Arg.getKind() == TemplateArgument::NullPtr) {
7973 return ImpCastExprToType(
7974 E: new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7975 Type: ParamType,
7976 CK: ParamType->getAs<MemberPointerType>()
7977 ? CK_NullToMemberPointer
7978 : CK_NullToPointer);
7979 }
7980 assert(Arg.getKind() == TemplateArgument::Declaration &&
7981 "Only declaration template arguments permitted here");
7982
7983 ValueDecl *VD = Arg.getAsDecl();
7984
7985 CXXScopeSpec SS;
7986 if (ParamType->isMemberPointerType()) {
7987 // If this is a pointer to member, we need to use a qualified name to
7988 // form a suitable pointer-to-member constant.
7989 assert(VD->getDeclContext()->isRecord() &&
7990 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7991 isa<IndirectFieldDecl>(VD)));
7992 CanQualType ClassType =
7993 Context.getCanonicalTagType(TD: cast<RecordDecl>(Val: VD->getDeclContext()));
7994 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7995 SS.MakeTrivial(Context, Qualifier, R: Loc);
7996 }
7997
7998 ExprResult RefExpr = BuildDeclarationNameExpr(
7999 SS, NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
8000 if (RefExpr.isInvalid())
8001 return ExprError();
8002
8003 // For a pointer, the argument declaration is the pointee. Take its address.
8004 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8005 if (ParamType->isPointerType() && !ElemT.isNull() &&
8006 Context.hasSimilarType(T1: ElemT, T2: ParamType->getPointeeType())) {
8007 // Decay an array argument if we want a pointer to its first element.
8008 RefExpr = DefaultFunctionArrayConversion(E: RefExpr.get());
8009 if (RefExpr.isInvalid())
8010 return ExprError();
8011 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8012 // For any other pointer, take the address (or form a pointer-to-member).
8013 RefExpr = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_AddrOf, InputExpr: RefExpr.get());
8014 if (RefExpr.isInvalid())
8015 return ExprError();
8016 } else if (ParamType->isRecordType()) {
8017 assert(isa<TemplateParamObjectDecl>(VD) &&
8018 "arg for class template param not a template parameter object");
8019 // No conversions apply in this case.
8020 return RefExpr;
8021 } else {
8022 assert(ParamType->isReferenceType() &&
8023 "unexpected type for decl template argument");
8024 // If the parameter has reference type, wrap it in paretheses so that this
8025 // expression will have the correct type under `decltype`.
8026 RefExpr = new (Context) ParenExpr(Loc, Loc, RefExpr.get());
8027 }
8028
8029 // At this point we should have the right value category.
8030 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8031 "value kind mismatch for non-type template argument");
8032
8033 // The type of the template parameter can differ from the type of the
8034 // argument in various ways; convert it now if necessary.
8035 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8036 QualType SrcExprType = RefExpr.get()->getType();
8037 if (!Context.hasSameType(T1: SrcExprType, T2: DestExprType)) {
8038 CastKind CK;
8039 if (Context.hasSimilarType(T1: SrcExprType, T2: DestExprType) ||
8040 IsFunctionConversion(FromType: SrcExprType, ToType: DestExprType)) {
8041 CK = CK_NoOp;
8042 } else if (ParamType->isVoidPointerType() && SrcExprType->isPointerType()) {
8043 CK = CK_BitCast;
8044 } else {
8045 // FIXME: Pointers to members can need conversion derived-to-base or
8046 // base-to-derived conversions. We currently don't retain enough
8047 // information to convert properly (we need to track a cast path or
8048 // subobject number in the template argument).
8049 llvm_unreachable(
8050 "unexpected conversion required for non-type template argument");
8051 }
8052 RefExpr = ImpCastExprToType(E: RefExpr.get(), Type: DestExprType, CK,
8053 VK: RefExpr.get()->getValueKind());
8054 }
8055
8056 return RefExpr;
8057}
8058
8059/// Construct a new expression that refers to the given
8060/// integral template argument with the given source-location
8061/// information.
8062///
8063/// This routine takes care of the mapping from an integral template
8064/// argument (which may have any integral type) to the appropriate
8065/// literal value.
8066static Expr *BuildExpressionFromIntegralTemplateArgumentValue(
8067 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8068 assert(OrigT->isIntegralOrEnumerationType());
8069
8070 // If this is an enum type that we're instantiating, we need to use an integer
8071 // type the same size as the enumerator. We don't want to build an
8072 // IntegerLiteral with enum type. The integer type of an enum type can be of
8073 // any integral type with C++11 enum classes, make sure we create the right
8074 // type of literal for it.
8075 QualType T = OrigT;
8076 if (const auto *ED = OrigT->getAsEnumDecl())
8077 T = ED->getIntegerType();
8078
8079 Expr *E;
8080 if (T->isAnyCharacterType()) {
8081 CharacterLiteralKind Kind;
8082 if (T->isWideCharType())
8083 Kind = CharacterLiteralKind::Wide;
8084 else if (T->isChar8Type() && S.getLangOpts().Char8)
8085 Kind = CharacterLiteralKind::UTF8;
8086 else if (T->isChar16Type())
8087 Kind = CharacterLiteralKind::UTF16;
8088 else if (T->isChar32Type())
8089 Kind = CharacterLiteralKind::UTF32;
8090 else
8091 Kind = CharacterLiteralKind::Ascii;
8092
8093 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8094 } else if (T->isBooleanType()) {
8095 E = CXXBoolLiteralExpr::Create(C: S.Context, Val: Int.getBoolValue(), Ty: T, Loc);
8096 } else {
8097 E = IntegerLiteral::Create(C: S.Context, V: Int, type: T, l: Loc);
8098 }
8099
8100 if (OrigT->isEnumeralType()) {
8101 // FIXME: This is a hack. We need a better way to handle substituted
8102 // non-type template parameters.
8103 E = CStyleCastExpr::Create(Context: S.Context, T: OrigT, VK: VK_PRValue, K: CK_IntegralCast, Op: E,
8104 BasePath: nullptr, FPO: S.CurFPFeatureOverrides(),
8105 WrittenTy: S.Context.getTrivialTypeSourceInfo(T: OrigT, Loc),
8106 L: Loc, R: Loc);
8107 }
8108
8109 return E;
8110}
8111
8112static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(
8113 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8114 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8115 auto *ILE = new (S.Context)
8116 InitListExpr(S.Context, Loc, Elts, Loc, /*isExplicit=*/false);
8117 ILE->setType(T);
8118 return ILE;
8119 };
8120
8121 switch (Val.getKind()) {
8122 case APValue::AddrLabelDiff:
8123 // This cannot occur in a template argument at all.
8124 case APValue::Array:
8125 case APValue::Struct:
8126 case APValue::Union:
8127 // These can only occur within a template parameter object, which is
8128 // represented as a TemplateArgument::Declaration.
8129 llvm_unreachable("unexpected template argument value");
8130
8131 case APValue::Int:
8132 return BuildExpressionFromIntegralTemplateArgumentValue(S, OrigT: T, Int: Val.getInt(),
8133 Loc);
8134
8135 case APValue::Float:
8136 return FloatingLiteral::Create(C: S.Context, V: Val.getFloat(), /*IsExact=*/isexact: true,
8137 Type: T, L: Loc);
8138
8139 case APValue::FixedPoint:
8140 return FixedPointLiteral::CreateFromRawInt(
8141 C: S.Context, V: Val.getFixedPoint().getValue(), type: T, l: Loc,
8142 Scale: Val.getFixedPoint().getScale());
8143
8144 case APValue::ComplexInt: {
8145 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8146 return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(
8147 S, OrigT: ElemT, Int: Val.getComplexIntReal(), Loc),
8148 BuildExpressionFromIntegralTemplateArgumentValue(
8149 S, OrigT: ElemT, Int: Val.getComplexIntImag(), Loc)});
8150 }
8151
8152 case APValue::ComplexFloat: {
8153 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8154 return MakeInitList(
8155 {FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatReal(), isexact: true,
8156 Type: ElemT, L: Loc),
8157 FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatImag(), isexact: true,
8158 Type: ElemT, L: Loc)});
8159 }
8160
8161 case APValue::Vector: {
8162 QualType ElemT = T->castAs<VectorType>()->getElementType();
8163 llvm::SmallVector<Expr *, 8> Elts;
8164 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8165 Elts.push_back(Elt: BuildExpressionFromNonTypeTemplateArgumentValue(
8166 S, T: ElemT, Val: Val.getVectorElt(I), Loc));
8167 return MakeInitList(Elts);
8168 }
8169
8170 case APValue::Matrix:
8171 llvm_unreachable("Matrix template argument expression not yet supported");
8172
8173 case APValue::None:
8174 case APValue::Indeterminate:
8175 llvm_unreachable("Unexpected APValue kind.");
8176 case APValue::LValue:
8177 case APValue::MemberPointer:
8178 // There isn't necessarily a valid equivalent source-level syntax for
8179 // these; in particular, a naive lowering might violate access control.
8180 // So for now we lower to a ConstantExpr holding the value, wrapped around
8181 // an OpaqueValueExpr.
8182 // FIXME: We should have a better representation for this.
8183 ExprValueKind VK = VK_PRValue;
8184 if (T->isReferenceType()) {
8185 T = T->getPointeeType();
8186 VK = VK_LValue;
8187 }
8188 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8189 return ConstantExpr::Create(Context: S.Context, E: OVE, Result: Val);
8190 }
8191 llvm_unreachable("Unhandled APValue::ValueKind enum");
8192}
8193
8194ExprResult
8195Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
8196 SourceLocation Loc) {
8197 switch (Arg.getKind()) {
8198 case TemplateArgument::Null:
8199 case TemplateArgument::Type:
8200 case TemplateArgument::Template:
8201 case TemplateArgument::TemplateExpansion:
8202 case TemplateArgument::Pack:
8203 llvm_unreachable("not a non-type template argument");
8204
8205 case TemplateArgument::Expression:
8206 return Arg.getAsExpr();
8207
8208 case TemplateArgument::NullPtr:
8209 case TemplateArgument::Declaration:
8210 return BuildExpressionFromDeclTemplateArgument(
8211 Arg, ParamType: Arg.getNonTypeTemplateArgumentType(), Loc);
8212
8213 case TemplateArgument::Integral:
8214 return BuildExpressionFromIntegralTemplateArgumentValue(
8215 S&: *this, OrigT: Arg.getIntegralType(), Int: Arg.getAsIntegral(), Loc);
8216
8217 case TemplateArgument::StructuralValue:
8218 return BuildExpressionFromNonTypeTemplateArgumentValue(
8219 S&: *this, T: Arg.getStructuralValueType(), Val: Arg.getAsStructuralValue(), Loc);
8220 }
8221 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8222}
8223
8224/// Match two template parameters within template parameter lists.
8225static bool MatchTemplateParameterKind(
8226 Sema &S, NamedDecl *New,
8227 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8228 const NamedDecl *OldInstFrom, bool Complain,
8229 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8230 // Check the actual kind (type, non-type, template).
8231 if (Old->getKind() != New->getKind()) {
8232 if (Complain) {
8233 unsigned NextDiag = diag::err_template_param_different_kind;
8234 if (TemplateArgLoc.isValid()) {
8235 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8236 NextDiag = diag::note_template_param_different_kind;
8237 }
8238 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8239 << (Kind != Sema::TPL_TemplateMatch);
8240 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_prev_declaration)
8241 << (Kind != Sema::TPL_TemplateMatch);
8242 }
8243
8244 return false;
8245 }
8246
8247 // Check that both are parameter packs or neither are parameter packs.
8248 // However, if we are matching a template template argument to a
8249 // template template parameter, the template template parameter can have
8250 // a parameter pack where the template template argument does not.
8251 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8252 if (Complain) {
8253 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8254 if (TemplateArgLoc.isValid()) {
8255 S.Diag(Loc: TemplateArgLoc,
8256 DiagID: diag::err_template_arg_template_params_mismatch);
8257 NextDiag = diag::note_template_parameter_pack_non_pack;
8258 }
8259
8260 unsigned ParamKind = isa<TemplateTypeParmDecl>(Val: New)? 0
8261 : isa<NonTypeTemplateParmDecl>(Val: New)? 1
8262 : 2;
8263 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8264 << ParamKind << New->isParameterPack();
8265 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_parameter_pack_here)
8266 << ParamKind << Old->isParameterPack();
8267 }
8268
8269 return false;
8270 }
8271 // For non-type template parameters, check the type of the parameter.
8272 if (NonTypeTemplateParmDecl *OldNTTP =
8273 dyn_cast<NonTypeTemplateParmDecl>(Val: Old)) {
8274 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(Val: New);
8275
8276 // If we are matching a template template argument to a template
8277 // template parameter and one of the non-type template parameter types
8278 // is dependent, then we must wait until template instantiation time
8279 // to actually compare the arguments.
8280 if (Kind != Sema::TPL_TemplateTemplateParmMatch ||
8281 (!OldNTTP->getType()->isDependentType() &&
8282 !NewNTTP->getType()->isDependentType())) {
8283 // C++20 [temp.over.link]p6:
8284 // Two [non-type] template-parameters are equivalent [if] they have
8285 // equivalent types ignoring the use of type-constraints for
8286 // placeholder types
8287 QualType OldType = S.Context.getUnconstrainedType(T: OldNTTP->getType());
8288 QualType NewType = S.Context.getUnconstrainedType(T: NewNTTP->getType());
8289 if (!S.Context.hasSameType(T1: OldType, T2: NewType)) {
8290 if (Complain) {
8291 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8292 if (TemplateArgLoc.isValid()) {
8293 S.Diag(Loc: TemplateArgLoc,
8294 DiagID: diag::err_template_arg_template_params_mismatch);
8295 NextDiag = diag::note_template_nontype_parm_different_type;
8296 }
8297 S.Diag(Loc: NewNTTP->getLocation(), DiagID: NextDiag)
8298 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8299 S.Diag(Loc: OldNTTP->getLocation(),
8300 DiagID: diag::note_template_nontype_parm_prev_declaration)
8301 << OldNTTP->getType();
8302 }
8303 return false;
8304 }
8305 }
8306 }
8307 // For template template parameters, check the template parameter types.
8308 // The template parameter lists of template template
8309 // parameters must agree.
8310 else if (TemplateTemplateParmDecl *OldTTP =
8311 dyn_cast<TemplateTemplateParmDecl>(Val: Old)) {
8312 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(Val: New);
8313 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8314 return false;
8315 if (!S.TemplateParameterListsAreEqual(
8316 NewInstFrom, New: NewTTP->getTemplateParameters(), OldInstFrom,
8317 Old: OldTTP->getTemplateParameters(), Complain,
8318 Kind: (Kind == Sema::TPL_TemplateMatch
8319 ? Sema::TPL_TemplateTemplateParmMatch
8320 : Kind),
8321 TemplateArgLoc))
8322 return false;
8323 }
8324
8325 if (Kind != Sema::TPL_TemplateParamsEquivalent &&
8326 Kind != Sema::TPL_TemplateTemplateParmMatch &&
8327 !isa<TemplateTemplateParmDecl>(Val: Old)) {
8328 const Expr *NewC = nullptr, *OldC = nullptr;
8329
8330 if (isa<TemplateTypeParmDecl>(Val: New)) {
8331 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: New)->getTypeConstraint())
8332 NewC = TC->getImmediatelyDeclaredConstraint();
8333 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: Old)->getTypeConstraint())
8334 OldC = TC->getImmediatelyDeclaredConstraint();
8335 } else if (isa<NonTypeTemplateParmDecl>(Val: New)) {
8336 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: New)
8337 ->getPlaceholderTypeConstraint())
8338 NewC = E;
8339 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: Old)
8340 ->getPlaceholderTypeConstraint())
8341 OldC = E;
8342 } else
8343 llvm_unreachable("unexpected template parameter type");
8344
8345 auto Diagnose = [&] {
8346 S.Diag(Loc: NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8347 DiagID: diag::err_template_different_type_constraint);
8348 S.Diag(Loc: OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8349 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8350 };
8351
8352 if (!NewC != !OldC) {
8353 if (Complain)
8354 Diagnose();
8355 return false;
8356 }
8357
8358 if (NewC) {
8359 if (!S.AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldC, New: NewInstFrom,
8360 NewConstr: NewC)) {
8361 if (Complain)
8362 Diagnose();
8363 return false;
8364 }
8365 }
8366 }
8367
8368 return true;
8369}
8370
8371/// Diagnose a known arity mismatch when comparing template argument
8372/// lists.
8373static
8374void DiagnoseTemplateParameterListArityMismatch(Sema &S,
8375 TemplateParameterList *New,
8376 TemplateParameterList *Old,
8377 Sema::TemplateParameterListEqualKind Kind,
8378 SourceLocation TemplateArgLoc) {
8379 unsigned NextDiag = diag::err_template_param_list_different_arity;
8380 if (TemplateArgLoc.isValid()) {
8381 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8382 NextDiag = diag::note_template_param_list_different_arity;
8383 }
8384 S.Diag(Loc: New->getTemplateLoc(), DiagID: NextDiag)
8385 << (New->size() > Old->size())
8386 << (Kind != Sema::TPL_TemplateMatch)
8387 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8388 S.Diag(Loc: Old->getTemplateLoc(), DiagID: diag::note_template_prev_declaration)
8389 << (Kind != Sema::TPL_TemplateMatch)
8390 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8391}
8392
8393bool Sema::TemplateParameterListsAreEqual(
8394 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8395 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8396 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8397 if (Old->size() != New->size()) {
8398 if (Complain)
8399 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8400 TemplateArgLoc);
8401
8402 return false;
8403 }
8404
8405 // C++0x [temp.arg.template]p3:
8406 // A template-argument matches a template template-parameter (call it P)
8407 // when each of the template parameters in the template-parameter-list of
8408 // the template-argument's corresponding class template or alias template
8409 // (call it A) matches the corresponding template parameter in the
8410 // template-parameter-list of P. [...]
8411 TemplateParameterList::iterator NewParm = New->begin();
8412 TemplateParameterList::iterator NewParmEnd = New->end();
8413 for (TemplateParameterList::iterator OldParm = Old->begin(),
8414 OldParmEnd = Old->end();
8415 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8416 if (NewParm == NewParmEnd) {
8417 if (Complain)
8418 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8419 TemplateArgLoc);
8420 return false;
8421 }
8422 if (!MatchTemplateParameterKind(S&: *this, New: *NewParm, NewInstFrom, Old: *OldParm,
8423 OldInstFrom, Complain, Kind,
8424 TemplateArgLoc))
8425 return false;
8426 }
8427
8428 // Make sure we exhausted all of the arguments.
8429 if (NewParm != NewParmEnd) {
8430 if (Complain)
8431 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8432 TemplateArgLoc);
8433
8434 return false;
8435 }
8436
8437 if (Kind != TPL_TemplateParamsEquivalent) {
8438 const Expr *NewRC = New->getRequiresClause();
8439 const Expr *OldRC = Old->getRequiresClause();
8440
8441 auto Diagnose = [&] {
8442 Diag(Loc: NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8443 DiagID: diag::err_template_different_requires_clause);
8444 Diag(Loc: OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8445 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8446 };
8447
8448 if (!NewRC != !OldRC) {
8449 if (Complain)
8450 Diagnose();
8451 return false;
8452 }
8453
8454 if (NewRC) {
8455 if (!AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldRC, New: NewInstFrom,
8456 NewConstr: NewRC)) {
8457 if (Complain)
8458 Diagnose();
8459 return false;
8460 }
8461 }
8462 }
8463
8464 return true;
8465}
8466
8467bool
8468Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
8469 if (!S)
8470 return false;
8471
8472 // Find the nearest enclosing declaration scope.
8473 S = S->getDeclParent();
8474
8475 // C++ [temp.pre]p6: [P2096]
8476 // A template, explicit specialization, or partial specialization shall not
8477 // have C linkage.
8478 DeclContext *Ctx = S->getEntity();
8479 if (Ctx && Ctx->isExternCContext()) {
8480 SourceRange Range =
8481 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8482 ? TemplateParams->getParam(Idx: 0)->getSourceRange()
8483 : TemplateParams->getSourceRange();
8484 Diag(Loc: Range.getBegin(), DiagID: diag::err_template_linkage) << Range;
8485 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8486 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
8487 return true;
8488 }
8489 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8490
8491 // C++ [temp]p2:
8492 // A template-declaration can appear only as a namespace scope or
8493 // class scope declaration.
8494 // C++ [temp.expl.spec]p3:
8495 // An explicit specialization may be declared in any scope in which the
8496 // corresponding primary template may be defined.
8497 // C++ [temp.class.spec]p6: [P2096]
8498 // A partial specialization may be declared in any scope in which the
8499 // corresponding primary template may be defined.
8500 if (Ctx) {
8501 if (Ctx->isFileContext())
8502 return false;
8503 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Ctx)) {
8504 // C++ [temp.mem]p2:
8505 // A local class shall not have member templates.
8506
8507 // Trace the outer context chain, bypassing nested records and OpenMP
8508 // captured regions, to determine if the class in defined inside a
8509 // function or method.
8510 const DeclContext *OutCtx = RD->getDeclContext();
8511 while (isa_and_nonnull<CapturedDecl, CXXRecordDecl>(Val: OutCtx))
8512 OutCtx = OutCtx->getParent();
8513
8514 if (OutCtx && OutCtx->isFunctionOrMethod())
8515 return Diag(Loc: TemplateParams->getTemplateLoc(),
8516 DiagID: diag::err_template_inside_local_class)
8517 << TemplateParams->getSourceRange();
8518
8519 return false;
8520 }
8521 }
8522
8523 return Diag(Loc: TemplateParams->getTemplateLoc(),
8524 DiagID: diag::err_template_outside_namespace_or_class_scope)
8525 << TemplateParams->getSourceRange();
8526}
8527
8528/// Determine what kind of template specialization the given declaration
8529/// is.
8530static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8531 if (!D)
8532 return TSK_Undeclared;
8533
8534 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D))
8535 return Record->getTemplateSpecializationKind();
8536 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D))
8537 return Function->getTemplateSpecializationKind();
8538 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D))
8539 return Var->getTemplateSpecializationKind();
8540
8541 return TSK_Undeclared;
8542}
8543
8544/// Check whether a specialization is well-formed in the current
8545/// context.
8546///
8547/// This routine determines whether a template specialization can be declared
8548/// in the current context (C++ [temp.expl.spec]p2).
8549///
8550/// \param S the semantic analysis object for which this check is being
8551/// performed.
8552///
8553/// \param Specialized the entity being specialized or instantiated, which
8554/// may be a kind of template (class template, function template, etc.) or
8555/// a member of a class template (member function, static data member,
8556/// member class).
8557///
8558/// \param PrevDecl the previous declaration of this entity, if any.
8559///
8560/// \param Loc the location of the explicit specialization or instantiation of
8561/// this entity.
8562///
8563/// \param IsPartialSpecialization whether this is a partial specialization of
8564/// a class template.
8565///
8566/// \returns true if there was an error that we cannot recover from, false
8567/// otherwise.
8568static bool CheckTemplateSpecializationScope(Sema &S,
8569 NamedDecl *Specialized,
8570 NamedDecl *PrevDecl,
8571 SourceLocation Loc,
8572 bool IsPartialSpecialization) {
8573 // Keep these "kind" numbers in sync with the %select statements in the
8574 // various diagnostics emitted by this routine.
8575 int EntityKind = 0;
8576 if (isa<ClassTemplateDecl>(Val: Specialized))
8577 EntityKind = IsPartialSpecialization? 1 : 0;
8578 else if (isa<VarTemplateDecl>(Val: Specialized))
8579 EntityKind = IsPartialSpecialization ? 3 : 2;
8580 else if (isa<FunctionTemplateDecl>(Val: Specialized))
8581 EntityKind = 4;
8582 else if (isa<CXXMethodDecl>(Val: Specialized))
8583 EntityKind = 5;
8584 else if (isa<VarDecl>(Val: Specialized))
8585 EntityKind = 6;
8586 else if (isa<RecordDecl>(Val: Specialized))
8587 EntityKind = 7;
8588 else if (isa<EnumDecl>(Val: Specialized) && S.getLangOpts().CPlusPlus11)
8589 EntityKind = 8;
8590 else {
8591 S.Diag(Loc, DiagID: diag::err_template_spec_unknown_kind)
8592 << S.getLangOpts().CPlusPlus11;
8593 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8594 return true;
8595 }
8596
8597 // C++ [temp.expl.spec]p2:
8598 // An explicit specialization may be declared in any scope in which
8599 // the corresponding primary template may be defined.
8600 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8601 S.Diag(Loc, DiagID: diag::err_template_spec_decl_function_scope)
8602 << Specialized;
8603 return true;
8604 }
8605
8606 // C++ [temp.class.spec]p6:
8607 // A class template partial specialization may be declared in any
8608 // scope in which the primary template may be defined.
8609 DeclContext *SpecializedContext =
8610 Specialized->getDeclContext()->getRedeclContext();
8611 DeclContext *DC = S.CurContext->getRedeclContext();
8612
8613 // Make sure that this redeclaration (or definition) occurs in the same
8614 // scope or an enclosing namespace.
8615 if (!(DC->isFileContext() ? DC->Encloses(DC: SpecializedContext)
8616 : DC->Equals(DC: SpecializedContext))) {
8617 if (isa<TranslationUnitDecl>(Val: SpecializedContext))
8618 S.Diag(Loc, DiagID: diag::err_template_spec_redecl_global_scope)
8619 << EntityKind << Specialized;
8620 else {
8621 auto *ND = cast<NamedDecl>(Val: SpecializedContext);
8622 int Diag = diag::err_template_spec_redecl_out_of_scope;
8623 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8624 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8625 S.Diag(Loc, DiagID: Diag) << EntityKind << Specialized
8626 << ND << isa<CXXRecordDecl>(Val: ND);
8627 }
8628
8629 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8630
8631 // Don't allow specializing in the wrong class during error recovery.
8632 // Otherwise, things can go horribly wrong.
8633 if (DC->isRecord())
8634 return true;
8635 }
8636
8637 return false;
8638}
8639
8640static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8641 if (!E->isTypeDependent())
8642 return SourceLocation();
8643 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8644 Checker.TraverseStmt(S: E);
8645 if (Checker.MatchLoc.isInvalid())
8646 return E->getSourceRange();
8647 return Checker.MatchLoc;
8648}
8649
8650static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8651 if (!TL.getType()->isDependentType())
8652 return SourceLocation();
8653 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8654 Checker.TraverseTypeLoc(TL);
8655 if (Checker.MatchLoc.isInvalid())
8656 return TL.getSourceRange();
8657 return Checker.MatchLoc;
8658}
8659
8660/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8661/// that checks non-type template partial specialization arguments.
8662static bool CheckNonTypeTemplatePartialSpecializationArgs(
8663 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8664 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8665 bool HasError = false;
8666 for (unsigned I = 0; I != NumArgs; ++I) {
8667 if (Args[I].getKind() == TemplateArgument::Pack) {
8668 if (CheckNonTypeTemplatePartialSpecializationArgs(
8669 S, TemplateNameLoc, Param, Args: Args[I].pack_begin(),
8670 NumArgs: Args[I].pack_size(), IsDefaultArgument))
8671 return true;
8672
8673 continue;
8674 }
8675
8676 if (Args[I].getKind() != TemplateArgument::Expression)
8677 continue;
8678
8679 Expr *ArgExpr = Args[I].getAsExpr();
8680 if (ArgExpr->containsErrors()) {
8681 HasError = true;
8682 continue;
8683 }
8684
8685 // We can have a pack expansion of any of the bullets below.
8686 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Val: ArgExpr))
8687 ArgExpr = Expansion->getPattern();
8688
8689 // Strip off any implicit casts we added as part of type checking.
8690 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
8691 ArgExpr = ICE->getSubExpr();
8692
8693 // C++ [temp.class.spec]p8:
8694 // A non-type argument is non-specialized if it is the name of a
8695 // non-type parameter. All other non-type arguments are
8696 // specialized.
8697 //
8698 // Below, we check the two conditions that only apply to
8699 // specialized non-type arguments, so skip any non-specialized
8700 // arguments.
8701 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ArgExpr))
8702 if (isa<NonTypeTemplateParmDecl>(Val: DRE->getDecl()))
8703 continue;
8704
8705 if (isa<DependentTemplateIdExpr>(Val: ArgExpr))
8706 continue;
8707
8708 // C++ [temp.class.spec]p9:
8709 // Within the argument list of a class template partial
8710 // specialization, the following restrictions apply:
8711 // -- A partially specialized non-type argument expression
8712 // shall not involve a template parameter of the partial
8713 // specialization except when the argument expression is a
8714 // simple identifier.
8715 // -- The type of a template parameter corresponding to a
8716 // specialized non-type argument shall not be dependent on a
8717 // parameter of the specialization.
8718 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8719 // We implement a compromise between the original rules and DR1315:
8720 // -- A specialized non-type template argument shall not be
8721 // type-dependent and the corresponding template parameter
8722 // shall have a non-dependent type.
8723 SourceRange ParamUseRange =
8724 findTemplateParameterInType(Depth: Param->getDepth(), E: ArgExpr);
8725 if (ParamUseRange.isValid()) {
8726 if (IsDefaultArgument) {
8727 S.Diag(Loc: TemplateNameLoc,
8728 DiagID: diag::err_dependent_non_type_arg_in_partial_spec);
8729 S.Diag(Loc: ParamUseRange.getBegin(),
8730 DiagID: diag::note_dependent_non_type_default_arg_in_partial_spec)
8731 << ParamUseRange;
8732 } else {
8733 S.Diag(Loc: ParamUseRange.getBegin(),
8734 DiagID: diag::err_dependent_non_type_arg_in_partial_spec)
8735 << ParamUseRange;
8736 }
8737 return true;
8738 }
8739
8740 ParamUseRange = findTemplateParameter(
8741 Depth: Param->getDepth(), TL: Param->getTypeSourceInfo()->getTypeLoc());
8742 if (ParamUseRange.isValid()) {
8743 S.Diag(Loc: IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8744 DiagID: diag::err_dependent_typed_non_type_arg_in_partial_spec)
8745 << Param->getType();
8746 S.NoteTemplateParameterLocation(Decl: *Param);
8747 return true;
8748 }
8749 }
8750
8751 return HasError;
8752}
8753
8754bool Sema::CheckTemplatePartialSpecializationArgs(
8755 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8756 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8757 // We have to be conservative when checking a template in a dependent
8758 // context.
8759 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8760 return false;
8761
8762 TemplateParameterList *TemplateParams =
8763 PrimaryTemplate->getTemplateParameters();
8764 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8765 NonTypeTemplateParmDecl *Param
8766 = dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: I));
8767 if (!Param)
8768 continue;
8769
8770 if (CheckNonTypeTemplatePartialSpecializationArgs(S&: *this, TemplateNameLoc,
8771 Param, Args: &TemplateArgs[I],
8772 NumArgs: 1, IsDefaultArgument: I >= NumExplicit))
8773 return true;
8774 }
8775
8776 return false;
8777}
8778
8779DeclResult Sema::ActOnClassTemplateSpecialization(
8780 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8781 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8782 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8783 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8784 assert(TUK != TagUseKind::Reference && "References are not specializations");
8785
8786 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8787 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8788 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8789
8790 // Find the class template we're specializing
8791 TemplateName Name = TemplateId.Template.get();
8792 ClassTemplateDecl *ClassTemplate
8793 = dyn_cast_or_null<ClassTemplateDecl>(Val: Name.getAsTemplateDecl());
8794
8795 if (!ClassTemplate) {
8796 Diag(Loc: TemplateNameLoc, DiagID: diag::err_not_class_template_specialization)
8797 << (Name.getAsTemplateDecl() &&
8798 isa<TemplateTemplateParmDecl>(Val: Name.getAsTemplateDecl()));
8799 return true;
8800 }
8801
8802 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8803 auto Message = DSA->getMessage();
8804 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
8805 << ClassTemplate << !Message.empty() << Message;
8806 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
8807 }
8808
8809 if (S->isTemplateParamScope())
8810 EnterTemplatedContext(S, DC: ClassTemplate->getTemplatedDecl());
8811
8812 DeclContext *DC = ClassTemplate->getDeclContext();
8813
8814 bool isMemberSpecialization = false;
8815 bool isPartialSpecialization = false;
8816
8817 if (SS.isSet()) {
8818 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8819 diagnoseQualifiedDeclaration(SS, DC, Name: ClassTemplate->getDeclName(),
8820 Loc: TemplateNameLoc, TemplateId: &TemplateId,
8821 /*IsMemberSpecialization=*/false))
8822 return true;
8823 }
8824
8825 // Check the validity of the template headers that introduce this
8826 // template.
8827 // FIXME: We probably shouldn't complain about these headers for
8828 // friend declarations.
8829 bool Invalid = false;
8830 TemplateParameterList *TemplateParams =
8831 MatchTemplateParametersToScopeSpecifier(
8832 DeclStartLoc: KWLoc, DeclLoc: TemplateNameLoc, SS, TemplateId: &TemplateId, ParamLists: TemplateParameterLists,
8833 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
8834 if (Invalid)
8835 return true;
8836
8837 // Check that we can declare a template specialization here.
8838 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8839 return true;
8840
8841 if (TemplateParams && DC->isDependentContext()) {
8842 ContextRAII SavedContext(*this, DC);
8843 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
8844 return true;
8845 }
8846
8847 if (TemplateParams && TemplateParams->size() > 0) {
8848 isPartialSpecialization = true;
8849
8850 if (TUK == TagUseKind::Friend) {
8851 Diag(Loc: KWLoc, DiagID: diag::err_partial_specialization_friend)
8852 << SourceRange(LAngleLoc, RAngleLoc);
8853 return true;
8854 }
8855
8856 // C++ [temp.class.spec]p10:
8857 // The template parameter list of a specialization shall not
8858 // contain default template argument values.
8859 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8860 Decl *Param = TemplateParams->getParam(Idx: I);
8861 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
8862 if (TTP->hasDefaultArgument()) {
8863 Diag(Loc: TTP->getDefaultArgumentLoc(),
8864 DiagID: diag::err_default_arg_in_partial_spec);
8865 TTP->removeDefaultArgument();
8866 }
8867 } else if (NonTypeTemplateParmDecl *NTTP
8868 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
8869 if (NTTP->hasDefaultArgument()) {
8870 Diag(Loc: NTTP->getDefaultArgumentLoc(),
8871 DiagID: diag::err_default_arg_in_partial_spec)
8872 << NTTP->getDefaultArgument().getSourceRange();
8873 NTTP->removeDefaultArgument();
8874 }
8875 } else {
8876 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
8877 if (TTP->hasDefaultArgument()) {
8878 Diag(Loc: TTP->getDefaultArgument().getLocation(),
8879 DiagID: diag::err_default_arg_in_partial_spec)
8880 << TTP->getDefaultArgument().getSourceRange();
8881 TTP->removeDefaultArgument();
8882 }
8883 }
8884 }
8885 } else if (TemplateParams) {
8886 if (TUK == TagUseKind::Friend)
8887 Diag(Loc: KWLoc, DiagID: diag::err_template_spec_friend)
8888 << FixItHint::CreateRemoval(
8889 RemoveRange: SourceRange(TemplateParams->getTemplateLoc(),
8890 TemplateParams->getRAngleLoc()))
8891 << SourceRange(LAngleLoc, RAngleLoc);
8892 } else {
8893 assert(TUK == TagUseKind::Friend &&
8894 "should have a 'template<>' for this decl");
8895 }
8896
8897 // Check that the specialization uses the same tag kind as the
8898 // original template.
8899 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
8900 assert(Kind != TagTypeKind::Enum &&
8901 "Invalid enum tag in class template spec!");
8902 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(), NewTag: Kind,
8903 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
8904 Name: ClassTemplate->getIdentifier())) {
8905 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
8906 << ClassTemplate
8907 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
8908 Code: ClassTemplate->getTemplatedDecl()->getKindName());
8909 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
8910 DiagID: diag::note_previous_use);
8911 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8912 }
8913
8914 // Translate the parser's template argument list in our AST format.
8915 TemplateArgumentListInfo TemplateArgs =
8916 makeTemplateArgumentListInfo(S&: *this, TemplateId);
8917
8918 // Check for unexpanded parameter packs in any of the template arguments.
8919 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8920 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
8921 UPPC: isPartialSpecialization
8922 ? UPPC_PartialSpecialization
8923 : UPPC_ExplicitSpecialization))
8924 return true;
8925
8926 // Check that the template argument list is well-formed for this
8927 // template.
8928 CheckTemplateArgumentInfo CTAI;
8929 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
8930 /*DefaultArgs=*/{},
8931 /*PartialTemplateArgs=*/false, CTAI,
8932 /*UpdateArgsWithConversions=*/true))
8933 return true;
8934
8935 // Find the class template (partial) specialization declaration that
8936 // corresponds to these arguments.
8937 if (isPartialSpecialization) {
8938 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, PrimaryTemplate: ClassTemplate,
8939 NumExplicit: TemplateArgs.size(),
8940 TemplateArgs: CTAI.CanonicalConverted))
8941 return true;
8942
8943 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8944 // also do it during instantiation.
8945 if (!Name.isDependent() &&
8946 !TemplateSpecializationType::anyDependentTemplateArguments(
8947 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
8948 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
8949 << ClassTemplate->getDeclName();
8950 isPartialSpecialization = false;
8951 Invalid = true;
8952 }
8953 }
8954
8955 void *InsertPos = nullptr;
8956 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8957
8958 if (isPartialSpecialization)
8959 PrevDecl = ClassTemplate->findPartialSpecialization(
8960 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertPos);
8961 else
8962 PrevDecl =
8963 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
8964
8965 ClassTemplateSpecializationDecl *Specialization = nullptr;
8966
8967 // Check whether we can declare a class template specialization in
8968 // the current scope.
8969 if (TUK != TagUseKind::Friend &&
8970 CheckTemplateSpecializationScope(S&: *this, Specialized: ClassTemplate, PrevDecl,
8971 Loc: TemplateNameLoc,
8972 IsPartialSpecialization: isPartialSpecialization))
8973 return true;
8974
8975 if (!isPartialSpecialization) {
8976 // Create a new class template specialization declaration node for
8977 // this explicit specialization or friend declaration.
8978 Specialization = ClassTemplateSpecializationDecl::Create(
8979 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
8980 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
8981 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8982 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
8983 if (TemplateParameterLists.size() > 0) {
8984 Specialization->setTemplateParameterListsInfo(Context,
8985 TPLists: TemplateParameterLists);
8986 }
8987
8988 if (!PrevDecl)
8989 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
8990 } else {
8991 CanQualType CanonType = CanQualType::CreateUnsafe(
8992 Other: Context.getCanonicalTemplateSpecializationType(
8993 Keyword: ElaboratedTypeKeyword::None,
8994 T: TemplateName(ClassTemplate->getCanonicalDecl()),
8995 CanonicalArgs: CTAI.CanonicalConverted));
8996 if (Context.hasSameType(
8997 T1: CanonType,
8998 T2: ClassTemplate->getCanonicalInjectedSpecializationType(Ctx: Context)) &&
8999 (!Context.getLangOpts().CPlusPlus20 ||
9000 !TemplateParams->hasAssociatedConstraints())) {
9001 // C++ [temp.class.spec]p9b3:
9002 //
9003 // -- The argument list of the specialization shall not be identical
9004 // to the implicit argument list of the primary template.
9005 //
9006 // This rule has since been removed, because it's redundant given DR1495,
9007 // but we keep it because it produces better diagnostics and recovery.
9008 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
9009 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
9010 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
9011 return CheckClassTemplate(
9012 S, TagSpec, TUK, KWLoc, SS, Name: ClassTemplate->getIdentifier(),
9013 NameLoc: TemplateNameLoc, Attr, TemplateParams, AS: AS_none,
9014 /*ModulePrivateLoc=*/SourceLocation(),
9015 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
9016 OuterTemplateParamLists: TemplateParameterLists.data(), IsMemberSpecialization: isMemberSpecialization);
9017 }
9018
9019 // Create a new class template partial specialization declaration node.
9020 ClassTemplatePartialSpecializationDecl *PrevPartial =
9021 cast_or_null<ClassTemplatePartialSpecializationDecl>(Val: PrevDecl);
9022 ClassTemplatePartialSpecializationDecl *Partial =
9023 ClassTemplatePartialSpecializationDecl::Create(
9024 Context, TK: Kind, DC, StartLoc: KWLoc, IdLoc: TemplateNameLoc, Params: TemplateParams,
9025 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, CanonInjectedTST: CanonType, PrevDecl: PrevPartial);
9026 Partial->setTemplateArgsAsWritten(TemplateArgs);
9027 SetNestedNameSpecifier(S&: *this, T: Partial, SS);
9028 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9029 Partial->setTemplateParameterListsInfo(
9030 Context, TPLists: TemplateParameterLists.drop_back(N: 1));
9031 }
9032
9033 if (!PrevPartial)
9034 ClassTemplate->AddPartialSpecialization(D: Partial, InsertPos);
9035 Specialization = Partial;
9036
9037 // If we are providing an explicit specialization of a member class
9038 // template specialization, make a note of that.
9039 if (isMemberSpecialization)
9040 Partial->setMemberSpecialization();
9041
9042 CheckTemplatePartialSpecialization(Partial);
9043 }
9044
9045 // C++ [temp.expl.spec]p6:
9046 // If a template, a member template or the member of a class template is
9047 // explicitly specialized then that specialization shall be declared
9048 // before the first use of that specialization that would cause an implicit
9049 // instantiation to take place, in every translation unit in which such a
9050 // use occurs; no diagnostic is required.
9051 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9052 bool Okay = false;
9053 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9054 // Is there any previous explicit specialization declaration?
9055 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9056 Okay = true;
9057 break;
9058 }
9059 }
9060
9061 if (!Okay) {
9062 SourceRange Range(TemplateNameLoc, RAngleLoc);
9063 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
9064 << Context.getCanonicalTagType(TD: Specialization) << Range;
9065
9066 Diag(Loc: PrevDecl->getPointOfInstantiation(),
9067 DiagID: diag::note_instantiation_required_here)
9068 << (PrevDecl->getTemplateSpecializationKind()
9069 != TSK_ImplicitInstantiation);
9070 return true;
9071 }
9072 }
9073
9074 // If this is not a friend, note that this is an explicit specialization.
9075 if (TUK != TagUseKind::Friend)
9076 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9077
9078 // Check that this isn't a redefinition of this specialization.
9079 if (TUK == TagUseKind::Definition) {
9080 RecordDecl *Def = Specialization->getDefinition();
9081 NamedDecl *Hidden = nullptr;
9082 bool HiddenDefVisible = false;
9083 if (Def && SkipBody &&
9084 isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible)) {
9085 SkipBody->ShouldSkip = true;
9086 SkipBody->Previous = Def;
9087 if (!HiddenDefVisible && Hidden)
9088 makeMergedDefinitionVisible(ND: Hidden);
9089 } else if (Def) {
9090 SourceRange Range(TemplateNameLoc, RAngleLoc);
9091 Diag(Loc: TemplateNameLoc, DiagID: diag::err_redefinition) << Specialization << Range;
9092 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
9093 Specialization->setInvalidDecl();
9094 return true;
9095 }
9096 }
9097
9098 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
9099 ProcessAPINotes(D: Specialization);
9100
9101 // Add alignment attributes if necessary; these attributes are checked when
9102 // the ASTContext lays out the structure.
9103 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9104 if (LangOpts.HLSL)
9105 Specialization->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
9106 AddAlignmentAttributesForRecord(RD: Specialization);
9107 AddMsStructLayoutForRecord(RD: Specialization);
9108 }
9109
9110 if (ModulePrivateLoc.isValid())
9111 Diag(Loc: Specialization->getLocation(), DiagID: diag::err_module_private_specialization)
9112 << (isPartialSpecialization? 1 : 0)
9113 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
9114
9115 // C++ [temp.expl.spec]p9:
9116 // A template explicit specialization is in the scope of the
9117 // namespace in which the template was defined.
9118 //
9119 // We actually implement this paragraph where we set the semantic
9120 // context (in the creation of the ClassTemplateSpecializationDecl),
9121 // but we also maintain the lexical context where the actual
9122 // definition occurs.
9123 Specialization->setLexicalDeclContext(CurContext);
9124
9125 // We may be starting the definition of this specialization.
9126 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9127 Specialization->startDefinition();
9128
9129 if (TUK == TagUseKind::Friend) {
9130 CanQualType CanonType = Context.getCanonicalTagType(TD: Specialization);
9131 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9132 Keyword: ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9133 QualifierLoc: SS.getWithLocInContext(Context),
9134 /*TemplateKeywordLoc=*/SourceLocation(), T: Name, TLoc: TemplateNameLoc,
9135 SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted, Canon: CanonType);
9136
9137 // Build the fully-sugared type for this class template
9138 // specialization as the user wrote in the specialization
9139 // itself. This means that we'll pretty-print the type retrieved
9140 // from the specialization's declaration the way that the user
9141 // actually wrote the specialization, rather than formatting the
9142 // name based on the "canonical" representation used to store the
9143 // template arguments in the specialization.
9144 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext,
9145 L: TemplateNameLoc,
9146 Friend: WrittenTy,
9147 /*FIXME:*/FriendL: KWLoc);
9148 Friend->setAccess(AS_public);
9149 CurContext->addDecl(D: Friend);
9150 } else {
9151 // Add the specialization into its lexical context, so that it can
9152 // be seen when iterating through the list of declarations in that
9153 // context. However, specializations are not found by name lookup.
9154 CurContext->addDecl(D: Specialization);
9155 }
9156
9157 if (SkipBody && SkipBody->ShouldSkip)
9158 return SkipBody->Previous;
9159
9160 Specialization->setInvalidDecl(Invalid);
9161 inferGslOwnerPointerAttribute(Record: Specialization);
9162 return Specialization;
9163}
9164
9165Decl *Sema::ActOnTemplateDeclarator(Scope *S,
9166 MultiTemplateParamsArg TemplateParameterLists,
9167 Declarator &D) {
9168 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9169 ActOnDocumentableDecl(D: NewDecl);
9170 return NewDecl;
9171}
9172
9173ConceptDecl *Sema::ActOnStartConceptDefinition(
9174 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9175 const IdentifierInfo *Name, SourceLocation NameLoc) {
9176 DeclContext *DC = CurContext;
9177
9178 if (!DC->getRedeclContext()->isFileContext()) {
9179 Diag(Loc: NameLoc,
9180 DiagID: diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9181 return nullptr;
9182 }
9183
9184 if (TemplateParameterLists.size() > 1) {
9185 Diag(Loc: NameLoc, DiagID: diag::err_concept_extra_headers);
9186 return nullptr;
9187 }
9188
9189 TemplateParameterList *Params = TemplateParameterLists.front();
9190
9191 if (Params->size() == 0) {
9192 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_parameters);
9193 return nullptr;
9194 }
9195
9196 // Ensure that the parameter pack, if present, is the last parameter in the
9197 // template.
9198 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9199 ParamEnd = Params->end();
9200 ParamIt != ParamEnd; ++ParamIt) {
9201 Decl const *Param = *ParamIt;
9202 if (Param->isParameterPack()) {
9203 if (++ParamIt == ParamEnd)
9204 break;
9205 Diag(Loc: Param->getLocation(),
9206 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
9207 return nullptr;
9208 }
9209 }
9210
9211 ConceptDecl *NewDecl =
9212 ConceptDecl::Create(C&: Context, DC, L: NameLoc, Name, Params);
9213
9214 if (NewDecl->hasAssociatedConstraints()) {
9215 // C++2a [temp.concept]p4:
9216 // A concept shall not have associated constraints.
9217 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_associated_constraints);
9218 NewDecl->setInvalidDecl();
9219 }
9220
9221 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9222 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9223 forRedeclarationInCurContext());
9224 LookupName(R&: Previous, S);
9225 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9226 /*AllowInlineNamespace*/ false);
9227
9228 // We cannot properly handle redeclarations until we parse the constraint
9229 // expression, so only inject the name if we are sure we are not redeclaring a
9230 // symbol
9231 if (Previous.empty())
9232 PushOnScopeChains(D: NewDecl, S, AddToContext: true);
9233
9234 return NewDecl;
9235}
9236
9237static bool RemoveLookupResult(LookupResult &R, NamedDecl *C) {
9238 bool Found = false;
9239 LookupResult::Filter F = R.makeFilter();
9240 while (F.hasNext()) {
9241 NamedDecl *D = F.next();
9242 if (D == C) {
9243 F.erase();
9244 Found = true;
9245 break;
9246 }
9247 }
9248 F.done();
9249 return Found;
9250}
9251
9252ConceptDecl *
9253Sema::ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
9254 Expr *ConstraintExpr,
9255 const ParsedAttributesView &Attrs) {
9256 assert(!C->hasDefinition() && "Concept already defined");
9257 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr)) {
9258 C->setInvalidDecl();
9259 return nullptr;
9260 }
9261 C->setDefinition(ConstraintExpr);
9262 ProcessDeclAttributeList(S, D: C, AttrList: Attrs);
9263
9264 // Check for conflicting previous declaration.
9265 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9266 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9267 forRedeclarationInCurContext());
9268 LookupName(R&: Previous, S);
9269 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9270 /*AllowInlineNamespace*/ false);
9271 bool WasAlreadyAdded = RemoveLookupResult(R&: Previous, C);
9272 bool AddToScope = true;
9273 CheckConceptRedefinition(NewDecl: C, Previous, AddToScope);
9274
9275 ActOnDocumentableDecl(D: C);
9276 if (!WasAlreadyAdded && AddToScope)
9277 PushOnScopeChains(D: C, S);
9278
9279 return C;
9280}
9281
9282void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
9283 LookupResult &Previous, bool &AddToScope) {
9284 AddToScope = true;
9285
9286 if (Previous.empty())
9287 return;
9288
9289 auto *OldConcept = dyn_cast<ConceptDecl>(Val: Previous.getRepresentativeDecl()->getUnderlyingDecl());
9290 if (!OldConcept) {
9291 auto *Old = Previous.getRepresentativeDecl();
9292 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_kind)
9293 << NewDecl->getDeclName();
9294 notePreviousDefinition(Old, New: NewDecl->getLocation());
9295 AddToScope = false;
9296 return;
9297 }
9298 // Check if we can merge with a concept declaration.
9299 bool IsSame = Context.isSameEntity(X: NewDecl, Y: OldConcept);
9300 if (!IsSame) {
9301 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_concept)
9302 << NewDecl->getDeclName();
9303 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9304 AddToScope = false;
9305 return;
9306 }
9307 if (hasReachableDefinition(D: OldConcept) &&
9308 IsRedefinitionInModule(New: NewDecl, Old: OldConcept)) {
9309 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition)
9310 << NewDecl->getDeclName();
9311 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9312 AddToScope = false;
9313 return;
9314 }
9315 if (!Previous.isSingleResult()) {
9316 // FIXME: we should produce an error in case of ambig and failed lookups.
9317 // Other decls (e.g. namespaces) also have this shortcoming.
9318 return;
9319 }
9320 // We unwrap canonical decl late to check for module visibility.
9321 Context.setPrimaryMergedDecl(D: NewDecl, Primary: OldConcept->getCanonicalDecl());
9322}
9323
9324bool Sema::CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc) {
9325 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Val: Concept);
9326 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9327 Diag(Loc, DiagID: diag::err_recursive_concept) << CE;
9328 Diag(Loc: CE->getLocation(), DiagID: diag::note_declared_at);
9329 CE->setInvalidDecl();
9330 return true;
9331 }
9332 // Concept template parameters don't have a definition and can't
9333 // be defined recursively.
9334 return false;
9335}
9336
9337/// \brief Strips various properties off an implicit instantiation
9338/// that has just been explicitly specialized.
9339static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9340 if (MinGW || (isa<FunctionDecl>(Val: D) &&
9341 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization()))
9342 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9343
9344 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D))
9345 FD->setInlineSpecified(false);
9346}
9347
9348/// Create an ExplicitInstantiationDecl to record source-location info for an
9349/// explicit template instantiation statement, and add it to \p CurContext.
9350///
9351/// For class templates / nested classes, the caller should build a
9352/// TypeSourceInfo that encodes the tag keyword, qualifier, name, and template
9353/// arguments, and pass empty QualifierLoc / null ArgsAsWritten.
9354///
9355/// For function / variable templates, the caller should pass TypeAsWritten for
9356/// the declared type, and separate QualifierLoc / ArgsAsWritten.
9357static void addExplicitInstantiationDecl(
9358 ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec,
9359 SourceLocation ExternLoc, SourceLocation TemplateLoc,
9360 NestedNameSpecifierLoc QualifierLoc,
9361 const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc,
9362 TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK) {
9363 auto *EID = ExplicitInstantiationDecl::Create(
9364 C&: Context, DC: CurContext, Specialization: Spec, ExternLoc, TemplateLoc, QualifierLoc,
9365 ArgsAsWritten, NameLoc, TypeAsWritten, TSK);
9366 Context.addExplicitInstantiationDecl(Spec, EID);
9367 CurContext->addDecl(D: EID);
9368}
9369
9370/// Compute the diagnostic location for an explicit instantiation
9371// declaration or definition.
9372static SourceLocation
9373DiagLocForExplicitInstantiation(NamedDecl *D,
9374 SourceLocation PointOfInstantiation) {
9375 for (auto *EID : D->getASTContext().getExplicitInstantiationDecls(Spec: D))
9376 if (EID->getTemplateSpecializationKind() ==
9377 TSK_ExplicitInstantiationDefinition)
9378 return EID->getTemplateLoc();
9379
9380 // Explicit instantiations following a specialization have no effect and
9381 // hence no PointOfInstantiation. In that case, walk decl backwards
9382 // until a valid name loc is found.
9383 SourceLocation PrevDiagLoc = PointOfInstantiation;
9384 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9385 Prev = Prev->getPreviousDecl()) {
9386 PrevDiagLoc = Prev->getLocation();
9387 }
9388 assert(PrevDiagLoc.isValid() &&
9389 "Explicit instantiation without point of instantiation?");
9390 return PrevDiagLoc;
9391}
9392
9393bool
9394Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
9395 TemplateSpecializationKind NewTSK,
9396 NamedDecl *PrevDecl,
9397 TemplateSpecializationKind PrevTSK,
9398 SourceLocation PrevPointOfInstantiation,
9399 bool &HasNoEffect) {
9400 HasNoEffect = false;
9401
9402 switch (NewTSK) {
9403 case TSK_Undeclared:
9404 case TSK_ImplicitInstantiation:
9405 assert(
9406 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9407 "previous declaration must be implicit!");
9408 return false;
9409
9410 case TSK_ExplicitSpecialization:
9411 switch (PrevTSK) {
9412 case TSK_Undeclared:
9413 case TSK_ExplicitSpecialization:
9414 // Okay, we're just specializing something that is either already
9415 // explicitly specialized or has merely been mentioned without any
9416 // instantiation.
9417 return false;
9418
9419 case TSK_ImplicitInstantiation:
9420 if (PrevPointOfInstantiation.isInvalid()) {
9421 // The declaration itself has not actually been instantiated, so it is
9422 // still okay to specialize it.
9423 StripImplicitInstantiation(
9424 D: PrevDecl, MinGW: Context.getTargetInfo().getTriple().isOSCygMing());
9425 return false;
9426 }
9427 // Fall through
9428 [[fallthrough]];
9429
9430 case TSK_ExplicitInstantiationDeclaration:
9431 case TSK_ExplicitInstantiationDefinition:
9432 assert((PrevTSK == TSK_ImplicitInstantiation ||
9433 PrevPointOfInstantiation.isValid()) &&
9434 "Explicit instantiation without point of instantiation?");
9435
9436 // C++ [temp.expl.spec]p6:
9437 // If a template, a member template or the member of a class template
9438 // is explicitly specialized then that specialization shall be declared
9439 // before the first use of that specialization that would cause an
9440 // implicit instantiation to take place, in every translation unit in
9441 // which such a use occurs; no diagnostic is required.
9442 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9443 // Is there any previous explicit specialization declaration?
9444 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization)
9445 return false;
9446 }
9447
9448 Diag(Loc: NewLoc, DiagID: diag::err_specialization_after_instantiation)
9449 << PrevDecl;
9450 Diag(Loc: PrevPointOfInstantiation, DiagID: diag::note_instantiation_required_here)
9451 << (PrevTSK != TSK_ImplicitInstantiation);
9452
9453 return true;
9454 }
9455 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9456
9457 case TSK_ExplicitInstantiationDeclaration:
9458 switch (PrevTSK) {
9459 case TSK_ExplicitInstantiationDeclaration:
9460 // This explicit instantiation declaration is redundant (that's okay).
9461 HasNoEffect = true;
9462 return false;
9463
9464 case TSK_Undeclared:
9465 case TSK_ImplicitInstantiation:
9466 // We're explicitly instantiating something that may have already been
9467 // implicitly instantiated; that's fine.
9468 return false;
9469
9470 case TSK_ExplicitSpecialization:
9471 // C++0x [temp.explicit]p4:
9472 // For a given set of template parameters, if an explicit instantiation
9473 // of a template appears after a declaration of an explicit
9474 // specialization for that template, the explicit instantiation has no
9475 // effect.
9476 HasNoEffect = true;
9477 return false;
9478
9479 case TSK_ExplicitInstantiationDefinition:
9480 // C++0x [temp.explicit]p10:
9481 // If an entity is the subject of both an explicit instantiation
9482 // declaration and an explicit instantiation definition in the same
9483 // translation unit, the definition shall follow the declaration.
9484 Diag(Loc: NewLoc,
9485 DiagID: diag::err_explicit_instantiation_declaration_after_definition);
9486
9487 // Explicit instantiations following a specialization have no effect and
9488 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9489 // until a valid name loc is found.
9490 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9491 DiagID: diag::note_explicit_instantiation_definition_here);
9492 HasNoEffect = true;
9493 return false;
9494 }
9495 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9496
9497 case TSK_ExplicitInstantiationDefinition:
9498 switch (PrevTSK) {
9499 case TSK_Undeclared:
9500 case TSK_ImplicitInstantiation:
9501 // We're explicitly instantiating something that may have already been
9502 // implicitly instantiated; that's fine.
9503 return false;
9504
9505 case TSK_ExplicitSpecialization:
9506 // C++ DR 259, C++0x [temp.explicit]p4:
9507 // For a given set of template parameters, if an explicit
9508 // instantiation of a template appears after a declaration of
9509 // an explicit specialization for that template, the explicit
9510 // instantiation has no effect.
9511 Diag(Loc: NewLoc, DiagID: diag::warn_explicit_instantiation_after_specialization)
9512 << PrevDecl;
9513 Diag(Loc: PrevDecl->getLocation(),
9514 DiagID: diag::note_previous_template_specialization);
9515 HasNoEffect = true;
9516 return false;
9517
9518 case TSK_ExplicitInstantiationDeclaration:
9519 // We're explicitly instantiating a definition for something for which we
9520 // were previously asked to suppress instantiations. That's fine.
9521
9522 // C++0x [temp.explicit]p4:
9523 // For a given set of template parameters, if an explicit instantiation
9524 // of a template appears after a declaration of an explicit
9525 // specialization for that template, the explicit instantiation has no
9526 // effect.
9527 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9528 // Is there any previous explicit specialization declaration?
9529 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9530 HasNoEffect = true;
9531 break;
9532 }
9533 }
9534
9535 return false;
9536
9537 case TSK_ExplicitInstantiationDefinition:
9538 // C++0x [temp.spec]p5:
9539 // For a given template and a given set of template-arguments,
9540 // - an explicit instantiation definition shall appear at most once
9541 // in a program,
9542
9543 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9544 Diag(Loc: NewLoc, DiagID: (getLangOpts().MSVCCompat)
9545 ? diag::ext_explicit_instantiation_duplicate
9546 : diag::err_explicit_instantiation_duplicate)
9547 << PrevDecl;
9548 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9549 DiagID: diag::note_previous_explicit_instantiation);
9550 HasNoEffect = true;
9551 return false;
9552 }
9553 }
9554
9555 llvm_unreachable("Missing specialization/instantiation case?");
9556}
9557
9558bool Sema::CheckDependentFunctionTemplateSpecialization(
9559 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9560 LookupResult &Previous) {
9561 // Remove anything from Previous that isn't a function template in
9562 // the correct context.
9563 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9564 LookupResult::Filter F = Previous.makeFilter();
9565 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9566 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9567 while (F.hasNext()) {
9568 NamedDecl *D = F.next()->getUnderlyingDecl();
9569 if (!isa<FunctionTemplateDecl>(Val: D)) {
9570 F.erase();
9571 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAFunctionTemplate, y&: D));
9572 continue;
9573 }
9574
9575 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9576 NS: D->getDeclContext()->getRedeclContext())) {
9577 F.erase();
9578 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAMemberOfEnclosing, y&: D));
9579 continue;
9580 }
9581 }
9582 F.done();
9583
9584 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9585 if (Previous.empty()) {
9586 NestedNameSpecifier FriendQualifier = FD->getQualifier();
9587 if (IsFriend && FriendQualifier.isDependent() &&
9588 FriendQualifier.getKind() == NestedNameSpecifier::Kind::Type &&
9589 FriendQualifier.getAsType()->getAs<TemplateSpecializationType>()) {
9590 FD->setDependentTemplateSpecialization(
9591 Context, Templates: Previous.asUnresolvedSet(), TemplateArgs: ExplicitTemplateArgs);
9592 return false;
9593 }
9594
9595 Diag(Loc: FD->getLocation(), DiagID: diag::err_dependent_function_template_spec_no_match)
9596 << IsFriend;
9597 for (auto &P : DiscardedCandidates)
9598 Diag(Loc: P.second->getLocation(),
9599 DiagID: diag::note_dependent_function_template_spec_discard_reason)
9600 << P.first << IsFriend;
9601 return true;
9602 }
9603
9604 FD->setDependentTemplateSpecialization(Context, Templates: Previous.asUnresolvedSet(),
9605 TemplateArgs: ExplicitTemplateArgs);
9606 return false;
9607}
9608
9609bool Sema::CheckFunctionTemplateSpecialization(
9610 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9611 LookupResult &Previous, bool QualifiedFriend) {
9612 // The set of function template specializations that could match this
9613 // explicit function template specialization.
9614 UnresolvedSet<8> Candidates;
9615 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9616 /*ForTakingAddress=*/false);
9617
9618 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9619 ConvertedTemplateArgs;
9620
9621 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9622 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9623 I != E; ++I) {
9624 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9625 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Ovl)) {
9626 // Only consider templates found within the same semantic lookup scope as
9627 // FD.
9628 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9629 NS: Ovl->getDeclContext()->getRedeclContext()))
9630 continue;
9631
9632 QualType FT = FD->getType();
9633 // C++11 [dcl.constexpr]p8:
9634 // A constexpr specifier for a non-static member function that is not
9635 // a constructor declares that member function to be const.
9636 //
9637 // When matching a constexpr member function template specialization
9638 // against the primary template, we don't yet know whether the
9639 // specialization has an implicit 'const' (because we don't know whether
9640 // it will be a static member function until we know which template it
9641 // specializes). This rule was removed in C++14.
9642 if (auto *NewMD = dyn_cast<CXXMethodDecl>(Val: FD);
9643 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9644 !isa<CXXConstructorDecl, CXXDestructorDecl>(Val: NewMD)) {
9645 auto *OldMD = dyn_cast<CXXMethodDecl>(Val: FunTmpl->getTemplatedDecl());
9646 if (OldMD && OldMD->isConst()) {
9647 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9648 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9649 EPI.TypeQuals.addConst();
9650 FT = Context.getFunctionType(ResultTy: FPT->getReturnType(),
9651 Args: FPT->getParamTypes(), EPI);
9652 }
9653 }
9654
9655 TemplateArgumentListInfo Args;
9656 if (ExplicitTemplateArgs)
9657 Args = *ExplicitTemplateArgs;
9658
9659 // C++ [temp.expl.spec]p11:
9660 // A trailing template-argument can be left unspecified in the
9661 // template-id naming an explicit function template specialization
9662 // provided it can be deduced from the function argument type.
9663 // Perform template argument deduction to determine whether we may be
9664 // specializing this template.
9665 // FIXME: It is somewhat wasteful to build
9666 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9667 FunctionDecl *Specialization = nullptr;
9668 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9669 FunctionTemplate: cast<FunctionTemplateDecl>(Val: FunTmpl->getFirstDecl()),
9670 ExplicitTemplateArgs: ExplicitTemplateArgs ? &Args : nullptr, ArgFunctionType: FT, Specialization, Info);
9671 TDK != TemplateDeductionResult::Success) {
9672 // Template argument deduction failed; record why it failed, so
9673 // that we can provide nifty diagnostics.
9674 FailedCandidates.addCandidate().set(
9675 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9676 Info: MakeDeductionFailureInfo(Context, TDK, Info));
9677 (void)TDK;
9678 continue;
9679 }
9680
9681 // Target attributes are part of the cuda function signature, so
9682 // the deduced template's cuda target must match that of the
9683 // specialization. Given that C++ template deduction does not
9684 // take target attributes into account, we reject candidates
9685 // here that have a different target.
9686 if (LangOpts.CUDA &&
9687 CUDA().IdentifyTarget(D: Specialization,
9688 /* IgnoreImplicitHDAttr = */ true) !=
9689 CUDA().IdentifyTarget(D: FD, /* IgnoreImplicitHDAttr = */ true)) {
9690 FailedCandidates.addCandidate().set(
9691 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9692 Info: MakeDeductionFailureInfo(
9693 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
9694 continue;
9695 }
9696
9697 // Record this candidate.
9698 if (ExplicitTemplateArgs)
9699 ConvertedTemplateArgs[Specialization] = std::move(Args);
9700 Candidates.addDecl(D: Specialization, AS: I.getAccess());
9701 }
9702 }
9703
9704 // For a qualified friend declaration (with no explicit marker to indicate
9705 // that a template specialization was intended), note all (template and
9706 // non-template) candidates.
9707 if (QualifiedFriend && Candidates.empty()) {
9708 Diag(Loc: FD->getLocation(), DiagID: diag::err_qualified_friend_no_match)
9709 << FD->getDeclName() << FDLookupContext;
9710 // FIXME: We should form a single candidate list and diagnose all
9711 // candidates at once, to get proper sorting and limiting.
9712 for (auto *OldND : Previous) {
9713 if (auto *OldFD = dyn_cast<FunctionDecl>(Val: OldND->getUnderlyingDecl()))
9714 NoteOverloadCandidate(Found: OldND, Fn: OldFD, RewriteKind: CRK_None, DestType: FD->getType(), TakingAddress: false);
9715 }
9716 FailedCandidates.NoteCandidates(S&: *this, Loc: FD->getLocation());
9717 return true;
9718 }
9719
9720 // Find the most specialized function template.
9721 UnresolvedSetIterator Result = getMostSpecialized(
9722 SBegin: Candidates.begin(), SEnd: Candidates.end(), FailedCandidates, Loc: FD->getLocation(),
9723 NoneDiag: PDiag(DiagID: diag::err_function_template_spec_no_match) << FD->getDeclName(),
9724 AmbigDiag: PDiag(DiagID: diag::err_function_template_spec_ambiguous)
9725 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9726 CandidateDiag: PDiag(DiagID: diag::note_function_template_spec_matched));
9727
9728 if (Result == Candidates.end())
9729 return true;
9730
9731 // Ignore access information; it doesn't figure into redeclaration checking.
9732 FunctionDecl *Specialization = cast<FunctionDecl>(Val: *Result);
9733
9734 if (const auto *PT = Specialization->getPrimaryTemplate();
9735 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9736 auto Message = DSA->getMessage();
9737 Diag(Loc: FD->getLocation(), DiagID: diag::warn_invalid_specialization)
9738 << PT << !Message.empty() << Message;
9739 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
9740 }
9741
9742 // C++23 [except.spec]p13:
9743 // An exception specification is considered to be needed when:
9744 // - [...]
9745 // - the exception specification is compared to that of another declaration
9746 // (e.g., an explicit specialization or an overriding virtual function);
9747 // - [...]
9748 //
9749 // The exception specification of a defaulted function is evaluated as
9750 // described above only when needed; similarly, the noexcept-specifier of a
9751 // specialization of a function template or member function of a class
9752 // template is instantiated only when needed.
9753 //
9754 // The standard doesn't specify what the "comparison with another declaration"
9755 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9756 // not state which properties of an explicit specialization must match the
9757 // primary template.
9758 //
9759 // We assume that an explicit specialization must correspond with (per
9760 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9761 // the declaration produced by substitution into the function template.
9762 //
9763 // Since the determination whether two function declarations correspond does
9764 // not consider exception specification, we only need to instantiate it once
9765 // we determine the primary template when comparing types per
9766 // [basic.link]p11.1.
9767 auto *SpecializationFPT =
9768 Specialization->getType()->castAs<FunctionProtoType>();
9769 // If the function has a dependent exception specification, resolve it after
9770 // we have selected the primary template so we can check whether it matches.
9771 if (getLangOpts().CPlusPlus17 &&
9772 isUnresolvedExceptionSpec(ESpecType: SpecializationFPT->getExceptionSpecType()) &&
9773 !ResolveExceptionSpec(Loc: FD->getLocation(), FPT: SpecializationFPT))
9774 return true;
9775
9776 FunctionTemplateSpecializationInfo *SpecInfo
9777 = Specialization->getTemplateSpecializationInfo();
9778 assert(SpecInfo && "Function template specialization info missing?");
9779
9780 // Note: do not overwrite location info if previous template
9781 // specialization kind was explicit.
9782 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9783 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9784 Specialization->setLocation(FD->getLocation());
9785 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9786 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9787 // function can differ from the template declaration with respect to
9788 // the constexpr specifier.
9789 // FIXME: We need an update record for this AST mutation.
9790 // FIXME: What if there are multiple such prior declarations (for instance,
9791 // from different modules)?
9792 Specialization->setConstexprKind(FD->getConstexprKind());
9793 }
9794
9795 // FIXME: Check if the prior specialization has a point of instantiation.
9796 // If so, we have run afoul of .
9797
9798 // If this is a friend declaration, then we're not really declaring
9799 // an explicit specialization.
9800 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9801
9802 // Check the scope of this explicit specialization.
9803 if (!isFriend &&
9804 CheckTemplateSpecializationScope(S&: *this,
9805 Specialized: Specialization->getPrimaryTemplate(),
9806 PrevDecl: Specialization, Loc: FD->getLocation(),
9807 IsPartialSpecialization: false))
9808 return true;
9809
9810 // C++ [temp.expl.spec]p6:
9811 // If a template, a member template or the member of a class template is
9812 // explicitly specialized then that specialization shall be declared
9813 // before the first use of that specialization that would cause an implicit
9814 // instantiation to take place, in every translation unit in which such a
9815 // use occurs; no diagnostic is required.
9816 bool HasNoEffect = false;
9817 if (!isFriend &&
9818 CheckSpecializationInstantiationRedecl(NewLoc: FD->getLocation(),
9819 NewTSK: TSK_ExplicitSpecialization,
9820 PrevDecl: Specialization,
9821 PrevTSK: SpecInfo->getTemplateSpecializationKind(),
9822 PrevPointOfInstantiation: SpecInfo->getPointOfInstantiation(),
9823 HasNoEffect))
9824 return true;
9825
9826 // Mark the prior declaration as an explicit specialization, so that later
9827 // clients know that this is an explicit specialization.
9828 // A dependent friend specialization which has a definition should be treated
9829 // as explicit specialization, despite being invalid.
9830 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9831 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9832 // Since explicit specializations do not inherit '=delete' from their
9833 // primary function template - check if the 'specialization' that was
9834 // implicitly generated (during template argument deduction for partial
9835 // ordering) from the most specialized of all the function templates that
9836 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9837 // first check that it was implicitly generated during template argument
9838 // deduction by making sure it wasn't referenced, and then reset the deleted
9839 // flag to not-deleted, so that we can inherit that information from 'FD'.
9840 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9841 !Specialization->getCanonicalDecl()->isReferenced()) {
9842 // FIXME: This assert will not hold in the presence of modules.
9843 assert(
9844 Specialization->getCanonicalDecl() == Specialization &&
9845 "This must be the only existing declaration of this specialization");
9846 // FIXME: We need an update record for this AST mutation.
9847 Specialization->setDeletedAsWritten(D: false);
9848 }
9849 // FIXME: We need an update record for this AST mutation.
9850 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9851 MarkUnusedFileScopedDecl(D: Specialization);
9852 }
9853
9854 // Turn the given function declaration into a function template
9855 // specialization, with the template arguments from the previous
9856 // specialization.
9857 // Take copies of (semantic and syntactic) template argument lists.
9858 TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy(
9859 Context, Args: Specialization->getTemplateSpecializationArgs()->asArray());
9860 FD->setFunctionTemplateSpecialization(
9861 Template: Specialization->getPrimaryTemplate(), TemplateArgs: TemplArgs, /*InsertPos=*/nullptr,
9862 TSK: SpecInfo->getTemplateSpecializationKind(),
9863 TemplateArgsAsWritten: ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9864
9865 // A function template specialization inherits the target attributes
9866 // of its template. (We require the attributes explicitly in the
9867 // code to match, but a template may have implicit attributes by
9868 // virtue e.g. of being constexpr, and it passes these implicit
9869 // attributes on to its specializations.)
9870 if (LangOpts.CUDA)
9871 CUDA().inheritTargetAttrs(FD, TD: *Specialization->getPrimaryTemplate());
9872
9873 // The "previous declaration" for this function template specialization is
9874 // the prior function template specialization.
9875 Previous.clear();
9876 Previous.addDecl(D: Specialization);
9877 return false;
9878}
9879
9880bool
9881Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9882 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9883 "Only for non-template members");
9884
9885 // Try to find the member we are instantiating.
9886 NamedDecl *FoundInstantiation = nullptr;
9887 NamedDecl *Instantiation = nullptr;
9888 NamedDecl *InstantiatedFrom = nullptr;
9889 MemberSpecializationInfo *MSInfo = nullptr;
9890
9891 if (Previous.empty()) {
9892 // Nowhere to look anyway.
9893 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Member)) {
9894 UnresolvedSet<8> Candidates;
9895 for (NamedDecl *Candidate : Previous) {
9896 auto *Method = dyn_cast<CXXMethodDecl>(Val: Candidate->getUnderlyingDecl());
9897 // Ignore any candidates that aren't member functions.
9898 if (!Method)
9899 continue;
9900
9901 QualType Adjusted = Function->getType();
9902 if (!hasExplicitCallingConv(T: Adjusted))
9903 Adjusted = adjustCCAndNoReturn(ArgFunctionType: Adjusted, FunctionType: Method->getType());
9904 // Ignore any candidates with the wrong type.
9905 // This doesn't handle deduced return types, but both function
9906 // declarations should be undeduced at this point.
9907 // FIXME: The exception specification should probably be ignored when
9908 // comparing the types.
9909 if (!Context.hasSameType(T1: Adjusted, T2: Method->getType()))
9910 continue;
9911
9912 // Ignore any candidates with unsatisfied constraints.
9913 if (ConstraintSatisfaction Satisfaction;
9914 Method->getTrailingRequiresClause() &&
9915 (CheckFunctionConstraints(FD: Method, Satisfaction,
9916 /*UsageLoc=*/Member->getLocation(),
9917 /*ForOverloadResolution=*/true) ||
9918 !Satisfaction.IsSatisfied))
9919 continue;
9920
9921 Candidates.addDecl(D: Candidate);
9922 }
9923
9924 // If we have no viable candidates left after filtering, we are done.
9925 if (Candidates.empty())
9926 return false;
9927
9928 // Find the function that is more constrained than every other function it
9929 // has been compared to.
9930 UnresolvedSetIterator Best = Candidates.begin();
9931 CXXMethodDecl *BestMethod = nullptr;
9932 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9933 I != E; ++I) {
9934 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9935 if (I == Best ||
9936 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) == Method) {
9937 Best = I;
9938 BestMethod = Method;
9939 }
9940 }
9941
9942 FoundInstantiation = *Best;
9943 Instantiation = BestMethod;
9944 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9945 MSInfo = BestMethod->getMemberSpecializationInfo();
9946
9947 // Make sure the best candidate is more constrained than all of the others.
9948 bool Ambiguous = false;
9949 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9950 I != E; ++I) {
9951 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9952 if (I != Best &&
9953 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) != BestMethod) {
9954 Ambiguous = true;
9955 break;
9956 }
9957 }
9958
9959 if (Ambiguous) {
9960 Diag(Loc: Member->getLocation(), DiagID: diag::err_function_member_spec_ambiguous)
9961 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9962 for (NamedDecl *Candidate : Candidates) {
9963 Candidate = Candidate->getUnderlyingDecl();
9964 Diag(Loc: Candidate->getLocation(), DiagID: diag::note_function_member_spec_matched)
9965 << Candidate;
9966 }
9967 return true;
9968 }
9969 } else if (isa<VarDecl>(Val: Member)) {
9970 VarDecl *PrevVar;
9971 if (Previous.isSingleResult() &&
9972 (PrevVar = dyn_cast<VarDecl>(Val: Previous.getFoundDecl())))
9973 if (PrevVar->isStaticDataMember()) {
9974 FoundInstantiation = Previous.getRepresentativeDecl();
9975 Instantiation = PrevVar;
9976 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9977 MSInfo = PrevVar->getMemberSpecializationInfo();
9978 }
9979 } else if (isa<RecordDecl>(Val: Member)) {
9980 CXXRecordDecl *PrevRecord;
9981 if (Previous.isSingleResult() &&
9982 (PrevRecord = dyn_cast<CXXRecordDecl>(Val: Previous.getFoundDecl()))) {
9983 FoundInstantiation = Previous.getRepresentativeDecl();
9984 Instantiation = PrevRecord;
9985 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9986 MSInfo = PrevRecord->getMemberSpecializationInfo();
9987 }
9988 } else if (isa<EnumDecl>(Val: Member)) {
9989 EnumDecl *PrevEnum;
9990 if (Previous.isSingleResult() &&
9991 (PrevEnum = dyn_cast<EnumDecl>(Val: Previous.getFoundDecl()))) {
9992 FoundInstantiation = Previous.getRepresentativeDecl();
9993 Instantiation = PrevEnum;
9994 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9995 MSInfo = PrevEnum->getMemberSpecializationInfo();
9996 }
9997 }
9998
9999 if (!Instantiation) {
10000 // There is no previous declaration that matches. Since member
10001 // specializations are always out-of-line, the caller will complain about
10002 // this mismatch later.
10003 return false;
10004 }
10005
10006 // A member specialization in a friend declaration isn't really declaring
10007 // an explicit specialization, just identifying a specific (possibly implicit)
10008 // specialization. Don't change the template specialization kind.
10009 //
10010 // FIXME: Is this really valid? Other compilers reject.
10011 if (Member->getFriendObjectKind() != Decl::FOK_None) {
10012 // Preserve instantiation information.
10013 if (InstantiatedFrom && isa<CXXMethodDecl>(Val: Member)) {
10014 cast<CXXMethodDecl>(Val: Member)->setInstantiationOfMemberFunction(
10015 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom),
10016 TSK: cast<CXXMethodDecl>(Val: Instantiation)->getTemplateSpecializationKind());
10017 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Val: Member)) {
10018 cast<CXXRecordDecl>(Val: Member)->setInstantiationOfMemberClass(
10019 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom),
10020 TSK: cast<CXXRecordDecl>(Val: Instantiation)->getTemplateSpecializationKind());
10021 }
10022
10023 Previous.clear();
10024 Previous.addDecl(D: FoundInstantiation);
10025 return false;
10026 }
10027
10028 // Make sure that this is a specialization of a member.
10029 if (!InstantiatedFrom) {
10030 Diag(Loc: Member->getLocation(), DiagID: diag::err_spec_member_not_instantiated)
10031 << Member;
10032 Diag(Loc: Instantiation->getLocation(), DiagID: diag::note_specialized_decl);
10033 return true;
10034 }
10035
10036 // C++ [temp.expl.spec]p6:
10037 // If a template, a member template or the member of a class template is
10038 // explicitly specialized then that specialization shall be declared
10039 // before the first use of that specialization that would cause an implicit
10040 // instantiation to take place, in every translation unit in which such a
10041 // use occurs; no diagnostic is required.
10042 assert(MSInfo && "Member specialization info missing?");
10043
10044 bool HasNoEffect = false;
10045 if (CheckSpecializationInstantiationRedecl(NewLoc: Member->getLocation(),
10046 NewTSK: TSK_ExplicitSpecialization,
10047 PrevDecl: Instantiation,
10048 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10049 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10050 HasNoEffect))
10051 return true;
10052
10053 // Check the scope of this explicit specialization.
10054 if (CheckTemplateSpecializationScope(S&: *this,
10055 Specialized: InstantiatedFrom,
10056 PrevDecl: Instantiation, Loc: Member->getLocation(),
10057 IsPartialSpecialization: false))
10058 return true;
10059
10060 // Note that this member specialization is an "instantiation of" the
10061 // corresponding member of the original template.
10062 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Val: Member)) {
10063 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Val: Instantiation);
10064 if (InstantiationFunction->getTemplateSpecializationKind() ==
10065 TSK_ImplicitInstantiation) {
10066 // Explicit specializations of member functions of class templates do not
10067 // inherit '=delete' from the member function they are specializing.
10068 if (InstantiationFunction->isDeleted()) {
10069 // FIXME: This assert will not hold in the presence of modules.
10070 assert(InstantiationFunction->getCanonicalDecl() ==
10071 InstantiationFunction);
10072 // FIXME: We need an update record for this AST mutation.
10073 InstantiationFunction->setDeletedAsWritten(D: false);
10074 }
10075 }
10076
10077 MemberFunction->setInstantiationOfMemberFunction(
10078 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10079 } else if (auto *MemberVar = dyn_cast<VarDecl>(Val: Member)) {
10080 MemberVar->setInstantiationOfStaticDataMember(
10081 VD: cast<VarDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10082 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Val: Member)) {
10083 MemberClass->setInstantiationOfMemberClass(
10084 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10085 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Val: Member)) {
10086 MemberEnum->setInstantiationOfMemberEnum(
10087 ED: cast<EnumDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10088 } else {
10089 llvm_unreachable("unknown member specialization kind");
10090 }
10091
10092 // Save the caller the trouble of having to figure out which declaration
10093 // this specialization matches.
10094 Previous.clear();
10095 Previous.addDecl(D: FoundInstantiation);
10096 return false;
10097}
10098
10099/// Complete the explicit specialization of a member of a class template by
10100/// updating the instantiated member to be marked as an explicit specialization.
10101///
10102/// \param OrigD The member declaration instantiated from the template.
10103/// \param Loc The location of the explicit specialization of the member.
10104template<typename DeclT>
10105static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10106 SourceLocation Loc) {
10107 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10108 return;
10109
10110 // FIXME: Inform AST mutation listeners of this AST mutation.
10111 // FIXME: If there are multiple in-class declarations of the member (from
10112 // multiple modules, or a declaration and later definition of a member type),
10113 // should we update all of them?
10114 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10115 OrigD->setLocation(Loc);
10116}
10117
10118void Sema::CompleteMemberSpecialization(NamedDecl *Member,
10119 LookupResult &Previous) {
10120 NamedDecl *Instantiation = cast<NamedDecl>(Val: Member->getCanonicalDecl());
10121 if (Instantiation == Member)
10122 return;
10123
10124 if (auto *Function = dyn_cast<CXXMethodDecl>(Val: Instantiation))
10125 completeMemberSpecializationImpl(S&: *this, OrigD: Function, Loc: Member->getLocation());
10126 else if (auto *Var = dyn_cast<VarDecl>(Val: Instantiation))
10127 completeMemberSpecializationImpl(S&: *this, OrigD: Var, Loc: Member->getLocation());
10128 else if (auto *Record = dyn_cast<CXXRecordDecl>(Val: Instantiation))
10129 completeMemberSpecializationImpl(S&: *this, OrigD: Record, Loc: Member->getLocation());
10130 else if (auto *Enum = dyn_cast<EnumDecl>(Val: Instantiation))
10131 completeMemberSpecializationImpl(S&: *this, OrigD: Enum, Loc: Member->getLocation());
10132 else
10133 llvm_unreachable("unknown member specialization kind");
10134}
10135
10136/// Check the scope of an explicit instantiation.
10137///
10138/// \returns true if a serious error occurs, false otherwise.
10139static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
10140 SourceLocation InstLoc,
10141 bool WasQualifiedName) {
10142 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
10143 DeclContext *CurContext = S.CurContext->getRedeclContext();
10144
10145 if (CurContext->isRecord()) {
10146 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_in_class)
10147 << D;
10148 return true;
10149 }
10150
10151 // C++11 [temp.explicit]p3:
10152 // An explicit instantiation shall appear in an enclosing namespace of its
10153 // template. If the name declared in the explicit instantiation is an
10154 // unqualified name, the explicit instantiation shall appear in the
10155 // namespace where its template is declared or, if that namespace is inline
10156 // (7.3.1), any namespace from its enclosing namespace set.
10157 //
10158 // This is DR275, which we do not retroactively apply to C++98/03.
10159 if (WasQualifiedName) {
10160 if (CurContext->Encloses(DC: OrigContext))
10161 return false;
10162 } else {
10163 if (CurContext->InEnclosingNamespaceSetOf(NS: OrigContext))
10164 return false;
10165 }
10166
10167 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: OrigContext)) {
10168 if (WasQualifiedName)
10169 S.Diag(Loc: InstLoc,
10170 DiagID: S.getLangOpts().CPlusPlus11?
10171 diag::err_explicit_instantiation_out_of_scope :
10172 diag::warn_explicit_instantiation_out_of_scope_0x)
10173 << D << NS;
10174 else
10175 S.Diag(Loc: InstLoc,
10176 DiagID: S.getLangOpts().CPlusPlus11?
10177 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10178 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10179 << D << NS;
10180 } else
10181 S.Diag(Loc: InstLoc,
10182 DiagID: S.getLangOpts().CPlusPlus11?
10183 diag::err_explicit_instantiation_must_be_global :
10184 diag::warn_explicit_instantiation_must_be_global_0x)
10185 << D;
10186 S.Diag(Loc: D->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10187 return false;
10188}
10189
10190/// Common checks for whether an explicit instantiation of \p D is valid.
10191static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
10192 SourceLocation InstLoc,
10193 bool WasQualifiedName,
10194 TemplateSpecializationKind TSK) {
10195 // C++ [temp.explicit]p13:
10196 // An explicit instantiation declaration shall not name a specialization of
10197 // a template with internal linkage.
10198 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10199 D->getFormalLinkage() == Linkage::Internal) {
10200 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_internal_linkage) << D;
10201 return true;
10202 }
10203
10204 // C++11 [temp.explicit]p3: [DR 275]
10205 // An explicit instantiation shall appear in an enclosing namespace of its
10206 // template.
10207 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10208 return true;
10209
10210 return false;
10211}
10212
10213/// Determine whether the given scope specifier has a template-id in it.
10214static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
10215 // C++11 [temp.explicit]p3:
10216 // If the explicit instantiation is for a member function, a member class
10217 // or a static data member of a class template specialization, the name of
10218 // the class template specialization in the qualified-id for the member
10219 // name shall be a simple-template-id.
10220 //
10221 // C++98 has the same restriction, just worded differently.
10222 for (NestedNameSpecifier NNS = SS.getScopeRep();
10223 NNS.getKind() == NestedNameSpecifier::Kind::Type;
10224 /**/) {
10225 const Type *T = NNS.getAsType();
10226 if (isa<TemplateSpecializationType>(Val: T))
10227 return true;
10228 NNS = T->getPrefix();
10229 }
10230 return false;
10231}
10232
10233/// Make a dllexport or dllimport attr on a class template specialization take
10234/// effect.
10235static void dllExportImportClassTemplateSpecialization(
10236 Sema &S, ClassTemplateSpecializationDecl *Def) {
10237 auto *A = cast_or_null<InheritableAttr>(Val: getDLLAttr(D: Def));
10238 assert(A && "dllExportImportClassTemplateSpecialization called "
10239 "on Def without dllexport or dllimport");
10240
10241 // We reject explicit instantiations in class scope, so there should
10242 // never be any delayed exported classes to worry about.
10243 assert(S.DelayedDllExportClasses.empty() &&
10244 "delayed exports present at explicit instantiation");
10245 S.checkClassLevelDLLAttribute(Class: Def);
10246
10247 // Propagate attribute to base class templates.
10248 for (auto &B : Def->bases()) {
10249 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10250 Val: B.getType()->getAsCXXRecordDecl()))
10251 S.propagateDLLAttrToBaseClassTemplate(Class: Def, ClassAttr: A, BaseTemplateSpec: BT, BaseLoc: B.getBeginLoc());
10252 }
10253
10254 S.referenceDLLExportedClassMethods();
10255}
10256
10257DeclResult Sema::ActOnExplicitInstantiation(
10258 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10259 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10260 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10261 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10262 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10263 // Find the class template we're specializing
10264 TemplateName Name = TemplateD.get();
10265 TemplateDecl *TD = Name.getAsTemplateDecl();
10266 // Check that the specialization uses the same tag kind as the
10267 // original template.
10268 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10269 assert(Kind != TagTypeKind::Enum &&
10270 "Invalid enum tag in class template explicit instantiation!");
10271
10272 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: TD);
10273
10274 if (!ClassTemplate) {
10275 NonTagKind NTK = getNonTagTypeDeclKind(D: TD, TTK: Kind);
10276 Diag(Loc: TemplateNameLoc, DiagID: diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10277 Diag(Loc: TD->getLocation(), DiagID: diag::note_previous_use);
10278 return true;
10279 }
10280
10281 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(),
10282 NewTag: Kind, /*isDefinition*/false, NewTagLoc: KWLoc,
10283 Name: ClassTemplate->getIdentifier())) {
10284 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
10285 << ClassTemplate
10286 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
10287 Code: ClassTemplate->getTemplatedDecl()->getKindName());
10288 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
10289 DiagID: diag::note_previous_use);
10290 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10291 }
10292
10293 // C++0x [temp.explicit]p2:
10294 // There are two forms of explicit instantiation: an explicit instantiation
10295 // definition and an explicit instantiation declaration. An explicit
10296 // instantiation declaration begins with the extern keyword. [...]
10297 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10298 ? TSK_ExplicitInstantiationDefinition
10299 : TSK_ExplicitInstantiationDeclaration;
10300
10301 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10302 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10303 // Check for dllexport class template instantiation declarations,
10304 // except for MinGW mode.
10305 for (const ParsedAttr &AL : Attr) {
10306 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10307 Diag(Loc: ExternLoc,
10308 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10309 Diag(Loc: AL.getLoc(), DiagID: diag::note_attribute);
10310 break;
10311 }
10312 }
10313
10314 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10315 Diag(Loc: ExternLoc,
10316 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10317 Diag(Loc: A->getLocation(), DiagID: diag::note_attribute);
10318 }
10319 }
10320
10321 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10322 // instantiation declarations for most purposes.
10323 bool DLLImportExplicitInstantiationDef = false;
10324 if (TSK == TSK_ExplicitInstantiationDefinition &&
10325 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10326 // Check for dllimport class template instantiation definitions.
10327 bool DLLImport =
10328 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10329 for (const ParsedAttr &AL : Attr) {
10330 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10331 DLLImport = true;
10332 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10333 // dllexport trumps dllimport here.
10334 DLLImport = false;
10335 break;
10336 }
10337 }
10338 if (DLLImport) {
10339 TSK = TSK_ExplicitInstantiationDeclaration;
10340 DLLImportExplicitInstantiationDef = true;
10341 }
10342 }
10343
10344 // Translate the parser's template argument list in our AST format.
10345 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10346 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10347
10348 // Check that the template argument list is well-formed for this
10349 // template.
10350 CheckTemplateArgumentInfo CTAI;
10351 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
10352 /*DefaultArgs=*/{}, PartialTemplateArgs: false, CTAI,
10353 /*UpdateArgsWithConversions=*/true,
10354 /*ConstraintsNotSatisfied=*/nullptr))
10355 return true;
10356
10357 // Find the class template specialization declaration that
10358 // corresponds to these arguments.
10359 void *InsertPos = nullptr;
10360 ClassTemplateSpecializationDecl *PrevDecl =
10361 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
10362
10363 TemplateSpecializationKind PrevDecl_TSK
10364 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10365
10366 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10367 Context.getTargetInfo().getTriple().isOSCygMing()) {
10368 // Check for dllexport class template instantiation definitions in MinGW
10369 // mode, if a previous declaration of the instantiation was seen.
10370 for (const ParsedAttr &AL : Attr) {
10371 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10372 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10373 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attr_dllexport_explicit_inst_def);
10374 } else {
10375 Diag(Loc: AL.getLoc(),
10376 DiagID: diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10377 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_prev_decl_missing_dllexport);
10378 }
10379 break;
10380 }
10381 }
10382 }
10383
10384 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10385 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10386 llvm::none_of(Range: Attr, P: [](const ParsedAttr &AL) {
10387 return AL.getKind() == ParsedAttr::AT_DLLExport;
10388 })) {
10389 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10390 Diag(Loc: TemplateLoc, DiagID: diag::warn_dllexport_on_decl_ignored);
10391 Diag(Loc: DEA->getLoc(), DiagID: diag::note_dllexport_on_decl);
10392 }
10393 }
10394
10395 if (CheckExplicitInstantiation(S&: *this, D: ClassTemplate, InstLoc: TemplateNameLoc,
10396 WasQualifiedName: SS.isSet(), TSK))
10397 return true;
10398
10399 ClassTemplateSpecializationDecl *Specialization = nullptr;
10400
10401 bool HasNoEffect = false;
10402 if (PrevDecl) {
10403 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateNameLoc, NewTSK: TSK,
10404 PrevDecl, PrevTSK: PrevDecl_TSK,
10405 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
10406 HasNoEffect))
10407 return PrevDecl;
10408
10409 // Even though HasNoEffect == true means that this explicit instantiation
10410 // has no effect on semantics, we go on to put its syntax in the AST.
10411
10412 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10413 PrevDecl_TSK == TSK_Undeclared) {
10414 // Since the only prior class template specialization with these
10415 // arguments was referenced but not declared, reuse that
10416 // declaration node as our own, updating the source location
10417 // for the template name to reflect our new declaration.
10418 // (Other source locations will be updated later.)
10419 Specialization = PrevDecl;
10420 Specialization->setLocation(TemplateNameLoc);
10421 PrevDecl = nullptr;
10422 }
10423
10424 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10425 DLLImportExplicitInstantiationDef) {
10426 // The new specialization might add a dllimport attribute.
10427 HasNoEffect = false;
10428 }
10429 }
10430
10431 if (!Specialization) {
10432 // Create a new class template specialization declaration node for
10433 // this explicit specialization.
10434 Specialization = ClassTemplateSpecializationDecl::Create(
10435 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
10436 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
10437 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
10438
10439 // A MSInheritanceAttr attached to the previous declaration must be
10440 // propagated to the new node prior to instantiation.
10441 if (PrevDecl) {
10442 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10443 auto *Clone = A->clone(C&: getASTContext());
10444 Clone->setInherited(true);
10445 Specialization->addAttr(A: Clone);
10446 Consumer.AssignInheritanceModel(RD: Specialization);
10447 }
10448 }
10449
10450 if (!HasNoEffect && !PrevDecl) {
10451 // Insert the new specialization.
10452 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
10453 }
10454 }
10455
10456 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10457
10458 // Set source locations for keywords.
10459 Specialization->setExternKeywordLoc(ExternLoc);
10460 Specialization->setTemplateKeywordLoc(TemplateLoc);
10461 Specialization->setBraceRange(SourceRange());
10462
10463 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10464 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
10465 ProcessAPINotes(D: Specialization);
10466
10467 // Add the explicit instantiation into its lexical context. However,
10468 // since explicit instantiations are never found by name lookup, we
10469 // just put it into the declaration context directly.
10470 Specialization->setLexicalDeclContext(CurContext);
10471 CurContext->addDecl(D: Specialization);
10472
10473 // Syntax is now OK, so return if it has no other effect on semantics.
10474 if (HasNoEffect) {
10475 // Set the template specialization kind.
10476 Specialization->setTemplateSpecializationKind(TSK);
10477
10478 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
10479 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10480 Keyword: KW, ElaboratedKeywordLoc: KWLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: SourceLocation(), T: Name,
10481 TLoc: TemplateNameLoc, SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted,
10482 Canon: Context.getCanonicalTagType(TD: Specialization));
10483 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
10484 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10485 NameLoc: TemplateNameLoc, TypeAsWritten: TSI, TSK);
10486 return Specialization;
10487 }
10488
10489 // C++ [temp.explicit]p3:
10490 // A definition of a class template or class member template
10491 // shall be in scope at the point of the explicit instantiation of
10492 // the class template or class member template.
10493 //
10494 // This check comes when we actually try to perform the
10495 // instantiation.
10496 ClassTemplateSpecializationDecl *Def
10497 = cast_or_null<ClassTemplateSpecializationDecl>(
10498 Val: Specialization->getDefinition());
10499 if (!Def)
10500 InstantiateClassTemplateSpecialization(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Specialization, TSK,
10501 /*Complain=*/true,
10502 PrimaryStrictPackMatch: CTAI.StrictPackMatch);
10503 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10504 MarkVTableUsed(Loc: TemplateNameLoc, Class: Specialization, DefinitionRequired: true);
10505 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10506 }
10507
10508 // Instantiate the members of this class template specialization.
10509 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10510 Val: Specialization->getDefinition());
10511 if (Def) {
10512 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
10513 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10514 // TSK_ExplicitInstantiationDefinition
10515 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10516 (TSK == TSK_ExplicitInstantiationDefinition ||
10517 DLLImportExplicitInstantiationDef)) {
10518 // FIXME: Need to notify the ASTMutationListener that we did this.
10519 Def->setTemplateSpecializationKind(TSK);
10520
10521 if (!getDLLAttr(D: Def) && getDLLAttr(D: Specialization) &&
10522 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10523 // An explicit instantiation definition can add a dll attribute to a
10524 // template with a previous instantiation declaration. MinGW doesn't
10525 // allow this.
10526 auto *A = cast<InheritableAttr>(
10527 Val: getDLLAttr(D: Specialization)->clone(C&: getASTContext()));
10528 A->setInherited(true);
10529 Def->addAttr(A);
10530 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10531 }
10532 }
10533
10534 // Fix a TSK_ImplicitInstantiation followed by a
10535 // TSK_ExplicitInstantiationDefinition
10536 bool NewlyDLLExported =
10537 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10538 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10539 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10540 // An explicit instantiation definition can add a dll attribute to a
10541 // template with a previous implicit instantiation. MinGW doesn't allow
10542 // this. We limit clang to only adding dllexport, to avoid potentially
10543 // strange codegen behavior. For example, if we extend this conditional
10544 // to dllimport, and we have a source file calling a method on an
10545 // implicitly instantiated template class instance and then declaring a
10546 // dllimport explicit instantiation definition for the same template
10547 // class, the codegen for the method call will not respect the dllimport,
10548 // while it will with cl. The Def will already have the DLL attribute,
10549 // since the Def and Specialization will be the same in the case of
10550 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10551 // attribute to the Specialization; we just need to make it take effect.
10552 assert(Def == Specialization &&
10553 "Def and Specialization should match for implicit instantiation");
10554 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10555 }
10556
10557 // In MinGW mode, export the template instantiation if the declaration
10558 // was marked dllexport.
10559 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10560 Context.getTargetInfo().getTriple().isOSCygMing() &&
10561 PrevDecl->hasAttr<DLLExportAttr>()) {
10562 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10563 }
10564
10565 // Set the template specialization kind. Make sure it is set before
10566 // instantiating the members which will trigger ASTConsumer callbacks.
10567 Specialization->setTemplateSpecializationKind(TSK);
10568 InstantiateClassTemplateSpecializationMembers(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Def, TSK);
10569 } else {
10570
10571 // Set the template specialization kind.
10572 Specialization->setTemplateSpecializationKind(TSK);
10573 }
10574
10575 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
10576 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10577 Keyword: KW, ElaboratedKeywordLoc: KWLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: SourceLocation(), T: Name,
10578 TLoc: TemplateNameLoc, SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted,
10579 Canon: Context.getCanonicalTagType(TD: Specialization));
10580 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
10581 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10582 NameLoc: TemplateNameLoc, TypeAsWritten: TSI, TSK);
10583 return Specialization;
10584}
10585
10586DeclResult
10587Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10588 SourceLocation TemplateLoc, unsigned TagSpec,
10589 SourceLocation KWLoc, CXXScopeSpec &SS,
10590 IdentifierInfo *Name, SourceLocation NameLoc,
10591 const ParsedAttributesView &Attr) {
10592
10593 bool Owned = false;
10594 bool IsDependent = false;
10595 Decl *TagD =
10596 ActOnTag(S, TagSpec, TUK: TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10597 Attr, AS: AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10598 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent, ScopedEnumKWLoc: SourceLocation(),
10599 ScopedEnumUsesClassTag: false, UnderlyingType: TypeResult(), /*IsTypeSpecifier*/ false,
10600 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10601 .get();
10602 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10603
10604 if (!TagD)
10605 return true;
10606
10607 TagDecl *Tag = cast<TagDecl>(Val: TagD);
10608 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10609
10610 if (Tag->isInvalidDecl())
10611 return true;
10612
10613 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: Tag);
10614 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10615 if (!Pattern) {
10616 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_nontemplate_type)
10617 << Context.getCanonicalTagType(TD: Record);
10618 Diag(Loc: Record->getLocation(), DiagID: diag::note_nontemplate_decl_here);
10619 return true;
10620 }
10621
10622 // C++0x [temp.explicit]p2:
10623 // If the explicit instantiation is for a class or member class, the
10624 // elaborated-type-specifier in the declaration shall include a
10625 // simple-template-id.
10626 //
10627 // C++98 has the same restriction, just worded differently.
10628 if (!ScopeSpecifierHasTemplateId(SS))
10629 Diag(Loc: TemplateLoc, DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10630 << Record << SS.getRange();
10631
10632 // C++0x [temp.explicit]p2:
10633 // There are two forms of explicit instantiation: an explicit instantiation
10634 // definition and an explicit instantiation declaration. An explicit
10635 // instantiation declaration begins with the extern keyword. [...]
10636 TemplateSpecializationKind TSK
10637 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10638 : TSK_ExplicitInstantiationDeclaration;
10639
10640 CheckExplicitInstantiation(S&: *this, D: Record, InstLoc: NameLoc, WasQualifiedName: true, TSK);
10641
10642 // Verify that it is okay to explicitly instantiate here.
10643 CXXRecordDecl *PrevDecl
10644 = cast_or_null<CXXRecordDecl>(Val: Record->getPreviousDecl());
10645 if (!PrevDecl && Record->getDefinition())
10646 PrevDecl = Record;
10647 if (PrevDecl) {
10648 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10649 bool HasNoEffect = false;
10650 assert(MSInfo && "No member specialization information?");
10651 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateLoc, NewTSK: TSK,
10652 PrevDecl,
10653 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10654 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10655 HasNoEffect))
10656 return true;
10657 if (HasNoEffect) {
10658 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10659 ElaboratedTypeKeyword KW =
10660 TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
10661 QualType TagTy = Context.getTagType(Keyword: KW, Qualifier: SS.getScopeRep(), TD: Record, OwnsTag: false);
10662 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T: TagTy);
10663 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10664 TL.setElaboratedKeywordLoc(KWLoc);
10665 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10666 TL.setNameLoc(NameLoc);
10667 addExplicitInstantiationDecl(Context, CurContext, Spec: Record, ExternLoc,
10668 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(),
10669 ArgsAsWritten: nullptr, NameLoc, TypeAsWritten: TSI, TSK);
10670 return TagD;
10671 }
10672 }
10673
10674 CXXRecordDecl *RecordDef
10675 = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10676 if (!RecordDef) {
10677 // C++ [temp.explicit]p3:
10678 // A definition of a member class of a class template shall be in scope
10679 // at the point of an explicit instantiation of the member class.
10680 CXXRecordDecl *Def
10681 = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition());
10682 if (!Def) {
10683 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_undefined_member)
10684 << 0 << Record->getDeclName() << Record->getDeclContext();
10685 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_forward_declaration)
10686 << Pattern;
10687 return true;
10688 } else {
10689 if (InstantiateClass(PointOfInstantiation: NameLoc, Instantiation: Record, Pattern: Def,
10690 TemplateArgs: getTemplateInstantiationArgs(D: Record),
10691 TSK))
10692 return true;
10693
10694 RecordDef = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10695 if (!RecordDef)
10696 return true;
10697 }
10698 }
10699
10700 // Instantiate all of the members of the class.
10701 InstantiateClassMembers(PointOfInstantiation: NameLoc, Instantiation: RecordDef,
10702 TemplateArgs: getTemplateInstantiationArgs(D: Record), TSK);
10703
10704 if (TSK == TSK_ExplicitInstantiationDefinition)
10705 MarkVTableUsed(Loc: NameLoc, Class: RecordDef, DefinitionRequired: true);
10706
10707 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10708 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
10709 QualType TagTy = Context.getTagType(Keyword: KW, Qualifier: SS.getScopeRep(), TD: Record, OwnsTag: false);
10710 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T: TagTy);
10711 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10712 TL.setElaboratedKeywordLoc(KWLoc);
10713 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10714 TL.setNameLoc(NameLoc);
10715 addExplicitInstantiationDecl(Context, CurContext, Spec: Record, ExternLoc,
10716 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10717 NameLoc, TypeAsWritten: TSI, TSK);
10718 return TagD;
10719}
10720
10721DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10722 SourceLocation ExternLoc,
10723 SourceLocation TemplateLoc,
10724 Declarator &D) {
10725 // Explicit instantiations always require a name.
10726 // TODO: check if/when DNInfo should replace Name.
10727 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10728 DeclarationName Name = NameInfo.getName();
10729 if (!Name) {
10730 if (!D.isInvalidType())
10731 Diag(Loc: D.getDeclSpec().getBeginLoc(),
10732 DiagID: diag::err_explicit_instantiation_requires_name)
10733 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10734
10735 return true;
10736 }
10737
10738 // Get the innermost enclosing declaration scope.
10739 S = S->getDeclParent();
10740
10741 // Determine the type of the declaration.
10742 TypeSourceInfo *T = GetTypeForDeclarator(D);
10743 QualType R = T->getType();
10744 if (R.isNull())
10745 return true;
10746
10747 // C++ [dcl.stc]p1:
10748 // A storage-class-specifier shall not be specified in [...] an explicit
10749 // instantiation (14.7.2) directive.
10750 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10751 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_of_typedef)
10752 << Name;
10753 return true;
10754 } else if (D.getDeclSpec().getStorageClassSpec()
10755 != DeclSpec::SCS_unspecified) {
10756 // Complain about then remove the storage class specifier.
10757 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_storage_class)
10758 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10759
10760 D.getMutableDeclSpec().ClearStorageClassSpecs();
10761 }
10762
10763 // C++0x [temp.explicit]p1:
10764 // [...] An explicit instantiation of a function template shall not use the
10765 // inline or constexpr specifiers.
10766 // Presumably, this also applies to member functions of class templates as
10767 // well.
10768 if (D.getDeclSpec().isInlineSpecified())
10769 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10770 DiagID: getLangOpts().CPlusPlus11 ?
10771 diag::err_explicit_instantiation_inline :
10772 diag::warn_explicit_instantiation_inline_0x)
10773 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10774 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10775 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10776 // not already specified.
10777 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10778 DiagID: diag::err_explicit_instantiation_constexpr);
10779
10780 // A deduction guide is not on the list of entities that can be explicitly
10781 // instantiated.
10782 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10783 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
10784 << /*explicit instantiation*/ 0;
10785 return true;
10786 }
10787
10788 // C++0x [temp.explicit]p2:
10789 // There are two forms of explicit instantiation: an explicit instantiation
10790 // definition and an explicit instantiation declaration. An explicit
10791 // instantiation declaration begins with the extern keyword. [...]
10792 TemplateSpecializationKind TSK
10793 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10794 : TSK_ExplicitInstantiationDeclaration;
10795
10796 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10797 LookupParsedName(R&: Previous, S, SS: &D.getCXXScopeSpec(),
10798 /*ObjectType=*/QualType());
10799
10800 if (!R->isFunctionType()) {
10801 // C++ [temp.explicit]p1:
10802 // A [...] static data member of a class template can be explicitly
10803 // instantiated from the member definition associated with its class
10804 // template.
10805 // C++1y [temp.explicit]p1:
10806 // A [...] variable [...] template specialization can be explicitly
10807 // instantiated from its template.
10808 if (Previous.isAmbiguous())
10809 return true;
10810
10811 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10812 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10813 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
10814
10815 if (!PrevTemplate) {
10816 if (!Prev || !Prev->isStaticDataMember()) {
10817 // We expect to see a static data member here.
10818 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_not_known)
10819 << Name;
10820 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10821 P != PEnd; ++P)
10822 Diag(Loc: (*P)->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10823 return true;
10824 }
10825
10826 if (!Prev->getInstantiatedFromStaticDataMember()) {
10827 // FIXME: Check for explicit specialization?
10828 Diag(Loc: D.getIdentifierLoc(),
10829 DiagID: diag::err_explicit_instantiation_data_member_not_instantiated)
10830 << Prev;
10831 Diag(Loc: Prev->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10832 // FIXME: Can we provide a note showing where this was declared?
10833 return true;
10834 }
10835 } else {
10836 // Explicitly instantiate a variable template.
10837
10838 // C++1y [dcl.spec.auto]p6:
10839 // ... A program that uses auto or decltype(auto) in a context not
10840 // explicitly allowed in this section is ill-formed.
10841 //
10842 // This includes auto-typed variable template instantiations.
10843 if (R->isUndeducedType()) {
10844 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10845 DiagID: diag::err_auto_not_allowed_var_inst);
10846 return true;
10847 }
10848
10849 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10850 // C++1y [temp.explicit]p3:
10851 // If the explicit instantiation is for a variable, the unqualified-id
10852 // in the declaration shall be a template-id.
10853 Diag(Loc: D.getIdentifierLoc(),
10854 DiagID: diag::err_explicit_instantiation_without_template_id)
10855 << PrevTemplate;
10856 Diag(Loc: PrevTemplate->getLocation(),
10857 DiagID: diag::note_explicit_instantiation_here);
10858 return true;
10859 }
10860
10861 // Translate the parser's template argument list into our AST format.
10862 TemplateArgumentListInfo TemplateArgs =
10863 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10864
10865 DeclResult Res =
10866 CheckVarTemplateId(Template: PrevTemplate, TemplateLoc, TemplateNameLoc: D.getIdentifierLoc(),
10867 TemplateArgs, /*SetWrittenArgs=*/true);
10868 if (Res.isInvalid())
10869 return true;
10870
10871 if (!Res.isUsable()) {
10872 // We somehow specified dependent template arguments in an explicit
10873 // instantiation. This should probably only happen during error
10874 // recovery.
10875 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_dependent);
10876 return true;
10877 }
10878
10879 // Ignore access control bits, we don't need them for redeclaration
10880 // checking.
10881 Prev = cast<VarDecl>(Val: Res.get());
10882 ArgsAsWritten =
10883 ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
10884 }
10885
10886 // C++0x [temp.explicit]p2:
10887 // If the explicit instantiation is for a member function, a member class
10888 // or a static data member of a class template specialization, the name of
10889 // the class template specialization in the qualified-id for the member
10890 // name shall be a simple-template-id.
10891 //
10892 // C++98 has the same restriction, just worded differently.
10893 //
10894 // This does not apply to variable template specializations, where the
10895 // template-id is in the unqualified-id instead.
10896 if (!ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()) && !PrevTemplate)
10897 Diag(Loc: D.getIdentifierLoc(),
10898 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10899 << Prev << D.getCXXScopeSpec().getRange();
10900
10901 CheckExplicitInstantiation(S&: *this, D: Prev, InstLoc: D.getIdentifierLoc(), WasQualifiedName: true, TSK);
10902
10903 // Verify that it is okay to explicitly instantiate here.
10904 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10905 SourceLocation POI = Prev->getPointOfInstantiation();
10906 bool HasNoEffect = false;
10907 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK, PrevDecl: Prev,
10908 PrevTSK, PrevPointOfInstantiation: POI, HasNoEffect))
10909 return true;
10910
10911 if (!HasNoEffect) {
10912 // Instantiate static data member or variable template.
10913 Prev->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
10914 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: Prev)) {
10915 VTSD->setExternKeywordLoc(ExternLoc);
10916 VTSD->setTemplateKeywordLoc(TemplateLoc);
10917 }
10918
10919 // Merge attributes.
10920 ProcessDeclAttributeList(S, D: Prev, AttrList: D.getDeclSpec().getAttributes());
10921 if (PrevTemplate)
10922 ProcessAPINotes(D: Prev);
10923
10924 if (TSK == TSK_ExplicitInstantiationDefinition)
10925 InstantiateVariableDefinition(PointOfInstantiation: D.getIdentifierLoc(), Var: Prev);
10926 }
10927
10928 // Check the new variable specialization against the parsed input.
10929 if (PrevTemplate && !Context.hasSameType(T1: Prev->getType(), T2: R)) {
10930 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10931 DiagID: diag::err_invalid_var_template_spec_type)
10932 << 0 << PrevTemplate << R << Prev->getType();
10933 Diag(Loc: PrevTemplate->getLocation(), DiagID: diag::note_template_declared_here)
10934 << 2 << PrevTemplate->getDeclName();
10935 return true;
10936 }
10937
10938 addExplicitInstantiationDecl(
10939 Context, CurContext, Spec: Prev, ExternLoc, TemplateLoc,
10940 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
10941 NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
10942 return (Decl *)nullptr;
10943 }
10944
10945 // If the declarator is a template-id, translate the parser's template
10946 // argument list into our AST format.
10947 bool HasExplicitTemplateArgs = false;
10948 TemplateArgumentListInfo TemplateArgs;
10949 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10950 TemplateArgs = makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10951 HasExplicitTemplateArgs = true;
10952 }
10953
10954 // C++ [temp.explicit]p1:
10955 // A [...] function [...] can be explicitly instantiated from its template.
10956 // A member function [...] of a class template can be explicitly
10957 // instantiated from the member definition associated with its class
10958 // template.
10959 UnresolvedSet<8> TemplateMatches;
10960 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10961 OverloadCandidateSet::CSK_Normal);
10962 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10963 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10964 P != PEnd; ++P) {
10965 NamedDecl *Prev = *P;
10966 if (!HasExplicitTemplateArgs) {
10967 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Prev)) {
10968 QualType Adjusted = adjustCCAndNoReturn(ArgFunctionType: R, FunctionType: Method->getType(),
10969 /*AdjustExceptionSpec*/true);
10970 if (Context.hasSameUnqualifiedType(T1: Method->getType(), T2: Adjusted)) {
10971 if (Method->getPrimaryTemplate()) {
10972 TemplateMatches.addDecl(D: Method, AS: P.getAccess());
10973 } else {
10974 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10975 C.FoundDecl = P.getPair();
10976 C.Function = Method;
10977 C.Viable = true;
10978 ConstraintSatisfaction S;
10979 if (Method->getTrailingRequiresClause() &&
10980 (CheckFunctionConstraints(FD: Method, Satisfaction&: S, UsageLoc: D.getIdentifierLoc(),
10981 /*ForOverloadResolution=*/true) ||
10982 !S.IsSatisfied)) {
10983 C.Viable = false;
10984 C.FailureKind = ovl_fail_constraints_not_satisfied;
10985 }
10986 }
10987 }
10988 }
10989 }
10990
10991 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Prev);
10992 if (!FunTmpl)
10993 continue;
10994
10995 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10996 FunctionDecl *Specialization = nullptr;
10997 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
10998 FunctionTemplate: FunTmpl, ExplicitTemplateArgs: (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), ArgFunctionType: R,
10999 Specialization, Info);
11000 TDK != TemplateDeductionResult::Success) {
11001 // Keep track of almost-matches.
11002 FailedTemplateCandidates.addCandidate().set(
11003 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
11004 Info: MakeDeductionFailureInfo(Context, TDK, Info));
11005 (void)TDK;
11006 continue;
11007 }
11008
11009 // Target attributes are part of the cuda function signature, so
11010 // the cuda target of the instantiated function must match that of its
11011 // template. Given that C++ template deduction does not take
11012 // target attributes into account, we reject candidates here that
11013 // have a different target.
11014 if (LangOpts.CUDA &&
11015 CUDA().IdentifyTarget(D: Specialization,
11016 /* IgnoreImplicitHDAttr = */ true) !=
11017 CUDA().IdentifyTarget(Attrs: D.getDeclSpec().getAttributes())) {
11018 FailedTemplateCandidates.addCandidate().set(
11019 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
11020 Info: MakeDeductionFailureInfo(
11021 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
11022 continue;
11023 }
11024
11025 TemplateMatches.addDecl(D: Specialization, AS: P.getAccess());
11026 }
11027
11028 FunctionDecl *Specialization = nullptr;
11029 if (!NonTemplateMatches.empty()) {
11030 unsigned Msg = 0;
11031 OverloadCandidateDisplayKind DisplayKind;
11032 OverloadCandidateSet::iterator Best;
11033 switch (NonTemplateMatches.BestViableFunction(S&: *this, Loc: D.getIdentifierLoc(),
11034 Best)) {
11035 case OR_Success:
11036 case OR_Deleted:
11037 Specialization = cast<FunctionDecl>(Val: Best->Function);
11038 break;
11039 case OR_Ambiguous:
11040 Msg = diag::err_explicit_instantiation_ambiguous;
11041 DisplayKind = OCD_AmbiguousCandidates;
11042 break;
11043 case OR_No_Viable_Function:
11044 Msg = diag::err_explicit_instantiation_no_candidate;
11045 DisplayKind = OCD_AllCandidates;
11046 break;
11047 }
11048 if (Msg) {
11049 PartialDiagnostic Diag = PDiag(DiagID: Msg) << Name;
11050 NonTemplateMatches.NoteCandidates(
11051 PA: PartialDiagnosticAt(D.getIdentifierLoc(), Diag), S&: *this, OCD: DisplayKind,
11052 Args: {});
11053 return true;
11054 }
11055 }
11056
11057 if (!Specialization) {
11058 // Find the most specialized function template specialization.
11059 UnresolvedSetIterator Result = getMostSpecialized(
11060 SBegin: TemplateMatches.begin(), SEnd: TemplateMatches.end(),
11061 FailedCandidates&: FailedTemplateCandidates, Loc: D.getIdentifierLoc(),
11062 NoneDiag: PDiag(DiagID: diag::err_explicit_instantiation_not_known) << Name,
11063 AmbigDiag: PDiag(DiagID: diag::err_explicit_instantiation_ambiguous) << Name,
11064 CandidateDiag: PDiag(DiagID: diag::note_explicit_instantiation_candidate));
11065
11066 if (Result == TemplateMatches.end())
11067 return true;
11068
11069 // Ignore access control bits, we don't need them for redeclaration checking.
11070 Specialization = cast<FunctionDecl>(Val: *Result);
11071 }
11072
11073 // C++11 [except.spec]p4
11074 // In an explicit instantiation an exception-specification may be specified,
11075 // but is not required.
11076 // If an exception-specification is specified in an explicit instantiation
11077 // directive, it shall be compatible with the exception-specifications of
11078 // other declarations of that function.
11079 if (auto *FPT = R->getAs<FunctionProtoType>())
11080 if (FPT->hasExceptionSpec()) {
11081 unsigned DiagID =
11082 diag::err_mismatched_exception_spec_explicit_instantiation;
11083 if (getLangOpts().MicrosoftExt)
11084 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11085 bool Result = CheckEquivalentExceptionSpec(
11086 DiagID: PDiag(DiagID) << Specialization->getType(),
11087 NoteID: PDiag(DiagID: diag::note_explicit_instantiation_here),
11088 Old: Specialization->getType()->getAs<FunctionProtoType>(),
11089 OldLoc: Specialization->getLocation(), New: FPT, NewLoc: D.getBeginLoc());
11090 // In Microsoft mode, mismatching exception specifications just cause a
11091 // warning.
11092 if (!getLangOpts().MicrosoftExt && Result)
11093 return true;
11094 }
11095
11096 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11097 Diag(Loc: D.getIdentifierLoc(),
11098 DiagID: diag::err_explicit_instantiation_member_function_not_instantiated)
11099 << Specialization
11100 << (Specialization->getTemplateSpecializationKind() ==
11101 TSK_ExplicitSpecialization);
11102 Diag(Loc: Specialization->getLocation(), DiagID: diag::note_explicit_instantiation_here);
11103 return true;
11104 }
11105
11106 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11107 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11108 PrevDecl = Specialization;
11109
11110 if (PrevDecl) {
11111 bool HasNoEffect = false;
11112 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK,
11113 PrevDecl,
11114 PrevTSK: PrevDecl->getTemplateSpecializationKind(),
11115 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
11116 HasNoEffect))
11117 return true;
11118
11119 if (HasNoEffect) {
11120 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11121 if (HasExplicitTemplateArgs)
11122 ArgsAsWritten =
11123 ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
11124 addExplicitInstantiationDecl(
11125 Context, CurContext, Spec: Specialization, ExternLoc, TemplateLoc,
11126 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11127 NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
11128 return (Decl *)nullptr;
11129 }
11130 }
11131
11132 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11133 // functions
11134 // valarray<size_t>::valarray(size_t) and
11135 // valarray<size_t>::~valarray()
11136 // that it declared to have internal linkage with the internal_linkage
11137 // attribute. Ignore the explicit instantiation declaration in this case.
11138 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11139 TSK == TSK_ExplicitInstantiationDeclaration) {
11140 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Specialization->getDeclContext()))
11141 if (RD->getIdentifier() && RD->getIdentifier()->isStr(Str: "valarray") &&
11142 RD->isInStdNamespace())
11143 return (Decl*) nullptr;
11144 }
11145
11146 ProcessDeclAttributeList(S, D: Specialization, AttrList: D.getDeclSpec().getAttributes());
11147 ProcessAPINotes(D: Specialization);
11148
11149 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11150 // instantiation declarations.
11151 if (TSK == TSK_ExplicitInstantiationDefinition &&
11152 Specialization->hasAttr<DLLImportAttr>() &&
11153 Context.getTargetInfo().getCXXABI().isMicrosoft())
11154 TSK = TSK_ExplicitInstantiationDeclaration;
11155
11156 Specialization->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
11157 if (Specialization->isDefined()) {
11158 // Let the ASTConsumer know that this function has been explicitly
11159 // instantiated now, and its linkage might have changed.
11160 Consumer.HandleTopLevelDecl(D: DeclGroupRef(Specialization));
11161 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
11162 // C++2c [expr.prim.lambda.closure]/19 A member of a closure type shall not
11163 // be explicitly instantiated.
11164 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Specialization->getParent());
11165 RD && RD->isLambda()) {
11166 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_lambda_explicit_temp_spec)
11167 << /*instantiation*/ 1;
11168 Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here) << RD;
11169 return (Decl *)nullptr;
11170 }
11171 InstantiateFunctionDefinition(PointOfInstantiation: D.getIdentifierLoc(), Function: Specialization);
11172 }
11173
11174 // C++0x [temp.explicit]p2:
11175 // If the explicit instantiation is for a member function, a member class
11176 // or a static data member of a class template specialization, the name of
11177 // the class template specialization in the qualified-id for the member
11178 // name shall be a simple-template-id.
11179 //
11180 // C++98 has the same restriction, just worded differently.
11181 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11182 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11183 D.getCXXScopeSpec().isSet() &&
11184 !ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()))
11185 Diag(Loc: D.getIdentifierLoc(),
11186 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
11187 << Specialization << D.getCXXScopeSpec().getRange();
11188
11189 CheckExplicitInstantiation(
11190 S&: *this,
11191 D: FunTmpl ? (NamedDecl *)FunTmpl
11192 : Specialization->getInstantiatedFromMemberFunction(),
11193 InstLoc: D.getIdentifierLoc(), WasQualifiedName: D.getCXXScopeSpec().isSet(), TSK);
11194
11195 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11196 if (HasExplicitTemplateArgs)
11197 ArgsAsWritten = ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
11198 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
11199 TemplateLoc,
11200 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context),
11201 ArgsAsWritten, NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
11202 return (Decl *)nullptr;
11203}
11204
11205TypeResult Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11206 const CXXScopeSpec &SS,
11207 const IdentifierInfo *Name,
11208 SourceLocation TagLoc,
11209 SourceLocation NameLoc) {
11210 // This has to hold, because SS is expected to be defined.
11211 assert(Name && "Expected a name in a dependent tag");
11212
11213 NestedNameSpecifier NNS = SS.getScopeRep();
11214 if (!NNS)
11215 return true;
11216
11217 if (TUK == TagUseKind::Friend &&
11218 DiagnosePackIndexingInFriendNNS(Loc: NameLoc, NNSLoc: SS.getWithLocInContext(Context)))
11219 return true;
11220
11221 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
11222
11223 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11224 Diag(Loc: NameLoc, DiagID: diag::err_dependent_tag_decl)
11225 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11226 return true;
11227 }
11228
11229 // Create the resulting type.
11230 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
11231 QualType Result = Context.getDependentNameType(Keyword: Kwd, NNS, Name);
11232
11233 // Create type-source location information for this type.
11234 TypeLocBuilder TLB;
11235 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: Result);
11236 TL.setElaboratedKeywordLoc(TagLoc);
11237 TL.setQualifierLoc(SS.getWithLocInContext(Context));
11238 TL.setNameLoc(NameLoc);
11239 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
11240}
11241
11242TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11243 const CXXScopeSpec &SS,
11244 const IdentifierInfo &II,
11245 SourceLocation IdLoc,
11246 ImplicitTypenameContext IsImplicitTypename) {
11247 if (SS.isInvalid())
11248 return true;
11249
11250 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11251 DiagCompat(Loc: TypenameLoc, CompatDiagId: diag_compat::typename_outside_of_template)
11252 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11253
11254 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11255 TypeSourceInfo *TSI = nullptr;
11256 QualType T =
11257 CheckTypenameType(Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11258 : ElaboratedTypeKeyword::None,
11259 KeywordLoc: TypenameLoc, QualifierLoc, II, IILoc: IdLoc, TSI: &TSI,
11260 /*DeducedTSTContext=*/true);
11261 if (T.isNull())
11262 return true;
11263 return CreateParsedType(T, TInfo: TSI);
11264}
11265
11266TypeResult
11267Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11268 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11269 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11270 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11271 ASTTemplateArgsPtr TemplateArgsIn,
11272 SourceLocation RAngleLoc) {
11273 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11274 Diag(Loc: TypenameLoc, DiagID: getLangOpts().CPlusPlus11
11275 ? diag::compat_cxx11_typename_outside_of_template
11276 : diag::compat_pre_cxx11_typename_outside_of_template)
11277 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11278
11279 // Strangely, non-type results are not ignored by this lookup, so the
11280 // program is ill-formed if it finds an injected-class-name.
11281 if (TypenameLoc.isValid()) {
11282 auto *LookupRD =
11283 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: false));
11284 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11285 Diag(Loc: TemplateIILoc,
11286 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
11287 << TemplateII << 0 /*injected-class-name used as template name*/
11288 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11289 }
11290 }
11291
11292 // Translate the parser's template argument list in our AST format.
11293 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11294 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11295
11296 QualType T = CheckTemplateIdType(
11297 Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11298 : ElaboratedTypeKeyword::None,
11299 Name: TemplateIn.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
11300 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11301 if (T.isNull())
11302 return true;
11303
11304 // Provide source-location information for the template specialization type.
11305 TypeLocBuilder Builder;
11306 TemplateSpecializationTypeLoc SpecTL
11307 = Builder.push<TemplateSpecializationTypeLoc>(T);
11308 SpecTL.set(ElaboratedKeywordLoc: TypenameLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
11309 NameLoc: TemplateIILoc, TAL: TemplateArgs);
11310 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11311 return CreateParsedType(T, TInfo: TSI);
11312}
11313
11314/// Determine whether this failed name lookup should be treated as being
11315/// disabled by a usage of std::enable_if.
11316static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
11317 SourceRange &CondRange, Expr *&Cond) {
11318 // We must be looking for a ::type...
11319 if (!II.isStr(Str: "type"))
11320 return false;
11321
11322 // ... within an explicitly-written template specialization...
11323 if (NNS.getNestedNameSpecifier().getKind() != NestedNameSpecifier::Kind::Type)
11324 return false;
11325
11326 // FIXME: Look through sugar.
11327 auto EnableIfTSTLoc =
11328 NNS.castAsTypeLoc().getAs<TemplateSpecializationTypeLoc>();
11329 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11330 return false;
11331 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11332
11333 // ... which names a complete class template declaration...
11334 const TemplateDecl *EnableIfDecl =
11335 EnableIfTST->getTemplateName().getAsTemplateDecl();
11336 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11337 return false;
11338
11339 // ... called "enable_if".
11340 const IdentifierInfo *EnableIfII =
11341 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11342 if (!EnableIfII || !EnableIfII->isStr(Str: "enable_if"))
11343 return false;
11344
11345 // Assume the first template argument is the condition.
11346 CondRange = EnableIfTSTLoc.getArgLoc(i: 0).getSourceRange();
11347
11348 // Dig out the condition.
11349 Cond = nullptr;
11350 if (EnableIfTSTLoc.getArgLoc(i: 0).getArgument().getKind()
11351 != TemplateArgument::Expression)
11352 return true;
11353
11354 Cond = EnableIfTSTLoc.getArgLoc(i: 0).getSourceExpression();
11355
11356 // Ignore Boolean literals; they add no value.
11357 if (isa<CXXBoolLiteralExpr>(Val: Cond->IgnoreParenCasts()))
11358 Cond = nullptr;
11359
11360 return true;
11361}
11362
11363QualType
11364Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11365 SourceLocation KeywordLoc,
11366 NestedNameSpecifierLoc QualifierLoc,
11367 const IdentifierInfo &II,
11368 SourceLocation IILoc,
11369 TypeSourceInfo **TSI,
11370 bool DeducedTSTContext) {
11371 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11372 DeducedTSTContext);
11373 if (T.isNull())
11374 return QualType();
11375
11376 TypeLocBuilder TLB;
11377 if (isa<DependentNameType>(Val: T)) {
11378 auto TL = TLB.push<DependentNameTypeLoc>(T);
11379 TL.setElaboratedKeywordLoc(KeywordLoc);
11380 TL.setQualifierLoc(QualifierLoc);
11381 TL.setNameLoc(IILoc);
11382 } else if (isa<DeducedTemplateSpecializationType>(Val: T)) {
11383 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
11384 TL.setElaboratedKeywordLoc(KeywordLoc);
11385 TL.setQualifierLoc(QualifierLoc);
11386 TL.setNameLoc(IILoc);
11387 } else if (isa<TemplateTypeParmType>(Val: T)) {
11388 // FIXME: There might be a 'typename' keyword here, but we just drop it
11389 // as it can't be represented.
11390 assert(!QualifierLoc);
11391 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11392 } else if (isa<TagType>(Val: T)) {
11393 auto TL = TLB.push<TagTypeLoc>(T);
11394 TL.setElaboratedKeywordLoc(KeywordLoc);
11395 TL.setQualifierLoc(QualifierLoc);
11396 TL.setNameLoc(IILoc);
11397 } else if (isa<TypedefType>(Val: T)) {
11398 TLB.push<TypedefTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11399 } else {
11400 TLB.push<UnresolvedUsingTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11401 }
11402 *TSI = TLB.getTypeSourceInfo(Context, T);
11403 return T;
11404}
11405
11406/// Build the type that describes a C++ typename specifier,
11407/// e.g., "typename T::type".
11408QualType
11409Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11410 SourceLocation KeywordLoc,
11411 NestedNameSpecifierLoc QualifierLoc,
11412 const IdentifierInfo &II,
11413 SourceLocation IILoc, bool DeducedTSTContext) {
11414 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11415
11416 CXXScopeSpec SS;
11417 SS.Adopt(Other: QualifierLoc);
11418
11419 DeclContext *Ctx = nullptr;
11420 if (QualifierLoc) {
11421 Ctx = computeDeclContext(SS);
11422 if (!Ctx) {
11423 // If the nested-name-specifier is dependent and couldn't be
11424 // resolved to a type, build a typename type.
11425 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11426 return Context.getDependentNameType(Keyword,
11427 NNS: QualifierLoc.getNestedNameSpecifier(),
11428 Name: &II);
11429 }
11430
11431 // If the nested-name-specifier refers to the current instantiation,
11432 // the "typename" keyword itself is superfluous. In C++03, the
11433 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11434 // allows such extraneous "typename" keywords, and we retroactively
11435 // apply this DR to C++03 code with only a warning. In any case we continue.
11436
11437 if (RequireCompleteDeclContext(SS, DC: Ctx))
11438 return QualType();
11439 }
11440
11441 DeclarationName Name(&II);
11442 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11443 if (Ctx)
11444 LookupQualifiedName(R&: Result, LookupCtx: Ctx, SS);
11445 else
11446 LookupName(R&: Result, S: CurScope);
11447 unsigned DiagID = 0;
11448 Decl *Referenced = nullptr;
11449 switch (Result.getResultKind()) {
11450 case LookupResultKind::NotFound: {
11451 // If we're looking up 'type' within a template named 'enable_if', produce
11452 // a more specific diagnostic.
11453 SourceRange CondRange;
11454 Expr *Cond = nullptr;
11455 if (Ctx && isEnableIf(NNS: QualifierLoc, II, CondRange, Cond)) {
11456 // If we have a condition, narrow it down to the specific failed
11457 // condition.
11458 if (Cond) {
11459 Expr *FailedCond;
11460 std::string FailedDescription;
11461 std::tie(args&: FailedCond, args&: FailedDescription) =
11462 findFailedBooleanCondition(Cond);
11463
11464 Diag(Loc: FailedCond->getExprLoc(),
11465 DiagID: diag::err_typename_nested_not_found_requirement)
11466 << FailedDescription
11467 << FailedCond->getSourceRange();
11468 return QualType();
11469 }
11470
11471 Diag(Loc: CondRange.getBegin(),
11472 DiagID: diag::err_typename_nested_not_found_enable_if)
11473 << Ctx << CondRange;
11474 return QualType();
11475 }
11476
11477 DiagID = Ctx ? diag::err_typename_nested_not_found
11478 : diag::err_unknown_typename;
11479 break;
11480 }
11481
11482 case LookupResultKind::FoundUnresolvedValue: {
11483 // We found a using declaration that is a value. Most likely, the using
11484 // declaration itself is meant to have the 'typename' keyword.
11485 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11486 IILoc);
11487 Diag(Loc: IILoc, DiagID: diag::err_typename_refers_to_using_value_decl)
11488 << Name << Ctx << FullRange;
11489 if (UnresolvedUsingValueDecl *Using
11490 = dyn_cast<UnresolvedUsingValueDecl>(Val: Result.getRepresentativeDecl())){
11491 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11492 Diag(Loc, DiagID: diag::note_using_value_decl_missing_typename)
11493 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
11494 }
11495 }
11496 // Fall through to create a dependent typename type, from which we can
11497 // recover better.
11498 [[fallthrough]];
11499
11500 case LookupResultKind::NotFoundInCurrentInstantiation:
11501 // Okay, it's a member of an unknown instantiation.
11502 return Context.getDependentNameType(Keyword,
11503 NNS: QualifierLoc.getNestedNameSpecifier(),
11504 Name: &II);
11505
11506 case LookupResultKind::Found:
11507 // FXIME: Missing support for UsingShadowDecl on this path?
11508 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: Result.getFoundDecl())) {
11509 // C++ [class.qual]p2:
11510 // In a lookup in which function names are not ignored and the
11511 // nested-name-specifier nominates a class C, if the name specified
11512 // after the nested-name-specifier, when looked up in C, is the
11513 // injected-class-name of C [...] then the name is instead considered
11514 // to name the constructor of class C.
11515 //
11516 // Unlike in an elaborated-type-specifier, function names are not ignored
11517 // in typename-specifier lookup. However, they are ignored in all the
11518 // contexts where we form a typename type with no keyword (that is, in
11519 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11520 //
11521 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11522 // ignore functions, but that appears to be an oversight.
11523 checkTypeDeclType(LookupCtx: Ctx,
11524 DCK: Keyword == ElaboratedTypeKeyword::Typename
11525 ? DiagCtorKind::Typename
11526 : DiagCtorKind::None,
11527 TD: Type, NameLoc: IILoc);
11528 // FIXME: This appears to be the only case where a template type parameter
11529 // can have an elaborated keyword. We should preserve it somehow.
11530 if (isa<TemplateTypeParmDecl>(Val: Type)) {
11531 assert(Keyword == ElaboratedTypeKeyword::Typename);
11532 assert(!QualifierLoc);
11533 Keyword = ElaboratedTypeKeyword::None;
11534 }
11535 return Context.getTypeDeclType(
11536 Keyword, Qualifier: QualifierLoc.getNestedNameSpecifier(), Decl: Type);
11537 }
11538
11539 // C++ [dcl.type.simple]p2:
11540 // A type-specifier of the form
11541 // typename[opt] nested-name-specifier[opt] template-name
11542 // is a placeholder for a deduced class type [...].
11543 if (getLangOpts().CPlusPlus17) {
11544 if (auto *TD = getAsTypeTemplateDecl(D: Result.getFoundDecl())) {
11545 if (!DeducedTSTContext) {
11546 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11547 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11548 Diag(Loc: IILoc, DiagID: diag::err_dependent_deduced_tst)
11549 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
11550 << QualType(Qualifier.getAsType(), 0);
11551 else
11552 Diag(Loc: IILoc, DiagID: diag::err_deduced_tst)
11553 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD));
11554 NoteTemplateLocation(Decl: *TD);
11555 return QualType();
11556 }
11557 TemplateName Name = Context.getQualifiedTemplateName(
11558 Qualifier: QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11559 Template: TemplateName(TD));
11560 return Context.getDeducedTemplateSpecializationType(
11561 DK: DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11562 Template: Name);
11563 }
11564 }
11565
11566 DiagID = Ctx ? diag::err_typename_nested_not_type
11567 : diag::err_typename_not_type;
11568 Referenced = Result.getFoundDecl();
11569 break;
11570
11571 case LookupResultKind::FoundOverloaded:
11572 DiagID = Ctx ? diag::err_typename_nested_not_type
11573 : diag::err_typename_not_type;
11574 Referenced = *Result.begin();
11575 break;
11576
11577 case LookupResultKind::Ambiguous:
11578 return QualType();
11579 }
11580
11581 // If we get here, it's because name lookup did not find a
11582 // type. Emit an appropriate diagnostic and return an error.
11583 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11584 IILoc);
11585 if (Ctx)
11586 Diag(Loc: IILoc, DiagID) << FullRange << Name << Ctx;
11587 else
11588 Diag(Loc: IILoc, DiagID) << FullRange << Name;
11589 if (Referenced)
11590 Diag(Loc: Referenced->getLocation(),
11591 DiagID: Ctx ? diag::note_typename_member_refers_here
11592 : diag::note_typename_refers_here)
11593 << Name;
11594 return QualType();
11595}
11596
11597namespace {
11598 // See Sema::RebuildTypeInCurrentInstantiation
11599 class CurrentInstantiationRebuilder
11600 : public TreeTransform<CurrentInstantiationRebuilder> {
11601 SourceLocation Loc;
11602 DeclarationName Entity;
11603
11604 public:
11605 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11606
11607 CurrentInstantiationRebuilder(Sema &SemaRef,
11608 SourceLocation Loc,
11609 DeclarationName Entity)
11610 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11611 Loc(Loc), Entity(Entity) { }
11612
11613 /// Determine whether the given type \p T has already been
11614 /// transformed.
11615 ///
11616 /// For the purposes of type reconstruction, a type has already been
11617 /// transformed if it is NULL or if it is not dependent.
11618 bool AlreadyTransformed(QualType T) {
11619 return T.isNull() || !T->isInstantiationDependentType();
11620 }
11621
11622 /// Returns the location of the entity whose type is being
11623 /// rebuilt.
11624 SourceLocation getBaseLocation() { return Loc; }
11625
11626 /// Returns the name of the entity whose type is being rebuilt.
11627 DeclarationName getBaseEntity() { return Entity; }
11628
11629 /// Sets the "base" location and entity when that
11630 /// information is known based on another transformation.
11631 void setBase(SourceLocation Loc, DeclarationName Entity) {
11632 this->Loc = Loc;
11633 this->Entity = Entity;
11634 }
11635
11636 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11637 // Lambdas never need to be transformed.
11638 return E;
11639 }
11640 };
11641} // end anonymous namespace
11642
11643TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11644 SourceLocation Loc,
11645 DeclarationName Name) {
11646 if (!T || !T->getType()->isInstantiationDependentType())
11647 return T;
11648
11649 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11650 return Rebuilder.TransformType(TSI: T);
11651}
11652
11653ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11654 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11655 DeclarationName());
11656 return Rebuilder.TransformExpr(E);
11657}
11658
11659bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11660 if (SS.isInvalid())
11661 return true;
11662
11663 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11664 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11665 DeclarationName());
11666 NestedNameSpecifierLoc Rebuilt
11667 = Rebuilder.TransformNestedNameSpecifierLoc(NNS: QualifierLoc);
11668 if (!Rebuilt)
11669 return true;
11670
11671 SS.Adopt(Other: Rebuilt);
11672 return false;
11673}
11674
11675bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11676 TemplateParameterList *Params) {
11677 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11678 Decl *Param = Params->getParam(Idx: I);
11679
11680 // There is nothing to rebuild in a type parameter.
11681 if (isa<TemplateTypeParmDecl>(Val: Param))
11682 continue;
11683
11684 // Rebuild the template parameter list of a template template parameter.
11685 if (TemplateTemplateParmDecl *TTP
11686 = dyn_cast<TemplateTemplateParmDecl>(Val: Param)) {
11687 if (RebuildTemplateParamsInCurrentInstantiation(
11688 Params: TTP->getTemplateParameters()))
11689 return true;
11690
11691 continue;
11692 }
11693
11694 // Rebuild the type of a non-type template parameter.
11695 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Val: Param);
11696 TypeSourceInfo *NewTSI
11697 = RebuildTypeInCurrentInstantiation(T: NTTP->getTypeSourceInfo(),
11698 Loc: NTTP->getLocation(),
11699 Name: NTTP->getDeclName());
11700 if (!NewTSI)
11701 return true;
11702
11703 if (NewTSI->getType()->isUndeducedType()) {
11704 // C++17 [temp.dep.expr]p3:
11705 // An id-expression is type-dependent if it contains
11706 // - an identifier associated by name lookup with a non-type
11707 // template-parameter declared with a type that contains a
11708 // placeholder type (7.1.7.4),
11709 NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: NewTSI);
11710 }
11711
11712 if (NewTSI != NTTP->getTypeSourceInfo()) {
11713 NTTP->setTypeSourceInfo(NewTSI);
11714 NTTP->setType(NewTSI->getType());
11715 }
11716 }
11717
11718 return false;
11719}
11720
11721std::string
11722Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11723 const TemplateArgumentList &Args) {
11724 return getTemplateArgumentBindingsText(Params, Args: Args.data(), NumArgs: Args.size());
11725}
11726
11727std::string
11728Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11729 const TemplateArgument *Args,
11730 unsigned NumArgs) {
11731 SmallString<128> Str;
11732 llvm::raw_svector_ostream Out(Str);
11733
11734 if (!Params || Params->size() == 0 || NumArgs == 0)
11735 return std::string();
11736
11737 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11738 if (I >= NumArgs)
11739 break;
11740
11741 if (I == 0)
11742 Out << "[with ";
11743 else
11744 Out << ", ";
11745
11746 if (const IdentifierInfo *Id = Params->getParam(Idx: I)->getIdentifier()) {
11747 Out << Id->getName();
11748 } else {
11749 Out << '$' << I;
11750 }
11751
11752 Out << " = ";
11753 Args[I].print(Policy: getPrintingPolicy(), Out,
11754 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
11755 Policy: getPrintingPolicy(), TPL: Params, Idx: I));
11756 }
11757
11758 Out << ']';
11759 return std::string(Out.str());
11760}
11761
11762void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11763 CachedTokens &Toks) {
11764 if (!FD)
11765 return;
11766
11767 auto LPT = std::make_unique<LateParsedTemplate>();
11768
11769 // Take tokens to avoid allocations
11770 LPT->Toks.swap(RHS&: Toks);
11771 LPT->D = FnD;
11772 LPT->FPO = getCurFPFeatures();
11773 LateParsedTemplateMap.insert(KV: std::make_pair(x&: FD, y: std::move(LPT)));
11774
11775 FD->setLateTemplateParsed(true);
11776}
11777
11778void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11779 if (!FD)
11780 return;
11781 FD->setLateTemplateParsed(false);
11782}
11783
11784bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11785 DeclContext *DC = CurContext;
11786
11787 while (DC) {
11788 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
11789 const FunctionDecl *FD = RD->isLocalClass();
11790 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11791 } else if (DC->isTranslationUnit() || DC->isNamespace())
11792 return false;
11793
11794 DC = DC->getParent();
11795 }
11796 return false;
11797}
11798
11799namespace {
11800/// Walk the path from which a declaration was instantiated, and check
11801/// that every explicit specialization along that path is visible. This enforces
11802/// C++ [temp.expl.spec]/6:
11803///
11804/// If a template, a member template or a member of a class template is
11805/// explicitly specialized then that specialization shall be declared before
11806/// the first use of that specialization that would cause an implicit
11807/// instantiation to take place, in every translation unit in which such a
11808/// use occurs; no diagnostic is required.
11809///
11810/// and also C++ [temp.class.spec]/1:
11811///
11812/// A partial specialization shall be declared before the first use of a
11813/// class template specialization that would make use of the partial
11814/// specialization as the result of an implicit or explicit instantiation
11815/// in every translation unit in which such a use occurs; no diagnostic is
11816/// required.
11817class ExplicitSpecializationVisibilityChecker {
11818 Sema &S;
11819 SourceLocation Loc;
11820 llvm::SmallVector<Module *, 8> Modules;
11821 Sema::AcceptableKind Kind;
11822
11823public:
11824 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11825 Sema::AcceptableKind Kind)
11826 : S(S), Loc(Loc), Kind(Kind) {}
11827
11828 void check(NamedDecl *ND) {
11829 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
11830 return checkImpl(Spec: FD);
11831 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
11832 return checkImpl(Spec: RD);
11833 if (auto *VD = dyn_cast<VarDecl>(Val: ND))
11834 return checkImpl(Spec: VD);
11835 if (auto *ED = dyn_cast<EnumDecl>(Val: ND))
11836 return checkImpl(Spec: ED);
11837 }
11838
11839private:
11840 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11841 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11842 : Sema::MissingImportKind::ExplicitSpecialization;
11843 const bool Recover = true;
11844
11845 // If we got a custom set of modules (because only a subset of the
11846 // declarations are interesting), use them, otherwise let
11847 // diagnoseMissingImport intelligently pick some.
11848 if (Modules.empty())
11849 S.diagnoseMissingImport(Loc, Decl: D, MIK: Kind, Recover);
11850 else
11851 S.diagnoseMissingImport(Loc, Decl: D, DeclLoc: D->getLocation(), Modules, MIK: Kind, Recover);
11852 }
11853
11854 bool CheckMemberSpecialization(const NamedDecl *D) {
11855 return Kind == Sema::AcceptableKind::Visible
11856 ? S.hasVisibleMemberSpecialization(D)
11857 : S.hasReachableMemberSpecialization(D);
11858 }
11859
11860 bool CheckExplicitSpecialization(const NamedDecl *D) {
11861 return Kind == Sema::AcceptableKind::Visible
11862 ? S.hasVisibleExplicitSpecialization(D)
11863 : S.hasReachableExplicitSpecialization(D);
11864 }
11865
11866 bool CheckDeclaration(const NamedDecl *D) {
11867 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11868 : S.hasReachableDeclaration(D);
11869 }
11870
11871 // Check a specific declaration. There are three problematic cases:
11872 //
11873 // 1) The declaration is an explicit specialization of a template
11874 // specialization.
11875 // 2) The declaration is an explicit specialization of a member of an
11876 // templated class.
11877 // 3) The declaration is an instantiation of a template, and that template
11878 // is an explicit specialization of a member of a templated class.
11879 //
11880 // We don't need to go any deeper than that, as the instantiation of the
11881 // surrounding class / etc is not triggered by whatever triggered this
11882 // instantiation, and thus should be checked elsewhere.
11883 template<typename SpecDecl>
11884 void checkImpl(SpecDecl *Spec) {
11885 bool IsHiddenExplicitSpecialization = false;
11886 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11887 // Some invalid friend declarations are written as specializations but are
11888 // instantiated implicitly.
11889 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11890 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11891 if (SpecKind == TSK_ExplicitSpecialization) {
11892 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11893 ? !CheckMemberSpecialization(D: Spec)
11894 : !CheckExplicitSpecialization(D: Spec);
11895 } else {
11896 checkInstantiated(Spec);
11897 }
11898
11899 if (IsHiddenExplicitSpecialization)
11900 diagnose(D: Spec->getMostRecentDecl(), IsPartialSpec: false);
11901 }
11902
11903 void checkInstantiated(FunctionDecl *FD) {
11904 if (auto *TD = FD->getPrimaryTemplate())
11905 checkTemplate(TD);
11906 }
11907
11908 void checkInstantiated(CXXRecordDecl *RD) {
11909 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD);
11910 if (!SD)
11911 return;
11912
11913 auto From = SD->getSpecializedTemplateOrPartial();
11914 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11915 checkTemplate(TD);
11916 else if (auto *TD =
11917 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11918 if (!CheckDeclaration(D: TD))
11919 diagnose(D: TD, IsPartialSpec: true);
11920 checkTemplate(TD);
11921 }
11922 }
11923
11924 void checkInstantiated(VarDecl *RD) {
11925 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(Val: RD);
11926 if (!SD)
11927 return;
11928
11929 auto From = SD->getSpecializedTemplateOrPartial();
11930 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11931 checkTemplate(TD);
11932 else if (auto *TD =
11933 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11934 if (!CheckDeclaration(D: TD))
11935 diagnose(D: TD, IsPartialSpec: true);
11936 checkTemplate(TD);
11937 }
11938 }
11939
11940 void checkInstantiated(EnumDecl *FD) {}
11941
11942 template<typename TemplDecl>
11943 void checkTemplate(TemplDecl *TD) {
11944 if (TD->isMemberSpecialization()) {
11945 if (!CheckMemberSpecialization(D: TD))
11946 diagnose(D: TD->getMostRecentDecl(), IsPartialSpec: false);
11947 }
11948 }
11949};
11950} // end anonymous namespace
11951
11952void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
11953 if (!getLangOpts().Modules)
11954 return;
11955
11956 ExplicitSpecializationVisibilityChecker(*this, Loc,
11957 Sema::AcceptableKind::Visible)
11958 .check(ND: Spec);
11959}
11960
11961void Sema::checkSpecializationReachability(SourceLocation Loc,
11962 NamedDecl *Spec) {
11963 if (!getLangOpts().CPlusPlusModules)
11964 return checkSpecializationVisibility(Loc, Spec);
11965
11966 ExplicitSpecializationVisibilityChecker(*this, Loc,
11967 Sema::AcceptableKind::Reachable)
11968 .check(ND: Spec);
11969}
11970
11971SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
11972 if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
11973 return N->getLocation();
11974 if (const auto *FD = dyn_cast<FunctionDecl>(Val: N)) {
11975 if (!FD->isFunctionTemplateSpecialization())
11976 return FD->getLocation();
11977 } else if (!isa<ClassTemplateSpecializationDecl,
11978 VarTemplateSpecializationDecl>(Val: N)) {
11979 return N->getLocation();
11980 }
11981 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11982 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11983 continue;
11984 return CSC.PointOfInstantiation;
11985 }
11986 return N->getLocation();
11987}
11988