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 &&
2114 !isTagRedeclarationInScope(D: Previous.getRepresentativeDecl(),
2115 Ctx: SemanticContext, S, AllowInlineNamespace: SS.isValid()))
2116 PrevDecl = PrevClassTemplate = nullptr;
2117
2118 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2119 Val: PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2120 if (SS.isEmpty() &&
2121 !(PrevClassTemplate &&
2122 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2123 DC: SemanticContext->getRedeclContext()))) {
2124 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
2125 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
2126 DiagID: diag::note_using_decl_target);
2127 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
2128 // Recover by ignoring the old declaration.
2129 PrevDecl = PrevClassTemplate = nullptr;
2130 }
2131 }
2132
2133 if (PrevClassTemplate) {
2134 // Ensure that the template parameter lists are compatible. Skip this check
2135 // for a friend in a dependent context: the template parameter list itself
2136 // could be dependent.
2137 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2138 !TemplateParameterListsAreEqual(
2139 NewInstFrom: TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2140 : CurContext,
2141 CurContext, KWLoc),
2142 New: TemplateParams, OldInstFrom: PrevClassTemplate,
2143 Old: PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2144 Kind: TPL_TemplateMatch))
2145 return true;
2146
2147 // C++ [temp.class]p4:
2148 // In a redeclaration, partial specialization, explicit
2149 // specialization or explicit instantiation of a class template,
2150 // the class-key shall agree in kind with the original class
2151 // template declaration (7.1.5.3).
2152 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2153 if (!isAcceptableTagRedeclaration(
2154 Previous: PrevRecordDecl, NewTag: Kind, isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc, Name)) {
2155 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
2156 << Name
2157 << FixItHint::CreateReplacement(RemoveRange: KWLoc, Code: PrevRecordDecl->getKindName());
2158 Diag(Loc: PrevRecordDecl->getLocation(), DiagID: diag::note_previous_use);
2159 Kind = PrevRecordDecl->getTagKind();
2160 }
2161
2162 // Check for redefinition of this class template.
2163 if (TUK == TagUseKind::Definition) {
2164 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2165 // If we have a prior definition that is not visible, treat this as
2166 // simply making that previous definition visible.
2167 NamedDecl *Hidden = nullptr;
2168 bool HiddenDefVisible = false;
2169 if (SkipBody &&
2170 isRedefinitionAllowedFor(D: Def, NewDefinitionLoc: NameLoc, Suggested: &Hidden, Visible&: HiddenDefVisible)) {
2171 SkipBody->ShouldSkip = true;
2172 SkipBody->Previous = Def;
2173 if (!HiddenDefVisible && Hidden) {
2174 auto *Tmpl =
2175 cast<CXXRecordDecl>(Val: Hidden)->getDescribedClassTemplate();
2176 assert(Tmpl && "original definition of a class template is not a "
2177 "class template?");
2178 makeMergedDefinitionVisible(ND: Hidden);
2179 makeMergedDefinitionVisible(ND: Tmpl);
2180 }
2181 } else {
2182 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
2183 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
2184 // FIXME: Would it make sense to try to "forget" the previous
2185 // definition, as part of error recovery?
2186 return true;
2187 }
2188 }
2189 }
2190 } else if (PrevDecl) {
2191 // C++ [temp]p5:
2192 // A class template shall not have the same name as any other
2193 // template, class, function, object, enumeration, enumerator,
2194 // namespace, or type in the same scope (3.3), except as specified
2195 // in (14.5.4).
2196 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
2197 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
2198 return true;
2199 }
2200
2201 // Check the template parameter list of this declaration, possibly
2202 // merging in the template parameter list from the previous class
2203 // template declaration. Skip this check for a friend in a dependent
2204 // context, because the template parameter list might be dependent.
2205 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2206 CheckTemplateParameterList(
2207 NewParams: TemplateParams,
2208 OldParams: PrevClassTemplate ? GetTemplateParameterList(TD: PrevClassTemplate)
2209 : nullptr,
2210 TPC: (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2211 SemanticContext->isDependentContext())
2212 ? TPC_ClassTemplateMember
2213 : TUK == TagUseKind::Friend ? TPC_FriendClassTemplate
2214 : TPC_Other,
2215 SkipBody))
2216 Invalid = true;
2217
2218 if (SS.isSet()) {
2219 // If the name of the template was qualified, we must be defining the
2220 // template out-of-line.
2221 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate)
2222 return Diag(Loc: NameLoc, DiagID: TUK == TagUseKind::Friend
2223 ? diag::err_friend_decl_does_not_match
2224 : diag::err_member_decl_does_not_match)
2225 << Name << SemanticContext << /*IsDefinition*/ true
2226 << SS.getRange();
2227 }
2228
2229 // If this is a templated friend in a dependent context we should not put it
2230 // on the redecl chain. In some cases, the templated friend can be the most
2231 // recent declaration tricking the template instantiator to make substitutions
2232 // there.
2233 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2234 bool ShouldAddRedecl =
2235 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2236
2237 CXXRecordDecl *NewClass = CXXRecordDecl::Create(
2238 C: Context, TK: Kind, DC: SemanticContext, StartLoc: KWLoc, IdLoc: NameLoc, Id: Name,
2239 PrevDecl: PrevClassTemplate && ShouldAddRedecl
2240 ? PrevClassTemplate->getTemplatedDecl()
2241 : nullptr);
2242 SetNestedNameSpecifier(S&: *this, T: NewClass, SS);
2243 if (NumOuterTemplateParamLists > 0)
2244 NewClass->setTemplateParameterListsInfo(
2245 Context,
2246 TPLists: llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2247
2248 // Add alignment attributes if necessary; these attributes are checked when
2249 // the ASTContext lays out the structure.
2250 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2251 if (LangOpts.HLSL)
2252 NewClass->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
2253 AddAlignmentAttributesForRecord(RD: NewClass);
2254 AddMsStructLayoutForRecord(RD: NewClass);
2255 }
2256
2257 ClassTemplateDecl *NewTemplate
2258 = ClassTemplateDecl::Create(C&: Context, DC: SemanticContext, L: NameLoc,
2259 Name: DeclarationName(Name), Params: TemplateParams,
2260 Decl: NewClass);
2261
2262 if (ShouldAddRedecl)
2263 NewTemplate->setPreviousDecl(PrevClassTemplate);
2264
2265 NewClass->setDescribedClassTemplate(NewTemplate);
2266
2267 if (ModulePrivateLoc.isValid())
2268 NewTemplate->setModulePrivate();
2269
2270 if (IsMemberSpecialization) {
2271 assert(PrevClassTemplate &&
2272 "Member specialization without a primary template?");
2273 NewTemplate->setMemberSpecialization();
2274 }
2275
2276 // Set the access specifier.
2277 if (!Invalid && TUK != TagUseKind::Friend &&
2278 NewTemplate->getDeclContext()->isRecord())
2279 SetMemberAccessSpecifier(MemberDecl: NewTemplate, PrevMemberDecl: PrevClassTemplate, LexicalAS: AS);
2280
2281 // Set the lexical context of these templates
2282 NewClass->setLexicalDeclContext(CurContext);
2283 NewTemplate->setLexicalDeclContext(CurContext);
2284
2285 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2286 NewClass->startDefinition();
2287
2288 ProcessDeclAttributeList(S, D: NewClass, AttrList: Attr);
2289
2290 if (PrevClassTemplate) {
2291 mergeDeclAttributes(New: NewTemplate, Old: PrevClassTemplate);
2292 mergeDeclAttributes(New: NewClass, Old: PrevClassTemplate->getTemplatedDecl());
2293 }
2294
2295 AddPushedVisibilityAttribute(RD: NewClass);
2296 inferGslOwnerPointerAttribute(Record: NewClass);
2297 inferNullableClassAttribute(CRD: NewClass);
2298
2299 if (TUK != TagUseKind::Friend) {
2300 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2301 Scope *Outer = S;
2302 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2303 Outer = Outer->getParent();
2304 PushOnScopeChains(D: NewTemplate, S: Outer);
2305 } else {
2306 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2307 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2308 NewClass->setAccess(PrevClassTemplate->getAccess());
2309 }
2310
2311 NewTemplate->setObjectOfFriendDecl();
2312
2313 // Friend templates are visible in fairly strange ways.
2314 if (!CurContext->isDependentContext()) {
2315 DeclContext *DC = SemanticContext->getRedeclContext();
2316 DC->makeDeclVisibleInContext(D: NewTemplate);
2317 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2318 PushOnScopeChains(D: NewTemplate, S: EnclosingScope,
2319 /* AddToContext = */ false);
2320 }
2321
2322 FriendDecl *Friend = FriendDecl::Create(
2323 C&: Context, DC: CurContext, L: NewClass->getLocation(), Friend: NewTemplate, FriendL: FriendLoc);
2324 Friend->setAccess(AS_public);
2325 CurContext->addDecl(D: Friend);
2326 }
2327
2328 if (PrevClassTemplate)
2329 CheckRedeclarationInModule(New: NewTemplate, Old: PrevClassTemplate);
2330
2331 if (Invalid) {
2332 NewTemplate->setInvalidDecl();
2333 NewClass->setInvalidDecl();
2334 }
2335
2336 ActOnDocumentableDecl(D: NewTemplate);
2337
2338 if (SkipBody && SkipBody->ShouldSkip)
2339 return SkipBody->Previous;
2340
2341 return NewTemplate;
2342}
2343
2344/// Diagnose the presence of a default template argument on a
2345/// template parameter, which is ill-formed in certain contexts.
2346///
2347/// \returns true if the default template argument should be dropped.
2348static bool DiagnoseDefaultTemplateArgument(Sema &S,
2349 Sema::TemplateParamListContext TPC,
2350 SourceLocation ParamLoc,
2351 SourceRange DefArgRange) {
2352 switch (TPC) {
2353 case Sema::TPC_Other:
2354 case Sema::TPC_TemplateTemplateParameterPack:
2355 return false;
2356
2357 case Sema::TPC_FunctionTemplate:
2358 case Sema::TPC_FriendFunctionTemplateDefinition:
2359 // C++ [temp.param]p9:
2360 // A default template-argument shall not be specified in a
2361 // function template declaration or a function template
2362 // definition [...]
2363 // If a friend function template declaration specifies a default
2364 // template-argument, that declaration shall be a definition and shall be
2365 // the only declaration of the function template in the translation unit.
2366 // (C++98/03 doesn't have this wording; see DR226).
2367 S.DiagCompat(Loc: ParamLoc, CompatDiagId: diag_compat::templ_default_in_function_templ)
2368 << DefArgRange;
2369 return false;
2370
2371 case Sema::TPC_ClassTemplateMember:
2372 // C++0x [temp.param]p9:
2373 // A default template-argument shall not be specified in the
2374 // template-parameter-lists of the definition of a member of a
2375 // class template that appears outside of the member's class.
2376 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_template_member)
2377 << DefArgRange;
2378 return true;
2379
2380 case Sema::TPC_FriendClassTemplate:
2381 case Sema::TPC_FriendFunctionTemplate:
2382 // C++ [temp.param]p9:
2383 // A default template-argument shall not be specified in a
2384 // friend template declaration.
2385 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_friend_template)
2386 << DefArgRange;
2387 return true;
2388
2389 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2390 // for friend function templates if there is only a single
2391 // declaration (and it is a definition). Strange!
2392 }
2393
2394 llvm_unreachable("Invalid TemplateParamListContext!");
2395}
2396
2397/// Check for unexpanded parameter packs within the template parameters
2398/// of a template template parameter, recursively.
2399static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2400 TemplateTemplateParmDecl *TTP) {
2401 // A template template parameter which is a parameter pack is also a pack
2402 // expansion.
2403 if (TTP->isParameterPack())
2404 return false;
2405
2406 TemplateParameterList *Params = TTP->getTemplateParameters();
2407 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2408 NamedDecl *P = Params->getParam(Idx: I);
2409 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: P)) {
2410 if (!TTP->isParameterPack())
2411 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2412 if (TC->hasExplicitTemplateArgs())
2413 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2414 if (S.DiagnoseUnexpandedParameterPack(Arg: ArgLoc,
2415 UPPC: Sema::UPPC_TypeConstraint))
2416 return true;
2417 continue;
2418 }
2419
2420 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: P)) {
2421 if (!NTTP->isParameterPack() &&
2422 S.DiagnoseUnexpandedParameterPack(Loc: NTTP->getLocation(),
2423 T: NTTP->getTypeSourceInfo(),
2424 UPPC: Sema::UPPC_NonTypeTemplateParameterType))
2425 return true;
2426
2427 continue;
2428 }
2429
2430 if (TemplateTemplateParmDecl *InnerTTP
2431 = dyn_cast<TemplateTemplateParmDecl>(Val: P))
2432 if (DiagnoseUnexpandedParameterPacks(S, TTP: InnerTTP))
2433 return true;
2434 }
2435
2436 return false;
2437}
2438
2439bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2440 TemplateParameterList *OldParams,
2441 TemplateParamListContext TPC,
2442 SkipBodyInfo *SkipBody) {
2443 bool Invalid = false;
2444
2445 // C++ [temp.param]p10:
2446 // The set of default template-arguments available for use with a
2447 // template declaration or definition is obtained by merging the
2448 // default arguments from the definition (if in scope) and all
2449 // declarations in scope in the same way default function
2450 // arguments are (8.3.6).
2451 bool SawDefaultArgument = false;
2452 SourceLocation PreviousDefaultArgLoc;
2453
2454 // Dummy initialization to avoid warnings.
2455 TemplateParameterList::iterator OldParam = NewParams->end();
2456 if (OldParams)
2457 OldParam = OldParams->begin();
2458
2459 bool RemoveDefaultArguments = false;
2460 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2461 NewParamEnd = NewParams->end();
2462 NewParam != NewParamEnd; ++NewParam) {
2463 // Whether we've seen a duplicate default argument in the same translation
2464 // unit.
2465 bool RedundantDefaultArg = false;
2466 // Whether we've found inconsis inconsitent default arguments in different
2467 // translation unit.
2468 bool InconsistentDefaultArg = false;
2469 // The name of the module which contains the inconsistent default argument.
2470 std::string PrevModuleName;
2471
2472 SourceLocation OldDefaultLoc;
2473 SourceLocation NewDefaultLoc;
2474
2475 // Variable used to diagnose missing default arguments
2476 bool MissingDefaultArg = false;
2477
2478 // Variable used to diagnose non-final parameter packs
2479 bool SawParameterPack = false;
2480
2481 if (TemplateTypeParmDecl *NewTypeParm
2482 = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam)) {
2483 // Check the presence of a default argument here.
2484 if (NewTypeParm->hasDefaultArgument() &&
2485 DiagnoseDefaultTemplateArgument(
2486 S&: *this, TPC, ParamLoc: NewTypeParm->getLocation(),
2487 DefArgRange: NewTypeParm->getDefaultArgument().getSourceRange()))
2488 NewTypeParm->removeDefaultArgument();
2489
2490 // Merge default arguments for template type parameters.
2491 TemplateTypeParmDecl *OldTypeParm
2492 = OldParams? cast<TemplateTypeParmDecl>(Val: *OldParam) : nullptr;
2493 if (NewTypeParm->isParameterPack()) {
2494 assert(!NewTypeParm->hasDefaultArgument() &&
2495 "Parameter packs can't have a default argument!");
2496 SawParameterPack = true;
2497 } else if (OldTypeParm && hasVisibleDefaultArgument(D: OldTypeParm) &&
2498 NewTypeParm->hasDefaultArgument() &&
2499 (!SkipBody || !SkipBody->ShouldSkip)) {
2500 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2501 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2502 SawDefaultArgument = true;
2503
2504 if (!OldTypeParm->getOwningModule())
2505 RedundantDefaultArg = true;
2506 else if (!getASTContext().isSameDefaultTemplateArgument(X: OldTypeParm,
2507 Y: NewTypeParm)) {
2508 InconsistentDefaultArg = true;
2509 PrevModuleName =
2510 OldTypeParm->getImportedOwningModule()->getFullModuleName();
2511 }
2512 PreviousDefaultArgLoc = NewDefaultLoc;
2513 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2514 // Merge the default argument from the old declaration to the
2515 // new declaration.
2516 NewTypeParm->setInheritedDefaultArgument(C: Context, Prev: OldTypeParm);
2517 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2518 } else if (NewTypeParm->hasDefaultArgument()) {
2519 SawDefaultArgument = true;
2520 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2521 } else if (SawDefaultArgument)
2522 MissingDefaultArg = true;
2523 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2524 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam)) {
2525 // Check for unexpanded parameter packs, except in a template template
2526 // parameter pack, as in those any unexpanded packs should be expanded
2527 // along with the parameter itself.
2528 if (TPC != TPC_TemplateTemplateParameterPack &&
2529 !NewNonTypeParm->isParameterPack() &&
2530 DiagnoseUnexpandedParameterPack(Loc: NewNonTypeParm->getLocation(),
2531 T: NewNonTypeParm->getTypeSourceInfo(),
2532 UPPC: UPPC_NonTypeTemplateParameterType)) {
2533 Invalid = true;
2534 continue;
2535 }
2536
2537 // Check the presence of a default argument here.
2538 if (NewNonTypeParm->hasDefaultArgument() &&
2539 DiagnoseDefaultTemplateArgument(
2540 S&: *this, TPC, ParamLoc: NewNonTypeParm->getLocation(),
2541 DefArgRange: NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2542 NewNonTypeParm->removeDefaultArgument();
2543 }
2544
2545 // Merge default arguments for non-type template parameters
2546 NonTypeTemplateParmDecl *OldNonTypeParm
2547 = OldParams? cast<NonTypeTemplateParmDecl>(Val: *OldParam) : nullptr;
2548 if (NewNonTypeParm->isParameterPack()) {
2549 assert(!NewNonTypeParm->hasDefaultArgument() &&
2550 "Parameter packs can't have a default argument!");
2551 if (!NewNonTypeParm->isPackExpansion())
2552 SawParameterPack = true;
2553 } else if (OldNonTypeParm && hasVisibleDefaultArgument(D: OldNonTypeParm) &&
2554 NewNonTypeParm->hasDefaultArgument() &&
2555 (!SkipBody || !SkipBody->ShouldSkip)) {
2556 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2557 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2558 SawDefaultArgument = true;
2559 if (!OldNonTypeParm->getOwningModule())
2560 RedundantDefaultArg = true;
2561 else if (!getASTContext().isSameDefaultTemplateArgument(
2562 X: OldNonTypeParm, Y: NewNonTypeParm)) {
2563 InconsistentDefaultArg = true;
2564 PrevModuleName =
2565 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2566 }
2567 PreviousDefaultArgLoc = NewDefaultLoc;
2568 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2569 // Merge the default argument from the old declaration to the
2570 // new declaration.
2571 NewNonTypeParm->setInheritedDefaultArgument(C: Context, Parm: OldNonTypeParm);
2572 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2573 } else if (NewNonTypeParm->hasDefaultArgument()) {
2574 SawDefaultArgument = true;
2575 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2576 } else if (SawDefaultArgument)
2577 MissingDefaultArg = true;
2578 } else {
2579 TemplateTemplateParmDecl *NewTemplateParm
2580 = cast<TemplateTemplateParmDecl>(Val: *NewParam);
2581
2582 // Check for unexpanded parameter packs, recursively.
2583 if (::DiagnoseUnexpandedParameterPacks(S&: *this, TTP: NewTemplateParm)) {
2584 Invalid = true;
2585 continue;
2586 }
2587
2588 // Check the presence of a default argument here.
2589 if (NewTemplateParm->hasDefaultArgument() &&
2590 DiagnoseDefaultTemplateArgument(S&: *this, TPC,
2591 ParamLoc: NewTemplateParm->getLocation(),
2592 DefArgRange: NewTemplateParm->getDefaultArgument().getSourceRange()))
2593 NewTemplateParm->removeDefaultArgument();
2594
2595 // Merge default arguments for template template parameters
2596 TemplateTemplateParmDecl *OldTemplateParm
2597 = OldParams? cast<TemplateTemplateParmDecl>(Val: *OldParam) : nullptr;
2598 if (NewTemplateParm->isParameterPack()) {
2599 assert(!NewTemplateParm->hasDefaultArgument() &&
2600 "Parameter packs can't have a default argument!");
2601 if (!NewTemplateParm->isPackExpansion())
2602 SawParameterPack = true;
2603 } else if (OldTemplateParm &&
2604 hasVisibleDefaultArgument(D: OldTemplateParm) &&
2605 NewTemplateParm->hasDefaultArgument() &&
2606 (!SkipBody || !SkipBody->ShouldSkip)) {
2607 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2608 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2609 SawDefaultArgument = true;
2610 if (!OldTemplateParm->getOwningModule())
2611 RedundantDefaultArg = true;
2612 else if (!getASTContext().isSameDefaultTemplateArgument(
2613 X: OldTemplateParm, Y: NewTemplateParm)) {
2614 InconsistentDefaultArg = true;
2615 PrevModuleName =
2616 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2617 }
2618 PreviousDefaultArgLoc = NewDefaultLoc;
2619 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2620 // Merge the default argument from the old declaration to the
2621 // new declaration.
2622 NewTemplateParm->setInheritedDefaultArgument(C: Context, Prev: OldTemplateParm);
2623 PreviousDefaultArgLoc
2624 = OldTemplateParm->getDefaultArgument().getLocation();
2625 } else if (NewTemplateParm->hasDefaultArgument()) {
2626 SawDefaultArgument = true;
2627 PreviousDefaultArgLoc
2628 = NewTemplateParm->getDefaultArgument().getLocation();
2629 } else if (SawDefaultArgument)
2630 MissingDefaultArg = true;
2631 }
2632
2633 // C++11 [temp.param]p11:
2634 // If a template parameter of a primary class template or alias template
2635 // is a template parameter pack, it shall be the last template parameter.
2636 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2637 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2638 Diag(Loc: (*NewParam)->getLocation(),
2639 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
2640 Invalid = true;
2641 }
2642
2643 // [basic.def.odr]/13:
2644 // There can be more than one definition of a
2645 // ...
2646 // default template argument
2647 // ...
2648 // in a program provided that each definition appears in a different
2649 // translation unit and the definitions satisfy the [same-meaning
2650 // criteria of the ODR].
2651 //
2652 // Simply, the design of modules allows the definition of template default
2653 // argument to be repeated across translation unit. Note that the ODR is
2654 // checked elsewhere. But it is still not allowed to repeat template default
2655 // argument in the same translation unit.
2656 if (RedundantDefaultArg) {
2657 Diag(Loc: NewDefaultLoc, DiagID: diag::err_template_param_default_arg_redefinition);
2658 Diag(Loc: OldDefaultLoc, DiagID: diag::note_template_param_prev_default_arg);
2659 Invalid = true;
2660 } else if (InconsistentDefaultArg) {
2661 // We could only diagnose about the case that the OldParam is imported.
2662 // The case NewParam is imported should be handled in ASTReader.
2663 Diag(Loc: NewDefaultLoc,
2664 DiagID: diag::err_template_param_default_arg_inconsistent_redefinition);
2665 Diag(Loc: OldDefaultLoc,
2666 DiagID: diag::note_template_param_prev_default_arg_in_other_module)
2667 << PrevModuleName;
2668 Invalid = true;
2669 } else if (MissingDefaultArg &&
2670 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2671 TPC == TPC_FriendClassTemplate)) {
2672 // C++ 23[temp.param]p14:
2673 // If a template-parameter of a class template, variable template, or
2674 // alias template has a default template argument, each subsequent
2675 // template-parameter shall either have a default template argument
2676 // supplied or be a template parameter pack.
2677 Diag(Loc: (*NewParam)->getLocation(),
2678 DiagID: diag::err_template_param_default_arg_missing);
2679 Diag(Loc: PreviousDefaultArgLoc, DiagID: diag::note_template_param_prev_default_arg);
2680 Invalid = true;
2681 RemoveDefaultArguments = true;
2682 }
2683
2684 // If we have an old template parameter list that we're merging
2685 // in, move on to the next parameter.
2686 if (OldParams)
2687 ++OldParam;
2688 }
2689
2690 // We were missing some default arguments at the end of the list, so remove
2691 // all of the default arguments.
2692 if (RemoveDefaultArguments) {
2693 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2694 NewParamEnd = NewParams->end();
2695 NewParam != NewParamEnd; ++NewParam) {
2696 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam))
2697 TTP->removeDefaultArgument();
2698 else if (NonTypeTemplateParmDecl *NTTP
2699 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam))
2700 NTTP->removeDefaultArgument();
2701 else
2702 cast<TemplateTemplateParmDecl>(Val: *NewParam)->removeDefaultArgument();
2703 }
2704 }
2705
2706 return Invalid;
2707}
2708
2709namespace {
2710
2711/// A class which looks for a use of a certain level of template
2712/// parameter.
2713struct DependencyChecker : DynamicRecursiveASTVisitor {
2714 unsigned Depth;
2715
2716 // Whether we're looking for a use of a template parameter that makes the
2717 // overall construct type-dependent / a dependent type. This is strictly
2718 // best-effort for now; we may fail to match at all for a dependent type
2719 // in some cases if this is set.
2720 bool IgnoreNonTypeDependent;
2721
2722 bool Match;
2723 SourceLocation MatchLoc;
2724
2725 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2726 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2727 Match(false) {}
2728
2729 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2730 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2731 NamedDecl *ND = Params->getParam(Idx: 0);
2732 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(Val: ND)) {
2733 Depth = PD->getDepth();
2734 } else if (NonTypeTemplateParmDecl *PD =
2735 dyn_cast<NonTypeTemplateParmDecl>(Val: ND)) {
2736 Depth = PD->getDepth();
2737 } else {
2738 Depth = cast<TemplateTemplateParmDecl>(Val: ND)->getDepth();
2739 }
2740 }
2741
2742 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2743 if (ParmDepth >= Depth) {
2744 Match = true;
2745 MatchLoc = Loc;
2746 return true;
2747 }
2748 return false;
2749 }
2750
2751 bool TraverseStmt(Stmt *S) override {
2752 // Prune out non-type-dependent expressions if requested. This can
2753 // sometimes result in us failing to find a template parameter reference
2754 // (if a value-dependent expression creates a dependent type), but this
2755 // mode is best-effort only.
2756 if (auto *E = dyn_cast_or_null<Expr>(Val: S))
2757 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2758 return true;
2759 return DynamicRecursiveASTVisitor::TraverseStmt(S);
2760 }
2761
2762 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2763 if (IgnoreNonTypeDependent && !TL.isNull() &&
2764 !TL.getType()->isDependentType())
2765 return true;
2766 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2767 }
2768
2769 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2770 return !Matches(ParmDepth: TL.getTypePtr()->getDepth(), Loc: TL.getNameLoc());
2771 }
2772
2773 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2774 // For a best-effort search, keep looking until we find a location.
2775 return IgnoreNonTypeDependent || !Matches(ParmDepth: T->getDepth());
2776 }
2777
2778 bool TraverseTemplateName(TemplateName N, bool TraverseQualifier) override {
2779 if (TemplateTemplateParmDecl *PD =
2780 dyn_cast_or_null<TemplateTemplateParmDecl>(Val: N.getAsTemplateDecl()))
2781 if (Matches(ParmDepth: PD->getDepth()))
2782 return false;
2783 return DynamicRecursiveASTVisitor::TraverseTemplateName(Template: N,
2784 TraverseQualifier);
2785 }
2786
2787 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2788 if (NonTypeTemplateParmDecl *PD =
2789 dyn_cast<NonTypeTemplateParmDecl>(Val: E->getDecl()))
2790 if (Matches(ParmDepth: PD->getDepth(), Loc: E->getExprLoc()))
2791 return false;
2792 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(S: E);
2793 }
2794
2795 bool VisitDependentTemplateIdExpr(DependentTemplateIdExpr *E) override {
2796 if (Matches(ParmDepth: E->getParameter()->getDepth(), Loc: E->getExprLoc()))
2797 return false;
2798 return DynamicRecursiveASTVisitor::VisitDependentTemplateIdExpr(S: E);
2799 }
2800
2801 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2802 return TraverseType(T: T->getReplacementType());
2803 }
2804
2805 bool VisitSubstTemplateTypeParmPackType(
2806 SubstTemplateTypeParmPackType *T) override {
2807 return TraverseTemplateArgument(Arg: T->getArgumentPack());
2808 }
2809
2810 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2811 bool TraverseQualifier) override {
2812 // An InjectedClassNameType will never have a dependent template name,
2813 // so no need to traverse it.
2814 return TraverseTemplateArguments(
2815 Args: T->getTemplateArgs(Ctx: T->getDecl()->getASTContext()));
2816 }
2817};
2818} // end anonymous namespace
2819
2820/// Determines whether a given type depends on the given parameter
2821/// list.
2822static bool
2823DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2824 if (!Params->size())
2825 return false;
2826
2827 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2828 Checker.TraverseType(T);
2829 return Checker.Match;
2830}
2831
2832// Find the source range corresponding to the named type in the given
2833// nested-name-specifier, if any.
2834static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2835 QualType T,
2836 const CXXScopeSpec &SS) {
2837 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2838 for (;;) {
2839 NestedNameSpecifier NNS = NNSLoc.getNestedNameSpecifier();
2840 if (NNS.getKind() != NestedNameSpecifier::Kind::Type)
2841 break;
2842 if (Context.hasSameUnqualifiedType(T1: T, T2: QualType(NNS.getAsType(), 0)))
2843 return NNSLoc.castAsTypeLoc().getSourceRange();
2844 // FIXME: This will always be empty.
2845 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2846 }
2847
2848 return SourceRange();
2849}
2850
2851TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2852 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2853 TemplateIdAnnotation *TemplateId,
2854 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2855 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2856 IsMemberSpecialization = false;
2857 Invalid = false;
2858
2859 // The sequence of nested types to which we will match up the template
2860 // parameter lists. We first build this list by starting with the type named
2861 // by the nested-name-specifier and walking out until we run out of types.
2862 SmallVector<QualType, 4> NestedTypes;
2863 QualType T;
2864 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2865 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2866 if (CXXRecordDecl *Record =
2867 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: true)))
2868 T = Context.getCanonicalTagType(TD: Record);
2869 else
2870 T = QualType(Qualifier.getAsType(), 0);
2871 }
2872
2873 // If we found an explicit specialization that prevents us from needing
2874 // 'template<>' headers, this will be set to the location of that
2875 // explicit specialization.
2876 SourceLocation ExplicitSpecLoc;
2877
2878 while (!T.isNull()) {
2879 NestedTypes.push_back(Elt: T);
2880
2881 // Retrieve the parent of a record type.
2882 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2883 // If this type is an explicit specialization, we're done.
2884 if (ClassTemplateSpecializationDecl *Spec
2885 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
2886 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Spec) &&
2887 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2888 ExplicitSpecLoc = Spec->getLocation();
2889 break;
2890 }
2891 } else if (Record->getTemplateSpecializationKind()
2892 == TSK_ExplicitSpecialization) {
2893 ExplicitSpecLoc = Record->getLocation();
2894 break;
2895 }
2896
2897 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Record->getParent()))
2898 T = Context.getTypeDeclType(Decl: Parent);
2899 else
2900 T = QualType();
2901 continue;
2902 }
2903
2904 if (const TemplateSpecializationType *TST
2905 = T->getAs<TemplateSpecializationType>()) {
2906 TemplateName Name = TST->getTemplateName();
2907 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2908 // Look one step prior in a dependent template specialization type.
2909 if (NestedNameSpecifier NNS = DTS->getQualifier();
2910 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2911 T = QualType(NNS.getAsType(), 0);
2912 else
2913 T = QualType();
2914 continue;
2915 }
2916 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2917 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Template->getDeclContext()))
2918 T = Context.getTypeDeclType(Decl: Parent);
2919 else
2920 T = QualType();
2921 continue;
2922 }
2923 }
2924
2925 // Look one step prior in a dependent name type.
2926 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2927 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2928 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2929 T = QualType(NNS.getAsType(), 0);
2930 else
2931 T = QualType();
2932 continue;
2933 }
2934
2935 // Retrieve the parent of an enumeration type.
2936 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2937 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2938 // check here.
2939 EnumDecl *Enum = EnumT->getDecl();
2940
2941 // Get to the parent type.
2942 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Enum->getParent()))
2943 T = Context.getCanonicalTypeDeclType(TD: Parent);
2944 else
2945 T = QualType();
2946 continue;
2947 }
2948
2949 T = QualType();
2950 }
2951 // Reverse the nested types list, since we want to traverse from the outermost
2952 // to the innermost while checking template-parameter-lists.
2953 std::reverse(first: NestedTypes.begin(), last: NestedTypes.end());
2954
2955 // C++0x [temp.expl.spec]p17:
2956 // A member or a member template may be nested within many
2957 // enclosing class templates. In an explicit specialization for
2958 // such a member, the member declaration shall be preceded by a
2959 // template<> for each enclosing class template that is
2960 // explicitly specialized.
2961 bool SawNonEmptyTemplateParameterList = false;
2962
2963 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2964 if (SawNonEmptyTemplateParameterList) {
2965 if (!SuppressDiagnostic)
2966 Diag(Loc: DeclLoc, DiagID: diag::err_specialize_member_of_template)
2967 << !Recovery << Range;
2968 Invalid = true;
2969 IsMemberSpecialization = false;
2970 return true;
2971 }
2972
2973 return false;
2974 };
2975
2976 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2977 // Check that we can have an explicit specialization here.
2978 if (CheckExplicitSpecialization(Range, true))
2979 return true;
2980
2981 // We don't have a template header, but we should.
2982 SourceLocation ExpectedTemplateLoc;
2983 if (!ParamLists.empty())
2984 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2985 else
2986 ExpectedTemplateLoc = DeclStartLoc;
2987
2988 if (!SuppressDiagnostic)
2989 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_header)
2990 << Range
2991 << FixItHint::CreateInsertion(InsertionLoc: ExpectedTemplateLoc, Code: "template<> ");
2992 return false;
2993 };
2994
2995 unsigned ParamIdx = 0;
2996 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2997 ++TypeIdx) {
2998 T = NestedTypes[TypeIdx];
2999
3000 // Whether we expect a 'template<>' header.
3001 bool NeedEmptyTemplateHeader = false;
3002
3003 // Whether we expect a template header with parameters.
3004 bool NeedNonemptyTemplateHeader = false;
3005
3006 // For a dependent type, the set of template parameters that we
3007 // expect to see.
3008 TemplateParameterList *ExpectedTemplateParams = nullptr;
3009
3010 // C++0x [temp.expl.spec]p15:
3011 // A member or a member template may be nested within many enclosing
3012 // class templates. In an explicit specialization for such a member, the
3013 // member declaration shall be preceded by a template<> for each
3014 // enclosing class template that is explicitly specialized.
3015 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3016 if (ClassTemplatePartialSpecializationDecl *Partial
3017 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Record)) {
3018 ExpectedTemplateParams = Partial->getTemplateParameters();
3019 NeedNonemptyTemplateHeader = true;
3020 } else if (Record->isDependentType()) {
3021 if (Record->getDescribedClassTemplate()) {
3022 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3023 ->getTemplateParameters();
3024 NeedNonemptyTemplateHeader = true;
3025 }
3026 } else if (ClassTemplateSpecializationDecl *Spec
3027 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
3028 // C++0x [temp.expl.spec]p4:
3029 // Members of an explicitly specialized class template are defined
3030 // in the same manner as members of normal classes, and not using
3031 // the template<> syntax.
3032 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3033 NeedEmptyTemplateHeader = true;
3034 else
3035 continue;
3036 } else if (Record->getTemplateSpecializationKind()) {
3037 if (Record->getTemplateSpecializationKind()
3038 != TSK_ExplicitSpecialization &&
3039 TypeIdx == NumTypes - 1)
3040 IsMemberSpecialization = true;
3041
3042 continue;
3043 }
3044 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3045 TemplateName Name = TST->getTemplateName();
3046 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3047 ExpectedTemplateParams = Template->getTemplateParameters();
3048 NeedNonemptyTemplateHeader = true;
3049 } else if (Name.getAsDependentTemplateName()) {
3050 NeedNonemptyTemplateHeader = true;
3051 } else if (Name.getAsDeducedTemplateName()) {
3052 // FIXME: We actually could/should check the template arguments here
3053 // against the corresponding template parameter list.
3054 NeedNonemptyTemplateHeader = false;
3055 }
3056 }
3057
3058 // C++ [temp.expl.spec]p16:
3059 // In an explicit specialization declaration for a member of a class
3060 // template or a member template that appears in namespace scope, the
3061 // member template and some of its enclosing class templates may remain
3062 // unspecialized, except that the declaration shall not explicitly
3063 // specialize a class member template if its enclosing class templates
3064 // are not explicitly specialized as well.
3065 if (ParamIdx < ParamLists.size()) {
3066 if (ParamLists[ParamIdx]->size() == 0) {
3067 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3068 false))
3069 return nullptr;
3070 } else
3071 SawNonEmptyTemplateParameterList = true;
3072 }
3073
3074 if (NeedEmptyTemplateHeader) {
3075 // If we're on the last of the types, and we need a 'template<>' header
3076 // here, then it's a member specialization.
3077 if (TypeIdx == NumTypes - 1)
3078 IsMemberSpecialization = true;
3079
3080 if (ParamIdx < ParamLists.size()) {
3081 if (ParamLists[ParamIdx]->size() > 0) {
3082 // The header has template parameters when it shouldn't. Complain.
3083 if (!SuppressDiagnostic)
3084 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3085 DiagID: diag::err_template_param_list_matches_nontemplate)
3086 << T
3087 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3088 ParamLists[ParamIdx]->getRAngleLoc())
3089 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3090 Invalid = true;
3091 return nullptr;
3092 }
3093
3094 // Consume this template header.
3095 ++ParamIdx;
3096 continue;
3097 }
3098
3099 if (!IsFriend)
3100 if (DiagnoseMissingExplicitSpecialization(
3101 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3102 return nullptr;
3103
3104 continue;
3105 }
3106
3107 if (NeedNonemptyTemplateHeader) {
3108 // In friend declarations we can have template-ids which don't
3109 // depend on the corresponding template parameter lists. But
3110 // assume that empty parameter lists are supposed to match this
3111 // template-id.
3112 if (IsFriend && T->isDependentType()) {
3113 if (ParamIdx < ParamLists.size() &&
3114 DependsOnTemplateParameters(T, Params: ParamLists[ParamIdx]))
3115 ExpectedTemplateParams = nullptr;
3116 else
3117 continue;
3118 }
3119
3120 if (ParamIdx < ParamLists.size()) {
3121 // Check the template parameter list, if we can.
3122 if (ExpectedTemplateParams &&
3123 !TemplateParameterListsAreEqual(New: ParamLists[ParamIdx],
3124 Old: ExpectedTemplateParams,
3125 Complain: !SuppressDiagnostic, Kind: TPL_TemplateMatch))
3126 Invalid = true;
3127
3128 if (!Invalid &&
3129 CheckTemplateParameterList(NewParams: ParamLists[ParamIdx], OldParams: nullptr,
3130 TPC: TPC_ClassTemplateMember))
3131 Invalid = true;
3132
3133 ++ParamIdx;
3134 continue;
3135 }
3136
3137 if (!SuppressDiagnostic)
3138 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_template_parameters)
3139 << T
3140 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3141 Invalid = true;
3142 continue;
3143 }
3144 }
3145
3146 // If there were at least as many template-ids as there were template
3147 // parameter lists, then there are no template parameter lists remaining for
3148 // the declaration itself.
3149 if (ParamIdx >= ParamLists.size()) {
3150 if (TemplateId && !IsFriend) {
3151 // We don't have a template header for the declaration itself, but we
3152 // should.
3153 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3154 TemplateId->RAngleLoc));
3155
3156 // Fabricate an empty template parameter list for the invented header.
3157 return TemplateParameterList::Create(C: Context, TemplateLoc: SourceLocation(),
3158 LAngleLoc: SourceLocation(), Params: {},
3159 RAngleLoc: SourceLocation(), RequiresClause: nullptr);
3160 }
3161
3162 return nullptr;
3163 }
3164
3165 // If there were too many template parameter lists, complain about that now.
3166 if (ParamIdx < ParamLists.size() - 1) {
3167 bool HasAnyExplicitSpecHeader = false;
3168 bool AllExplicitSpecHeaders = true;
3169 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3170 if (ParamLists[I]->size() == 0)
3171 HasAnyExplicitSpecHeader = true;
3172 else
3173 AllExplicitSpecHeaders = false;
3174 }
3175
3176 if (!SuppressDiagnostic)
3177 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3178 DiagID: AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3179 : diag::err_template_spec_extra_headers)
3180 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3181 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3182
3183 // If there was a specialization somewhere, such that 'template<>' is
3184 // not required, and there were any 'template<>' headers, note where the
3185 // specialization occurred.
3186 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3187 !SuppressDiagnostic)
3188 Diag(Loc: ExplicitSpecLoc,
3189 DiagID: diag::note_explicit_template_spec_does_not_need_header)
3190 << NestedTypes.back();
3191
3192 // We have a template parameter list with no corresponding scope, which
3193 // means that the resulting template declaration can't be instantiated
3194 // properly (we'll end up with dependent nodes when we shouldn't).
3195 if (!AllExplicitSpecHeaders)
3196 Invalid = true;
3197 }
3198
3199 // C++ [temp.expl.spec]p16:
3200 // In an explicit specialization declaration for a member of a class
3201 // template or a member template that ap- pears in namespace scope, the
3202 // member template and some of its enclosing class templates may remain
3203 // unspecialized, except that the declaration shall not explicitly
3204 // specialize a class member template if its en- closing class templates
3205 // are not explicitly specialized as well.
3206 if (ParamLists.back()->size() == 0 &&
3207 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3208 false))
3209 return nullptr;
3210
3211 // Return the last template parameter list, which corresponds to the
3212 // entity being declared.
3213 return ParamLists.back();
3214}
3215
3216void Sema::NoteAllFoundTemplates(TemplateName Name) {
3217 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3218 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_declared_here)
3219 << (isa<FunctionTemplateDecl>(Val: Template)
3220 ? 0
3221 : isa<ClassTemplateDecl>(Val: Template)
3222 ? 1
3223 : isa<VarTemplateDecl>(Val: Template)
3224 ? 2
3225 : isa<TypeAliasTemplateDecl>(Val: Template) ? 3 : 4)
3226 << Template->getDeclName();
3227 return;
3228 }
3229
3230 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3231 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3232 IEnd = OST->end();
3233 I != IEnd; ++I)
3234 Diag(Loc: (*I)->getLocation(), DiagID: diag::note_template_declared_here)
3235 << 0 << (*I)->getDeclName();
3236
3237 return;
3238 }
3239}
3240
3241static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword,
3242 TemplateName BaseTemplate,
3243 SourceLocation TemplateLoc,
3244 ArrayRef<TemplateArgument> Ts) {
3245 auto lookUpCommonType = [&](TemplateArgument T1,
3246 TemplateArgument T2) -> QualType {
3247 // Don't bother looking for other specializations if both types are
3248 // builtins - users aren't allowed to specialize for them
3249 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3250 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3251 Ts: {T1, T2});
3252
3253 TemplateArgumentListInfo Args;
3254 Args.addArgument(Loc: TemplateArgumentLoc(
3255 T1, S.Context.getTrivialTypeSourceInfo(T: T1.getAsType())));
3256 Args.addArgument(Loc: TemplateArgumentLoc(
3257 T2, S.Context.getTrivialTypeSourceInfo(T: T2.getAsType())));
3258
3259 EnterExpressionEvaluationContext UnevaluatedContext(
3260 S, Sema::ExpressionEvaluationContext::Unevaluated);
3261 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3262 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3263
3264 QualType BaseTemplateInst = S.CheckTemplateIdType(
3265 Keyword, Template: BaseTemplate, TemplateLoc, TemplateArgs&: Args,
3266 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3267
3268 if (SFINAE.hasErrorOccurred())
3269 return QualType();
3270
3271 return BaseTemplateInst;
3272 };
3273
3274 // Note A: For the common_type trait applied to a template parameter pack T of
3275 // types, the member type shall be either defined or not present as follows:
3276 switch (Ts.size()) {
3277
3278 // If sizeof...(T) is zero, there shall be no member type.
3279 case 0:
3280 return QualType();
3281
3282 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3283 // pack T. The member typedef-name type shall denote the same type, if any, as
3284 // common_type_t<T0, T0>; otherwise there shall be no member type.
3285 case 1:
3286 return lookUpCommonType(Ts[0], Ts[0]);
3287
3288 // If sizeof...(T) is two, let the first and second types constituting T be
3289 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3290 // as decay_t<T1> and decay_t<T2>, respectively.
3291 case 2: {
3292 QualType T1 = Ts[0].getAsType();
3293 QualType T2 = Ts[1].getAsType();
3294 QualType D1 = S.BuiltinDecay(BaseType: T1, Loc: {});
3295 QualType D2 = S.BuiltinDecay(BaseType: T2, Loc: {});
3296
3297 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3298 // the same type, if any, as common_type_t<D1, D2>.
3299 if (!S.Context.hasSameType(T1, T2: D1) || !S.Context.hasSameType(T1: T2, T2: D2))
3300 return lookUpCommonType(D1, D2);
3301
3302 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3303 // denotes a valid type, let C denote that type.
3304 {
3305 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3306 EnterExpressionEvaluationContext UnevaluatedContext(
3307 S, Sema::ExpressionEvaluationContext::Unevaluated);
3308 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3309 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3310
3311 // false
3312 OpaqueValueExpr CondExpr(SourceLocation(), S.Context.BoolTy,
3313 VK_PRValue);
3314 ExprResult Cond = &CondExpr;
3315
3316 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3317 if (ConstRefQual) {
3318 D1.addConst();
3319 D2.addConst();
3320 }
3321
3322 // declval<D1>()
3323 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3324 ExprResult LHS = &LHSExpr;
3325
3326 // declval<D2>()
3327 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3328 ExprResult RHS = &RHSExpr;
3329
3330 ExprValueKind VK = VK_PRValue;
3331 ExprObjectKind OK = OK_Ordinary;
3332
3333 // decltype(false ? declval<D1>() : declval<D2>())
3334 QualType Result =
3335 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc: TemplateLoc);
3336
3337 if (Result.isNull() || SFINAE.hasErrorOccurred())
3338 return QualType();
3339
3340 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3341 return S.BuiltinDecay(BaseType: Result, Loc: TemplateLoc);
3342 };
3343
3344 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3345 return Res;
3346
3347 // Let:
3348 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3349 // COND-RES(X, Y) be
3350 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3351
3352 // C++20 only
3353 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3354 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3355 if (!S.Context.getLangOpts().CPlusPlus20)
3356 return QualType();
3357 return CheckConditionalOperands(true);
3358 }
3359 }
3360
3361 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3362 // denote the first, second, and (pack of) remaining types constituting T. Let
3363 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3364 // a type C, the member typedef-name type shall denote the same type, if any,
3365 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3366 default: {
3367 QualType Result = Ts.front().getAsType();
3368 for (auto T : llvm::drop_begin(RangeOrContainer&: Ts)) {
3369 Result = lookUpCommonType(Result, T.getAsType());
3370 if (Result.isNull())
3371 return QualType();
3372 }
3373 return Result;
3374 }
3375 }
3376}
3377
3378static bool isInVkNamespace(const RecordType *RT) {
3379 DeclContext *DC = RT->getDecl()->getDeclContext();
3380 if (!DC)
3381 return false;
3382
3383 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Val: DC);
3384 if (!ND)
3385 return false;
3386
3387 return ND->getQualifiedNameAsString() == "hlsl::vk";
3388}
3389
3390static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3391 QualType OperandArg,
3392 SourceLocation Loc) {
3393 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3394 bool Literal = false;
3395 SourceLocation LiteralLoc;
3396 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3397 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3398 assert(SpecDecl);
3399
3400 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3401 QualType ConstantType = LiteralArgs[0].getAsType();
3402 RT = ConstantType->getAsCanonical<RecordType>();
3403 Literal = true;
3404 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3405 }
3406
3407 if (RT && isInVkNamespace(RT) &&
3408 RT->getDecl()->getName() == "integral_constant") {
3409 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3410 assert(SpecDecl);
3411
3412 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3413
3414 QualType ConstantType = ConstantArgs[0].getAsType();
3415 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3416
3417 if (Literal)
3418 return SpirvOperand::createLiteral(Val: Value);
3419 return SpirvOperand::createConstant(ResultType: ConstantType, Val: Value);
3420 } else if (Literal) {
3421 SemaRef.Diag(Loc: LiteralLoc, DiagID: diag::err_hlsl_vk_literal_must_contain_constant);
3422 return SpirvOperand();
3423 }
3424 }
3425 if (SemaRef.RequireCompleteType(Loc, T: OperandArg,
3426 DiagID: diag::err_call_incomplete_argument))
3427 return SpirvOperand();
3428 return SpirvOperand::createType(T: OperandArg);
3429}
3430
3431static QualType checkBuiltinTemplateIdType(
3432 Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD,
3433 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3434 TemplateArgumentListInfo &TemplateArgs) {
3435 ASTContext &Context = SemaRef.getASTContext();
3436
3437 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3438 "Builtin template arguments do not match its parameters");
3439
3440 switch (BTD->getBuiltinTemplateKind()) {
3441 case BTK__make_integer_seq: {
3442 // Specializations of __make_integer_seq<S, T, N> are treated like
3443 // S<T, 0, ..., N-1>.
3444
3445 QualType OrigType = Converted[1].getAsType();
3446 // C++14 [inteseq.intseq]p1:
3447 // T shall be an integer type.
3448 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Ctx: Context)) {
3449 SemaRef.Diag(Loc: TemplateArgs[1].getLocation(),
3450 DiagID: diag::err_integer_sequence_integral_element_type);
3451 return QualType();
3452 }
3453
3454 TemplateArgument NumArgsArg = Converted[2];
3455 if (NumArgsArg.isDependent())
3456 return QualType();
3457
3458 TemplateArgumentListInfo SyntheticTemplateArgs;
3459 // The type argument, wrapped in substitution sugar, gets reused as the
3460 // first template argument in the synthetic template argument list.
3461 SyntheticTemplateArgs.addArgument(
3462 Loc: TemplateArgumentLoc(TemplateArgument(OrigType),
3463 SemaRef.Context.getTrivialTypeSourceInfo(
3464 T: OrigType, Loc: TemplateArgs[1].getLocation())));
3465
3466 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3467 // Expand N into 0 ... N-1.
3468 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3469 I < NumArgs; ++I) {
3470 TemplateArgument TA(Context, I, OrigType);
3471 SyntheticTemplateArgs.addArgument(Loc: SemaRef.getTrivialTemplateArgumentLoc(
3472 Arg: TA, NTTPType: OrigType, Loc: TemplateArgs[2].getLocation()));
3473 }
3474 } else {
3475 // C++14 [inteseq.make]p1:
3476 // If N is negative the program is ill-formed.
3477 SemaRef.Diag(Loc: TemplateArgs[2].getLocation(),
3478 DiagID: diag::err_integer_sequence_negative_length);
3479 return QualType();
3480 }
3481
3482 // The first template argument will be reused as the template decl that
3483 // our synthetic template arguments will be applied to.
3484 return SemaRef.CheckTemplateIdType(Keyword, Template: Converted[0].getAsTemplate(),
3485 TemplateLoc, TemplateArgs&: SyntheticTemplateArgs,
3486 /*Scope=*/nullptr,
3487 /*ForNestedNameSpecifier=*/false);
3488 }
3489
3490 case BTK__type_pack_element: {
3491 // Specializations of
3492 // __type_pack_element<Index, T_1, ..., T_N>
3493 // are treated like T_Index.
3494 assert(Converted.size() == 2 &&
3495 "__type_pack_element should be given an index and a parameter pack");
3496
3497 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3498 if (IndexArg.isDependent() || Ts.isDependent())
3499 return QualType();
3500
3501 llvm::APSInt Index = IndexArg.getAsIntegral();
3502 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3503 "type std::size_t, and hence be non-negative");
3504 // If the Index is out of bounds, the program is ill-formed.
3505 if (Index >= Ts.pack_size()) {
3506 SemaRef.Diag(Loc: TemplateArgs[0].getLocation(),
3507 DiagID: diag::err_type_pack_element_out_of_bounds);
3508 return QualType();
3509 }
3510
3511 // We simply return the type at index `Index`.
3512 int64_t N = Index.getExtValue();
3513 return Ts.getPackAsArray()[N].getAsType();
3514 }
3515
3516 case BTK__builtin_common_type: {
3517 assert(Converted.size() == 4);
3518 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3519 return QualType();
3520
3521 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3522 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3523 if (auto CT = builtinCommonTypeImpl(S&: SemaRef, Keyword, BaseTemplate,
3524 TemplateLoc, Ts);
3525 !CT.isNull()) {
3526 TemplateArgumentListInfo TAs;
3527 TAs.addArgument(Loc: TemplateArgumentLoc(
3528 TemplateArgument(CT), SemaRef.Context.getTrivialTypeSourceInfo(
3529 T: CT, Loc: TemplateArgs[1].getLocation())));
3530 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3531 return SemaRef.CheckTemplateIdType(Keyword, Template: HasTypeMember, TemplateLoc,
3532 TemplateArgs&: TAs, /*Scope=*/nullptr,
3533 /*ForNestedNameSpecifier=*/false);
3534 }
3535 QualType HasNoTypeMember = Converted[2].getAsType();
3536 return HasNoTypeMember;
3537 }
3538
3539 case BTK__hlsl_spirv_type: {
3540 assert(Converted.size() == 4);
3541
3542 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3543 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_hlsl_spirv_only) << BTD;
3544 }
3545
3546 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3547 return QualType();
3548
3549 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3550 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3551 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3552
3553 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3554
3555 llvm::SmallVector<SpirvOperand> Operands;
3556
3557 for (auto &OperandTA : OperandArgs) {
3558 QualType OperandArg = OperandTA.getAsType();
3559 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3560 Loc: TemplateArgs[3].getLocation());
3561 if (!Operand.isValid())
3562 return QualType();
3563 Operands.push_back(Elt: Operand);
3564 }
3565
3566 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3567 }
3568 case BTK__builtin_dedup_pack: {
3569 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3570 "a parameter pack");
3571 TemplateArgument Ts = Converted[0];
3572 // Delay the computation until we can compute the final result. We choose
3573 // not to remove the duplicates upfront before substitution to keep the code
3574 // simple.
3575 if (Ts.isDependent())
3576 return QualType();
3577 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3578 llvm::SmallVector<TemplateArgument> OutArgs;
3579 llvm::SmallDenseSet<QualType> Seen;
3580 // Synthesize a new template argument list, removing duplicates.
3581 for (auto T : Ts.getPackAsArray()) {
3582 assert(T.getKind() == clang::TemplateArgument::Type);
3583 if (!Seen.insert(V: T.getAsType().getCanonicalType()).second)
3584 continue;
3585 OutArgs.push_back(Elt: T);
3586 }
3587 return Context.getSubstBuiltinTemplatePack(
3588 ArgPack: TemplateArgument::CreatePackCopy(Context, Args: OutArgs));
3589 }
3590 }
3591 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3592}
3593
3594/// Determine whether this alias template is "enable_if_t".
3595/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3596static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3597 return AliasTemplate->getName() == "enable_if_t" ||
3598 AliasTemplate->getName() == "__enable_if_t";
3599}
3600
3601/// Collect all of the separable terms in the given condition, which
3602/// might be a conjunction.
3603///
3604/// FIXME: The right answer is to convert the logical expression into
3605/// disjunctive normal form, so we can find the first failed term
3606/// within each possible clause.
3607static void collectConjunctionTerms(Expr *Clause,
3608 SmallVectorImpl<Expr *> &Terms) {
3609 if (auto BinOp = dyn_cast<BinaryOperator>(Val: Clause->IgnoreParenImpCasts())) {
3610 if (BinOp->getOpcode() == BO_LAnd) {
3611 collectConjunctionTerms(Clause: BinOp->getLHS(), Terms);
3612 collectConjunctionTerms(Clause: BinOp->getRHS(), Terms);
3613 return;
3614 }
3615 }
3616
3617 Terms.push_back(Elt: Clause);
3618}
3619
3620// The ranges-v3 library uses an odd pattern of a top-level "||" with
3621// a left-hand side that is value-dependent but never true. Identify
3622// the idiom and ignore that term.
3623static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3624 // Top-level '||'.
3625 auto *BinOp = dyn_cast<BinaryOperator>(Val: Cond->IgnoreParenImpCasts());
3626 if (!BinOp) return Cond;
3627
3628 if (BinOp->getOpcode() != BO_LOr) return Cond;
3629
3630 // With an inner '==' that has a literal on the right-hand side.
3631 Expr *LHS = BinOp->getLHS();
3632 auto *InnerBinOp = dyn_cast<BinaryOperator>(Val: LHS->IgnoreParenImpCasts());
3633 if (!InnerBinOp) return Cond;
3634
3635 if (InnerBinOp->getOpcode() != BO_EQ ||
3636 !isa<IntegerLiteral>(Val: InnerBinOp->getRHS()))
3637 return Cond;
3638
3639 // If the inner binary operation came from a macro expansion named
3640 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3641 // of the '||', which is the real, user-provided condition.
3642 SourceLocation Loc = InnerBinOp->getExprLoc();
3643 if (!Loc.isMacroID()) return Cond;
3644
3645 StringRef MacroName = PP.getImmediateMacroName(Loc);
3646 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3647 return BinOp->getRHS();
3648
3649 return Cond;
3650}
3651
3652namespace {
3653
3654// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3655// within failing boolean expression, such as substituting template parameters
3656// for actual types.
3657class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3658public:
3659 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3660 : Policy(P) {}
3661
3662 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3663 const auto *DR = dyn_cast<DeclRefExpr>(Val: E);
3664 if (DR && DR->getQualifier()) {
3665 // If this is a qualified name, expand the template arguments in nested
3666 // qualifiers.
3667 DR->getQualifier().print(OS, Policy, ResolveTemplateArguments: true);
3668 // Then print the decl itself.
3669 const ValueDecl *VD = DR->getDecl();
3670 OS << *VD;
3671 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) {
3672 // This is a template variable, print the expanded template arguments.
3673 printTemplateArgumentList(
3674 OS, Args: IV->getTemplateArgs().asArray(), Policy,
3675 TPL: IV->getSpecializedTemplate()->getTemplateParameters());
3676 }
3677 return true;
3678 }
3679 return false;
3680 }
3681
3682private:
3683 const PrintingPolicy Policy;
3684};
3685
3686} // end anonymous namespace
3687
3688std::pair<Expr *, std::string>
3689Sema::findFailedBooleanCondition(Expr *Cond) {
3690 Cond = lookThroughRangesV3Condition(PP, Cond);
3691
3692 // Separate out all of the terms in a conjunction.
3693 SmallVector<Expr *, 4> Terms;
3694 collectConjunctionTerms(Clause: Cond, Terms);
3695
3696 // Determine which term failed.
3697 Expr *FailedCond = nullptr;
3698 for (Expr *Term : Terms) {
3699 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3700
3701 // Literals are uninteresting.
3702 if (isa<CXXBoolLiteralExpr>(Val: TermAsWritten) ||
3703 isa<IntegerLiteral>(Val: TermAsWritten))
3704 continue;
3705
3706 // The initialization of the parameter from the argument is
3707 // a constant-evaluated context.
3708 EnterExpressionEvaluationContext ConstantEvaluated(
3709 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3710
3711 bool Succeeded;
3712 if (Term->EvaluateAsBooleanCondition(Result&: Succeeded, Ctx: Context) &&
3713 !Succeeded) {
3714 FailedCond = TermAsWritten;
3715 break;
3716 }
3717 }
3718 if (!FailedCond)
3719 FailedCond = Cond->IgnoreParenImpCasts();
3720
3721 std::string Description;
3722 {
3723 llvm::raw_string_ostream Out(Description);
3724 PrintingPolicy Policy = getPrintingPolicy();
3725 Policy.PrintAsCanonical = true;
3726 FailedBooleanConditionPrinterHelper Helper(Policy);
3727 FailedCond->printPretty(OS&: Out, Helper: &Helper, Policy, Indentation: 0, NewlineSymbol: "\n", Context: nullptr);
3728 }
3729 return { FailedCond, Description };
3730}
3731
3732static TemplateName
3733resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope,
3734 const AssumedTemplateStorage *ATN,
3735 SourceLocation NameLoc) {
3736 // We assumed this undeclared identifier to be an (ADL-only) function
3737 // template name, but it was used in a context where a type was required.
3738 // Try to typo-correct it now.
3739 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3740 struct CandidateCallback : CorrectionCandidateCallback {
3741 bool ValidateCandidate(const TypoCorrection &TC) override {
3742 return TC.getCorrectionDecl() &&
3743 getAsTypeTemplateDecl(D: TC.getCorrectionDecl());
3744 }
3745 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3746 return std::make_unique<CandidateCallback>(args&: *this);
3747 }
3748 } FilterCCC;
3749
3750 TypoCorrection Corrected =
3751 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Scope,
3752 /*SS=*/nullptr, CCC&: FilterCCC, Mode: CorrectTypoKind::ErrorRecovery);
3753 if (Corrected && Corrected.getFoundDecl()) {
3754 S.diagnoseTypo(Correction: Corrected, TypoDiag: S.PDiag(DiagID: diag::err_no_template_suggest)
3755 << ATN->getDeclName());
3756 return S.Context.getQualifiedTemplateName(
3757 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3758 Template: TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()));
3759 }
3760
3761 return TemplateName();
3762}
3763
3764QualType Sema::CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
3765 TemplateName Name,
3766 SourceLocation TemplateLoc,
3767 TemplateArgumentListInfo &TemplateArgs,
3768 Scope *Scope, bool ForNestedNameSpecifier) {
3769 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3770
3771 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3772 if (!Template) {
3773 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3774 Template = S->getParameterPack();
3775 } else if (const auto *PI = UnderlyingName.getAsPackIndexingTemplate()) {
3776 Template = PI->getParameterPack();
3777 if (!Template)
3778 Template = PI->getPattern().getAsTemplateDecl();
3779 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3780 if (DTN->getName().getIdentifier())
3781 // When building a template-id where the template-name is dependent,
3782 // assume the template is a type template. Either our assumption is
3783 // correct, or the code is ill-formed and will be diagnosed when the
3784 // dependent name is substituted.
3785 return Context.getTemplateSpecializationType(Keyword, T: Name,
3786 SpecifiedArgs: TemplateArgs.arguments(),
3787 /*CanonicalArgs=*/{});
3788 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3789 if (TemplateName CorrectedName = ::resolveAssumedTemplateNameAsType(
3790 S&: *this, Scope, ATN, NameLoc: TemplateLoc);
3791 CorrectedName.isNull()) {
3792 Diag(Loc: TemplateLoc, DiagID: diag::err_no_template) << ATN->getDeclName();
3793 return QualType();
3794 } else {
3795 Name = CorrectedName;
3796 Template = Name.getAsTemplateDecl();
3797 }
3798 }
3799 }
3800 if (!Template ||
3801 isa<FunctionTemplateDecl, VarTemplateDecl, ConceptDecl>(Val: Template)) {
3802 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3803 if (ForNestedNameSpecifier)
3804 Diag(Loc: TemplateLoc, DiagID: diag::err_non_type_template_in_nested_name_specifier)
3805 << isa_and_nonnull<VarTemplateDecl>(Val: Template) << Name << R;
3806 else
3807 Diag(Loc: TemplateLoc, DiagID: diag::err_template_id_not_a_type) << Name << R;
3808 NoteAllFoundTemplates(Name);
3809 return QualType();
3810 }
3811
3812 // Check that the template argument list is well-formed for this
3813 // template.
3814 CheckTemplateArgumentInfo CTAI;
3815 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3816 DefaultArgs, /*PartialTemplateArgs=*/false,
3817 CTAI,
3818 /*UpdateArgsWithConversions=*/true))
3819 return QualType();
3820
3821 // FIXME: Diagnose uses of this template. DiagnoseUseOfDecl is quite slow,
3822 // and there are no diagnsotics currently implemented for TemplateDecls,
3823 // so avoid doing it for now.
3824 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Template, /*OdrUse=*/MightBeOdrUse: false);
3825
3826 QualType CanonType;
3827
3828 if (isa<TemplateTemplateParmDecl>(Val: Template)) {
3829 // We might have a substituted template template parameter pack. If so,
3830 // build a template specialization type for it.
3831 } else if (TypeAliasTemplateDecl *AliasTemplate =
3832 dyn_cast<TypeAliasTemplateDecl>(Val: Template)) {
3833
3834 // C++0x [dcl.type.elab]p2:
3835 // If the identifier resolves to a typedef-name or the simple-template-id
3836 // resolves to an alias template specialization, the
3837 // elaborated-type-specifier is ill-formed.
3838 if (Keyword != ElaboratedTypeKeyword::None &&
3839 Keyword != ElaboratedTypeKeyword::Typename) {
3840 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_tag_reference_non_tag)
3841 << AliasTemplate << NonTagKind::TypeAliasTemplate
3842 << KeywordHelpers::getTagTypeKindForKeyword(Keyword);
3843 SemaRef.Diag(Loc: AliasTemplate->getLocation(), DiagID: diag::note_declared_at);
3844 }
3845
3846 // Find the canonical type for this type alias template specialization.
3847 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3848
3849 // Diagnose uses of the pattern of this template.
3850 (void)DiagnoseUseOfDecl(D: Pattern, Locs: TemplateLoc);
3851 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Pattern, /*OdrUse=*/MightBeOdrUse: false);
3852
3853 if (Pattern->isInvalidDecl())
3854 return QualType();
3855
3856 // Only substitute for the innermost template argument list.
3857 MultiLevelTemplateArgumentList TemplateArgLists;
3858 TemplateArgLists.addOuterTemplateArguments(AssociatedDecl: Template, Args: CTAI.SugaredConverted,
3859 /*Final=*/true);
3860 TemplateArgLists.addOuterRetainedLevels(
3861 Num: AliasTemplate->getTemplateParameters()->getDepth());
3862
3863 LocalInstantiationScope Scope(*this);
3864
3865 // FIXME: The TemplateArgs passed here are not used for the context note,
3866 // nor they should, because this note will be pointing to the specialization
3867 // anyway. These arguments are needed for a hack for instantiating lambdas
3868 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3869 // arguments will be used for collating the template arguments needed to
3870 // instantiate the lambda.
3871 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3872 /*Entity=*/AliasTemplate,
3873 /*TemplateArgs=*/CTAI.SugaredConverted);
3874 if (Inst.isInvalid())
3875 return QualType();
3876
3877 std::optional<ContextRAII> SavedContext;
3878 if (!AliasTemplate->getDeclContext()->isFileContext())
3879 SavedContext.emplace(args&: *this, args: AliasTemplate->getDeclContext());
3880
3881 CanonType =
3882 SubstType(T: Pattern->getUnderlyingType(), TemplateArgs: TemplateArgLists,
3883 Loc: AliasTemplate->getLocation(), Entity: AliasTemplate->getDeclName());
3884 if (CanonType.isNull()) {
3885 // If this was enable_if and we failed to find the nested type
3886 // within enable_if in a SFINAE context, dig out the specific
3887 // enable_if condition that failed and present that instead.
3888 if (isEnableIfAliasTemplate(AliasTemplate)) {
3889 if (SFINAETrap *Trap = getSFINAEContext();
3890 TemplateDeductionInfo *DeductionInfo =
3891 Trap ? Trap->getDeductionInfo() : nullptr) {
3892 if (DeductionInfo->hasSFINAEDiagnostic() &&
3893 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3894 diag::err_typename_nested_not_found_enable_if &&
3895 TemplateArgs[0].getArgument().getKind() ==
3896 TemplateArgument::Expression) {
3897 Expr *FailedCond;
3898 std::string FailedDescription;
3899 std::tie(args&: FailedCond, args&: FailedDescription) =
3900 findFailedBooleanCondition(Cond: TemplateArgs[0].getSourceExpression());
3901
3902 // Remove the old SFINAE diagnostic.
3903 PartialDiagnosticAt OldDiag =
3904 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3905 DeductionInfo->takeSFINAEDiagnostic(PD&: OldDiag);
3906
3907 // Add a new SFINAE diagnostic specifying which condition
3908 // failed.
3909 DeductionInfo->addSFINAEDiagnostic(
3910 Loc: OldDiag.first,
3911 PD: PDiag(DiagID: diag::err_typename_nested_not_found_requirement)
3912 << FailedDescription << FailedCond->getSourceRange());
3913 }
3914 }
3915 }
3916
3917 return QualType();
3918 }
3919 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Val: Template)) {
3920 CanonType = checkBuiltinTemplateIdType(
3921 SemaRef&: *this, Keyword, BTD, Converted: CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3922 } else if (Name.isDependent() ||
3923 TemplateSpecializationType::anyDependentTemplateArguments(
3924 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
3925 // This class template specialization is a dependent
3926 // type. Therefore, its canonical type is another class template
3927 // specialization type that contains all of the converted
3928 // arguments in canonical form. This ensures that, e.g., A<T> and
3929 // A<T, T> have identical types when A is declared as:
3930 //
3931 // template<typename T, typename U = T> struct A;
3932 CanonType = Context.getCanonicalTemplateSpecializationType(
3933 Keyword: ElaboratedTypeKeyword::None,
3934 T: Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3935 CanonicalArgs: CTAI.CanonicalConverted);
3936 assert(CanonType->isCanonicalUnqualified());
3937
3938 // This might work out to be a current instantiation, in which
3939 // case the canonical type needs to be the InjectedClassNameType.
3940 //
3941 // TODO: in theory this could be a simple hashtable lookup; most
3942 // changes to CurContext don't change the set of current
3943 // instantiations.
3944 if (isa<ClassTemplateDecl>(Val: Template)) {
3945 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3946 // If we get out to a namespace, we're done.
3947 if (Ctx->isFileContext()) break;
3948
3949 // If this isn't a record, keep looking.
3950 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Ctx);
3951 if (!Record) continue;
3952
3953 // Look for one of the two cases with InjectedClassNameTypes
3954 // and check whether it's the same template.
3955 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Record) &&
3956 !Record->getDescribedClassTemplate())
3957 continue;
3958
3959 // Fetch the injected class name type and check whether its
3960 // injected type is equal to the type we just built.
3961 CanQualType ICNT = Context.getCanonicalTagType(TD: Record);
3962 CanQualType Injected =
3963 Record->getCanonicalTemplateSpecializationType(Ctx: Context);
3964
3965 if (CanonType != Injected)
3966 continue;
3967
3968 (void)DiagnoseUseOfDecl(D: Record, Locs: TemplateLoc);
3969 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Record, /*OdrUse=*/MightBeOdrUse: false);
3970
3971 // If so, the canonical type of this TST is the injected
3972 // class name type of the record we just found.
3973 CanonType = ICNT;
3974 break;
3975 }
3976 }
3977 } else if (ClassTemplateDecl *ClassTemplate =
3978 dyn_cast<ClassTemplateDecl>(Val: Template)) {
3979 // Find the class template specialization declaration that
3980 // corresponds to these arguments.
3981 llvm::FoldingSetInsertToken InsertToken;
3982 ClassTemplateSpecializationDecl *Decl =
3983 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertToken);
3984 if (!Decl) {
3985 // This is the first time we have referenced this class template
3986 // specialization. Create the canonical declaration and add it to
3987 // the set of specializations.
3988 Decl = ClassTemplateSpecializationDecl::Create(
3989 Context, TK: ClassTemplate->getTemplatedDecl()->getTagKind(),
3990 DC: ClassTemplate->getDeclContext(),
3991 StartLoc: ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3992 IdLoc: ClassTemplate->getLocation(), SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted,
3993 StrictPackMatch: CTAI.StrictPackMatch, PrevDecl: nullptr);
3994 ClassTemplate->AddSpecialization(D: Decl, InsertToken);
3995 if (ClassTemplate->isOutOfLine())
3996 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3997 }
3998
3999 if (Decl->getSpecializationKind() == TSK_Undeclared &&
4000 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4001 NonSFINAEContext _(*this);
4002 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4003 if (!Inst.isInvalid()) {
4004 MultiLevelTemplateArgumentList TemplateArgLists(Template,
4005 CTAI.CanonicalConverted,
4006 /*Final=*/false);
4007 InstantiateAttrsForDecl(TemplateArgs: TemplateArgLists,
4008 Pattern: ClassTemplate->getTemplatedDecl(), Inst: Decl);
4009 }
4010 }
4011
4012 // Diagnose uses of this specialization.
4013 (void)DiagnoseUseOfDecl(D: Decl, Locs: TemplateLoc);
4014 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Decl, /*OdrUse=*/MightBeOdrUse: false);
4015
4016 CanonType = Context.getCanonicalTagType(TD: Decl);
4017 assert(isa<RecordType>(CanonType) &&
4018 "type of non-dependent specialization is not a RecordType");
4019 } else {
4020 llvm_unreachable("Unhandled template kind");
4021 }
4022
4023 // Build the fully-sugared type for this class template
4024 // specialization, which refers back to the class template
4025 // specialization we created or found.
4026 return Context.getTemplateSpecializationType(
4027 Keyword, T: Name, SpecifiedArgs: TemplateArgs.arguments(), CanonicalArgs: CTAI.CanonicalConverted,
4028 Canon: CanonType);
4029}
4030
4031void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
4032 TemplateNameKind &TNK,
4033 SourceLocation NameLoc,
4034 IdentifierInfo *&II) {
4035 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4036
4037 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4038 assert(ATN && "not an assumed template name");
4039 II = ATN->getDeclName().getAsIdentifierInfo();
4040
4041 if (TemplateName Name =
4042 ::resolveAssumedTemplateNameAsType(S&: *this, Scope: S, ATN, NameLoc);
4043 !Name.isNull()) {
4044 // Resolved to a type template name.
4045 ParsedName = TemplateTy::make(P: Name);
4046 TNK = TNK_Type_template;
4047 }
4048}
4049
4050TypeResult Sema::ActOnTemplateIdType(
4051 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4052 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4053 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4054 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4055 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4056 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4057 ImplicitTypenameContext AllowImplicitTypename) {
4058 if (SS.isInvalid())
4059 return true;
4060
4061 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4062 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4063
4064 // C++ [temp.res]p3:
4065 // A qualified-id that refers to a type and in which the
4066 // nested-name-specifier depends on a template-parameter (14.6.2)
4067 // shall be prefixed by the keyword typename to indicate that the
4068 // qualified-id denotes a type, forming an
4069 // elaborated-type-specifier (7.1.5.3).
4070 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4071 // C++2a relaxes some of those restrictions in [temp.res]p5.
4072 QualType DNT = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
4073 NNS: SS.getScopeRep(), Name: TemplateII);
4074 NestedNameSpecifier NNS(DNT.getTypePtr());
4075 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4076 auto DB = DiagCompat(Loc: SS.getBeginLoc(), CompatDiagId: diag_compat::implicit_typename)
4077 << NNS;
4078 if (!getLangOpts().CPlusPlus20)
4079 DB << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "typename ");
4080 } else
4081 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_typename_missing_template) << NNS;
4082
4083 // FIXME: This is not quite correct recovery as we don't transform SS
4084 // into the corresponding dependent form (and we don't diagnose missing
4085 // 'template' keywords within SS as a result).
4086 return ActOnTypenameType(S: nullptr, TypenameLoc: SourceLocation(), SS, TemplateLoc: TemplateKWLoc,
4087 TemplateName: TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4088 TemplateArgs: TemplateArgsIn, RAngleLoc);
4089 }
4090
4091 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4092 // it's not actually allowed to be used as a type in most cases. Because
4093 // we annotate it before we know whether it's valid, we have to check for
4094 // this case here.
4095 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
4096 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4097 Diag(Loc: TemplateIILoc,
4098 DiagID: TemplateKWLoc.isInvalid()
4099 ? diag::err_out_of_line_qualified_id_type_names_constructor
4100 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4101 << TemplateII << 0 /*injected-class-name used as template name*/
4102 << 1 /*if any keyword was present, it was 'template'*/;
4103 }
4104 }
4105
4106 // Translate the parser's template argument list in our AST format.
4107 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4108 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4109
4110 QualType SpecTy = CheckTemplateIdType(
4111 Keyword: ElaboratedKeyword, Name: TemplateD.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
4112 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4113 if (SpecTy.isNull())
4114 return true;
4115
4116 // Build type-source information.
4117 TypeLocBuilder TLB;
4118 TLB.push<TemplateSpecializationTypeLoc>(T: SpecTy).set(
4119 ElaboratedKeywordLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
4120 NameLoc: TemplateIILoc, TAL: TemplateArgs);
4121 return CreateParsedType(T: SpecTy, TInfo: TLB.getTypeSourceInfo(Context, T: SpecTy));
4122}
4123
4124TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
4125 TypeSpecifierType TagSpec,
4126 SourceLocation TagLoc,
4127 CXXScopeSpec &SS,
4128 SourceLocation TemplateKWLoc,
4129 TemplateTy TemplateD,
4130 SourceLocation TemplateLoc,
4131 SourceLocation LAngleLoc,
4132 ASTTemplateArgsPtr TemplateArgsIn,
4133 SourceLocation RAngleLoc) {
4134 if (SS.isInvalid())
4135 return TypeResult(true);
4136
4137 // Translate the parser's template argument list in our AST format.
4138 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4139 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4140
4141 // Determine the tag kind
4142 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
4143 ElaboratedTypeKeyword Keyword
4144 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
4145
4146 QualType Result =
4147 CheckTemplateIdType(Keyword, Name: TemplateD.get(), TemplateLoc, TemplateArgs,
4148 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4149 if (Result.isNull())
4150 return TypeResult(true);
4151
4152 // Check the tag kind
4153 if (const RecordType *RT = Result->getAs<RecordType>()) {
4154 RecordDecl *D = RT->getDecl();
4155
4156 IdentifierInfo *Id = D->getIdentifier();
4157 assert(Id && "templated class must have an identifier");
4158
4159 if (!isAcceptableTagRedeclaration(Previous: D, NewTag: TagKind, isDefinition: TUK == TagUseKind::Definition,
4160 NewTagLoc: TagLoc, Name: Id)) {
4161 Diag(Loc: TagLoc, DiagID: diag::err_use_with_wrong_tag)
4162 << Result
4163 << FixItHint::CreateReplacement(RemoveRange: SourceRange(TagLoc), Code: D->getKindName());
4164 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_use);
4165 }
4166 }
4167
4168 // Provide source-location information for the template specialization.
4169 TypeLocBuilder TLB;
4170 TLB.push<TemplateSpecializationTypeLoc>(T: Result).set(
4171 ElaboratedKeywordLoc: TagLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc, NameLoc: TemplateLoc,
4172 TAL: TemplateArgs);
4173 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
4174}
4175
4176static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4177 NamedDecl *PrevDecl,
4178 SourceLocation Loc,
4179 bool IsPartialSpecialization);
4180
4181static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4182
4183static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg,
4184 unsigned Depth,
4185 unsigned Index) {
4186 switch (Arg.getKind()) {
4187 case TemplateArgument::Null:
4188 case TemplateArgument::NullPtr:
4189 case TemplateArgument::Integral:
4190 case TemplateArgument::Declaration:
4191 case TemplateArgument::StructuralValue:
4192 case TemplateArgument::Pack:
4193 case TemplateArgument::TemplateExpansion:
4194 return false;
4195
4196 case TemplateArgument::Type: {
4197 QualType Type = Arg.getAsType();
4198 const TemplateTypeParmType *TPT =
4199 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4200 return TPT && !Type.hasQualifiers() &&
4201 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4202 }
4203
4204 case TemplateArgument::Expression: {
4205 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg.getAsExpr());
4206 if (!DRE || !DRE->getDecl())
4207 return false;
4208 const NonTypeTemplateParmDecl *NTTP =
4209 dyn_cast<NonTypeTemplateParmDecl>(Val: DRE->getDecl());
4210 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4211 }
4212
4213 case TemplateArgument::Template:
4214 const TemplateTemplateParmDecl *TTP =
4215 dyn_cast_or_null<TemplateTemplateParmDecl>(
4216 Val: Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4217 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4218 }
4219 llvm_unreachable("unexpected kind of template argument");
4220}
4221
4222static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4223 TemplateParameterList *SpecParams,
4224 ArrayRef<TemplateArgument> Args) {
4225 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4226 return false;
4227
4228 unsigned Depth = Params->getDepth();
4229
4230 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4231 TemplateArgument Arg = Args[I];
4232
4233 // If the parameter is a pack expansion, the argument must be a pack
4234 // whose only element is a pack expansion.
4235 if (Params->getParam(Idx: I)->isParameterPack()) {
4236 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4237 !Arg.pack_begin()->isPackExpansion())
4238 return false;
4239 Arg = Arg.pack_begin()->getPackExpansionPattern();
4240 }
4241
4242 if (!isTemplateArgumentTemplateParameter(Arg, Depth, Index: I))
4243 return false;
4244
4245 // For NTTPs further specialization is allowed via deduced types, so
4246 // we need to make sure to only reject here if primary template and
4247 // specialization use the same type for the NTTP.
4248 if (auto *SpecNTTP =
4249 dyn_cast<NonTypeTemplateParmDecl>(Val: SpecParams->getParam(Idx: I))) {
4250 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: I));
4251 if (!NTTP || NTTP->getType().getCanonicalType() !=
4252 SpecNTTP->getType().getCanonicalType())
4253 return false;
4254 }
4255 }
4256
4257 return true;
4258}
4259
4260template<typename PartialSpecDecl>
4261static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4262 if (Partial->getDeclContext()->isDependentContext())
4263 return;
4264
4265 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4266 // for non-substitution-failure issues?
4267 TemplateDeductionInfo Info(Partial->getLocation());
4268 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4269 return;
4270
4271 auto *Template = Partial->getSpecializedTemplate();
4272 S.Diag(Partial->getLocation(),
4273 diag::ext_partial_spec_not_more_specialized_than_primary)
4274 << isa<VarTemplateDecl>(Template);
4275
4276 if (Info.hasSFINAEDiagnostic()) {
4277 PartialDiagnosticAt Diag = {SourceLocation(),
4278 PartialDiagnostic::NullDiagnostic()};
4279 Info.takeSFINAEDiagnostic(PD&: Diag);
4280 SmallString<128> SFINAEArgString;
4281 Diag.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
4282 S.Diag(Loc: Diag.first,
4283 DiagID: diag::note_partial_spec_not_more_specialized_than_primary)
4284 << SFINAEArgString;
4285 }
4286
4287 S.NoteTemplateLocation(Decl: *Template);
4288 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4289 Template->getAssociatedConstraints(TemplateAC);
4290 Partial->getAssociatedConstraints(PartialAC);
4291 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Partial, AC1: PartialAC, D2: Template,
4292 AC2: TemplateAC);
4293}
4294
4295static void
4296noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4297 const llvm::SmallBitVector &DeducibleParams) {
4298 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4299 if (!DeducibleParams[I]) {
4300 NamedDecl *Param = TemplateParams->getParam(Idx: I);
4301 if (Param->getDeclName())
4302 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4303 << Param->getDeclName();
4304 else
4305 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4306 << "(anonymous)";
4307 }
4308 }
4309}
4310
4311
4312template<typename PartialSpecDecl>
4313static void checkTemplatePartialSpecialization(Sema &S,
4314 PartialSpecDecl *Partial) {
4315 // C++1z [temp.class.spec]p8: (DR1495)
4316 // - The specialization shall be more specialized than the primary
4317 // template (14.5.5.2).
4318 checkMoreSpecializedThanPrimary(S, Partial);
4319
4320 // C++ [temp.class.spec]p8: (DR1315)
4321 // - Each template-parameter shall appear at least once in the
4322 // template-id outside a non-deduced context.
4323 // C++1z [temp.class.spec.match]p3 (P0127R2)
4324 // If the template arguments of a partial specialization cannot be
4325 // deduced because of the structure of its template-parameter-list
4326 // and the template-id, the program is ill-formed.
4327 auto *TemplateParams = Partial->getTemplateParameters();
4328 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4329 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4330 TemplateParams->getDepth(), DeducibleParams);
4331
4332 if (!DeducibleParams.all()) {
4333 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4334 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4335 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4336 << (NumNonDeducible > 1)
4337 << SourceRange(Partial->getLocation(),
4338 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4339 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4340 }
4341}
4342
4343void Sema::CheckTemplatePartialSpecialization(
4344 ClassTemplatePartialSpecializationDecl *Partial) {
4345 checkTemplatePartialSpecialization(S&: *this, Partial);
4346}
4347
4348void Sema::CheckTemplatePartialSpecialization(
4349 VarTemplatePartialSpecializationDecl *Partial) {
4350 checkTemplatePartialSpecialization(S&: *this, Partial);
4351}
4352
4353void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4354 // C++1z [temp.param]p11:
4355 // A template parameter of a deduction guide template that does not have a
4356 // default-argument shall be deducible from the parameter-type-list of the
4357 // deduction guide template.
4358 auto *TemplateParams = TD->getTemplateParameters();
4359 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4360 MarkDeducedTemplateParameters(FunctionTemplate: TD, Deduced&: DeducibleParams);
4361 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4362 // A parameter pack is deducible (to an empty pack).
4363 auto *Param = TemplateParams->getParam(Idx: I);
4364 if (Param->isParameterPack() || hasVisibleDefaultArgument(D: Param))
4365 DeducibleParams[I] = true;
4366 }
4367
4368 if (!DeducibleParams.all()) {
4369 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4370 Diag(Loc: TD->getLocation(), DiagID: diag::err_deduction_guide_template_not_deducible)
4371 << (NumNonDeducible > 1);
4372 noteNonDeducibleParameters(S&: *this, TemplateParams, DeducibleParams);
4373 }
4374}
4375
4376DeclResult Sema::ActOnVarTemplateSpecialization(
4377 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
4378 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4379 StorageClass SC, bool IsPartialSpecialization) {
4380 // D must be variable template id.
4381 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4382 "Variable template specialization is declared with a template id.");
4383
4384 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4385 TemplateArgumentListInfo TemplateArgs =
4386 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TemplateId);
4387 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4388 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4389 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4390
4391 TemplateName Name = TemplateId->Template.get();
4392
4393 // The template-id must name a variable template.
4394 VarTemplateDecl *VarTemplate =
4395 dyn_cast_or_null<VarTemplateDecl>(Val: Name.getAsTemplateDecl());
4396 if (!VarTemplate) {
4397 NamedDecl *FnTemplate;
4398 if (auto *OTS = Name.getAsOverloadedTemplate())
4399 FnTemplate = *OTS->begin();
4400 else
4401 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Val: Name.getAsTemplateDecl());
4402 if (FnTemplate)
4403 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template_but_method)
4404 << FnTemplate->getDeclName();
4405 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template)
4406 << IsPartialSpecialization;
4407 }
4408
4409 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4410 auto Message = DSA->getMessage();
4411 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
4412 << VarTemplate << !Message.empty() << Message;
4413 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
4414 }
4415
4416 // Check for unexpanded parameter packs in any of the template arguments.
4417 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4418 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
4419 UPPC: IsPartialSpecialization
4420 ? UPPC_PartialSpecialization
4421 : UPPC_ExplicitSpecialization))
4422 return true;
4423
4424 // Check that the template argument list is well-formed for this
4425 // template.
4426 CheckTemplateArgumentInfo CTAI;
4427 if (CheckTemplateArgumentList(Template: VarTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
4428 /*DefaultArgs=*/{},
4429 /*PartialTemplateArgs=*/false, CTAI,
4430 /*UpdateArgsWithConversions=*/true))
4431 return true;
4432
4433 // Find the variable template (partial) specialization declaration that
4434 // corresponds to these arguments.
4435 if (IsPartialSpecialization) {
4436 if (CheckTemplatePartialSpecializationArgs(Loc: TemplateNameLoc, PrimaryTemplate: VarTemplate,
4437 NumExplicitArgs: TemplateArgs.size(),
4438 Args: CTAI.CanonicalConverted))
4439 return true;
4440
4441 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4442 // we also do them during instantiation.
4443 if (!Name.isDependent() &&
4444 !TemplateSpecializationType::anyDependentTemplateArguments(
4445 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4446 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
4447 << VarTemplate->getDeclName();
4448 IsPartialSpecialization = false;
4449 }
4450
4451 if (isSameAsPrimaryTemplate(Params: VarTemplate->getTemplateParameters(),
4452 SpecParams: TemplateParams, Args: CTAI.CanonicalConverted) &&
4453 (!Context.getLangOpts().CPlusPlus20 ||
4454 !TemplateParams->hasAssociatedConstraints())) {
4455 // C++ [temp.class.spec]p9b3:
4456 //
4457 // -- The argument list of the specialization shall not be identical
4458 // to the implicit argument list of the primary template.
4459 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
4460 << /*variable template*/ 1
4461 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4462 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
4463 // FIXME: Recover from this by treating the declaration as a
4464 // redeclaration of the primary template.
4465 return true;
4466 }
4467 }
4468
4469 llvm::FoldingSetInsertToken InsertToken;
4470 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4471
4472 if (IsPartialSpecialization)
4473 PrevDecl = VarTemplate->findPartialSpecialization(
4474 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertToken);
4475 else
4476 PrevDecl =
4477 VarTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertToken);
4478
4479 VarTemplateSpecializationDecl *Specialization = nullptr;
4480
4481 // Check whether we can declare a variable template specialization in
4482 // the current scope.
4483 if (CheckTemplateSpecializationScope(S&: *this, Specialized: VarTemplate, PrevDecl,
4484 Loc: TemplateNameLoc,
4485 IsPartialSpecialization))
4486 return true;
4487
4488 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4489 // Since the only prior variable template specialization with these
4490 // arguments was referenced but not declared, reuse that
4491 // declaration node as our own, updating its source location and
4492 // the list of outer template parameters to reflect our new declaration.
4493 Specialization = PrevDecl;
4494 Specialization->setLocation(TemplateNameLoc);
4495 PrevDecl = nullptr;
4496 } else if (IsPartialSpecialization) {
4497 // Create a new class template partial specialization declaration node.
4498 VarTemplatePartialSpecializationDecl *PrevPartial =
4499 cast_or_null<VarTemplatePartialSpecializationDecl>(Val: PrevDecl);
4500 VarTemplatePartialSpecializationDecl *Partial =
4501 VarTemplatePartialSpecializationDecl::Create(
4502 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc,
4503 IdLoc: TemplateNameLoc, Params: TemplateParams, SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI,
4504 S: SC, Args: CTAI.CanonicalConverted);
4505 Partial->setTemplateArgsAsWritten(TemplateArgs);
4506
4507 if (!PrevPartial)
4508 VarTemplate->AddPartialSpecialization(D: Partial, InsertToken);
4509 Specialization = Partial;
4510
4511 CheckTemplatePartialSpecialization(Partial);
4512 } else {
4513 // Create a new class template specialization declaration node for
4514 // this explicit specialization or friend declaration.
4515 Specialization = VarTemplateSpecializationDecl::Create(
4516 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc, IdLoc: TemplateNameLoc,
4517 SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI, S: SC, Args: CTAI.CanonicalConverted);
4518 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4519
4520 if (!PrevDecl)
4521 VarTemplate->AddSpecialization(D: Specialization, InsertToken);
4522 }
4523
4524 // C++ [temp.expl.spec]p6:
4525 // If a template, a member template or the member of a class template is
4526 // explicitly specialized then that specialization shall be declared
4527 // before the first use of that specialization that would cause an implicit
4528 // instantiation to take place, in every translation unit in which such a
4529 // use occurs; no diagnostic is required.
4530 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4531 bool Okay = false;
4532 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4533 // Is there any previous explicit specialization declaration?
4534 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
4535 Okay = true;
4536 break;
4537 }
4538 }
4539
4540 if (!Okay) {
4541 SourceRange Range(TemplateNameLoc, RAngleLoc);
4542 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
4543 << Name << Range;
4544
4545 Diag(Loc: PrevDecl->getPointOfInstantiation(),
4546 DiagID: diag::note_instantiation_required_here)
4547 << (PrevDecl->getTemplateSpecializationKind() !=
4548 TSK_ImplicitInstantiation);
4549 return true;
4550 }
4551 }
4552
4553 Specialization->setLexicalDeclContext(CurContext);
4554
4555 // Add the specialization into its lexical context, so that it can
4556 // be seen when iterating through the list of declarations in that
4557 // context. However, specializations are not found by name lookup.
4558 CurContext->addDecl(D: Specialization);
4559
4560 // Note that this is an explicit specialization.
4561 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4562
4563 Previous.clear();
4564 if (PrevDecl)
4565 Previous.addDecl(D: PrevDecl);
4566 else if (Specialization->isStaticDataMember() &&
4567 Specialization->isOutOfLine())
4568 Specialization->setAccess(VarTemplate->getAccess());
4569
4570 return Specialization;
4571}
4572
4573namespace {
4574/// A partial specialization whose template arguments have matched
4575/// a given template-id.
4576struct PartialSpecMatchResult {
4577 VarTemplatePartialSpecializationDecl *Partial;
4578 TemplateArgumentList *Args;
4579};
4580
4581// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4582// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4583static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4584 if (Var->getName() != "format_kind" ||
4585 !Var->getDeclContext()->isStdNamespace())
4586 return false;
4587
4588 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4589 // release in which users can access std::format_kind.
4590 // We can use 20250520 as the final date, see the following commits.
4591 // GCC releases/gcc-15 branch:
4592 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4593 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4594 // GCC master branch:
4595 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4596 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4597 return PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2025'05'20);
4598}
4599} // end anonymous namespace
4600
4601DeclResult
4602Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4603 SourceLocation TemplateNameLoc,
4604 const TemplateArgumentListInfo &TemplateArgs,
4605 bool SetWrittenArgs) {
4606 assert(Template && "A variable template id without template?");
4607
4608 // Check that the template argument list is well-formed for this template.
4609 CheckTemplateArgumentInfo CTAI;
4610 if (CheckTemplateArgumentList(
4611 Template, TemplateLoc: TemplateNameLoc,
4612 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4613 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4614 /*UpdateArgsWithConversions=*/true))
4615 return true;
4616
4617 // Produce a placeholder value if the specialization is dependent.
4618 if (Template->getDeclContext()->isDependentContext() ||
4619 TemplateSpecializationType::anyDependentTemplateArguments(
4620 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4621 if (ParsingInitForAutoVars.empty())
4622 return DeclResult();
4623
4624 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4625 const TemplateArgument &Arg2) {
4626 return Context.isSameTemplateArgument(Arg1, Arg2);
4627 };
4628
4629 if (VarDecl *Var = Template->getTemplatedDecl();
4630 ParsingInitForAutoVars.count(Ptr: Var) &&
4631 // See comments on this function definition
4632 !IsLibstdcxxStdFormatKind(PP, Var) &&
4633 llvm::equal(
4634 LRange&: CTAI.CanonicalConverted,
4635 RRange: Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4636 P: IsSameTemplateArg)) {
4637 Diag(Loc: TemplateNameLoc,
4638 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4639 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4640 return true;
4641 }
4642
4643 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4644 Template->getPartialSpecializations(PS&: PartialSpecs);
4645 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4646 if (ParsingInitForAutoVars.count(Ptr: Partial) &&
4647 llvm::equal(LRange&: CTAI.CanonicalConverted,
4648 RRange: Partial->getTemplateArgs().asArray(),
4649 P: IsSameTemplateArg)) {
4650 Diag(Loc: TemplateNameLoc,
4651 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4652 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4653 << Partial->getType();
4654 return true;
4655 }
4656
4657 return DeclResult();
4658 }
4659
4660 // Find the variable template specialization declaration that
4661 // corresponds to these arguments.
4662 llvm::FoldingSetInsertToken InsertToken;
4663 if (VarTemplateSpecializationDecl *Spec =
4664 Template->findSpecialization(Args: CTAI.CanonicalConverted, InsertToken)) {
4665 checkSpecializationReachability(Loc: TemplateNameLoc, Spec);
4666 if (Spec->getType()->isUndeducedType()) {
4667 if (ParsingInitForAutoVars.count(Ptr: Spec))
4668 Diag(Loc: TemplateNameLoc,
4669 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4670 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4671 << Spec->getType();
4672 else
4673 // We are substituting the initializer of this variable template
4674 // specialization.
4675 Diag(Loc: TemplateNameLoc, DiagID: diag::err_var_template_spec_type_depends_on_self)
4676 << Spec << Spec->getType();
4677
4678 return true;
4679 }
4680 // If we already have a variable template specialization, return it.
4681 return Spec;
4682 }
4683
4684 // This is the first time we have referenced this variable template
4685 // specialization. Create the canonical declaration and add it to
4686 // the set of specializations, based on the closest partial specialization
4687 // that it represents. That is,
4688 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4689 const TemplateArgumentList *PartialSpecArgs = nullptr;
4690 bool AmbiguousPartialSpec = false;
4691 typedef PartialSpecMatchResult MatchResult;
4692 SmallVector<MatchResult, 4> Matched;
4693 SourceLocation PointOfInstantiation = TemplateNameLoc;
4694 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4695 /*ForTakingAddress=*/false);
4696
4697 // 1. Attempt to find the closest partial specialization that this
4698 // specializes, if any.
4699 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4700 // Perhaps better after unification of DeduceTemplateArguments() and
4701 // getMoreSpecializedPartialSpecialization().
4702 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4703 Template->getPartialSpecializations(PS&: PartialSpecs);
4704
4705 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4706 // C++ [temp.spec.partial.member]p2:
4707 // If the primary member template is explicitly specialized for a given
4708 // (implicit) specialization of the enclosing class template, the partial
4709 // specializations of the member template are ignored for this
4710 // specialization of the enclosing class template. If a partial
4711 // specialization of the member template is explicitly specialized for a
4712 // given (implicit) specialization of the enclosing class template, the
4713 // primary member template and its other partial specializations are still
4714 // considered for this specialization of the enclosing class template.
4715 if (Template->isMemberSpecialization() &&
4716 !Partial->isMemberSpecialization())
4717 continue;
4718
4719 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4720
4721 if (TemplateDeductionResult Result =
4722 DeduceTemplateArguments(Partial, TemplateArgs: CTAI.SugaredConverted, Info);
4723 Result != TemplateDeductionResult::Success) {
4724 // Store the failed-deduction information for use in diagnostics, later.
4725 // TODO: Actually use the failed-deduction info?
4726 FailedCandidates.addCandidate().set(
4727 Found: DeclAccessPair::make(D: Template, AS: AS_public), Spec: Partial,
4728 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
4729 (void)Result;
4730 } else {
4731 Matched.push_back(Elt: PartialSpecMatchResult());
4732 Matched.back().Partial = Partial;
4733 Matched.back().Args = Info.takeSugared();
4734 }
4735 }
4736
4737 if (Matched.size() >= 1) {
4738 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4739 if (Matched.size() == 1) {
4740 // -- If exactly one matching specialization is found, the
4741 // instantiation is generated from that specialization.
4742 // We don't need to do anything for this.
4743 } else {
4744 // -- If more than one matching specialization is found, the
4745 // partial order rules (14.5.4.2) are used to determine
4746 // whether one of the specializations is more specialized
4747 // than the others. If none of the specializations is more
4748 // specialized than all of the other matching
4749 // specializations, then the use of the variable template is
4750 // ambiguous and the program is ill-formed.
4751 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4752 PEnd = Matched.end();
4753 P != PEnd; ++P) {
4754 if (getMoreSpecializedPartialSpecialization(PS1: P->Partial, PS2: Best->Partial,
4755 Loc: PointOfInstantiation) ==
4756 P->Partial)
4757 Best = P;
4758 }
4759
4760 // Determine if the best partial specialization is more specialized than
4761 // the others.
4762 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4763 PEnd = Matched.end();
4764 P != PEnd; ++P) {
4765 if (P != Best && getMoreSpecializedPartialSpecialization(
4766 PS1: P->Partial, PS2: Best->Partial,
4767 Loc: PointOfInstantiation) != Best->Partial) {
4768 AmbiguousPartialSpec = true;
4769 break;
4770 }
4771 }
4772 }
4773
4774 // Instantiate using the best variable template partial specialization.
4775 InstantiationPattern = Best->Partial;
4776 PartialSpecArgs = Best->Args;
4777 } else {
4778 // -- If no match is found, the instantiation is generated
4779 // from the primary template.
4780 // InstantiationPattern = Template->getTemplatedDecl();
4781 }
4782
4783 // 2. Create the canonical declaration.
4784 // Note that we do not instantiate a definition until we see an odr-use
4785 // in DoMarkVarDeclReferenced().
4786 // FIXME: LateAttrs et al.?
4787 if (AmbiguousPartialSpec) {
4788 // Partial ordering did not produce a clear winner. Complain.
4789 Diag(Loc: PointOfInstantiation, DiagID: diag::err_partial_spec_ordering_ambiguous)
4790 << Template;
4791 // Print the matching partial specializations.
4792 for (MatchResult P : Matched)
4793 Diag(Loc: P.Partial->getLocation(), DiagID: diag::note_partial_spec_match)
4794 << getTemplateArgumentBindingsText(Params: P.Partial->getTemplateParameters(),
4795 Args: *P.Args);
4796 return true;
4797 }
4798
4799 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4800 VarTemplate: Template, FromVar: InstantiationPattern, PartialSpecArgs, Converted&: CTAI.CanonicalConverted,
4801 PointOfInstantiation: TemplateNameLoc /*, LateAttrs, StartingScope*/);
4802 if (!Decl)
4803 return true;
4804 if (SetWrittenArgs)
4805 Decl->setTemplateArgsAsWritten(TemplateArgs);
4806
4807 if (VarTemplatePartialSpecializationDecl *D =
4808 dyn_cast<VarTemplatePartialSpecializationDecl>(Val: InstantiationPattern))
4809 Decl->setInstantiationOf(PartialSpec: D, TemplateArgs: PartialSpecArgs);
4810
4811 checkSpecializationReachability(Loc: TemplateNameLoc, Spec: Decl);
4812
4813 assert(Decl && "No variable template specialization?");
4814 return Decl;
4815}
4816
4817ExprResult Sema::CheckVarTemplateId(
4818 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4819 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4820 const TemplateArgumentListInfo *TemplateArgs) {
4821
4822 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, TemplateNameLoc: NameInfo.getLoc(),
4823 TemplateArgs: *TemplateArgs, /*SetWrittenArgs=*/false);
4824 if (Decl.isInvalid())
4825 return ExprError();
4826
4827 if (!Decl.get())
4828 return ExprResult();
4829
4830 VarDecl *Var = cast<VarDecl>(Val: Decl.get());
4831 if (!Var->getTemplateSpecializationKind())
4832 Var->setTemplateSpecializationKind(TSK: TSK_ImplicitInstantiation,
4833 PointOfInstantiation: NameInfo.getLoc());
4834
4835 // Build an ordinary singleton decl ref.
4836 return BuildDeclarationNameExpr(SS, NameInfo, D: Var, FoundD, TemplateArgs);
4837}
4838
4839ExprResult Sema::CheckVarOrConceptTemplateTemplateId(
4840 const DeclarationNameInfo &NameInfo, TemplateName Template,
4841 const TemplateArgumentListInfo *TemplateArgs) {
4842 TemplateTemplateParmDecl *Parameter =
4843 Template.getAsTemplateTemplateParmDecl();
4844 assert(Parameter && "A variable template id without template?");
4845
4846 if (Parameter->templateParameterKind() !=
4847 TemplateNameKind::TNK_Var_template &&
4848 Parameter->templateParameterKind() !=
4849 TemplateNameKind::TNK_Concept_template)
4850 return ExprResult();
4851
4852 // Check that the template argument list is well-formed for this template.
4853 CheckTemplateArgumentInfo CTAI;
4854 if (CheckTemplateArgumentList(
4855 Template: Parameter, /*Template kw loc=*/TemplateLoc: {},
4856 // FIXME: TemplateArgs will not be modified because
4857 // UpdateArgsWithConversions is false, however, we should
4858 // CheckTemplateArgumentList to be const-correct.
4859 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4860 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4861 /*UpdateArgsWithConversions=*/false))
4862 return true;
4863
4864 return DependentTemplateIdExpr::Create(Context: getASTContext(), NameInfo, Name: Template,
4865 TemplateArgs: *TemplateArgs);
4866}
4867
4868void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4869 SourceLocation Loc) {
4870 Diag(Loc, DiagID: diag::err_template_missing_args)
4871 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4872 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4873 NoteTemplateLocation(Decl: *TD, ParamRange: TD->getTemplateParameters()->getSourceRange());
4874 }
4875}
4876
4877void Sema::diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
4878 bool TemplateKeyword,
4879 TemplateDecl *TD,
4880 SourceLocation Loc) {
4881 TemplateName Name = Context.getQualifiedTemplateName(
4882 Qualifier: SS.getScopeRep(), TemplateKeyword, Template: TemplateName(TD));
4883 diagnoseMissingTemplateArguments(Name, Loc);
4884}
4885
4886ExprResult Sema::CheckConceptTemplateId(
4887 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4888 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4889 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4890 bool DoCheckConstraintSatisfaction) {
4891 assert(NamedConcept && "A concept template id without a template?");
4892
4893 if (NamedConcept->isInvalidDecl())
4894 return ExprError();
4895
4896 CheckTemplateArgumentInfo CTAI;
4897 if (CheckTemplateArgumentList(
4898 Template: NamedConcept, TemplateLoc: ConceptNameInfo.getLoc(),
4899 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4900 /*DefaultArgs=*/{},
4901 /*PartialTemplateArgs=*/false, CTAI,
4902 /*UpdateArgsWithConversions=*/false))
4903 return ExprError();
4904
4905 DiagnoseUseOfDecl(D: NamedConcept, Locs: ConceptNameInfo.getLoc());
4906
4907 // There's a bug with CTAI.CanonicalConverted.
4908 // If the template argument contains a DependentDecltypeType that includes a
4909 // TypeAliasType, and the same written type had occurred previously in the
4910 // source, then the DependentDecltypeType would be canonicalized to that
4911 // previous type which would mess up the substitution.
4912 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4913 auto *CSD = ImplicitConceptSpecializationDecl::Create(
4914 C: Context, DC: NamedConcept->getDeclContext(), SL: NamedConcept->getLocation(),
4915 ConvertedArgs: CTAI.SugaredConverted);
4916 ConstraintSatisfaction Satisfaction;
4917 bool AreArgsDependent =
4918 TemplateSpecializationType::anyDependentTemplateArguments(
4919 *TemplateArgs, Converted: CTAI.SugaredConverted);
4920 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4921 /*Final=*/false);
4922 auto *CL = ConceptReference::Create(
4923 C: Context,
4924 NNS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4925 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept: TemplateName(NamedConcept),
4926 ArgsAsWritten: ASTTemplateArgumentListInfo::Create(C: Context, List: *TemplateArgs));
4927
4928 bool Error = false;
4929 if (const auto *Concept = dyn_cast<ConceptDecl>(Val: NamedConcept);
4930 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4931 DoCheckConstraintSatisfaction) {
4932
4933 LocalInstantiationScope Scope(*this);
4934
4935 EnterExpressionEvaluationContext EECtx{
4936 *this, ExpressionEvaluationContext::Unevaluated};
4937
4938 Error = CheckConstraintSatisfaction(
4939 Entity: NamedConcept, AssociatedConstraints: AssociatedConstraint(Concept->getConstraintExpr()), TemplateArgLists: MLTAL,
4940 TemplateIDRange: SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4941 TemplateArgs->getRAngleLoc()),
4942 Satisfaction, TopLevelConceptId: CL);
4943 Satisfaction.ContainsErrors = Error;
4944 }
4945
4946 if (Error)
4947 return ExprError();
4948
4949 return ConceptSpecializationExpr::Create(
4950 C: Context, ConceptRef: CL, SpecDecl: CSD, Satisfaction: AreArgsDependent ? nullptr : &Satisfaction);
4951}
4952
4953ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4954 SourceLocation TemplateKWLoc,
4955 LookupResult &R,
4956 bool RequiresADL,
4957 const TemplateArgumentListInfo *TemplateArgs) {
4958 // FIXME: Can we do any checking at this point? I guess we could check the
4959 // template arguments that we have against the template name, if the template
4960 // name refers to a single template. That's not a terribly common case,
4961 // though.
4962 // foo<int> could identify a single function unambiguously
4963 // This approach does NOT work, since f<int>(1);
4964 // gets resolved prior to resorting to overload resolution
4965 // i.e., template<class T> void f(double);
4966 // vs template<class T, class U> void f(U);
4967
4968 // These should be filtered out by our callers.
4969 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4970
4971 // Non-function templates require a template argument list.
4972 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4973 if (!TemplateArgs && !isa<FunctionTemplateDecl>(Val: TD)) {
4974 diagnoseMissingTemplateArguments(
4975 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, Loc: R.getNameLoc());
4976 return ExprError();
4977 }
4978 }
4979 bool KnownDependent = false;
4980 // In C++1y, check variable template ids.
4981 if (R.getAsSingle<VarTemplateDecl>()) {
4982 ExprResult Res = CheckVarTemplateId(
4983 SS, NameInfo: R.getLookupNameInfo(), Template: R.getAsSingle<VarTemplateDecl>(),
4984 FoundD: R.getRepresentativeDecl(), TemplateLoc: TemplateKWLoc, TemplateArgs);
4985 if (Res.isInvalid() || Res.isUsable())
4986 return Res;
4987 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4988 KnownDependent = true;
4989 }
4990
4991 // We don't want lookup warnings at this point.
4992 R.suppressDiagnostics();
4993
4994 if (R.getAsSingle<ConceptDecl>()) {
4995 assert(TemplateKWLoc.isInvalid() &&
4996 "template keyword in front of a concept id?");
4997 return CheckConceptTemplateId(SS, TemplateKWLoc, ConceptNameInfo: R.getLookupNameInfo(),
4998 FoundDecl: R.getRepresentativeDecl(),
4999 NamedConcept: R.getAsSingle<ConceptDecl>(), TemplateArgs);
5000 }
5001
5002 // Check variable template ids (C++17) and concept template parameters
5003 // (C++26).
5004 UnresolvedLookupExpr *ULE;
5005 if (R.getAsSingle<TemplateTemplateParmDecl>()) {
5006 assert(SS.isEmpty() && "template parameter with a scope specifier?");
5007 assert(TemplateKWLoc.isInvalid() &&
5008 "template keyword in front of a template parameter?");
5009 return CheckVarOrConceptTemplateTemplateId(
5010 NameInfo: R.getLookupNameInfo(),
5011 Template: TemplateName(R.getAsSingle<TemplateTemplateParmDecl>()), TemplateArgs);
5012 }
5013
5014 // Function templates
5015 ULE = UnresolvedLookupExpr::Create(
5016 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
5017 TemplateKWLoc, NameInfo: R.getLookupNameInfo(), RequiresADL, Args: TemplateArgs,
5018 Begin: R.begin(), End: R.end(), KnownDependent,
5019 /*KnownInstantiationDependent=*/false);
5020 // Model the templates with UnresolvedTemplateTy. The expression should then
5021 // either be transformed in an instantiation or be diagnosed in
5022 // CheckPlaceholderExpr.
5023 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5024 !R.getFoundDecl()->getAsFunction())
5025 ULE->setType(Context.UnresolvedTemplateTy);
5026
5027 return ULE;
5028}
5029
5030ExprResult Sema::BuildQualifiedTemplateIdExpr(
5031 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5032 const DeclarationNameInfo &NameInfo,
5033 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5034 assert(TemplateArgs || TemplateKWLoc.isValid());
5035
5036 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5037 if (LookupTemplateName(Found&: R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5038 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc))
5039 return ExprError();
5040
5041 if (R.isAmbiguous())
5042 return ExprError();
5043
5044 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5045 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5046
5047 if (R.empty()) {
5048 DeclContext *DC = computeDeclContext(SS);
5049 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
5050 << NameInfo.getName() << DC << SS.getRange();
5051 return ExprError();
5052 }
5053
5054 // If necessary, build an implicit class member access.
5055 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5056 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5057 /*S=*/nullptr);
5058
5059 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/RequiresADL: false, TemplateArgs);
5060}
5061
5062TemplateNameKind Sema::ActOnTemplateName(Scope *S,
5063 CXXScopeSpec &SS,
5064 SourceLocation TemplateKWLoc,
5065 const UnqualifiedId &Name,
5066 ParsedType ObjectType,
5067 bool EnteringContext,
5068 TemplateTy &Result,
5069 bool AllowInjectedClassName) {
5070 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5071 DiagCompat(Loc: TemplateKWLoc, CompatDiagId: diag_compat::template_outside_of_template)
5072 << FixItHint::CreateRemoval(RemoveRange: TemplateKWLoc);
5073
5074 if (SS.isInvalid())
5075 return TNK_Non_template;
5076
5077 // Figure out where isTemplateName is going to look.
5078 DeclContext *LookupCtx = nullptr;
5079 if (SS.isNotEmpty())
5080 LookupCtx = computeDeclContext(SS, EnteringContext);
5081 else if (ObjectType)
5082 LookupCtx = computeDeclContext(T: GetTypeFromParser(Ty: ObjectType));
5083
5084 // C++0x [temp.names]p5:
5085 // If a name prefixed by the keyword template is not the name of
5086 // a template, the program is ill-formed. [Note: the keyword
5087 // template may not be applied to non-template members of class
5088 // templates. -end note ] [ Note: as is the case with the
5089 // typename prefix, the template prefix is allowed in cases
5090 // where it is not strictly necessary; i.e., when the
5091 // nested-name-specifier or the expression on the left of the ->
5092 // or . is not dependent on a template-parameter, or the use
5093 // does not appear in the scope of a template. -end note]
5094 //
5095 // Note: C++03 was more strict here, because it banned the use of
5096 // the "template" keyword prior to a template-name that was not a
5097 // dependent name. C++ DR468 relaxed this requirement (the
5098 // "template" keyword is now permitted). We follow the C++0x
5099 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5100 bool MemberOfUnknownSpecialization;
5101 TemplateNameKind TNK = isTemplateName(S, SS, hasTemplateKeyword: TemplateKWLoc.isValid(), Name,
5102 ObjectTypePtr: ObjectType, EnteringContext, TemplateResult&: Result,
5103 MemberOfUnknownSpecialization);
5104 if (TNK != TNK_Non_template) {
5105 // We resolved this to a (non-dependent) template name. Return it.
5106 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
5107 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5108 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5109 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5110 // C++14 [class.qual]p2:
5111 // In a lookup in which function names are not ignored and the
5112 // nested-name-specifier nominates a class C, if the name specified
5113 // [...] is the injected-class-name of C, [...] the name is instead
5114 // considered to name the constructor
5115 //
5116 // We don't get here if naming the constructor would be valid, so we
5117 // just reject immediately and recover by treating the
5118 // injected-class-name as naming the template.
5119 Diag(Loc: Name.getBeginLoc(),
5120 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
5121 << Name.Identifier
5122 << 0 /*injected-class-name used as template name*/
5123 << TemplateKWLoc.isValid();
5124 }
5125 return TNK;
5126 }
5127
5128 if (!MemberOfUnknownSpecialization) {
5129 // Didn't find a template name, and the lookup wasn't dependent.
5130 // Do the lookup again to determine if this is a "nothing found" case or
5131 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5132 // need to do this.
5133 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
5134 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5135 LookupOrdinaryName);
5136 // Tell LookupTemplateName that we require a template so that it diagnoses
5137 // cases where it finds a non-template.
5138 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5139 ? RequiredTemplateKind(TemplateKWLoc)
5140 : TemplateNameIsRequired;
5141 if (!LookupTemplateName(Found&: R, S, SS, ObjectType: ObjectType.get(), EnteringContext, RequiredTemplate: RTK,
5142 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5143 !R.isAmbiguous()) {
5144 if (LookupCtx)
5145 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_no_member)
5146 << DNI.getName() << LookupCtx << SS.getRange();
5147 else
5148 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_undeclared_use)
5149 << DNI.getName() << SS.getRange();
5150 }
5151 return TNK_Non_template;
5152 }
5153
5154 NestedNameSpecifier Qualifier = SS.getScopeRep();
5155
5156 switch (Name.getKind()) {
5157 case UnqualifiedIdKind::IK_Identifier:
5158 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5159 Name: {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5160 return TNK_Dependent_template_name;
5161
5162 case UnqualifiedIdKind::IK_OperatorFunctionId:
5163 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5164 Name: {Qualifier, Name.OperatorFunctionId.Operator,
5165 TemplateKWLoc.isValid()}));
5166 return TNK_Function_template;
5167
5168 case UnqualifiedIdKind::IK_LiteralOperatorId:
5169 // This is a kind of template name, but can never occur in a dependent
5170 // scope (literal operators can only be declared at namespace scope).
5171 break;
5172
5173 default:
5174 break;
5175 }
5176
5177 // This name cannot possibly name a dependent template. Diagnose this now
5178 // rather than building a dependent template name that can never be valid.
5179 Diag(Loc: Name.getBeginLoc(),
5180 DiagID: diag::err_template_kw_refers_to_dependent_non_template)
5181 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5182 << TemplateKWLoc.isValid() << TemplateKWLoc;
5183 return TNK_Non_template;
5184}
5185
5186bool Sema::CheckTemplateTypeArgument(
5187 TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
5188 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5189 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5190 const TemplateArgument &Arg = AL.getArgument();
5191 QualType ArgType;
5192 TypeSourceInfo *TSI = nullptr;
5193
5194 // Check template type parameter.
5195 switch(Arg.getKind()) {
5196 case TemplateArgument::Type:
5197 // C++ [temp.arg.type]p1:
5198 // A template-argument for a template-parameter which is a
5199 // type shall be a type-id.
5200 ArgType = Arg.getAsType();
5201 TSI = AL.getTypeSourceInfo();
5202 break;
5203 case TemplateArgument::Template:
5204 case TemplateArgument::TemplateExpansion: {
5205 // We have a template type parameter but the template argument
5206 // is a template without any arguments.
5207 SourceRange SR = AL.getSourceRange();
5208 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
5209 diagnoseMissingTemplateArguments(Name, Loc: SR.getEnd());
5210 return true;
5211 }
5212 case TemplateArgument::Expression: {
5213 // We have a template type parameter but the template argument is an
5214 // expression; see if maybe it is missing the "typename" keyword.
5215 CXXScopeSpec SS;
5216 DeclarationNameInfo NameInfo;
5217
5218 if (DependentScopeDeclRefExpr *ArgExpr =
5219 dyn_cast<DependentScopeDeclRefExpr>(Val: Arg.getAsExpr())) {
5220 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5221 NameInfo = ArgExpr->getNameInfo();
5222 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5223 dyn_cast<CXXDependentScopeMemberExpr>(Val: Arg.getAsExpr())) {
5224 if (ArgExpr->isImplicitAccess()) {
5225 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5226 NameInfo = ArgExpr->getMemberNameInfo();
5227 }
5228 }
5229
5230 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5231 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5232 LookupParsedName(R&: Result, S: CurScope, SS: &SS, /*ObjectType=*/QualType());
5233
5234 if (Result.getAsSingle<TypeDecl>() ||
5235 Result.wasNotFoundInCurrentInstantiation()) {
5236 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5237 // Suggest that the user add 'typename' before the NNS.
5238 SourceLocation Loc = AL.getSourceRange().getBegin();
5239 Diag(Loc, DiagID: getLangOpts().MSVCCompat
5240 ? diag::ext_ms_template_type_arg_missing_typename
5241 : diag::err_template_arg_must_be_type_suggest)
5242 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
5243 NoteTemplateParameterLocation(Decl: *Param);
5244
5245 // Recover by synthesizing a type using the location information that we
5246 // already have.
5247 ArgType = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
5248 NNS: SS.getScopeRep(), Name: II);
5249 TypeLocBuilder TLB;
5250 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: ArgType);
5251 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5252 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5253 TL.setNameLoc(NameInfo.getLoc());
5254 TSI = TLB.getTypeSourceInfo(Context, T: ArgType);
5255
5256 // Overwrite our input TemplateArgumentLoc so that we can recover
5257 // properly.
5258 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5259 TemplateArgumentLocInfo(TSI));
5260
5261 break;
5262 }
5263 }
5264 // fallthrough
5265 [[fallthrough]];
5266 }
5267 default: {
5268 // We allow instantiating a template with template argument packs when
5269 // building deduction guides or mapping constraint template parameters.
5270 if (Arg.getKind() == TemplateArgument::Pack &&
5271 (CodeSynthesisContexts.back().Kind ==
5272 Sema::CodeSynthesisContext::BuildingDeductionGuides ||
5273 inParameterMappingSubstitution())) {
5274 SugaredConverted.push_back(Elt: Arg);
5275 CanonicalConverted.push_back(Elt: Arg);
5276 return false;
5277 }
5278 // We have a template type parameter but the template argument
5279 // is not a type.
5280 SourceRange SR = AL.getSourceRange();
5281 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_type) << SR;
5282 NoteTemplateParameterLocation(Decl: *Param);
5283
5284 return true;
5285 }
5286 }
5287
5288 if (CheckTemplateArgument(Arg: TSI))
5289 return true;
5290
5291 // Objective-C ARC:
5292 // If an explicitly-specified template argument type is a lifetime type
5293 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5294 if (getLangOpts().ObjCAutoRefCount &&
5295 ArgType->isObjCLifetimeType() &&
5296 !ArgType.getObjCLifetime()) {
5297 Qualifiers Qs;
5298 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5299 ArgType = Context.getQualifiedType(T: ArgType, Qs);
5300 }
5301
5302 SugaredConverted.push_back(Elt: TemplateArgument(ArgType));
5303 CanonicalConverted.push_back(
5304 Elt: TemplateArgument(Context.getCanonicalType(T: ArgType)));
5305 return false;
5306}
5307
5308/// Substitute template arguments into the default template argument for
5309/// the given template type parameter.
5310///
5311/// \param SemaRef the semantic analysis object for which we are performing
5312/// the substitution.
5313///
5314/// \param Template the template that we are synthesizing template arguments
5315/// for.
5316///
5317/// \param TemplateLoc the location of the template name that started the
5318/// template-id we are checking.
5319///
5320/// \param RAngleLoc the location of the right angle bracket ('>') that
5321/// terminates the template-id.
5322///
5323/// \param Param the template template parameter whose default we are
5324/// substituting into.
5325///
5326/// \param Converted the list of template arguments provided for template
5327/// parameters that precede \p Param in the template parameter list.
5328///
5329/// \param Output the resulting substituted template argument.
5330///
5331/// \returns true if an error occurred.
5332static bool SubstDefaultTemplateArgument(
5333 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5334 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5335 ArrayRef<TemplateArgument> SugaredConverted,
5336 ArrayRef<TemplateArgument> CanonicalConverted,
5337 TemplateArgumentLoc &Output) {
5338 Output = Param->getDefaultArgument();
5339
5340 // If the argument type is dependent, instantiate it now based
5341 // on the previously-computed template arguments.
5342 if (Output.getArgument().isInstantiationDependent()) {
5343 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5344 SugaredConverted,
5345 SourceRange(TemplateLoc, RAngleLoc));
5346 if (Inst.isInvalid())
5347 return true;
5348
5349 // Only substitute for the innermost template argument list.
5350 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5351 /*Final=*/true);
5352 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5353 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5354
5355 bool ForLambdaCallOperator = false;
5356 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Val: Template->getDeclContext()))
5357 ForLambdaCallOperator = Rec->isLambda();
5358 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5359 !ForLambdaCallOperator);
5360
5361 if (SemaRef.SubstTemplateArgument(Input: Output, TemplateArgs: TemplateArgLists, Output,
5362 Loc: Param->getDefaultArgumentLoc(),
5363 Entity: Param->getDeclName()))
5364 return true;
5365 }
5366
5367 return false;
5368}
5369
5370/// Substitute template arguments into the default template argument for
5371/// the given non-type template parameter.
5372///
5373/// \param SemaRef the semantic analysis object for which we are performing
5374/// the substitution.
5375///
5376/// \param Template the template that we are synthesizing template arguments
5377/// for.
5378///
5379/// \param TemplateLoc the location of the template name that started the
5380/// template-id we are checking.
5381///
5382/// \param RAngleLoc the location of the right angle bracket ('>') that
5383/// terminates the template-id.
5384///
5385/// \param Param the non-type template parameter whose default we are
5386/// substituting into.
5387///
5388/// \param Converted the list of template arguments provided for template
5389/// parameters that precede \p Param in the template parameter list.
5390///
5391/// \returns the substituted template argument, or NULL if an error occurred.
5392static bool SubstDefaultTemplateArgument(
5393 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5394 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5395 ArrayRef<TemplateArgument> SugaredConverted,
5396 ArrayRef<TemplateArgument> CanonicalConverted,
5397 TemplateArgumentLoc &Output) {
5398 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5399 SugaredConverted,
5400 SourceRange(TemplateLoc, RAngleLoc));
5401 if (Inst.isInvalid())
5402 return true;
5403
5404 // Only substitute for the innermost template argument list.
5405 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5406 /*Final=*/true);
5407 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5408 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5409
5410 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5411 EnterExpressionEvaluationContext ConstantEvaluated(
5412 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5413 return SemaRef.SubstTemplateArgument(Input: Param->getDefaultArgument(),
5414 TemplateArgs: TemplateArgLists, Output);
5415}
5416
5417/// Substitute template arguments into the default template argument for
5418/// the given template template parameter.
5419///
5420/// \param SemaRef the semantic analysis object for which we are performing
5421/// the substitution.
5422///
5423/// \param Template the template that we are synthesizing template arguments
5424/// for.
5425///
5426/// \param TemplateLoc the location of the template name that started the
5427/// template-id we are checking.
5428///
5429/// \param RAngleLoc the location of the right angle bracket ('>') that
5430/// terminates the template-id.
5431///
5432/// \param Param the template template parameter whose default we are
5433/// substituting into.
5434///
5435/// \param Converted the list of template arguments provided for template
5436/// parameters that precede \p Param in the template parameter list.
5437///
5438/// \param QualifierLoc Will be set to the nested-name-specifier (with
5439/// source-location information) that precedes the template name.
5440///
5441/// \returns the substituted template argument, or NULL if an error occurred.
5442static TemplateName SubstDefaultTemplateArgument(
5443 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5444 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5445 TemplateTemplateParmDecl *Param,
5446 ArrayRef<TemplateArgument> SugaredConverted,
5447 ArrayRef<TemplateArgument> CanonicalConverted,
5448 NestedNameSpecifierLoc &QualifierLoc) {
5449 Sema::InstantiatingTemplate Inst(
5450 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5451 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5452 if (Inst.isInvalid())
5453 return TemplateName();
5454
5455 // Only substitute for the innermost template argument list.
5456 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5457 /*Final=*/true);
5458 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5459 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5460
5461 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5462
5463 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5464 QualifierLoc = A.getTemplateQualifierLoc();
5465 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5466 Name: A.getArgument().getAsTemplate(),
5467 NameLoc: A.getTemplateNameLoc(), TemplateArgs: TemplateArgLists);
5468}
5469
5470TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
5471 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5472 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5473 ArrayRef<TemplateArgument> SugaredConverted,
5474 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5475 HasDefaultArg = false;
5476
5477 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
5478 if (!hasReachableDefaultArgument(D: TypeParm))
5479 return TemplateArgumentLoc();
5480
5481 HasDefaultArg = true;
5482 TemplateArgumentLoc Output;
5483 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5484 RAngleLoc, Param: TypeParm, SugaredConverted,
5485 CanonicalConverted, Output))
5486 return TemplateArgumentLoc();
5487 return Output;
5488 }
5489
5490 if (NonTypeTemplateParmDecl *NonTypeParm
5491 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5492 if (!hasReachableDefaultArgument(D: NonTypeParm))
5493 return TemplateArgumentLoc();
5494
5495 HasDefaultArg = true;
5496 TemplateArgumentLoc Output;
5497 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5498 RAngleLoc, Param: NonTypeParm, SugaredConverted,
5499 CanonicalConverted, Output))
5500 return TemplateArgumentLoc();
5501 return Output;
5502 }
5503
5504 TemplateTemplateParmDecl *TempTempParm
5505 = cast<TemplateTemplateParmDecl>(Val: Param);
5506 if (!hasReachableDefaultArgument(D: TempTempParm))
5507 return TemplateArgumentLoc();
5508
5509 HasDefaultArg = true;
5510 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5511 NestedNameSpecifierLoc QualifierLoc;
5512 TemplateName TName = SubstDefaultTemplateArgument(
5513 SemaRef&: *this, Template, TemplateKWLoc, TemplateLoc: TemplateNameLoc, RAngleLoc, Param: TempTempParm,
5514 SugaredConverted, CanonicalConverted, QualifierLoc);
5515 if (TName.isNull())
5516 return TemplateArgumentLoc();
5517
5518 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5519 QualifierLoc, A.getTemplateNameLoc());
5520}
5521
5522/// Convert a template-argument that we parsed as a type into a template, if
5523/// possible. C++ permits injected-class-names to perform dual service as
5524/// template template arguments and as template type arguments.
5525static TemplateArgumentLoc
5526convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5527 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5528 if (!TagLoc)
5529 return TemplateArgumentLoc();
5530
5531 // If this type was written as an injected-class-name, it can be used as a
5532 // template template argument.
5533 // If this type was written as an injected-class-name, it may have been
5534 // converted to a RecordType during instantiation. If the RecordType is
5535 // *not* wrapped in a TemplateSpecializationType and denotes a class
5536 // template specialization, it must have come from an injected-class-name.
5537
5538 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Ctx: Context);
5539 if (Name.isNull())
5540 return TemplateArgumentLoc();
5541
5542 return TemplateArgumentLoc(Context, Name,
5543 /*TemplateKWLoc=*/SourceLocation(),
5544 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5545}
5546
5547bool Sema::CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &ArgLoc,
5548 NamedDecl *Template,
5549 SourceLocation TemplateLoc,
5550 SourceLocation RAngleLoc,
5551 unsigned ArgumentPackIndex,
5552 CheckTemplateArgumentInfo &CTAI,
5553 CheckTemplateArgumentKind CTAK) {
5554 // Check template type parameters.
5555 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param))
5556 return CheckTemplateTypeArgument(Param: TTP, AL&: ArgLoc, SugaredConverted&: CTAI.SugaredConverted,
5557 CanonicalConverted&: CTAI.CanonicalConverted);
5558
5559 const TemplateArgument &Arg = ArgLoc.getArgument();
5560 // Check non-type template parameters.
5561 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5562 // Do substitution on the type of the non-type template parameter
5563 // with the template arguments we've seen thus far. But if the
5564 // template has a dependent context then we cannot substitute yet.
5565 QualType NTTPType = NTTP->getType();
5566 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5567 NTTPType = NTTP->getExpansionType(I: ArgumentPackIndex);
5568
5569 if (NTTPType->isInstantiationDependentType()) {
5570 // Do substitution on the type of the non-type template parameter.
5571 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5572 CTAI.SugaredConverted,
5573 SourceRange(TemplateLoc, RAngleLoc));
5574 if (Inst.isInvalid())
5575 return true;
5576
5577 MultiLevelTemplateArgumentList MLTAL(Template, CTAI.SugaredConverted,
5578 /*Final=*/true);
5579 MLTAL.addOuterRetainedLevels(Num: NTTP->getDepth());
5580 // If the parameter is a pack expansion, expand this slice of the pack.
5581 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5582 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5583 NTTPType = SubstType(T: PET->getPattern(), TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5584 Entity: NTTP->getDeclName());
5585 } else {
5586 NTTPType = SubstType(T: NTTPType, TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5587 Entity: NTTP->getDeclName());
5588 }
5589
5590 // If that worked, check the non-type template parameter type
5591 // for validity.
5592 if (!NTTPType.isNull())
5593 NTTPType = CheckNonTypeTemplateParameterType(T: NTTPType,
5594 Loc: NTTP->getLocation());
5595 if (NTTPType.isNull())
5596 return true;
5597 }
5598
5599 auto checkExpr = [&](Expr *E) -> Expr * {
5600 TemplateArgument SugaredResult, CanonicalResult;
5601 ExprResult Res = CheckTemplateArgument(
5602 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E, SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5603 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5604 // If the current template argument causes an error, give up now.
5605 if (Res.isInvalid())
5606 return nullptr;
5607 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5608 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5609 return Res.get();
5610 };
5611
5612 switch (Arg.getKind()) {
5613 case TemplateArgument::Null:
5614 llvm_unreachable("Should never see a NULL template argument here");
5615
5616 case TemplateArgument::Expression: {
5617 Expr *E = Arg.getAsExpr();
5618 Expr *R = checkExpr(E);
5619 if (!R)
5620 return true;
5621 // If the resulting expression is new, then use it in place of the
5622 // old expression in the template argument.
5623 if (R != E) {
5624 TemplateArgument TA(R, /*IsCanonical=*/false);
5625 ArgLoc = TemplateArgumentLoc(TA, R);
5626 }
5627 break;
5628 }
5629
5630 // As for the converted NTTP kinds, they still might need another
5631 // conversion, as the new corresponding parameter might be different.
5632 // Ideally, we would always perform substitution starting with sugared types
5633 // and never need these, as we would still have expressions. Since these are
5634 // needed so rarely, it's probably a better tradeoff to just convert them
5635 // back to expressions.
5636 case TemplateArgument::Integral:
5637 case TemplateArgument::Declaration:
5638 case TemplateArgument::NullPtr:
5639 case TemplateArgument::StructuralValue: {
5640 // FIXME: StructuralValue is untested here.
5641 ExprResult R =
5642 BuildExpressionFromNonTypeTemplateArgument(Arg, Loc: SourceLocation());
5643 assert(R.isUsable());
5644 if (!checkExpr(R.get()))
5645 return true;
5646 break;
5647 }
5648
5649 case TemplateArgument::Template:
5650 case TemplateArgument::TemplateExpansion:
5651 // We were given a template template argument. It may not be ill-formed;
5652 // see below.
5653 if (DependentTemplateName *DTN = Arg.getAsTemplateOrTemplatePattern()
5654 .getAsDependentTemplateName()) {
5655 // We have a template argument such as \c T::template X, which we
5656 // parsed as a template template argument. However, since we now
5657 // know that we need a non-type template argument, convert this
5658 // template name into an expression.
5659
5660 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5661 ArgLoc.getTemplateNameLoc());
5662
5663 CXXScopeSpec SS;
5664 SS.Adopt(Other: ArgLoc.getTemplateQualifierLoc());
5665 // FIXME: the template-template arg was a DependentTemplateName,
5666 // so it was provided with a template keyword. However, its source
5667 // location is not stored in the template argument structure.
5668 SourceLocation TemplateKWLoc;
5669 ExprResult E = DependentScopeDeclRefExpr::Create(
5670 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5671 TemplateArgs: nullptr);
5672
5673 // If we parsed the template argument as a pack expansion, create a
5674 // pack expansion expression.
5675 if (Arg.getKind() == TemplateArgument::TemplateExpansion) {
5676 E = ActOnPackExpansion(Pattern: E.get(), EllipsisLoc: ArgLoc.getTemplateEllipsisLoc());
5677 if (E.isInvalid())
5678 return true;
5679 }
5680
5681 TemplateArgument SugaredResult, CanonicalResult;
5682 E = CheckTemplateArgument(
5683 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E.get(), SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5684 /*StrictCheck=*/CTAI.PartialOrdering, CTAK: CTAK_Specified);
5685 if (E.isInvalid())
5686 return true;
5687
5688 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5689 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5690 break;
5691 }
5692
5693 // We have a template argument that actually does refer to a class
5694 // template, alias template, or template template parameter, and
5695 // therefore cannot be a non-type template argument.
5696 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_expr)
5697 << ArgLoc.getSourceRange();
5698 NoteTemplateParameterLocation(Decl: *Param);
5699
5700 return true;
5701
5702 case TemplateArgument::Type: {
5703 // We have a non-type template parameter but the template
5704 // argument is a type.
5705
5706 // C++ [temp.arg]p2:
5707 // In a template-argument, an ambiguity between a type-id and
5708 // an expression is resolved to a type-id, regardless of the
5709 // form of the corresponding template-parameter.
5710 //
5711 // We warn specifically about this case, since it can be rather
5712 // confusing for users.
5713 QualType T = Arg.getAsType();
5714 SourceRange SR = ArgLoc.getSourceRange();
5715 if (T->isFunctionType())
5716 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_nontype_ambig) << SR << T;
5717 else
5718 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_expr) << SR;
5719 NoteTemplateParameterLocation(Decl: *Param);
5720 return true;
5721 }
5722
5723 case TemplateArgument::Pack:
5724 llvm_unreachable("Caller must expand template argument packs");
5725 }
5726
5727 return false;
5728 }
5729
5730
5731 // Check template template parameters.
5732 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Val: Param);
5733
5734 TemplateParameterList *Params = TempParm->getTemplateParameters();
5735 if (TempParm->isExpandedParameterPack())
5736 Params = TempParm->getExpansionTemplateParameters(I: ArgumentPackIndex);
5737
5738 // Substitute into the template parameter list of the template
5739 // template parameter, since previously-supplied template arguments
5740 // may appear within the template template parameter.
5741 //
5742 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5743 {
5744 // Set up a template instantiation context.
5745 LocalInstantiationScope Scope(*this);
5746 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5747 CTAI.SugaredConverted,
5748 SourceRange(TemplateLoc, RAngleLoc));
5749 if (Inst.isInvalid())
5750 return true;
5751
5752 Params = SubstTemplateParams(
5753 Params, Owner: CurContext,
5754 TemplateArgs: MultiLevelTemplateArgumentList(Template, CTAI.SugaredConverted,
5755 /*Final=*/true),
5756 /*EvaluateConstraints=*/false);
5757 if (!Params)
5758 return true;
5759 }
5760
5761 // C++1z [temp.local]p1: (DR1004)
5762 // When [the injected-class-name] is used [...] as a template-argument for
5763 // a template template-parameter [...] it refers to the class template
5764 // itself.
5765 if (Arg.getKind() == TemplateArgument::Type) {
5766 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5767 Context, TLoc: ArgLoc.getTypeSourceInfo()->getTypeLoc());
5768 if (!ConvertedArg.getArgument().isNull())
5769 ArgLoc = ConvertedArg;
5770 }
5771
5772 switch (Arg.getKind()) {
5773 case TemplateArgument::Null:
5774 llvm_unreachable("Should never see a NULL template argument here");
5775
5776 case TemplateArgument::Template:
5777 case TemplateArgument::TemplateExpansion:
5778 if (CheckTemplateTemplateArgument(Param: TempParm, Params, Arg&: ArgLoc,
5779 PartialOrdering: CTAI.PartialOrdering,
5780 StrictPackMatch: &CTAI.StrictPackMatch))
5781 return true;
5782
5783 CTAI.SugaredConverted.push_back(Elt: Arg);
5784 CTAI.CanonicalConverted.push_back(
5785 Elt: Context.getCanonicalTemplateArgument(Arg));
5786 break;
5787
5788 case TemplateArgument::Expression:
5789 case TemplateArgument::Type: {
5790 auto Kind = 0;
5791 switch (TempParm->templateParameterKind()) {
5792 case TemplateNameKind::TNK_Var_template:
5793 Kind = 1;
5794 break;
5795 case TemplateNameKind::TNK_Concept_template:
5796 Kind = 2;
5797 break;
5798 default:
5799 break;
5800 }
5801
5802 // We have a template template parameter but the template
5803 // argument does not refer to a template.
5804 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_template)
5805 << Kind << getLangOpts().CPlusPlus11;
5806 return true;
5807 }
5808
5809 case TemplateArgument::Declaration:
5810 case TemplateArgument::Integral:
5811 case TemplateArgument::StructuralValue:
5812 case TemplateArgument::NullPtr:
5813 llvm_unreachable("non-type argument with template template parameter");
5814
5815 case TemplateArgument::Pack:
5816 llvm_unreachable("Caller must expand template argument packs");
5817 }
5818
5819 return false;
5820}
5821
5822/// Diagnose a missing template argument.
5823template<typename TemplateParmDecl>
5824static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5825 TemplateDecl *TD,
5826 const TemplateParmDecl *D,
5827 TemplateArgumentListInfo &Args) {
5828 // Dig out the most recent declaration of the template parameter; there may be
5829 // declarations of the template that are more recent than TD.
5830 D = cast<TemplateParmDecl>(cast<TemplateDecl>(Val: TD->getMostRecentDecl())
5831 ->getTemplateParameters()
5832 ->getParam(D->getIndex()));
5833
5834 // If there's a default argument that's not reachable, diagnose that we're
5835 // missing a module import.
5836 llvm::SmallVector<Module*, 8> Modules;
5837 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, Modules: &Modules)) {
5838 S.diagnoseMissingImport(Loc, cast<NamedDecl>(Val: TD),
5839 D->getDefaultArgumentLoc(), Modules,
5840 Sema::MissingImportKind::DefaultArgument,
5841 /*Recover*/true);
5842 return true;
5843 }
5844
5845 // FIXME: If there's a more recent default argument that *is* visible,
5846 // diagnose that it was declared too late.
5847
5848 TemplateParameterList *Params = TD->getTemplateParameters();
5849
5850 S.Diag(Loc, DiagID: diag::err_template_arg_list_different_arity)
5851 << /*not enough args*/0
5852 << (int)S.getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
5853 << TD;
5854 S.NoteTemplateLocation(Decl: *TD, ParamRange: Params->getSourceRange());
5855 return true;
5856}
5857
5858/// Check that the given template argument list is well-formed
5859/// for specializing the given template.
5860bool Sema::CheckTemplateArgumentList(
5861 TemplateDecl *Template, SourceLocation TemplateLoc,
5862 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5863 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5864 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5865 return CheckTemplateArgumentList(
5866 Template, Params: GetTemplateParameterList(TD: Template), TemplateLoc, TemplateArgs,
5867 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5868 ConstraintsNotSatisfied);
5869}
5870
5871/// Check that the given template argument list is well-formed
5872/// for specializing the given template.
5873bool Sema::CheckTemplateArgumentList(
5874 TemplateDecl *Template, TemplateParameterList *Params,
5875 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5876 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5877 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5878 bool *ConstraintsNotSatisfied) {
5879
5880 if (ConstraintsNotSatisfied)
5881 *ConstraintsNotSatisfied = false;
5882
5883 // Make a copy of the template arguments for processing. Only make the
5884 // changes at the end when successful in matching the arguments to the
5885 // template.
5886 TemplateArgumentListInfo NewArgs = TemplateArgs;
5887
5888 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5889
5890 // C++23 [temp.arg.general]p1:
5891 // [...] The type and form of each template-argument specified in
5892 // a template-id shall match the type and form specified for the
5893 // corresponding parameter declared by the template in its
5894 // template-parameter-list.
5895 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Val: Template);
5896 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5897 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5898 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5899 LocalInstantiationScope InstScope(*this, true);
5900 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5901 ParamEnd = Params->end(),
5902 Param = ParamBegin;
5903 Param != ParamEnd;
5904 /* increment in loop */) {
5905 if (size_t ParamIdx = Param - ParamBegin;
5906 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5907 // All written arguments should have been consumed by this point.
5908 assert(ArgIdx == NumArgs && "bad default argument deduction");
5909 if (ParamIdx == DefaultArgs.StartPos) {
5910 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5911 // Default arguments from a DeducedTemplateName are already converted.
5912 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5913 CTAI.SugaredConverted.push_back(Elt: DefArg);
5914 CTAI.CanonicalConverted.push_back(
5915 Elt: Context.getCanonicalTemplateArgument(Arg: DefArg));
5916 ++Param;
5917 }
5918 continue;
5919 }
5920 }
5921
5922 // If we have an expanded parameter pack, make sure we don't have too
5923 // many arguments.
5924 if (UnsignedOrNone Expansions = getExpandedPackSize(Param: *Param)) {
5925 if (*Expansions == SugaredArgumentPack.size()) {
5926 // We're done with this parameter pack. Pack up its arguments and add
5927 // them to the list.
5928 CTAI.SugaredConverted.push_back(
5929 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
5930 SugaredArgumentPack.clear();
5931
5932 CTAI.CanonicalConverted.push_back(
5933 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
5934 CanonicalArgumentPack.clear();
5935
5936 // This argument is assigned to the next parameter.
5937 ++Param;
5938 continue;
5939 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5940 // Not enough arguments for this parameter pack.
5941 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
5942 << /*not enough args*/0
5943 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
5944 << Template;
5945 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
5946 return true;
5947 }
5948 }
5949
5950 // Check for builtins producing template packs in this context, we do not
5951 // support them yet.
5952 if (const NonTypeTemplateParmDecl *NTTP =
5953 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param);
5954 NTTP && NTTP->isPackExpansion()) {
5955 auto TL = NTTP->getTypeSourceInfo()
5956 ->getTypeLoc()
5957 .castAs<PackExpansionTypeLoc>();
5958 llvm::SmallVector<UnexpandedParameterPack> Unexpanded;
5959 collectUnexpandedParameterPacks(TL: TL.getPatternLoc(), Unexpanded);
5960 for (const auto &UPP : Unexpanded) {
5961 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5962 if (!TST)
5963 continue;
5964 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5965 // Expanding a built-in pack in this context is not yet supported.
5966 Diag(Loc: TL.getEllipsisLoc(),
5967 DiagID: diag::err_unsupported_builtin_template_pack_expansion)
5968 << TST->getTemplateName();
5969 return true;
5970 }
5971 }
5972
5973 if (ArgIdx < NumArgs) {
5974 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5975 bool NonPackParameter =
5976 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(Param: *Param);
5977 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5978
5979 if (ArgIsExpansion && CTAI.MatchingTTP) {
5980 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5981 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5982 ++Param) {
5983 TemplateArgument &Arg = Args[Param - First];
5984 Arg = ArgLoc.getArgument();
5985 if (!(*Param)->isTemplateParameterPack() ||
5986 getExpandedPackSize(Param: *Param))
5987 Arg = Arg.getPackExpansionPattern();
5988 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5989 SaveAndRestore _1(CTAI.PartialOrdering, false);
5990 SaveAndRestore _2(CTAI.MatchingTTP, true);
5991 if (CheckTemplateArgument(Param: *Param, ArgLoc&: NewArgLoc, Template, TemplateLoc,
5992 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
5993 CTAK: CTAK_Specified))
5994 return true;
5995 Arg = NewArgLoc.getArgument();
5996 CTAI.CanonicalConverted.back().setIsDefaulted(
5997 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg, Param: *Param,
5998 Args: CTAI.CanonicalConverted,
5999 Depth: Params->getDepth()));
6000 }
6001 ArgLoc = TemplateArgumentLoc(
6002 TemplateArgument::CreatePackCopy(Context, Args),
6003 TemplateArgumentLocInfo(Context, ArgLoc.getLocation()));
6004 } else {
6005 SaveAndRestore _1(CTAI.PartialOrdering, false);
6006 if (CheckTemplateArgument(Param: *Param, ArgLoc, Template, TemplateLoc,
6007 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
6008 CTAK: CTAK_Specified))
6009 return true;
6010 CTAI.CanonicalConverted.back().setIsDefaulted(
6011 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg: ArgLoc.getArgument(),
6012 Param: *Param, Args: CTAI.CanonicalConverted,
6013 Depth: Params->getDepth()));
6014 if (ArgIsExpansion && NonPackParameter) {
6015 // CWG1430/CWG2686: we have a pack expansion as an argument to an
6016 // alias template, builtin template, or concept, and it's not part of
6017 // a parameter pack. This can't be canonicalized, so reject it now.
6018 if (isa<TypeAliasTemplateDecl, ConceptDecl, BuiltinTemplateDecl>(
6019 Val: Template)) {
6020 unsigned DiagSelect = isa<ConceptDecl>(Val: Template) ? 1
6021 : isa<BuiltinTemplateDecl>(Val: Template) ? 2
6022 : 0;
6023 Diag(Loc: ArgLoc.getLocation(),
6024 DiagID: diag::err_template_expansion_into_fixed_list)
6025 << DiagSelect << ArgLoc.getSourceRange();
6026 NoteTemplateParameterLocation(Decl: **Param);
6027 return true;
6028 }
6029 }
6030 }
6031
6032 // We're now done with this argument.
6033 ++ArgIdx;
6034
6035 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6036 // Directly convert the remaining arguments, because we don't know what
6037 // parameters they'll match up with.
6038
6039 if (!SugaredArgumentPack.empty()) {
6040 // If we were part way through filling in an expanded parameter pack,
6041 // fall back to just producing individual arguments.
6042 CTAI.SugaredConverted.insert(I: CTAI.SugaredConverted.end(),
6043 From: SugaredArgumentPack.begin(),
6044 To: SugaredArgumentPack.end());
6045 SugaredArgumentPack.clear();
6046
6047 CTAI.CanonicalConverted.insert(I: CTAI.CanonicalConverted.end(),
6048 From: CanonicalArgumentPack.begin(),
6049 To: CanonicalArgumentPack.end());
6050 CanonicalArgumentPack.clear();
6051 }
6052
6053 while (ArgIdx < NumArgs) {
6054 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6055 CTAI.SugaredConverted.push_back(Elt: Arg);
6056 CTAI.CanonicalConverted.push_back(
6057 Elt: Context.getCanonicalTemplateArgument(Arg));
6058 ++ArgIdx;
6059 }
6060
6061 return false;
6062 }
6063
6064 if ((*Param)->isTemplateParameterPack()) {
6065 // The template parameter was a template parameter pack, so take the
6066 // deduced argument and place it on the argument pack. Note that we
6067 // stay on the same template parameter so that we can deduce more
6068 // arguments.
6069 SugaredArgumentPack.push_back(Elt: CTAI.SugaredConverted.pop_back_val());
6070 CanonicalArgumentPack.push_back(Elt: CTAI.CanonicalConverted.pop_back_val());
6071 } else {
6072 // Move to the next template parameter.
6073 ++Param;
6074 }
6075 continue;
6076 }
6077
6078 // If we're checking a partial template argument list, we're done.
6079 if (PartialTemplateArgs) {
6080 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6081 CTAI.SugaredConverted.push_back(
6082 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6083 CTAI.CanonicalConverted.push_back(
6084 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6085 }
6086 return false;
6087 }
6088
6089 // If we have a template parameter pack with no more corresponding
6090 // arguments, just break out now and we'll fill in the argument pack below.
6091 if ((*Param)->isTemplateParameterPack()) {
6092 assert(!getExpandedPackSize(*Param) &&
6093 "Should have dealt with this already");
6094
6095 // A non-expanded parameter pack before the end of the parameter list
6096 // only occurs for an ill-formed template parameter list, unless we've
6097 // got a partial argument list for a function template, so just bail out.
6098 if (Param + 1 != ParamEnd) {
6099 assert(
6100 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6101 "Concept templates must have parameter packs at the end.");
6102 return true;
6103 }
6104
6105 CTAI.SugaredConverted.push_back(
6106 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6107 SugaredArgumentPack.clear();
6108
6109 CTAI.CanonicalConverted.push_back(
6110 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6111 CanonicalArgumentPack.clear();
6112
6113 ++Param;
6114 continue;
6115 }
6116
6117 // Check whether we have a default argument.
6118 bool HasDefaultArg;
6119
6120 // Retrieve the default template argument from the template
6121 // parameter. For each kind of template parameter, we substitute the
6122 // template arguments provided thus far and any "outer" template arguments
6123 // (when the template parameter was part of a nested template) into
6124 // the default argument.
6125 TemplateArgumentLoc Arg = SubstDefaultTemplateArgumentIfAvailable(
6126 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateNameLoc: TemplateLoc, RAngleLoc,
6127 Param: *Param, SugaredConverted: CTAI.SugaredConverted, CanonicalConverted: CTAI.CanonicalConverted, HasDefaultArg);
6128
6129 if (Arg.getArgument().isNull()) {
6130 if (!HasDefaultArg) {
6131 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *Param))
6132 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: TTP,
6133 Args&: NewArgs);
6134 if (NonTypeTemplateParmDecl *NTTP =
6135 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param))
6136 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: NTTP,
6137 Args&: NewArgs);
6138 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template,
6139 D: cast<TemplateTemplateParmDecl>(Val: *Param),
6140 Args&: NewArgs);
6141 }
6142 return true;
6143 }
6144
6145 // Introduce an instantiation record that describes where we are using
6146 // the default template argument. We're not actually instantiating a
6147 // template here, we just create this object to put a note into the
6148 // context stack.
6149 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6150 CTAI.SugaredConverted,
6151 SourceRange(TemplateLoc, RAngleLoc));
6152 if (Inst.isInvalid())
6153 return true;
6154
6155 SaveAndRestore _1(CTAI.PartialOrdering, false);
6156 SaveAndRestore _2(CTAI.MatchingTTP, false);
6157 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6158 // Check the default template argument.
6159 if (CheckTemplateArgument(Param: *Param, ArgLoc&: Arg, Template, TemplateLoc, RAngleLoc, ArgumentPackIndex: 0,
6160 CTAI, CTAK: CTAK_Specified))
6161 return true;
6162
6163 CTAI.SugaredConverted.back().setIsDefaulted(true);
6164 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6165
6166 // Core issue 150 (assumed resolution): if this is a template template
6167 // parameter, keep track of the default template arguments from the
6168 // template definition.
6169 if (isTemplateTemplateParameter)
6170 NewArgs.addArgument(Loc: Arg);
6171
6172 // Move to the next template parameter and argument.
6173 ++Param;
6174 ++ArgIdx;
6175 }
6176
6177 // If we're performing a partial argument substitution, allow any trailing
6178 // pack expansions; they might be empty. This can happen even if
6179 // PartialTemplateArgs is false (the list of arguments is complete but
6180 // still dependent).
6181 if (CTAI.MatchingTTP ||
6182 (CurrentInstantiationScope &&
6183 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6184 while (ArgIdx < NumArgs &&
6185 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6186 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6187 CTAI.SugaredConverted.push_back(Elt: Arg);
6188 CTAI.CanonicalConverted.push_back(
6189 Elt: Context.getCanonicalTemplateArgument(Arg));
6190 }
6191 }
6192
6193 // If we have any leftover arguments, then there were too many arguments.
6194 // Complain and fail.
6195 if (ArgIdx < NumArgs) {
6196 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
6197 << /*too many args*/1
6198 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
6199 << Template
6200 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6201 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
6202 return true;
6203 }
6204
6205 // No problems found with the new argument list, propagate changes back
6206 // to caller.
6207 if (UpdateArgsWithConversions)
6208 TemplateArgs = std::move(NewArgs);
6209
6210 if (!PartialTemplateArgs) {
6211 // Setup the context/ThisScope for the case where we are needing to
6212 // re-instantiate constraints outside of normal instantiation.
6213 DeclContext *NewContext = Template->getDeclContext();
6214
6215 // If this template is in a template, make sure we extract the templated
6216 // decl.
6217 if (auto *TD = dyn_cast<TemplateDecl>(Val: NewContext))
6218 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6219 auto *RD = dyn_cast<CXXRecordDecl>(Val: NewContext);
6220
6221 Qualifiers ThisQuals;
6222 if (const auto *Method =
6223 dyn_cast_or_null<CXXMethodDecl>(Val: Template->getTemplatedDecl()))
6224 ThisQuals = Method->getMethodQualifiers();
6225
6226 ContextRAII Context(*this, NewContext);
6227 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6228
6229 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
6230 D: Template, DC: NewContext, /*Final=*/true, Innermost: CTAI.SugaredConverted,
6231 /*RelativeToPrimary=*/true,
6232 /*Pattern=*/nullptr,
6233 /*ForConceptInstantiation=*/ForConstraintInstantiation: true);
6234 if (!isa<ConceptDecl>(Val: Template) &&
6235 EnsureTemplateArgumentListConstraints(
6236 Template, TemplateArgs: MLTAL,
6237 TemplateIDRange: SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6238 if (ConstraintsNotSatisfied)
6239 *ConstraintsNotSatisfied = true;
6240 return true;
6241 }
6242 }
6243
6244 return false;
6245}
6246
6247namespace {
6248 class UnnamedLocalNoLinkageFinder
6249 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6250 {
6251 Sema &S;
6252 SourceRange SR;
6253
6254 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
6255
6256 public:
6257 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6258
6259 bool Visit(QualType T) {
6260 return T.isNull() ? false : inherited::Visit(T: T.getTypePtr());
6261 }
6262
6263#define TYPE(Class, Parent) \
6264 bool Visit##Class##Type(const Class##Type *);
6265#define ABSTRACT_TYPE(Class, Parent) \
6266 bool Visit##Class##Type(const Class##Type *) { return false; }
6267#define NON_CANONICAL_TYPE(Class, Parent) \
6268 bool Visit##Class##Type(const Class##Type *) { return false; }
6269#include "clang/AST/TypeNodes.inc"
6270
6271 bool VisitTagDecl(const TagDecl *Tag);
6272 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6273 };
6274} // end anonymous namespace
6275
6276bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6277 return false;
6278}
6279
6280bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6281 return Visit(T: T->getElementType());
6282}
6283
6284bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6285 return Visit(T: T->getPointeeType());
6286}
6287
6288bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6289 const BlockPointerType* T) {
6290 return Visit(T: T->getPointeeType());
6291}
6292
6293bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6294 const LValueReferenceType* T) {
6295 return Visit(T: T->getPointeeType());
6296}
6297
6298bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6299 const RValueReferenceType* T) {
6300 return Visit(T: T->getPointeeType());
6301}
6302
6303bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6304 const MemberPointerType *T) {
6305 if (Visit(T: T->getPointeeType()))
6306 return true;
6307 if (auto *RD = T->getMostRecentCXXRecordDecl())
6308 return VisitTagDecl(Tag: RD);
6309 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6310}
6311
6312bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6313 const ConstantArrayType* T) {
6314 return Visit(T: T->getElementType());
6315}
6316
6317bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6318 const IncompleteArrayType* T) {
6319 return Visit(T: T->getElementType());
6320}
6321
6322bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6323 const VariableArrayType* T) {
6324 return Visit(T: T->getElementType());
6325}
6326
6327bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6328 const DependentSizedArrayType* T) {
6329 return Visit(T: T->getElementType());
6330}
6331
6332bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6333 const DependentSizedExtVectorType* T) {
6334 return Visit(T: T->getElementType());
6335}
6336
6337bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6338 const DependentSizedMatrixType *T) {
6339 return Visit(T: T->getElementType());
6340}
6341
6342bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6343 const DependentAddressSpaceType *T) {
6344 return Visit(T: T->getPointeeType());
6345}
6346
6347bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6348 return Visit(T: T->getElementType());
6349}
6350
6351bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6352 const DependentVectorType *T) {
6353 return Visit(T: T->getElementType());
6354}
6355
6356bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6357 return Visit(T: T->getElementType());
6358}
6359
6360bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6361 const ConstantMatrixType *T) {
6362 return Visit(T: T->getElementType());
6363}
6364
6365bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6366 const FunctionProtoType* T) {
6367 for (const auto &A : T->param_types()) {
6368 if (Visit(T: A))
6369 return true;
6370 }
6371
6372 return Visit(T: T->getReturnType());
6373}
6374
6375bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6376 const FunctionNoProtoType* T) {
6377 return Visit(T: T->getReturnType());
6378}
6379
6380bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6381 const UnresolvedUsingType*) {
6382 return false;
6383}
6384
6385bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6386 return false;
6387}
6388
6389bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6390 return Visit(T: T->getUnmodifiedType());
6391}
6392
6393bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6394 return false;
6395}
6396
6397bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6398 const PackIndexingType *) {
6399 return false;
6400}
6401
6402bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6403 const UnaryTransformType*) {
6404 return false;
6405}
6406
6407bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6408 return Visit(T: T->getDeducedType());
6409}
6410
6411bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6412 const DeducedTemplateSpecializationType *T) {
6413 return Visit(T: T->getDeducedType());
6414}
6415
6416bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6417 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6418}
6419
6420bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6421 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6422}
6423
6424bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6425 const TemplateTypeParmType*) {
6426 return false;
6427}
6428
6429bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6430 const SubstTemplateTypeParmPackType *) {
6431 return false;
6432}
6433
6434bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6435 const SubstBuiltinTemplatePackType *) {
6436 return false;
6437}
6438
6439bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6440 const TemplateSpecializationType*) {
6441 return false;
6442}
6443
6444bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6445 const InjectedClassNameType* T) {
6446 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6447}
6448
6449bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6450 const DependentNameType* T) {
6451 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6452}
6453
6454bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6455 const PackExpansionType* T) {
6456 return Visit(T: T->getPattern());
6457}
6458
6459bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6460 return false;
6461}
6462
6463bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6464 const ObjCInterfaceType *) {
6465 return false;
6466}
6467
6468bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6469 const ObjCObjectPointerType *) {
6470 return false;
6471}
6472
6473bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6474 return Visit(T: T->getValueType());
6475}
6476
6477bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6478 const OverflowBehaviorType *T) {
6479 return Visit(T: T->getUnderlyingType());
6480}
6481
6482bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6483 return false;
6484}
6485
6486bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6487 return false;
6488}
6489
6490bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6491 const ArrayParameterType *T) {
6492 return VisitConstantArrayType(T);
6493}
6494
6495bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6496 const DependentBitIntType *T) {
6497 return false;
6498}
6499
6500bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6501 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6502 S.Diag(Loc: SR.getBegin(), DiagID: S.getLangOpts().CPlusPlus11
6503 ? diag::warn_cxx98_compat_template_arg_local_type
6504 : diag::ext_template_arg_local_type)
6505 << S.Context.getCanonicalTagType(TD: Tag) << SR;
6506 return true;
6507 }
6508
6509 if (!Tag->hasNameForLinkage()) {
6510 S.Diag(Loc: SR.getBegin(),
6511 DiagID: S.getLangOpts().CPlusPlus11 ?
6512 diag::warn_cxx98_compat_template_arg_unnamed_type :
6513 diag::ext_template_arg_unnamed_type) << SR;
6514 S.Diag(Loc: Tag->getLocation(), DiagID: diag::note_template_unnamed_type_here);
6515 return true;
6516 }
6517
6518 return false;
6519}
6520
6521bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6522 NestedNameSpecifier NNS) {
6523 switch (NNS.getKind()) {
6524 case NestedNameSpecifier::Kind::Null:
6525 case NestedNameSpecifier::Kind::Namespace:
6526 case NestedNameSpecifier::Kind::Global:
6527 case NestedNameSpecifier::Kind::MicrosoftSuper:
6528 return false;
6529 case NestedNameSpecifier::Kind::Type:
6530 return Visit(T: QualType(NNS.getAsType(), 0));
6531 }
6532 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6533}
6534
6535bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6536 const HLSLAttributedResourceType *T) {
6537 if (T->hasContainedType() && Visit(T: T->getContainedType()))
6538 return true;
6539 return Visit(T: T->getWrappedType());
6540}
6541
6542bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6543 const HLSLInlineSpirvType *T) {
6544 for (auto &Operand : T->getOperands())
6545 if (Operand.isConstant() && Operand.isLiteral())
6546 if (Visit(T: Operand.getResultType()))
6547 return true;
6548 return false;
6549}
6550
6551bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6552 assert(ArgInfo && "invalid TypeSourceInfo");
6553 QualType Arg = ArgInfo->getType();
6554 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6555 QualType CanonArg = Context.getCanonicalType(T: Arg);
6556
6557 if (CanonArg->isVariablyModifiedType()) {
6558 return Diag(Loc: SR.getBegin(), DiagID: diag::err_variably_modified_template_arg) << Arg;
6559 } else if (Context.hasSameUnqualifiedType(T1: Arg, T2: Context.OverloadTy)) {
6560 return Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_overload_type) << SR;
6561 }
6562
6563 // C++03 [temp.arg.type]p2:
6564 // A local type, a type with no linkage, an unnamed type or a type
6565 // compounded from any of these types shall not be used as a
6566 // template-argument for a template type-parameter.
6567 //
6568 // C++11 allows these, and even in C++03 we allow them as an extension with
6569 // a warning.
6570 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6571 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6572 (void)Finder.Visit(T: CanonArg);
6573 }
6574
6575 return false;
6576}
6577
6578enum NullPointerValueKind {
6579 NPV_NotNullPointer,
6580 NPV_NullPointer,
6581 NPV_Error
6582};
6583
6584/// Determine whether the given template argument is a null pointer
6585/// value of the appropriate type.
6586static NullPointerValueKind
6587isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param,
6588 QualType ParamType, Expr *Arg,
6589 Decl *Entity = nullptr) {
6590 if (Arg->isValueDependent() || Arg->isTypeDependent())
6591 return NPV_NotNullPointer;
6592
6593 // dllimport'd entities aren't constant but are available inside of template
6594 // arguments.
6595 if (Entity && Entity->hasAttr<DLLImportAttr>())
6596 return NPV_NotNullPointer;
6597
6598 if (!S.isCompleteType(Loc: Arg->getExprLoc(), T: ParamType))
6599 llvm_unreachable(
6600 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6601
6602 if (!S.getLangOpts().CPlusPlus11)
6603 return NPV_NotNullPointer;
6604
6605 // Determine whether we have a constant expression.
6606 ExprResult ArgRV = S.DefaultFunctionArrayConversion(E: Arg);
6607 if (ArgRV.isInvalid())
6608 return NPV_Error;
6609 Arg = ArgRV.get();
6610
6611 Expr::EvalResult EvalResult;
6612 SmallVector<PartialDiagnosticAt, 8> Notes;
6613 EvalResult.Diag = &Notes;
6614 if (!Arg->EvaluateAsRValue(Result&: EvalResult, Ctx: S.Context) ||
6615 EvalResult.HasSideEffects) {
6616 SourceLocation DiagLoc = Arg->getExprLoc();
6617
6618 // If our only note is the usual "invalid subexpression" note, just point
6619 // the caret at its location rather than producing an essentially
6620 // redundant note.
6621 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6622 diag::note_invalid_subexpr_in_const_expr) {
6623 DiagLoc = Notes[0].first;
6624 Notes.clear();
6625 }
6626
6627 S.Diag(Loc: DiagLoc, DiagID: diag::err_template_arg_not_address_constant)
6628 << Arg->getType() << Arg->getSourceRange();
6629 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6630 S.Diag(Loc: Notes[I].first, PD: Notes[I].second);
6631
6632 S.NoteTemplateParameterLocation(Decl: *Param);
6633 return NPV_Error;
6634 }
6635
6636 // C++11 [temp.arg.nontype]p1:
6637 // - an address constant expression of type std::nullptr_t
6638 if (Arg->getType()->isNullPtrType())
6639 return NPV_NullPointer;
6640
6641 // - a constant expression that evaluates to a null pointer value (4.10); or
6642 // - a constant expression that evaluates to a null member pointer value
6643 // (4.11); or
6644 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6645 (EvalResult.Val.isMemberPointer() &&
6646 !EvalResult.Val.getMemberPointerDecl())) {
6647 // If our expression has an appropriate type, we've succeeded.
6648 bool ObjCLifetimeConversion;
6649 if (S.Context.hasSameUnqualifiedType(T1: Arg->getType(), T2: ParamType) ||
6650 S.IsQualificationConversion(FromType: Arg->getType(), ToType: ParamType, CStyle: false,
6651 ObjCLifetimeConversion))
6652 return NPV_NullPointer;
6653
6654 // The types didn't match, but we know we got a null pointer; complain,
6655 // then recover as if the types were correct.
6656 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_wrongtype_null_constant)
6657 << Arg->getType() << ParamType << Arg->getSourceRange();
6658 S.NoteTemplateParameterLocation(Decl: *Param);
6659 return NPV_NullPointer;
6660 }
6661
6662 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6663 // We found a pointer that isn't null, but doesn't refer to an object.
6664 // We could just return NPV_NotNullPointer, but we can print a better
6665 // message with the information we have here.
6666 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_invalid)
6667 << EvalResult.Val.getAsString(Ctx: S.Context, Ty: ParamType);
6668 S.NoteTemplateParameterLocation(Decl: *Param);
6669 return NPV_Error;
6670 }
6671
6672 // If we don't have a null pointer value, but we do have a NULL pointer
6673 // constant, suggest a cast to the appropriate type.
6674 if (Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_NeverValueDependent)) {
6675 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6676 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_untyped_null_constant)
6677 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code)
6678 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: Arg->getEndLoc()),
6679 Code: ")");
6680 S.NoteTemplateParameterLocation(Decl: *Param);
6681 return NPV_NullPointer;
6682 }
6683
6684 // FIXME: If we ever want to support general, address-constant expressions
6685 // as non-type template arguments, we should return the ExprResult here to
6686 // be interpreted by the caller.
6687 return NPV_NotNullPointer;
6688}
6689
6690/// Checks whether the given template argument is compatible with its
6691/// template parameter.
6692static bool
6693CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param,
6694 QualType ParamType, Expr *ArgIn,
6695 Expr *Arg, QualType ArgType) {
6696 bool ObjCLifetimeConversion;
6697 if (ParamType->isPointerType() &&
6698 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6699 S.IsQualificationConversion(FromType: ArgType, ToType: ParamType, CStyle: false,
6700 ObjCLifetimeConversion)) {
6701 // For pointer-to-object types, qualification conversions are
6702 // permitted.
6703 } else {
6704 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6705 if (!ParamRef->getPointeeType()->isFunctionType()) {
6706 // C++ [temp.arg.nontype]p5b3:
6707 // For a non-type template-parameter of type reference to
6708 // object, no conversions apply. The type referred to by the
6709 // reference may be more cv-qualified than the (otherwise
6710 // identical) type of the template- argument. The
6711 // template-parameter is bound directly to the
6712 // template-argument, which shall be an lvalue.
6713
6714 // FIXME: Other qualifiers?
6715 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6716 unsigned ArgQuals = ArgType.getCVRQualifiers();
6717
6718 if ((ParamQuals | ArgQuals) != ParamQuals) {
6719 S.Diag(Loc: Arg->getBeginLoc(),
6720 DiagID: diag::err_template_arg_ref_bind_ignores_quals)
6721 << ParamType << Arg->getType() << Arg->getSourceRange();
6722 S.NoteTemplateParameterLocation(Decl: *Param);
6723 return true;
6724 }
6725 }
6726 }
6727
6728 // At this point, the template argument refers to an object or
6729 // function with external linkage. We now need to check whether the
6730 // argument and parameter types are compatible.
6731 if (!S.Context.hasSameUnqualifiedType(T1: ArgType,
6732 T2: ParamType.getNonReferenceType())) {
6733 // We can't perform this conversion or binding.
6734 if (ParamType->isReferenceType())
6735 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_no_ref_bind)
6736 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6737 else
6738 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
6739 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6740 S.NoteTemplateParameterLocation(Decl: *Param);
6741 return true;
6742 }
6743 }
6744
6745 return false;
6746}
6747
6748/// Checks whether the given template argument is the address
6749/// of an object or function according to C++ [temp.arg.nontype]p1.
6750static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6751 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6752 bool IsSpecified, TemplateArgument &SugaredConverted,
6753 TemplateArgument &CanonicalConverted) {
6754 Expr *Arg = ArgIn;
6755 QualType ArgType = Arg->getType();
6756
6757 bool AddressTaken = false;
6758 SourceLocation AddrOpLoc;
6759 if (S.getLangOpts().MicrosoftExt) {
6760 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6761 // dereference and address-of operators.
6762 Arg = Arg->IgnoreParenCasts();
6763
6764 bool ExtWarnMSTemplateArg = false;
6765 UnaryOperatorKind FirstOpKind;
6766 SourceLocation FirstOpLoc;
6767 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6768 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6769 if (UnOpKind == UO_Deref)
6770 ExtWarnMSTemplateArg = true;
6771 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6772 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6773 if (!AddrOpLoc.isValid()) {
6774 FirstOpKind = UnOpKind;
6775 FirstOpLoc = UnOp->getOperatorLoc();
6776 }
6777 } else
6778 break;
6779 }
6780 if (FirstOpLoc.isValid()) {
6781 if (ExtWarnMSTemplateArg)
6782 S.Diag(Loc: ArgIn->getBeginLoc(), DiagID: diag::ext_ms_deref_template_argument)
6783 << ArgIn->getSourceRange();
6784
6785 if (FirstOpKind == UO_AddrOf)
6786 AddressTaken = true;
6787 else if (Arg->getType()->isPointerType()) {
6788 // We cannot let pointers get dereferenced here, that is obviously not a
6789 // constant expression.
6790 assert(FirstOpKind == UO_Deref);
6791 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6792 << Arg->getSourceRange();
6793 }
6794 }
6795 } else {
6796 // See through any implicit casts we added to fix the type.
6797 // Also ignore parentheses for deduced template arguments.
6798 Arg = IsSpecified ? Arg->IgnoreImpCasts() : Arg->IgnoreParenImpCasts();
6799
6800 // C++ [temp.arg.nontype]p1:
6801 //
6802 // A template-argument for a non-type, non-template
6803 // template-parameter shall be one of: [...]
6804 //
6805 // -- the address of an object or function with external
6806 // linkage, including function templates and function
6807 // template-ids but excluding non-static class members,
6808 // expressed as & id-expression where the & is optional if
6809 // the name refers to a function or array, or if the
6810 // corresponding template-parameter is a reference; or
6811
6812 // In C++98/03 mode, give an extension warning on any extra parentheses.
6813 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6814 if (IsSpecified) {
6815 bool ExtraParens = false;
6816 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
6817 if (!ExtraParens) {
6818 S.DiagCompat(Loc: Arg->getBeginLoc(),
6819 CompatDiagId: diag_compat::template_arg_extra_parens)
6820 << Arg->getSourceRange();
6821 ExtraParens = true;
6822 }
6823
6824 Arg = Parens->getSubExpr();
6825 }
6826 }
6827
6828 while (SubstNonTypeTemplateParmExpr *subst =
6829 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6830 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6831
6832 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6833 if (UnOp->getOpcode() == UO_AddrOf) {
6834 Arg = UnOp->getSubExpr();
6835 AddressTaken = true;
6836 AddrOpLoc = UnOp->getOperatorLoc();
6837 }
6838 }
6839
6840 while (SubstNonTypeTemplateParmExpr *subst =
6841 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6842 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6843 }
6844
6845 ValueDecl *Entity = nullptr;
6846 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg))
6847 Entity = DRE->getDecl();
6848 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Val: Arg))
6849 Entity = CUE->getGuidDecl();
6850
6851 // If our parameter has pointer type, check for a null template value.
6852 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6853 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ArgIn,
6854 Entity)) {
6855 case NPV_NullPointer:
6856 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
6857 SugaredConverted = TemplateArgument(ParamType,
6858 /*isNullPtr=*/true);
6859 CanonicalConverted =
6860 TemplateArgument(S.Context.getCanonicalType(T: ParamType),
6861 /*isNullPtr=*/true);
6862 return false;
6863
6864 case NPV_Error:
6865 return true;
6866
6867 case NPV_NotNullPointer:
6868 break;
6869 }
6870 }
6871
6872 // Stop checking the precise nature of the argument if it is value dependent,
6873 // it should be checked when instantiated.
6874 if (Arg->isValueDependent()) {
6875 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6876 CanonicalConverted =
6877 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
6878 return false;
6879 }
6880
6881 if (!Entity) {
6882 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6883 << Arg->getSourceRange();
6884 S.NoteTemplateParameterLocation(Decl: *Param);
6885 return true;
6886 }
6887
6888 // Cannot refer to non-static data members
6889 if (isa<FieldDecl>(Val: Entity) || isa<IndirectFieldDecl>(Val: Entity)) {
6890 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_field)
6891 << Entity << Arg->getSourceRange();
6892 S.NoteTemplateParameterLocation(Decl: *Param);
6893 return true;
6894 }
6895
6896 // Cannot refer to non-static member functions
6897 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Entity)) {
6898 if (!Method->isStatic()) {
6899 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_method)
6900 << Method << Arg->getSourceRange();
6901 S.NoteTemplateParameterLocation(Decl: *Param);
6902 return true;
6903 }
6904 }
6905
6906 FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Entity);
6907 VarDecl *Var = dyn_cast<VarDecl>(Val: Entity);
6908 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Val: Entity);
6909
6910 // A non-type template argument must refer to an object or function.
6911 if (!Func && !Var && !Guid) {
6912 // We found something, but we don't know specifically what it is.
6913 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_object_or_func)
6914 << Arg->getSourceRange();
6915 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_refers_here);
6916 return true;
6917 }
6918
6919 // Address / reference template args must have external linkage in C++98.
6920 if (Entity->getFormalLinkage() == Linkage::Internal) {
6921 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_object_internal)
6922 << !Func << Entity << Arg->getSourceRange();
6923 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6924 << !Func;
6925 } else if (!Entity->hasLinkage()) {
6926 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_object_no_linkage)
6927 << !Func << Entity << Arg->getSourceRange();
6928 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6929 << !Func;
6930 return true;
6931 }
6932
6933 if (Var) {
6934 // A value of reference type is not an object.
6935 if (Var->getType()->isReferenceType()) {
6936 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_reference_var)
6937 << Var->getType() << Arg->getSourceRange();
6938 S.NoteTemplateParameterLocation(Decl: *Param);
6939 return true;
6940 }
6941
6942 // A template argument must have static storage duration.
6943 if (Var->getTLSKind()) {
6944 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_thread_local)
6945 << Arg->getSourceRange();
6946 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_template_arg_refers_here);
6947 return true;
6948 }
6949 }
6950
6951 if (AddressTaken && ParamType->isReferenceType()) {
6952 // If we originally had an address-of operator, but the
6953 // parameter has reference type, complain and (if things look
6954 // like they will work) drop the address-of operator.
6955 if (!S.Context.hasSameUnqualifiedType(T1: Entity->getType(),
6956 T2: ParamType.getNonReferenceType())) {
6957 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6958 << ParamType;
6959 S.NoteTemplateParameterLocation(Decl: *Param);
6960 return true;
6961 }
6962
6963 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6964 << ParamType
6965 << FixItHint::CreateRemoval(RemoveRange: AddrOpLoc);
6966 S.NoteTemplateParameterLocation(Decl: *Param);
6967
6968 ArgType = Entity->getType();
6969 }
6970
6971 // If the template parameter has pointer type, either we must have taken the
6972 // address or the argument must decay to a pointer.
6973 if (!AddressTaken && ParamType->isPointerType()) {
6974 if (Func) {
6975 // Function-to-pointer decay.
6976 ArgType = S.Context.getPointerType(T: Func->getType());
6977 } else if (Entity->getType()->isArrayType()) {
6978 // Array-to-pointer decay.
6979 ArgType = S.Context.getArrayDecayedType(T: Entity->getType());
6980 } else {
6981 // If the template parameter has pointer type but the address of
6982 // this object was not taken, complain and (possibly) recover by
6983 // taking the address of the entity.
6984 ArgType = S.Context.getPointerType(T: Entity->getType());
6985 if (!S.Context.hasSameUnqualifiedType(T1: ArgType, T2: ParamType)) {
6986 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
6987 << ParamType;
6988 S.NoteTemplateParameterLocation(Decl: *Param);
6989 return true;
6990 }
6991
6992 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
6993 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code: "&");
6994
6995 S.NoteTemplateParameterLocation(Decl: *Param);
6996 }
6997 }
6998
6999 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7000 Arg, ArgType))
7001 return true;
7002
7003 // Create the template argument.
7004 SugaredConverted = TemplateArgument(Entity, ParamType);
7005 CanonicalConverted =
7006 TemplateArgument(cast<ValueDecl>(Val: Entity->getCanonicalDecl()),
7007 S.Context.getCanonicalType(T: ParamType));
7008 S.MarkAnyDeclReferenced(Loc: Arg->getBeginLoc(), D: Entity, MightBeOdrUse: false);
7009 return false;
7010}
7011
7012/// Checks whether the given template argument is a pointer to
7013/// member constant according to C++ [temp.arg.nontype]p1.
7014static bool CheckTemplateArgumentPointerToMember(
7015 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7016 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7017 bool Invalid = false;
7018
7019 Expr *Arg = ResultArg;
7020 bool ObjCLifetimeConversion;
7021
7022 // C++ [temp.arg.nontype]p1:
7023 //
7024 // A template-argument for a non-type, non-template
7025 // template-parameter shall be one of: [...]
7026 //
7027 // -- a pointer to member expressed as described in 5.3.1.
7028 DeclRefExpr *DRE = nullptr;
7029
7030 // In C++98/03 mode, give an extension warning on any extra parentheses.
7031 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7032 bool ExtraParens = false;
7033 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
7034 if (!Invalid && !ExtraParens) {
7035 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_extra_parens)
7036 << Arg->getSourceRange();
7037 ExtraParens = true;
7038 }
7039
7040 Arg = Parens->getSubExpr();
7041 }
7042
7043 while (SubstNonTypeTemplateParmExpr *subst =
7044 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
7045 Arg = subst->getReplacement()->IgnoreImpCasts();
7046
7047 // A pointer-to-member constant written &Class::member.
7048 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
7049 if (UnOp->getOpcode() == UO_AddrOf) {
7050 DRE = dyn_cast<DeclRefExpr>(Val: UnOp->getSubExpr());
7051 if (DRE && !DRE->getQualifier())
7052 DRE = nullptr;
7053 }
7054 }
7055 // A constant of pointer-to-member type.
7056 else if ((DRE = dyn_cast<DeclRefExpr>(Val: Arg))) {
7057 ValueDecl *VD = DRE->getDecl();
7058 if (VD->getType()->isMemberPointerType()) {
7059 if (isa<NonTypeTemplateParmDecl>(Val: VD)) {
7060 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7061 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7062 CanonicalConverted =
7063 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7064 } else {
7065 SugaredConverted = TemplateArgument(VD, ParamType);
7066 CanonicalConverted =
7067 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7068 S.Context.getCanonicalType(T: ParamType));
7069 }
7070 return Invalid;
7071 }
7072 }
7073
7074 DRE = nullptr;
7075 }
7076
7077 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7078
7079 // Check for a null pointer value.
7080 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ResultArg,
7081 Entity)) {
7082 case NPV_Error:
7083 return true;
7084 case NPV_NullPointer:
7085 S.Diag(Loc: ResultArg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7086 SugaredConverted = TemplateArgument(ParamType,
7087 /*isNullPtr*/ true);
7088 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(T: ParamType),
7089 /*isNullPtr*/ true);
7090 return false;
7091 case NPV_NotNullPointer:
7092 break;
7093 }
7094
7095 if (S.IsQualificationConversion(FromType: ResultArg->getType(),
7096 ToType: ParamType.getNonReferenceType(), CStyle: false,
7097 ObjCLifetimeConversion)) {
7098 ResultArg = S.ImpCastExprToType(E: ResultArg, Type: ParamType, CK: CK_NoOp,
7099 VK: ResultArg->getValueKind())
7100 .get();
7101 } else if (!S.Context.hasSameUnqualifiedType(
7102 T1: ResultArg->getType(), T2: ParamType.getNonReferenceType())) {
7103 // We can't perform this conversion.
7104 S.Diag(Loc: ResultArg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
7105 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7106 S.NoteTemplateParameterLocation(Decl: *Param);
7107 return true;
7108 }
7109
7110 if (!DRE)
7111 return S.Diag(Loc: Arg->getBeginLoc(),
7112 DiagID: diag::err_template_arg_not_pointer_to_member_form)
7113 << Arg->getSourceRange();
7114
7115 if (isa<FieldDecl>(Val: DRE->getDecl()) ||
7116 isa<IndirectFieldDecl>(Val: DRE->getDecl()) ||
7117 isa<CXXMethodDecl>(Val: DRE->getDecl())) {
7118 assert((isa<FieldDecl>(DRE->getDecl()) ||
7119 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7120 cast<CXXMethodDecl>(DRE->getDecl())
7121 ->isImplicitObjectMemberFunction()) &&
7122 "Only non-static member pointers can make it here");
7123
7124 // Okay: this is the address of a non-static member, and therefore
7125 // a member pointer constant.
7126 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7127 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7128 CanonicalConverted =
7129 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7130 } else {
7131 ValueDecl *D = DRE->getDecl();
7132 SugaredConverted = TemplateArgument(D, ParamType);
7133 CanonicalConverted =
7134 TemplateArgument(cast<ValueDecl>(Val: D->getCanonicalDecl()),
7135 S.Context.getCanonicalType(T: ParamType));
7136 }
7137 return Invalid;
7138 }
7139
7140 // We found something else, but we don't know specifically what it is.
7141 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_pointer_to_member_form)
7142 << Arg->getSourceRange();
7143 S.Diag(Loc: DRE->getDecl()->getLocation(), DiagID: diag::note_template_arg_refers_here);
7144 return true;
7145}
7146
7147/// Check a template argument against its corresponding
7148/// non-type template parameter.
7149///
7150/// This routine implements the semantics of C++ [temp.arg.nontype].
7151/// If an error occurred, it returns ExprError(); otherwise, it
7152/// returns the converted template argument. \p ParamType is the
7153/// type of the non-type template parameter after it has been instantiated.
7154ExprResult Sema::CheckTemplateArgument(NamedDecl *Param, QualType ParamType,
7155 Expr *Arg,
7156 TemplateArgument &SugaredConverted,
7157 TemplateArgument &CanonicalConverted,
7158 bool StrictCheck,
7159 CheckTemplateArgumentKind CTAK) {
7160 SourceLocation StartLoc = Arg->getBeginLoc();
7161 auto *ArgPE = dyn_cast<PackExpansionExpr>(Val: Arg);
7162 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7163 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7164 DeductionArg = NewDeductionArg;
7165 if (ArgPE) {
7166 // Recreate a pack expansion if we unwrapped one.
7167 Arg = new (Context) PackExpansionExpr(
7168 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7169 } else {
7170 Arg = DeductionArg;
7171 }
7172 };
7173
7174 // If the parameter type somehow involves auto, deduce the type now.
7175 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7176 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7177 if (IsDeduced) {
7178 // When checking a deduced template argument, deduce from its type even if
7179 // the type is dependent, in order to check the types of non-type template
7180 // arguments line up properly in partial ordering.
7181 TypeSourceInfo *TSI =
7182 Context.getTrivialTypeSourceInfo(T: ParamType, Loc: Param->getLocation());
7183 if (isa<DeducedTemplateSpecializationType>(Val: DeducedT)) {
7184 InitializedEntity Entity =
7185 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7186 InitializationKind Kind = InitializationKind::CreateForInit(
7187 Loc: DeductionArg->getBeginLoc(), /*DirectInit*/false, Init: DeductionArg);
7188 Expr *Inits[1] = {DeductionArg};
7189 ParamType =
7190 DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind, Init: Inits);
7191 if (ParamType.isNull())
7192 return ExprError();
7193 } else {
7194 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7195 Param->getTemplateDepth() + 1);
7196 ParamType = QualType();
7197 TemplateDeductionResult Result =
7198 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeductionArg, Result&: ParamType, Info,
7199 /*DependentDeduction=*/true,
7200 // We do not check constraints right now because the
7201 // immediately-declared constraint of the auto type is
7202 // also an associated constraint, and will be checked
7203 // along with the other associated constraints after
7204 // checking the template argument list.
7205 /*IgnoreConstraints=*/true);
7206 if (Result != TemplateDeductionResult::Success) {
7207 ParamType = TSI->getType();
7208 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7209 if (Result == TemplateDeductionResult::AlreadyDiagnosed)
7210 return ExprError();
7211 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param))
7212 Diag(Loc: Arg->getExprLoc(),
7213 DiagID: diag::err_non_type_template_parm_type_deduction_failure)
7214 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7215 << Arg->getSourceRange();
7216 NoteTemplateParameterLocation(Decl: *Param);
7217 return ExprError();
7218 }
7219 ParamType = SubstAutoTypeDependent(TypeWithAuto: ParamType);
7220 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7221 }
7222 }
7223 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7224 // an error. The error message normally references the parameter
7225 // declaration, but here we'll pass the argument location because that's
7226 // where the parameter type is deduced.
7227 ParamType = CheckNonTypeTemplateParameterType(T: ParamType, Loc: Arg->getExprLoc());
7228 if (ParamType.isNull()) {
7229 NoteTemplateParameterLocation(Decl: *Param);
7230 return ExprError();
7231 }
7232 }
7233
7234 // We should have already dropped all cv-qualifiers by now.
7235 assert(!ParamType.hasQualifiers() &&
7236 "non-type template parameter type cannot be qualified");
7237
7238 // If either the parameter has a dependent type or the argument is
7239 // type-dependent, there's nothing we can check now.
7240 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7241 // Force the argument to the type of the parameter to maintain invariants.
7242 if (!IsDeduced) {
7243 ExprResult E = ImpCastExprToType(
7244 E: DeductionArg, Type: ParamType.getNonLValueExprType(Context), CK: CK_Dependent,
7245 VK: ParamType->isLValueReferenceType() ? VK_LValue
7246 : ParamType->isRValueReferenceType() ? VK_XValue
7247 : VK_PRValue);
7248 if (E.isInvalid())
7249 return ExprError();
7250 setDeductionArg(E.get());
7251 }
7252 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7253 CanonicalConverted = TemplateArgument(
7254 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7255 return Arg;
7256 }
7257
7258 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7259 if (CTAK == CTAK_Deduced && !StrictCheck &&
7260 (ParamType->isReferenceType()
7261 ? !Context.hasSameType(T1: ParamType.getNonReferenceType(),
7262 T2: DeductionArg->getType())
7263 : !Context.hasSameUnqualifiedType(T1: ParamType,
7264 T2: DeductionArg->getType()))) {
7265 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7266 // we should actually be checking the type of the template argument in P,
7267 // not the type of the template argument deduced from A, against the
7268 // template parameter type.
7269 Diag(Loc: StartLoc, DiagID: diag::err_deduced_non_type_template_arg_type_mismatch)
7270 << Arg->getType() << ParamType.getUnqualifiedType();
7271 NoteTemplateParameterLocation(Decl: *Param);
7272 return ExprError();
7273 }
7274
7275 // If the argument is a pack expansion, we don't know how many times it would
7276 // expand. If we continue checking the argument, this will make the template
7277 // definition ill-formed if it would be ill-formed for any number of
7278 // expansions during instantiation time. When partial ordering or matching
7279 // template template parameters, this is exactly what we want. Otherwise, the
7280 // normal template rules apply: we accept the template if it would be valid
7281 // for any number of expansions (i.e. none).
7282 if (ArgPE && !StrictCheck) {
7283 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7284 CanonicalConverted = TemplateArgument(
7285 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7286 return Arg;
7287 }
7288
7289 // Avoid making a copy when initializing a template parameter of class type
7290 // from a template parameter object of the same type. This is going beyond
7291 // the standard, but is required for soundness: in
7292 // template<A a> struct X { X *p; X<a> *q; };
7293 // ... we need p and q to have the same type.
7294 //
7295 // Similarly, don't inject a call to a copy constructor when initializing
7296 // from a template parameter of the same type.
7297 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7298 if (ParamType->isRecordType() && isa<DeclRefExpr>(Val: InnerArg) &&
7299 Context.hasSameUnqualifiedType(T1: ParamType, T2: InnerArg->getType())) {
7300 NamedDecl *ND = cast<DeclRefExpr>(Val: InnerArg)->getDecl();
7301 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(Val: ND)) {
7302
7303 SugaredConverted = TemplateArgument(TPO, ParamType);
7304 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7305 ParamType.getCanonicalType());
7306 return Arg;
7307 }
7308 if (isa<NonTypeTemplateParmDecl>(Val: ND)) {
7309 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7310 CanonicalConverted =
7311 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7312 return Arg;
7313 }
7314 }
7315
7316 // The initialization of the parameter from the argument is
7317 // a constant-evaluated context.
7318 EnterExpressionEvaluationContext ConstantEvaluated(
7319 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7320
7321 bool IsConvertedConstantExpression = true;
7322 if (isa<InitListExpr>(Val: DeductionArg) || ParamType->isRecordType()) {
7323 InitializationKind Kind = InitializationKind::CreateForInit(
7324 Loc: StartLoc, /*DirectInit=*/false, Init: DeductionArg);
7325 Expr *Inits[1] = {DeductionArg};
7326 InitializedEntity Entity =
7327 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7328 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7329 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Inits);
7330 if (Result.isInvalid() || !Result.get())
7331 return ExprError();
7332 Result = ActOnConstantExpression(Res: Result.get());
7333 if (Result.isInvalid() || !Result.get())
7334 return ExprError();
7335 setDeductionArg(ActOnFinishFullExpr(Expr: Result.get(), CC: Arg->getBeginLoc(),
7336 /*DiscardedValue=*/false,
7337 /*IsConstexpr=*/true,
7338 /*IsTemplateArgument=*/true)
7339 .get());
7340 IsConvertedConstantExpression = false;
7341 }
7342
7343 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7344 // C++17 [temp.arg.nontype]p1:
7345 // A template-argument for a non-type template parameter shall be
7346 // a converted constant expression of the type of the template-parameter.
7347 APValue Value;
7348 ExprResult ArgResult;
7349 if (IsConvertedConstantExpression) {
7350 ArgResult = BuildConvertedConstantExpression(
7351 From: DeductionArg, T: ParamType,
7352 CCE: StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Dest: Param);
7353 assert(!ArgResult.isUnset());
7354 if (ArgResult.isInvalid()) {
7355 NoteTemplateParameterLocation(Decl: *Param);
7356 return ExprError();
7357 }
7358 } else {
7359 ArgResult = DeductionArg;
7360 }
7361
7362 // For a value-dependent argument, CheckConvertedConstantExpression is
7363 // permitted (and expected) to be unable to determine a value.
7364 if (ArgResult.get()->isValueDependent()) {
7365 setDeductionArg(ArgResult.get());
7366 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7367 CanonicalConverted =
7368 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7369 return Arg;
7370 }
7371
7372 APValue PreNarrowingValue;
7373 ArgResult = EvaluateConvertedConstantExpression(
7374 E: ArgResult.get(), T: ParamType, Value, CCE: CCEKind::TemplateArg, /*RequireInt=*/
7375 false, PreNarrowingValue);
7376 if (ArgResult.isInvalid())
7377 return ExprError();
7378 setDeductionArg(ArgResult.get());
7379
7380 if (Value.isLValue()) {
7381 APValue::LValueBase Base = Value.getLValueBase();
7382 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7383 // For a non-type template-parameter of pointer or reference type,
7384 // the value of the constant expression shall not refer to
7385 assert(ParamType->isPointerOrReferenceType() ||
7386 ParamType->isNullPtrType());
7387 // -- a temporary object
7388 // -- a string literal
7389 // -- the result of a typeid expression, or
7390 // -- a predefined __func__ variable
7391 if (Base &&
7392 (!VD ||
7393 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(Val: VD))) {
7394 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
7395 << Arg->getSourceRange();
7396 return ExprError();
7397 }
7398
7399 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7400 VD->getType()->isArrayType() &&
7401 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7402 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7403 if (ArgPE) {
7404 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7405 CanonicalConverted =
7406 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7407 } else {
7408 SugaredConverted = TemplateArgument(VD, ParamType);
7409 CanonicalConverted =
7410 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7411 ParamType.getCanonicalType());
7412 }
7413 return Arg;
7414 }
7415
7416 // -- a subobject [until C++20]
7417 if (!getLangOpts().CPlusPlus20) {
7418 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7419 Value.isLValueOnePastTheEnd()) {
7420 Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_subobject)
7421 << Value.getAsString(Ctx: Context, Ty: ParamType);
7422 return ExprError();
7423 }
7424 assert((VD || !ParamType->isReferenceType()) &&
7425 "null reference should not be a constant expression");
7426 assert((!VD || !ParamType->isNullPtrType()) &&
7427 "non-null value of type nullptr_t?");
7428 }
7429 }
7430
7431 if (Value.isAddrLabelDiff())
7432 return Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_addr_label_diff);
7433
7434 if (ArgPE) {
7435 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7436 CanonicalConverted =
7437 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7438 } else {
7439 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7440 CanonicalConverted =
7441 TemplateArgument(Context, ParamType.getCanonicalType(), Value);
7442 }
7443 return Arg;
7444 }
7445
7446 // These should have all been handled above using the C++17 rules.
7447 assert(!ArgPE && !StrictCheck);
7448
7449 // C++ [temp.arg.nontype]p5:
7450 // The following conversions are performed on each expression used
7451 // as a non-type template-argument. If a non-type
7452 // template-argument cannot be converted to the type of the
7453 // corresponding template-parameter then the program is
7454 // ill-formed.
7455 if (ParamType->isIntegralOrEnumerationType()) {
7456 // C++11:
7457 // -- for a non-type template-parameter of integral or
7458 // enumeration type, conversions permitted in a converted
7459 // constant expression are applied.
7460 //
7461 // C++98:
7462 // -- for a non-type template-parameter of integral or
7463 // enumeration type, integral promotions (4.5) and integral
7464 // conversions (4.7) are applied.
7465
7466 if (getLangOpts().CPlusPlus11) {
7467 // C++ [temp.arg.nontype]p1:
7468 // A template-argument for a non-type, non-template template-parameter
7469 // shall be one of:
7470 //
7471 // -- for a non-type template-parameter of integral or enumeration
7472 // type, a converted constant expression of the type of the
7473 // template-parameter; or
7474 llvm::APSInt Value;
7475 ExprResult ArgResult = CheckConvertedConstantExpression(
7476 From: Arg, T: ParamType, Value, CCE: CCEKind::TemplateArg);
7477 if (ArgResult.isInvalid())
7478 return ExprError();
7479 Arg = ArgResult.get();
7480
7481 // We can't check arbitrary value-dependent arguments.
7482 if (Arg->isValueDependent()) {
7483 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7484 CanonicalConverted =
7485 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7486 return Arg;
7487 }
7488
7489 // Widen the argument value to sizeof(parameter type). This is almost
7490 // always a no-op, except when the parameter type is bool. In
7491 // that case, this may extend the argument from 1 bit to 8 bits.
7492 QualType IntegerType = ParamType;
7493 if (const auto *ED = IntegerType->getAsEnumDecl())
7494 IntegerType = ED->getIntegerType();
7495 Value = Value.extOrTrunc(width: IntegerType->isBitIntType()
7496 ? Context.getIntWidth(T: IntegerType)
7497 : Context.getTypeSize(T: IntegerType));
7498
7499 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7500 CanonicalConverted =
7501 TemplateArgument(Context, Value, Context.getCanonicalType(T: ParamType));
7502 return Arg;
7503 }
7504
7505 ExprResult ArgResult = DefaultLvalueConversion(E: Arg);
7506 if (ArgResult.isInvalid())
7507 return ExprError();
7508 Arg = ArgResult.get();
7509
7510 QualType ArgType = Arg->getType();
7511
7512 // C++ [temp.arg.nontype]p1:
7513 // A template-argument for a non-type, non-template
7514 // template-parameter shall be one of:
7515 //
7516 // -- an integral constant-expression of integral or enumeration
7517 // type; or
7518 // -- the name of a non-type template-parameter; or
7519 llvm::APSInt Value;
7520 if (!ArgType->isIntegralOrEnumerationType()) {
7521 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_integral_or_enumeral)
7522 << ArgType << Arg->getSourceRange();
7523 NoteTemplateParameterLocation(Decl: *Param);
7524 return ExprError();
7525 }
7526 if (!Arg->isValueDependent()) {
7527 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7528 QualType T;
7529
7530 public:
7531 TmplArgICEDiagnoser(QualType T) : T(T) { }
7532
7533 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7534 SourceLocation Loc) override {
7535 return S.Diag(Loc, DiagID: diag::err_template_arg_not_ice) << T;
7536 }
7537 } Diagnoser(ArgType);
7538
7539 Arg = VerifyIntegerConstantExpression(E: Arg, Result: &Value, Diagnoser).get();
7540 if (!Arg)
7541 return ExprError();
7542 }
7543
7544 // From here on out, all we care about is the unqualified form
7545 // of the argument type.
7546 ArgType = ArgType.getUnqualifiedType();
7547
7548 // Try to convert the argument to the parameter's type.
7549 if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
7550 // Okay: no conversion necessary
7551 } else if (ParamType->isBooleanType()) {
7552 // This is an integral-to-boolean conversion.
7553 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralToBoolean).get();
7554 } else if (IsIntegralPromotion(From: Arg, FromType: ArgType, ToType: ParamType) ||
7555 !ParamType->isEnumeralType()) {
7556 // This is an integral promotion or conversion.
7557 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralCast).get();
7558 } else {
7559 // We can't perform this conversion.
7560 Diag(Loc: StartLoc, DiagID: diag::err_template_arg_not_convertible)
7561 << Arg->getType() << ParamType << Arg->getSourceRange();
7562 NoteTemplateParameterLocation(Decl: *Param);
7563 return ExprError();
7564 }
7565
7566 // Add the value of this argument to the list of converted
7567 // arguments. We use the bitwidth and signedness of the template
7568 // parameter.
7569 if (Arg->isValueDependent()) {
7570 // The argument is value-dependent. Create a new
7571 // TemplateArgument with the converted expression.
7572 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7573 CanonicalConverted =
7574 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7575 return Arg;
7576 }
7577
7578 QualType IntegerType = ParamType;
7579 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7580 IntegerType = ED->getIntegerType();
7581 }
7582
7583 if (ParamType->isBooleanType()) {
7584 // Value must be zero or one.
7585 Value = Value != 0;
7586 unsigned AllowedBits = Context.getTypeSize(T: IntegerType);
7587 if (Value.getBitWidth() != AllowedBits)
7588 Value = Value.extOrTrunc(width: AllowedBits);
7589 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7590 } else {
7591 llvm::APSInt OldValue = Value;
7592
7593 // Coerce the template argument's value to the value it will have
7594 // based on the template parameter's type.
7595 unsigned AllowedBits = IntegerType->isBitIntType()
7596 ? Context.getIntWidth(T: IntegerType)
7597 : Context.getTypeSize(T: IntegerType);
7598 if (Value.getBitWidth() != AllowedBits)
7599 Value = Value.extOrTrunc(width: AllowedBits);
7600 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7601
7602 // Complain if an unsigned parameter received a negative value.
7603 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7604 (OldValue.isSigned() && OldValue.isNegative())) {
7605 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_negative)
7606 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7607 << Arg->getSourceRange();
7608 NoteTemplateParameterLocation(Decl: *Param);
7609 }
7610
7611 // Complain if we overflowed the template parameter's type.
7612 unsigned RequiredBits;
7613 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7614 RequiredBits = OldValue.getActiveBits();
7615 else if (OldValue.isUnsigned())
7616 RequiredBits = OldValue.getActiveBits() + 1;
7617 else
7618 RequiredBits = OldValue.getSignificantBits();
7619 if (RequiredBits > AllowedBits) {
7620 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_too_large)
7621 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7622 << Arg->getSourceRange();
7623 NoteTemplateParameterLocation(Decl: *Param);
7624 }
7625 }
7626
7627 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7628 SugaredConverted = TemplateArgument(Context, Value, T);
7629 CanonicalConverted =
7630 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7631 return Arg;
7632 }
7633
7634 QualType ArgType = Arg->getType();
7635 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7636 bool IsSpecified = CTAK == CTAK_Specified;
7637
7638 // Handle pointer-to-function, reference-to-function, and
7639 // pointer-to-member-function all in (roughly) the same way.
7640 if (// -- For a non-type template-parameter of type pointer to
7641 // function, only the function-to-pointer conversion (4.3) is
7642 // applied. If the template-argument represents a set of
7643 // overloaded functions (or a pointer to such), the matching
7644 // function is selected from the set (13.4).
7645 (ParamType->isPointerType() &&
7646 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7647 // -- For a non-type template-parameter of type reference to
7648 // function, no conversions apply. If the template-argument
7649 // represents a set of overloaded functions, the matching
7650 // function is selected from the set (13.4).
7651 (ParamType->isReferenceType() &&
7652 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7653 // -- For a non-type template-parameter of type pointer to
7654 // member function, no conversions apply. If the
7655 // template-argument represents a set of overloaded member
7656 // functions, the matching member function is selected from
7657 // the set (13.4).
7658 (ParamType->isMemberPointerType() &&
7659 ParamType->castAs<MemberPointerType>()->getPointeeType()
7660 ->isFunctionType())) {
7661
7662 if (Arg->getType() == Context.OverloadTy) {
7663 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg, TargetType: ParamType,
7664 Complain: true,
7665 Found&: FoundResult)) {
7666 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7667 return ExprError();
7668
7669 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7670 if (Res.isInvalid())
7671 return ExprError();
7672 Arg = Res.get();
7673 ArgType = Arg->getType();
7674 } else
7675 return ExprError();
7676 }
7677
7678 if (!ParamType->isMemberPointerType()) {
7679 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7680 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7681 CanonicalConverted))
7682 return ExprError();
7683 return Arg;
7684 }
7685
7686 if (CheckTemplateArgumentPointerToMember(
7687 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7688 return ExprError();
7689 return Arg;
7690 }
7691
7692 if (ParamType->isPointerType()) {
7693 // -- for a non-type template-parameter of type pointer to
7694 // object, qualification conversions (4.4) and the
7695 // array-to-pointer conversion (4.2) are applied.
7696 // C++0x also allows a value of std::nullptr_t.
7697 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7698 "Only object pointers allowed here");
7699
7700 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7701 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7702 CanonicalConverted))
7703 return ExprError();
7704 return Arg;
7705 }
7706
7707 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7708 // -- For a non-type template-parameter of type reference to
7709 // object, no conversions apply. The type referred to by the
7710 // reference may be more cv-qualified than the (otherwise
7711 // identical) type of the template-argument. The
7712 // template-parameter is bound directly to the
7713 // template-argument, which must be an lvalue.
7714 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7715 "Only object references allowed here");
7716
7717 if (Arg->getType() == Context.OverloadTy) {
7718 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg,
7719 TargetType: ParamRefType->getPointeeType(),
7720 Complain: true,
7721 Found&: FoundResult)) {
7722 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7723 return ExprError();
7724 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7725 if (Res.isInvalid())
7726 return ExprError();
7727 Arg = Res.get();
7728 ArgType = Arg->getType();
7729 } else
7730 return ExprError();
7731 }
7732
7733 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7734 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7735 CanonicalConverted))
7736 return ExprError();
7737 return Arg;
7738 }
7739
7740 // Deal with parameters of type std::nullptr_t.
7741 if (ParamType->isNullPtrType()) {
7742 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7743 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7744 CanonicalConverted =
7745 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7746 return Arg;
7747 }
7748
7749 switch (isNullPointerValueTemplateArgument(S&: *this, Param, ParamType, Arg)) {
7750 case NPV_NotNullPointer:
7751 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_not_convertible)
7752 << Arg->getType() << ParamType;
7753 NoteTemplateParameterLocation(Decl: *Param);
7754 return ExprError();
7755
7756 case NPV_Error:
7757 return ExprError();
7758
7759 case NPV_NullPointer:
7760 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7761 SugaredConverted = TemplateArgument(ParamType,
7762 /*isNullPtr=*/true);
7763 CanonicalConverted = TemplateArgument(Context.getCanonicalType(T: ParamType),
7764 /*isNullPtr=*/true);
7765 return Arg;
7766 }
7767 }
7768
7769 // -- For a non-type template-parameter of type pointer to data
7770 // member, qualification conversions (4.4) are applied.
7771 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7772
7773 if (CheckTemplateArgumentPointerToMember(
7774 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7775 return ExprError();
7776 return Arg;
7777}
7778
7779static void DiagnoseTemplateParameterListArityMismatch(
7780 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7781 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7782
7783bool Sema::CheckDeclCompatibleWithTemplateTemplate(
7784 TemplateDecl *Template, TemplateTemplateParmDecl *Param,
7785 const TemplateArgumentLoc &Arg) {
7786 // C++0x [temp.arg.template]p1:
7787 // A template-argument for a template template-parameter shall be
7788 // the name of a class template or an alias template, expressed as an
7789 // id-expression. When the template-argument names a class template, only
7790 // primary class templates are considered when matching the
7791 // template template argument with the corresponding parameter;
7792 // partial specializations are not considered even if their
7793 // parameter lists match that of the template template parameter.
7794 //
7795
7796 TemplateNameKind Kind = TNK_Non_template;
7797 unsigned DiagFoundKind = 0;
7798
7799 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Val: Template)) {
7800 switch (TTP->templateParameterKind()) {
7801 case TemplateNameKind::TNK_Concept_template:
7802 DiagFoundKind = 3;
7803 break;
7804 case TemplateNameKind::TNK_Var_template:
7805 DiagFoundKind = 2;
7806 break;
7807 default:
7808 DiagFoundKind = 1;
7809 break;
7810 }
7811 Kind = TTP->templateParameterKind();
7812 } else if (isa<ConceptDecl>(Val: Template)) {
7813 Kind = TemplateNameKind::TNK_Concept_template;
7814 DiagFoundKind = 3;
7815 } else if (isa<FunctionTemplateDecl>(Val: Template)) {
7816 Kind = TemplateNameKind::TNK_Function_template;
7817 DiagFoundKind = 0;
7818 } else if (isa<VarTemplateDecl>(Val: Template)) {
7819 Kind = TemplateNameKind::TNK_Var_template;
7820 DiagFoundKind = 2;
7821 } else if (isa<ClassTemplateDecl>(Val: Template) ||
7822 isa<TypeAliasTemplateDecl>(Val: Template) ||
7823 isa<BuiltinTemplateDecl>(Val: Template)) {
7824 Kind = TemplateNameKind::TNK_Type_template;
7825 DiagFoundKind = 1;
7826 } else {
7827 assert(false && "Unexpected Decl");
7828 }
7829
7830 if (Kind == Param->templateParameterKind()) {
7831 return true;
7832 }
7833
7834 unsigned DiagKind = 0;
7835 switch (Param->templateParameterKind()) {
7836 case TemplateNameKind::TNK_Concept_template:
7837 DiagKind = 2;
7838 break;
7839 case TemplateNameKind::TNK_Var_template:
7840 DiagKind = 1;
7841 break;
7842 default:
7843 DiagKind = 0;
7844 break;
7845 }
7846 Diag(Loc: Arg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
7847 << DiagKind;
7848 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_arg_refers_to_template_here)
7849 << DiagFoundKind << Template;
7850 return false;
7851}
7852
7853/// Check a template argument against its corresponding
7854/// template template parameter.
7855///
7856/// This routine implements the semantics of C++ [temp.arg.template].
7857/// It returns true if an error occurred, and false otherwise.
7858bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7859 TemplateParameterList *Params,
7860 TemplateArgumentLoc &Arg,
7861 bool PartialOrdering,
7862 bool *StrictPackMatch) {
7863 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7864 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7865 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7866 if (!Template) {
7867 // FIXME: Handle AssumedTemplateNames
7868 // Any dependent template name is fine.
7869 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7870 return false;
7871 }
7872
7873 if (Template->isInvalidDecl())
7874 return true;
7875
7876 if (!CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg)) {
7877 return true;
7878 }
7879
7880 // C++1z [temp.arg.template]p3: (DR 150)
7881 // A template-argument matches a template template-parameter P when P
7882 // is at least as specialized as the template-argument A.
7883 if (!isTemplateTemplateParameterAtLeastAsSpecializedAs(
7884 PParam: Params, PArg: Param, AArg: Template, DefaultArgs, ArgLoc: Arg.getLocation(),
7885 PartialOrdering, StrictPackMatch))
7886 return true;
7887 // P2113
7888 // C++20[temp.func.order]p2
7889 // [...] If both deductions succeed, the partial ordering selects the
7890 // more constrained template (if one exists) as determined below.
7891 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7892 Params->getAssociatedConstraints(AC&: ParamsAC);
7893 // C++20[temp.arg.template]p3
7894 // [...] In this comparison, if P is unconstrained, the constraints on A
7895 // are not considered.
7896 if (ParamsAC.empty())
7897 return false;
7898
7899 Template->getAssociatedConstraints(AC&: TemplateAC);
7900
7901 bool IsParamAtLeastAsConstrained;
7902 if (IsAtLeastAsConstrained(D1: Param, AC1: ParamsAC, D2: Template, AC2: TemplateAC,
7903 Result&: IsParamAtLeastAsConstrained))
7904 return true;
7905 if (!IsParamAtLeastAsConstrained) {
7906 Diag(Loc: Arg.getLocation(),
7907 DiagID: diag::err_template_template_parameter_not_at_least_as_constrained)
7908 << Template << Param << Arg.getSourceRange();
7909 Diag(Loc: Param->getLocation(), DiagID: diag::note_entity_declared_at) << Param;
7910 Diag(Loc: Template->getLocation(), DiagID: diag::note_entity_declared_at) << Template;
7911 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Param, AC1: ParamsAC, D2: Template,
7912 AC2: TemplateAC);
7913 return true;
7914 }
7915 return false;
7916}
7917
7918static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7919 unsigned HereDiagID,
7920 unsigned ExternalDiagID) {
7921 if (Decl.getLocation().isValid())
7922 return S.Diag(Loc: Decl.getLocation(), DiagID: HereDiagID);
7923
7924 SmallString<128> Str;
7925 llvm::raw_svector_ostream Out(Str);
7926 PrintingPolicy PP = S.getPrintingPolicy();
7927 PP.TerseOutput = 1;
7928 Decl.print(Out, Policy: PP);
7929 return S.Diag(Loc: Decl.getLocation(), DiagID: ExternalDiagID) << Out.str();
7930}
7931
7932void Sema::NoteTemplateLocation(const NamedDecl &Decl,
7933 std::optional<SourceRange> ParamRange) {
7934 SemaDiagnosticBuilder DB =
7935 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_decl_here,
7936 ExternalDiagID: diag::note_template_decl_external);
7937 if (ParamRange && ParamRange->isValid()) {
7938 assert(Decl.getLocation().isValid() &&
7939 "Parameter range has location when Decl does not");
7940 DB << *ParamRange;
7941 }
7942}
7943
7944void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
7945 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_param_here,
7946 ExternalDiagID: diag::note_template_param_external);
7947}
7948
7949/// Given a non-type template argument that refers to a
7950/// declaration and the type of its corresponding non-type template
7951/// parameter, produce an expression that properly refers to that
7952/// declaration.
7953ExprResult Sema::BuildExpressionFromDeclTemplateArgument(
7954 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc) {
7955 // C++ [temp.param]p8:
7956 //
7957 // A non-type template-parameter of type "array of T" or
7958 // "function returning T" is adjusted to be of type "pointer to
7959 // T" or "pointer to function returning T", respectively.
7960 if (ParamType->isArrayType())
7961 ParamType = Context.getArrayDecayedType(T: ParamType);
7962 else if (ParamType->isFunctionType())
7963 ParamType = Context.getPointerType(T: ParamType);
7964
7965 // For a NULL non-type template argument, return nullptr casted to the
7966 // parameter's type.
7967 if (Arg.getKind() == TemplateArgument::NullPtr) {
7968 return ImpCastExprToType(
7969 E: new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7970 Type: ParamType,
7971 CK: ParamType->getAs<MemberPointerType>()
7972 ? CK_NullToMemberPointer
7973 : CK_NullToPointer);
7974 }
7975 assert(Arg.getKind() == TemplateArgument::Declaration &&
7976 "Only declaration template arguments permitted here");
7977
7978 ValueDecl *VD = Arg.getAsDecl();
7979
7980 CXXScopeSpec SS;
7981 if (ParamType->isMemberPointerType()) {
7982 // If this is a pointer to member, we need to use a qualified name to
7983 // form a suitable pointer-to-member constant.
7984 assert(VD->getDeclContext()->isRecord() &&
7985 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7986 isa<IndirectFieldDecl>(VD)));
7987 CanQualType ClassType =
7988 Context.getCanonicalTagType(TD: cast<RecordDecl>(Val: VD->getDeclContext()));
7989 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7990 SS.MakeTrivial(Context, Qualifier, R: Loc);
7991 }
7992
7993 ExprResult RefExpr = BuildDeclarationNameExpr(
7994 SS, NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
7995 if (RefExpr.isInvalid())
7996 return ExprError();
7997
7998 // For a pointer, the argument declaration is the pointee. Take its address.
7999 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8000 if (ParamType->isPointerType() && !ElemT.isNull() &&
8001 Context.hasSimilarType(T1: ElemT, T2: ParamType->getPointeeType())) {
8002 // Decay an array argument if we want a pointer to its first element.
8003 RefExpr = DefaultFunctionArrayConversion(E: RefExpr.get());
8004 if (RefExpr.isInvalid())
8005 return ExprError();
8006 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8007 // For any other pointer, take the address (or form a pointer-to-member).
8008 RefExpr = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_AddrOf, InputExpr: RefExpr.get());
8009 if (RefExpr.isInvalid())
8010 return ExprError();
8011 } else if (ParamType->isRecordType()) {
8012 assert(isa<TemplateParamObjectDecl>(VD) &&
8013 "arg for class template param not a template parameter object");
8014 // No conversions apply in this case.
8015 return RefExpr;
8016 } else {
8017 assert(ParamType->isReferenceType() &&
8018 "unexpected type for decl template argument");
8019 // If the parameter has reference type, wrap it in paretheses so that this
8020 // expression will have the correct type under `decltype`.
8021 RefExpr = new (Context) ParenExpr(Loc, Loc, RefExpr.get());
8022 }
8023
8024 // At this point we should have the right value category.
8025 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8026 "value kind mismatch for non-type template argument");
8027
8028 // The type of the template parameter can differ from the type of the
8029 // argument in various ways; convert it now if necessary.
8030 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8031 QualType SrcExprType = RefExpr.get()->getType();
8032 if (!Context.hasSameType(T1: SrcExprType, T2: DestExprType)) {
8033 CastKind CK;
8034 if (Context.hasSimilarType(T1: SrcExprType, T2: DestExprType) ||
8035 IsFunctionConversion(FromType: SrcExprType, ToType: DestExprType)) {
8036 CK = CK_NoOp;
8037 } else if (ParamType->isVoidPointerType() && SrcExprType->isPointerType()) {
8038 CK = CK_BitCast;
8039 } else {
8040 // FIXME: Pointers to members can need conversion derived-to-base or
8041 // base-to-derived conversions. We currently don't retain enough
8042 // information to convert properly (we need to track a cast path or
8043 // subobject number in the template argument).
8044 llvm_unreachable(
8045 "unexpected conversion required for non-type template argument");
8046 }
8047 RefExpr = ImpCastExprToType(E: RefExpr.get(), Type: DestExprType, CK,
8048 VK: RefExpr.get()->getValueKind());
8049 }
8050
8051 return RefExpr;
8052}
8053
8054/// Construct a new expression that refers to the given
8055/// integral template argument with the given source-location
8056/// information.
8057///
8058/// This routine takes care of the mapping from an integral template
8059/// argument (which may have any integral type) to the appropriate
8060/// literal value.
8061static Expr *BuildExpressionFromIntegralTemplateArgumentValue(
8062 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8063 assert(OrigT->isIntegralOrEnumerationType());
8064
8065 // If this is an enum type that we're instantiating, we need to use an integer
8066 // type the same size as the enumerator. We don't want to build an
8067 // IntegerLiteral with enum type. The integer type of an enum type can be of
8068 // any integral type with C++11 enum classes, make sure we create the right
8069 // type of literal for it.
8070 QualType T = OrigT;
8071 if (const auto *ED = OrigT->getAsEnumDecl())
8072 T = ED->getIntegerType();
8073
8074 Expr *E;
8075 if (T->isAnyCharacterType()) {
8076 CharacterLiteralKind Kind;
8077 if (T->isWideCharType())
8078 Kind = CharacterLiteralKind::Wide;
8079 else if (T->isChar8Type() && S.getLangOpts().Char8)
8080 Kind = CharacterLiteralKind::UTF8;
8081 else if (T->isChar16Type())
8082 Kind = CharacterLiteralKind::UTF16;
8083 else if (T->isChar32Type())
8084 Kind = CharacterLiteralKind::UTF32;
8085 else
8086 Kind = CharacterLiteralKind::Ascii;
8087
8088 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8089 } else if (T->isBooleanType()) {
8090 E = CXXBoolLiteralExpr::Create(C: S.Context, Val: Int.getBoolValue(), Ty: T, Loc);
8091 } else {
8092 E = IntegerLiteral::Create(C: S.Context, V: Int, type: T, l: Loc);
8093 }
8094
8095 if (OrigT->isEnumeralType()) {
8096 // FIXME: This is a hack. We need a better way to handle substituted
8097 // non-type template parameters.
8098 E = CStyleCastExpr::Create(Context: S.Context, T: OrigT, VK: VK_PRValue, K: CK_IntegralCast, Op: E,
8099 BasePath: nullptr, FPO: S.CurFPFeatureOverrides(),
8100 WrittenTy: S.Context.getTrivialTypeSourceInfo(T: OrigT, Loc),
8101 L: Loc, R: Loc);
8102 }
8103
8104 return E;
8105}
8106
8107static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(
8108 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8109 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8110 auto *ILE = new (S.Context)
8111 InitListExpr(S.Context, Loc, Elts, Loc, /*isExplicit=*/false);
8112 ILE->setType(T);
8113 return ILE;
8114 };
8115
8116 switch (Val.getKind()) {
8117 case APValue::AddrLabelDiff:
8118 // This cannot occur in a template argument at all.
8119 case APValue::Array:
8120 case APValue::Struct:
8121 case APValue::Union:
8122 // These can only occur within a template parameter object, which is
8123 // represented as a TemplateArgument::Declaration.
8124 llvm_unreachable("unexpected template argument value");
8125
8126 case APValue::Int:
8127 return BuildExpressionFromIntegralTemplateArgumentValue(S, OrigT: T, Int: Val.getInt(),
8128 Loc);
8129
8130 case APValue::Float:
8131 return FloatingLiteral::Create(C: S.Context, V: Val.getFloat(), /*IsExact=*/isexact: true,
8132 Type: T, L: Loc);
8133
8134 case APValue::FixedPoint:
8135 return FixedPointLiteral::CreateFromRawInt(
8136 C: S.Context, V: Val.getFixedPoint().getValue(), type: T, l: Loc,
8137 Scale: Val.getFixedPoint().getScale());
8138
8139 case APValue::ComplexInt: {
8140 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8141 return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(
8142 S, OrigT: ElemT, Int: Val.getComplexIntReal(), Loc),
8143 BuildExpressionFromIntegralTemplateArgumentValue(
8144 S, OrigT: ElemT, Int: Val.getComplexIntImag(), Loc)});
8145 }
8146
8147 case APValue::ComplexFloat: {
8148 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8149 return MakeInitList(
8150 {FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatReal(), isexact: true,
8151 Type: ElemT, L: Loc),
8152 FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatImag(), isexact: true,
8153 Type: ElemT, L: Loc)});
8154 }
8155
8156 case APValue::Vector: {
8157 QualType ElemT = T->castAs<VectorType>()->getElementType();
8158 llvm::SmallVector<Expr *, 8> Elts;
8159 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8160 Elts.push_back(Elt: BuildExpressionFromNonTypeTemplateArgumentValue(
8161 S, T: ElemT, Val: Val.getVectorElt(I), Loc));
8162 return MakeInitList(Elts);
8163 }
8164
8165 case APValue::Matrix:
8166 llvm_unreachable("Matrix template argument expression not yet supported");
8167
8168 case APValue::None:
8169 case APValue::Indeterminate:
8170 llvm_unreachable("Unexpected APValue kind.");
8171 case APValue::LValue:
8172 case APValue::MemberPointer:
8173 // There isn't necessarily a valid equivalent source-level syntax for
8174 // these; in particular, a naive lowering might violate access control.
8175 // So for now we lower to a ConstantExpr holding the value, wrapped around
8176 // an OpaqueValueExpr.
8177 // FIXME: We should have a better representation for this.
8178 ExprValueKind VK = VK_PRValue;
8179 if (T->isReferenceType()) {
8180 T = T->getPointeeType();
8181 VK = VK_LValue;
8182 }
8183 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8184 return ConstantExpr::Create(Context: S.Context, E: OVE, Result: Val);
8185 }
8186 llvm_unreachable("Unhandled APValue::ValueKind enum");
8187}
8188
8189ExprResult
8190Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
8191 SourceLocation Loc) {
8192 switch (Arg.getKind()) {
8193 case TemplateArgument::Null:
8194 case TemplateArgument::Type:
8195 case TemplateArgument::Template:
8196 case TemplateArgument::TemplateExpansion:
8197 case TemplateArgument::Pack:
8198 llvm_unreachable("not a non-type template argument");
8199
8200 case TemplateArgument::Expression:
8201 return Arg.getAsExpr();
8202
8203 case TemplateArgument::NullPtr:
8204 case TemplateArgument::Declaration:
8205 return BuildExpressionFromDeclTemplateArgument(
8206 Arg, ParamType: Arg.getNonTypeTemplateArgumentType(), Loc);
8207
8208 case TemplateArgument::Integral:
8209 return BuildExpressionFromIntegralTemplateArgumentValue(
8210 S&: *this, OrigT: Arg.getIntegralType(), Int: Arg.getAsIntegral(), Loc);
8211
8212 case TemplateArgument::StructuralValue:
8213 return BuildExpressionFromNonTypeTemplateArgumentValue(
8214 S&: *this, T: Arg.getStructuralValueType(), Val: Arg.getAsStructuralValue(), Loc);
8215 }
8216 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8217}
8218
8219/// Match two template parameters within template parameter lists.
8220static bool MatchTemplateParameterKind(
8221 Sema &S, NamedDecl *New,
8222 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8223 const NamedDecl *OldInstFrom, bool Complain,
8224 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8225 // Check the actual kind (type, non-type, template).
8226 if (Old->getKind() != New->getKind()) {
8227 if (Complain) {
8228 unsigned NextDiag = diag::err_template_param_different_kind;
8229 if (TemplateArgLoc.isValid()) {
8230 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8231 NextDiag = diag::note_template_param_different_kind;
8232 }
8233 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8234 << (Kind != Sema::TPL_TemplateMatch);
8235 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_prev_declaration)
8236 << (Kind != Sema::TPL_TemplateMatch);
8237 }
8238
8239 return false;
8240 }
8241
8242 // Check that both are parameter packs or neither are parameter packs.
8243 // However, if we are matching a template template argument to a
8244 // template template parameter, the template template parameter can have
8245 // a parameter pack where the template template argument does not.
8246 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8247 if (Complain) {
8248 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8249 if (TemplateArgLoc.isValid()) {
8250 S.Diag(Loc: TemplateArgLoc,
8251 DiagID: diag::err_template_arg_template_params_mismatch);
8252 NextDiag = diag::note_template_parameter_pack_non_pack;
8253 }
8254
8255 unsigned ParamKind = isa<TemplateTypeParmDecl>(Val: New)? 0
8256 : isa<NonTypeTemplateParmDecl>(Val: New)? 1
8257 : 2;
8258 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8259 << ParamKind << New->isParameterPack();
8260 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_parameter_pack_here)
8261 << ParamKind << Old->isParameterPack();
8262 }
8263
8264 return false;
8265 }
8266 // For non-type template parameters, check the type of the parameter.
8267 if (NonTypeTemplateParmDecl *OldNTTP =
8268 dyn_cast<NonTypeTemplateParmDecl>(Val: Old)) {
8269 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(Val: New);
8270
8271 // If we are matching a template template argument to a template
8272 // template parameter and one of the non-type template parameter types
8273 // is dependent, then we must wait until template instantiation time
8274 // to actually compare the arguments.
8275 if (Kind != Sema::TPL_TemplateTemplateParmMatch ||
8276 (!OldNTTP->getType()->isDependentType() &&
8277 !NewNTTP->getType()->isDependentType())) {
8278 // C++20 [temp.over.link]p6:
8279 // Two [non-type] template-parameters are equivalent [if] they have
8280 // equivalent types ignoring the use of type-constraints for
8281 // placeholder types
8282 QualType OldType = S.Context.getUnconstrainedType(T: OldNTTP->getType());
8283 QualType NewType = S.Context.getUnconstrainedType(T: NewNTTP->getType());
8284 if (!S.Context.hasSameType(T1: OldType, T2: NewType)) {
8285 if (Complain) {
8286 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8287 if (TemplateArgLoc.isValid()) {
8288 S.Diag(Loc: TemplateArgLoc,
8289 DiagID: diag::err_template_arg_template_params_mismatch);
8290 NextDiag = diag::note_template_nontype_parm_different_type;
8291 }
8292 S.Diag(Loc: NewNTTP->getLocation(), DiagID: NextDiag)
8293 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8294 S.Diag(Loc: OldNTTP->getLocation(),
8295 DiagID: diag::note_template_nontype_parm_prev_declaration)
8296 << OldNTTP->getType();
8297 }
8298 return false;
8299 }
8300 }
8301 }
8302 // For template template parameters, check the template parameter types.
8303 // The template parameter lists of template template
8304 // parameters must agree.
8305 else if (TemplateTemplateParmDecl *OldTTP =
8306 dyn_cast<TemplateTemplateParmDecl>(Val: Old)) {
8307 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(Val: New);
8308 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8309 return false;
8310 if (!S.TemplateParameterListsAreEqual(
8311 NewInstFrom, New: NewTTP->getTemplateParameters(), OldInstFrom,
8312 Old: OldTTP->getTemplateParameters(), Complain,
8313 Kind: (Kind == Sema::TPL_TemplateMatch
8314 ? Sema::TPL_TemplateTemplateParmMatch
8315 : Kind),
8316 TemplateArgLoc))
8317 return false;
8318 }
8319
8320 if (Kind != Sema::TPL_TemplateParamsEquivalent &&
8321 Kind != Sema::TPL_TemplateTemplateParmMatch &&
8322 !isa<TemplateTemplateParmDecl>(Val: Old)) {
8323 const Expr *NewC = nullptr, *OldC = nullptr;
8324
8325 if (isa<TemplateTypeParmDecl>(Val: New)) {
8326 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: New)->getTypeConstraint())
8327 NewC = TC->getImmediatelyDeclaredConstraint();
8328 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: Old)->getTypeConstraint())
8329 OldC = TC->getImmediatelyDeclaredConstraint();
8330 } else if (isa<NonTypeTemplateParmDecl>(Val: New)) {
8331 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: New)
8332 ->getPlaceholderTypeConstraint())
8333 NewC = E;
8334 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: Old)
8335 ->getPlaceholderTypeConstraint())
8336 OldC = E;
8337 } else
8338 llvm_unreachable("unexpected template parameter type");
8339
8340 auto Diagnose = [&] {
8341 S.Diag(Loc: NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8342 DiagID: diag::err_template_different_type_constraint);
8343 S.Diag(Loc: OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8344 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8345 };
8346
8347 if (!NewC != !OldC) {
8348 if (Complain)
8349 Diagnose();
8350 return false;
8351 }
8352
8353 if (NewC) {
8354 if (!S.AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldC, New: NewInstFrom,
8355 NewConstr: NewC)) {
8356 if (Complain)
8357 Diagnose();
8358 return false;
8359 }
8360 }
8361 }
8362
8363 return true;
8364}
8365
8366/// Diagnose a known arity mismatch when comparing template argument
8367/// lists.
8368static
8369void DiagnoseTemplateParameterListArityMismatch(Sema &S,
8370 TemplateParameterList *New,
8371 TemplateParameterList *Old,
8372 Sema::TemplateParameterListEqualKind Kind,
8373 SourceLocation TemplateArgLoc) {
8374 unsigned NextDiag = diag::err_template_param_list_different_arity;
8375 if (TemplateArgLoc.isValid()) {
8376 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8377 NextDiag = diag::note_template_param_list_different_arity;
8378 }
8379 S.Diag(Loc: New->getTemplateLoc(), DiagID: NextDiag)
8380 << (New->size() > Old->size())
8381 << (Kind != Sema::TPL_TemplateMatch)
8382 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8383 S.Diag(Loc: Old->getTemplateLoc(), DiagID: diag::note_template_prev_declaration)
8384 << (Kind != Sema::TPL_TemplateMatch)
8385 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8386}
8387
8388bool Sema::TemplateParameterListsAreEqual(
8389 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8390 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8391 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8392 if (Old->size() != New->size()) {
8393 if (Complain)
8394 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8395 TemplateArgLoc);
8396
8397 return false;
8398 }
8399
8400 // C++0x [temp.arg.template]p3:
8401 // A template-argument matches a template template-parameter (call it P)
8402 // when each of the template parameters in the template-parameter-list of
8403 // the template-argument's corresponding class template or alias template
8404 // (call it A) matches the corresponding template parameter in the
8405 // template-parameter-list of P. [...]
8406 TemplateParameterList::iterator NewParm = New->begin();
8407 TemplateParameterList::iterator NewParmEnd = New->end();
8408 for (TemplateParameterList::iterator OldParm = Old->begin(),
8409 OldParmEnd = Old->end();
8410 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8411 if (NewParm == NewParmEnd) {
8412 if (Complain)
8413 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8414 TemplateArgLoc);
8415 return false;
8416 }
8417 if (!MatchTemplateParameterKind(S&: *this, New: *NewParm, NewInstFrom, Old: *OldParm,
8418 OldInstFrom, Complain, Kind,
8419 TemplateArgLoc))
8420 return false;
8421 }
8422
8423 // Make sure we exhausted all of the arguments.
8424 if (NewParm != NewParmEnd) {
8425 if (Complain)
8426 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8427 TemplateArgLoc);
8428
8429 return false;
8430 }
8431
8432 if (Kind != TPL_TemplateParamsEquivalent) {
8433 const Expr *NewRC = New->getRequiresClause();
8434 const Expr *OldRC = Old->getRequiresClause();
8435
8436 auto Diagnose = [&] {
8437 Diag(Loc: NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8438 DiagID: diag::err_template_different_requires_clause);
8439 Diag(Loc: OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8440 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8441 };
8442
8443 if (!NewRC != !OldRC) {
8444 if (Complain)
8445 Diagnose();
8446 return false;
8447 }
8448
8449 if (NewRC) {
8450 if (!AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldRC, New: NewInstFrom,
8451 NewConstr: NewRC)) {
8452 if (Complain)
8453 Diagnose();
8454 return false;
8455 }
8456 }
8457 }
8458
8459 return true;
8460}
8461
8462bool
8463Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
8464 if (!S)
8465 return false;
8466
8467 // Find the nearest enclosing declaration scope.
8468 S = S->getDeclParent();
8469
8470 // C++ [temp.pre]p6: [P2096]
8471 // A template, explicit specialization, or partial specialization shall not
8472 // have C linkage.
8473 DeclContext *Ctx = S->getEntity();
8474 if (Ctx && Ctx->isExternCContext()) {
8475 SourceRange Range =
8476 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8477 ? TemplateParams->getParam(Idx: 0)->getSourceRange()
8478 : TemplateParams->getSourceRange();
8479 Diag(Loc: Range.getBegin(), DiagID: diag::err_template_linkage) << Range;
8480 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8481 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
8482 return true;
8483 }
8484 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8485
8486 // C++ [temp]p2:
8487 // A template-declaration can appear only as a namespace scope or
8488 // class scope declaration.
8489 // C++ [temp.expl.spec]p3:
8490 // An explicit specialization may be declared in any scope in which the
8491 // corresponding primary template may be defined.
8492 // C++ [temp.class.spec]p6: [P2096]
8493 // A partial specialization may be declared in any scope in which the
8494 // corresponding primary template may be defined.
8495 if (Ctx) {
8496 if (Ctx->isFileContext())
8497 return false;
8498 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Ctx)) {
8499 // C++ [temp.mem]p2:
8500 // A local class shall not have member templates.
8501
8502 // Trace the outer context chain, bypassing nested records and OpenMP
8503 // captured regions, to determine if the class in defined inside a
8504 // function or method.
8505 const DeclContext *OutCtx = RD->getDeclContext();
8506 while (isa_and_nonnull<CapturedDecl, CXXRecordDecl>(Val: OutCtx))
8507 OutCtx = OutCtx->getParent();
8508
8509 if (OutCtx && OutCtx->isFunctionOrMethod())
8510 return Diag(Loc: TemplateParams->getTemplateLoc(),
8511 DiagID: diag::err_template_inside_local_class)
8512 << TemplateParams->getSourceRange();
8513
8514 return false;
8515 }
8516 }
8517
8518 return Diag(Loc: TemplateParams->getTemplateLoc(),
8519 DiagID: diag::err_template_outside_namespace_or_class_scope)
8520 << TemplateParams->getSourceRange();
8521}
8522
8523/// Determine what kind of template specialization the given declaration
8524/// is.
8525static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8526 if (!D)
8527 return TSK_Undeclared;
8528
8529 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D))
8530 return Record->getTemplateSpecializationKind();
8531 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D))
8532 return Function->getTemplateSpecializationKind();
8533 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D))
8534 return Var->getTemplateSpecializationKind();
8535
8536 return TSK_Undeclared;
8537}
8538
8539/// Check whether a specialization is well-formed in the current
8540/// context.
8541///
8542/// This routine determines whether a template specialization can be declared
8543/// in the current context (C++ [temp.expl.spec]p2).
8544///
8545/// \param S the semantic analysis object for which this check is being
8546/// performed.
8547///
8548/// \param Specialized the entity being specialized or instantiated, which
8549/// may be a kind of template (class template, function template, etc.) or
8550/// a member of a class template (member function, static data member,
8551/// member class).
8552///
8553/// \param PrevDecl the previous declaration of this entity, if any.
8554///
8555/// \param Loc the location of the explicit specialization or instantiation of
8556/// this entity.
8557///
8558/// \param IsPartialSpecialization whether this is a partial specialization of
8559/// a class template.
8560///
8561/// \returns true if there was an error that we cannot recover from, false
8562/// otherwise.
8563static bool CheckTemplateSpecializationScope(Sema &S,
8564 NamedDecl *Specialized,
8565 NamedDecl *PrevDecl,
8566 SourceLocation Loc,
8567 bool IsPartialSpecialization) {
8568 // Keep these "kind" numbers in sync with the %select statements in the
8569 // various diagnostics emitted by this routine.
8570 int EntityKind = 0;
8571 if (isa<ClassTemplateDecl>(Val: Specialized))
8572 EntityKind = IsPartialSpecialization? 1 : 0;
8573 else if (isa<VarTemplateDecl>(Val: Specialized))
8574 EntityKind = IsPartialSpecialization ? 3 : 2;
8575 else if (isa<FunctionTemplateDecl>(Val: Specialized))
8576 EntityKind = 4;
8577 else if (isa<CXXMethodDecl>(Val: Specialized))
8578 EntityKind = 5;
8579 else if (isa<VarDecl>(Val: Specialized))
8580 EntityKind = 6;
8581 else if (isa<RecordDecl>(Val: Specialized))
8582 EntityKind = 7;
8583 else if (isa<EnumDecl>(Val: Specialized) && S.getLangOpts().CPlusPlus11)
8584 EntityKind = 8;
8585 else {
8586 S.Diag(Loc, DiagID: diag::err_template_spec_unknown_kind)
8587 << S.getLangOpts().CPlusPlus11;
8588 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8589 return true;
8590 }
8591
8592 // C++ [temp.expl.spec]p2:
8593 // An explicit specialization may be declared in any scope in which
8594 // the corresponding primary template may be defined.
8595 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8596 S.Diag(Loc, DiagID: diag::err_template_spec_decl_function_scope)
8597 << Specialized;
8598 return true;
8599 }
8600
8601 // C++ [temp.class.spec]p6:
8602 // A class template partial specialization may be declared in any
8603 // scope in which the primary template may be defined.
8604 DeclContext *SpecializedContext =
8605 Specialized->getDeclContext()->getRedeclContext();
8606 DeclContext *DC = S.CurContext->getRedeclContext();
8607
8608 // Make sure that this redeclaration (or definition) occurs in the same
8609 // scope or an enclosing namespace.
8610 if (!(DC->isFileContext() ? DC->Encloses(DC: SpecializedContext)
8611 : DC->Equals(DC: SpecializedContext))) {
8612 if (isa<TranslationUnitDecl>(Val: SpecializedContext))
8613 S.Diag(Loc, DiagID: diag::err_template_spec_redecl_global_scope)
8614 << EntityKind << Specialized;
8615 else {
8616 auto *ND = cast<NamedDecl>(Val: SpecializedContext);
8617 int Diag = diag::err_template_spec_redecl_out_of_scope;
8618 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8619 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8620 S.Diag(Loc, DiagID: Diag) << EntityKind << Specialized
8621 << ND << isa<CXXRecordDecl>(Val: ND);
8622 }
8623
8624 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8625
8626 // Don't allow specializing in the wrong class during error recovery.
8627 // Otherwise, things can go horribly wrong.
8628 if (DC->isRecord())
8629 return true;
8630 }
8631
8632 return false;
8633}
8634
8635static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8636 if (!E->isTypeDependent())
8637 return SourceLocation();
8638 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8639 Checker.TraverseStmt(S: E);
8640 if (Checker.MatchLoc.isInvalid())
8641 return E->getSourceRange();
8642 return Checker.MatchLoc;
8643}
8644
8645static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8646 if (!TL.getType()->isDependentType())
8647 return SourceLocation();
8648 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8649 Checker.TraverseTypeLoc(TL);
8650 if (Checker.MatchLoc.isInvalid())
8651 return TL.getSourceRange();
8652 return Checker.MatchLoc;
8653}
8654
8655/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8656/// that checks non-type template partial specialization arguments.
8657static bool CheckNonTypeTemplatePartialSpecializationArgs(
8658 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8659 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8660 bool HasError = false;
8661 for (unsigned I = 0; I != NumArgs; ++I) {
8662 if (Args[I].getKind() == TemplateArgument::Pack) {
8663 if (CheckNonTypeTemplatePartialSpecializationArgs(
8664 S, TemplateNameLoc, Param, Args: Args[I].pack_begin(),
8665 NumArgs: Args[I].pack_size(), IsDefaultArgument))
8666 return true;
8667
8668 continue;
8669 }
8670
8671 if (Args[I].getKind() != TemplateArgument::Expression)
8672 continue;
8673
8674 Expr *ArgExpr = Args[I].getAsExpr();
8675 if (ArgExpr->containsErrors()) {
8676 HasError = true;
8677 continue;
8678 }
8679
8680 // We can have a pack expansion of any of the bullets below.
8681 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Val: ArgExpr))
8682 ArgExpr = Expansion->getPattern();
8683
8684 // Strip off any implicit casts we added as part of type checking.
8685 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
8686 ArgExpr = ICE->getSubExpr();
8687
8688 // C++ [temp.class.spec]p8:
8689 // A non-type argument is non-specialized if it is the name of a
8690 // non-type parameter. All other non-type arguments are
8691 // specialized.
8692 //
8693 // Below, we check the two conditions that only apply to
8694 // specialized non-type arguments, so skip any non-specialized
8695 // arguments.
8696 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ArgExpr))
8697 if (isa<NonTypeTemplateParmDecl>(Val: DRE->getDecl()))
8698 continue;
8699
8700 if (isa<DependentTemplateIdExpr>(Val: ArgExpr))
8701 continue;
8702
8703 // C++ [temp.class.spec]p9:
8704 // Within the argument list of a class template partial
8705 // specialization, the following restrictions apply:
8706 // -- A partially specialized non-type argument expression
8707 // shall not involve a template parameter of the partial
8708 // specialization except when the argument expression is a
8709 // simple identifier.
8710 // -- The type of a template parameter corresponding to a
8711 // specialized non-type argument shall not be dependent on a
8712 // parameter of the specialization.
8713 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8714 // We implement a compromise between the original rules and DR1315:
8715 // -- A specialized non-type template argument shall not be
8716 // type-dependent and the corresponding template parameter
8717 // shall have a non-dependent type.
8718 SourceRange ParamUseRange =
8719 findTemplateParameterInType(Depth: Param->getDepth(), E: ArgExpr);
8720 if (ParamUseRange.isValid()) {
8721 if (IsDefaultArgument) {
8722 S.Diag(Loc: TemplateNameLoc,
8723 DiagID: diag::err_dependent_non_type_arg_in_partial_spec);
8724 S.Diag(Loc: ParamUseRange.getBegin(),
8725 DiagID: diag::note_dependent_non_type_default_arg_in_partial_spec)
8726 << ParamUseRange;
8727 } else {
8728 S.Diag(Loc: ParamUseRange.getBegin(),
8729 DiagID: diag::err_dependent_non_type_arg_in_partial_spec)
8730 << ParamUseRange;
8731 }
8732 return true;
8733 }
8734
8735 ParamUseRange = findTemplateParameter(
8736 Depth: Param->getDepth(), TL: Param->getTypeSourceInfo()->getTypeLoc());
8737 if (ParamUseRange.isValid()) {
8738 S.Diag(Loc: IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8739 DiagID: diag::err_dependent_typed_non_type_arg_in_partial_spec)
8740 << Param->getType();
8741 S.NoteTemplateParameterLocation(Decl: *Param);
8742 return true;
8743 }
8744 }
8745
8746 return HasError;
8747}
8748
8749bool Sema::CheckTemplatePartialSpecializationArgs(
8750 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8751 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8752 // We have to be conservative when checking a template in a dependent
8753 // context.
8754 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8755 return false;
8756
8757 TemplateParameterList *TemplateParams =
8758 PrimaryTemplate->getTemplateParameters();
8759 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8760 NonTypeTemplateParmDecl *Param
8761 = dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: I));
8762 if (!Param)
8763 continue;
8764
8765 if (CheckNonTypeTemplatePartialSpecializationArgs(S&: *this, TemplateNameLoc,
8766 Param, Args: &TemplateArgs[I],
8767 NumArgs: 1, IsDefaultArgument: I >= NumExplicit))
8768 return true;
8769 }
8770
8771 return false;
8772}
8773
8774DeclResult Sema::ActOnClassTemplateSpecialization(
8775 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8776 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8777 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8778 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8779 assert(TUK != TagUseKind::Reference && "References are not specializations");
8780
8781 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8782 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8783 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8784
8785 // Find the class template we're specializing
8786 TemplateName Name = TemplateId.Template.get();
8787 ClassTemplateDecl *ClassTemplate
8788 = dyn_cast_or_null<ClassTemplateDecl>(Val: Name.getAsTemplateDecl());
8789
8790 if (!ClassTemplate) {
8791 Diag(Loc: TemplateNameLoc, DiagID: diag::err_not_class_template_specialization)
8792 << (Name.getAsTemplateDecl() &&
8793 isa<TemplateTemplateParmDecl>(Val: Name.getAsTemplateDecl()));
8794 return true;
8795 }
8796
8797 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8798 auto Message = DSA->getMessage();
8799 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
8800 << ClassTemplate << !Message.empty() << Message;
8801 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
8802 }
8803
8804 if (S->isTemplateParamScope())
8805 EnterTemplatedContext(S, DC: ClassTemplate->getTemplatedDecl());
8806
8807 DeclContext *DC = ClassTemplate->getDeclContext();
8808
8809 bool isMemberSpecialization = false;
8810 bool isPartialSpecialization = false;
8811
8812 if (SS.isSet()) {
8813 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8814 diagnoseQualifiedDeclaration(SS, DC, Name: ClassTemplate->getDeclName(),
8815 Loc: TemplateNameLoc, TemplateId: &TemplateId,
8816 /*IsMemberSpecialization=*/false))
8817 return true;
8818 }
8819
8820 // Check the validity of the template headers that introduce this
8821 // template.
8822 // FIXME: We probably shouldn't complain about these headers for
8823 // friend declarations.
8824 bool Invalid = false;
8825 TemplateParameterList *TemplateParams =
8826 MatchTemplateParametersToScopeSpecifier(
8827 DeclStartLoc: KWLoc, DeclLoc: TemplateNameLoc, SS, TemplateId: &TemplateId, ParamLists: TemplateParameterLists,
8828 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
8829 if (Invalid)
8830 return true;
8831
8832 // Check that we can declare a template specialization here.
8833 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8834 return true;
8835
8836 if (TemplateParams && DC->isDependentContext()) {
8837 ContextRAII SavedContext(*this, DC);
8838 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
8839 return true;
8840 }
8841
8842 if (TemplateParams && TemplateParams->size() > 0) {
8843 isPartialSpecialization = true;
8844
8845 if (TUK == TagUseKind::Friend) {
8846 Diag(Loc: KWLoc, DiagID: diag::err_partial_specialization_friend)
8847 << SourceRange(LAngleLoc, RAngleLoc);
8848 return true;
8849 }
8850
8851 // C++ [temp.class.spec]p10:
8852 // The template parameter list of a specialization shall not
8853 // contain default template argument values.
8854 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8855 Decl *Param = TemplateParams->getParam(Idx: I);
8856 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
8857 if (TTP->hasDefaultArgument()) {
8858 Diag(Loc: TTP->getDefaultArgumentLoc(),
8859 DiagID: diag::err_default_arg_in_partial_spec);
8860 TTP->removeDefaultArgument();
8861 }
8862 } else if (NonTypeTemplateParmDecl *NTTP
8863 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
8864 if (NTTP->hasDefaultArgument()) {
8865 Diag(Loc: NTTP->getDefaultArgumentLoc(),
8866 DiagID: diag::err_default_arg_in_partial_spec)
8867 << NTTP->getDefaultArgument().getSourceRange();
8868 NTTP->removeDefaultArgument();
8869 }
8870 } else {
8871 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
8872 if (TTP->hasDefaultArgument()) {
8873 Diag(Loc: TTP->getDefaultArgument().getLocation(),
8874 DiagID: diag::err_default_arg_in_partial_spec)
8875 << TTP->getDefaultArgument().getSourceRange();
8876 TTP->removeDefaultArgument();
8877 }
8878 }
8879 }
8880 } else if (TemplateParams) {
8881 if (TUK == TagUseKind::Friend)
8882 Diag(Loc: KWLoc, DiagID: diag::err_template_spec_friend)
8883 << FixItHint::CreateRemoval(
8884 RemoveRange: SourceRange(TemplateParams->getTemplateLoc(),
8885 TemplateParams->getRAngleLoc()))
8886 << SourceRange(LAngleLoc, RAngleLoc);
8887 } else {
8888 assert(TUK == TagUseKind::Friend &&
8889 "should have a 'template<>' for this decl");
8890 }
8891
8892 // Check that the specialization uses the same tag kind as the
8893 // original template.
8894 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
8895 assert(Kind != TagTypeKind::Enum &&
8896 "Invalid enum tag in class template spec!");
8897 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(), NewTag: Kind,
8898 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
8899 Name: ClassTemplate->getIdentifier())) {
8900 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
8901 << ClassTemplate
8902 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
8903 Code: ClassTemplate->getTemplatedDecl()->getKindName());
8904 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
8905 DiagID: diag::note_previous_use);
8906 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8907 }
8908
8909 // Translate the parser's template argument list in our AST format.
8910 TemplateArgumentListInfo TemplateArgs =
8911 makeTemplateArgumentListInfo(S&: *this, TemplateId);
8912
8913 // Check for unexpanded parameter packs in any of the template arguments.
8914 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8915 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
8916 UPPC: isPartialSpecialization
8917 ? UPPC_PartialSpecialization
8918 : UPPC_ExplicitSpecialization))
8919 return true;
8920
8921 // Check that the template argument list is well-formed for this
8922 // template.
8923 CheckTemplateArgumentInfo CTAI;
8924 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
8925 /*DefaultArgs=*/{},
8926 /*PartialTemplateArgs=*/false, CTAI,
8927 /*UpdateArgsWithConversions=*/true))
8928 return true;
8929
8930 // Find the class template (partial) specialization declaration that
8931 // corresponds to these arguments.
8932 if (isPartialSpecialization) {
8933 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, PrimaryTemplate: ClassTemplate,
8934 NumExplicit: TemplateArgs.size(),
8935 TemplateArgs: CTAI.CanonicalConverted))
8936 return true;
8937
8938 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8939 // also do it during instantiation.
8940 if (!Name.isDependent() &&
8941 !TemplateSpecializationType::anyDependentTemplateArguments(
8942 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
8943 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
8944 << ClassTemplate->getDeclName();
8945 isPartialSpecialization = false;
8946 Invalid = true;
8947 }
8948 }
8949
8950 llvm::FoldingSetInsertToken InsertToken;
8951 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8952
8953 if (isPartialSpecialization)
8954 PrevDecl = ClassTemplate->findPartialSpecialization(
8955 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertToken);
8956 else
8957 PrevDecl =
8958 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertToken);
8959
8960 ClassTemplateSpecializationDecl *Specialization = nullptr;
8961
8962 // Check whether we can declare a class template specialization in
8963 // the current scope.
8964 if (TUK != TagUseKind::Friend &&
8965 CheckTemplateSpecializationScope(S&: *this, Specialized: ClassTemplate, PrevDecl,
8966 Loc: TemplateNameLoc,
8967 IsPartialSpecialization: isPartialSpecialization))
8968 return true;
8969
8970 if (!isPartialSpecialization) {
8971 // Create a new class template specialization declaration node for
8972 // this explicit specialization or friend declaration.
8973 Specialization = ClassTemplateSpecializationDecl::Create(
8974 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
8975 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
8976 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8977 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
8978 if (TemplateParameterLists.size() > 0) {
8979 Specialization->setTemplateParameterListsInfo(Context,
8980 TPLists: TemplateParameterLists);
8981 }
8982
8983 if (!PrevDecl)
8984 ClassTemplate->AddSpecialization(D: Specialization, InsertToken);
8985 } else {
8986 CanQualType CanonType = CanQualType::CreateUnsafe(
8987 Other: Context.getCanonicalTemplateSpecializationType(
8988 Keyword: ElaboratedTypeKeyword::None,
8989 T: TemplateName(ClassTemplate->getCanonicalDecl()),
8990 CanonicalArgs: CTAI.CanonicalConverted));
8991 if (Context.hasSameType(
8992 T1: CanonType,
8993 T2: ClassTemplate->getCanonicalInjectedSpecializationType(Ctx: Context)) &&
8994 (!Context.getLangOpts().CPlusPlus20 ||
8995 !TemplateParams->hasAssociatedConstraints())) {
8996 // C++ [temp.class.spec]p9b3:
8997 //
8998 // -- The argument list of the specialization shall not be identical
8999 // to the implicit argument list of the primary template.
9000 //
9001 // This rule has since been removed, because it's redundant given DR1495,
9002 // but we keep it because it produces better diagnostics and recovery.
9003 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
9004 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
9005 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
9006 return CheckClassTemplate(
9007 S, TagSpec, TUK, KWLoc, SS, Name: ClassTemplate->getIdentifier(),
9008 NameLoc: TemplateNameLoc, Attr, TemplateParams, AS: AS_none,
9009 /*ModulePrivateLoc=*/SourceLocation(),
9010 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
9011 OuterTemplateParamLists: TemplateParameterLists.data(), IsMemberSpecialization: isMemberSpecialization);
9012 }
9013
9014 // Create a new class template partial specialization declaration node.
9015 ClassTemplatePartialSpecializationDecl *PrevPartial =
9016 cast_or_null<ClassTemplatePartialSpecializationDecl>(Val: PrevDecl);
9017 ClassTemplatePartialSpecializationDecl *Partial =
9018 ClassTemplatePartialSpecializationDecl::Create(
9019 Context, TK: Kind, DC, StartLoc: KWLoc, IdLoc: TemplateNameLoc, Params: TemplateParams,
9020 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, CanonInjectedTST: CanonType, PrevDecl: PrevPartial);
9021 Partial->setTemplateArgsAsWritten(TemplateArgs);
9022 SetNestedNameSpecifier(S&: *this, T: Partial, SS);
9023 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9024 Partial->setTemplateParameterListsInfo(
9025 Context, TPLists: TemplateParameterLists.drop_back(N: 1));
9026 }
9027
9028 if (!PrevPartial)
9029 ClassTemplate->AddPartialSpecialization(D: Partial, InsertToken);
9030 Specialization = Partial;
9031
9032 // If we are providing an explicit specialization of a member class
9033 // template specialization, make a note of that.
9034 if (isMemberSpecialization)
9035 Partial->setMemberSpecialization();
9036
9037 CheckTemplatePartialSpecialization(Partial);
9038 }
9039
9040 // C++ [temp.expl.spec]p6:
9041 // If a template, a member template or the member of a class template is
9042 // explicitly specialized then that specialization shall be declared
9043 // before the first use of that specialization that would cause an implicit
9044 // instantiation to take place, in every translation unit in which such a
9045 // use occurs; no diagnostic is required.
9046 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9047 bool Okay = false;
9048 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9049 // Is there any previous explicit specialization declaration?
9050 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9051 Okay = true;
9052 break;
9053 }
9054 }
9055
9056 if (!Okay) {
9057 SourceRange Range(TemplateNameLoc, RAngleLoc);
9058 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
9059 << Context.getCanonicalTagType(TD: Specialization) << Range;
9060
9061 Diag(Loc: PrevDecl->getPointOfInstantiation(),
9062 DiagID: diag::note_instantiation_required_here)
9063 << (PrevDecl->getTemplateSpecializationKind()
9064 != TSK_ImplicitInstantiation);
9065 return true;
9066 }
9067 }
9068
9069 // If this is not a friend, note that this is an explicit specialization.
9070 if (TUK != TagUseKind::Friend)
9071 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9072
9073 // Check that this isn't a redefinition of this specialization.
9074 if (TUK == TagUseKind::Definition) {
9075 RecordDecl *Def = Specialization->getDefinition();
9076 NamedDecl *Hidden = nullptr;
9077 bool HiddenDefVisible = false;
9078 if (Def && SkipBody &&
9079 isRedefinitionAllowedFor(D: Def, NewDefinitionLoc: TemplateNameLoc, Suggested: &Hidden,
9080 Visible&: HiddenDefVisible)) {
9081 SkipBody->ShouldSkip = true;
9082 SkipBody->Previous = Def;
9083 if (!HiddenDefVisible && Hidden)
9084 makeMergedDefinitionVisible(ND: Hidden);
9085 } else if (Def) {
9086 SourceRange Range(TemplateNameLoc, RAngleLoc);
9087 Diag(Loc: TemplateNameLoc, DiagID: diag::err_redefinition) << Specialization << Range;
9088 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
9089 Specialization->setInvalidDecl();
9090 return true;
9091 }
9092 }
9093
9094 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
9095 ProcessAPINotes(D: Specialization);
9096
9097 // Add alignment attributes if necessary; these attributes are checked when
9098 // the ASTContext lays out the structure.
9099 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9100 if (LangOpts.HLSL)
9101 Specialization->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
9102 AddAlignmentAttributesForRecord(RD: Specialization);
9103 AddMsStructLayoutForRecord(RD: Specialization);
9104 }
9105
9106 if (ModulePrivateLoc.isValid())
9107 Diag(Loc: Specialization->getLocation(), DiagID: diag::err_module_private_specialization)
9108 << (isPartialSpecialization? 1 : 0)
9109 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
9110
9111 // C++ [temp.expl.spec]p9:
9112 // A template explicit specialization is in the scope of the
9113 // namespace in which the template was defined.
9114 //
9115 // We actually implement this paragraph where we set the semantic
9116 // context (in the creation of the ClassTemplateSpecializationDecl),
9117 // but we also maintain the lexical context where the actual
9118 // definition occurs.
9119 Specialization->setLexicalDeclContext(CurContext);
9120
9121 // We may be starting the definition of this specialization.
9122 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9123 Specialization->startDefinition();
9124
9125 if (TUK == TagUseKind::Friend) {
9126 CanQualType CanonType = Context.getCanonicalTagType(TD: Specialization);
9127 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9128 Keyword: ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9129 QualifierLoc: SS.getWithLocInContext(Context),
9130 /*TemplateKeywordLoc=*/SourceLocation(), T: Name, TLoc: TemplateNameLoc,
9131 SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted, Canon: CanonType);
9132
9133 // Build the fully-sugared type for this class template
9134 // specialization as the user wrote in the specialization
9135 // itself. This means that we'll pretty-print the type retrieved
9136 // from the specialization's declaration the way that the user
9137 // actually wrote the specialization, rather than formatting the
9138 // name based on the "canonical" representation used to store the
9139 // template arguments in the specialization.
9140 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext,
9141 L: TemplateNameLoc,
9142 Friend: WrittenTy,
9143 /*FIXME:*/FriendL: KWLoc);
9144 Friend->setAccess(AS_public);
9145 CurContext->addDecl(D: Friend);
9146 } else {
9147 // Add the specialization into its lexical context, so that it can
9148 // be seen when iterating through the list of declarations in that
9149 // context. However, specializations are not found by name lookup.
9150 CurContext->addDecl(D: Specialization);
9151 }
9152
9153 if (SkipBody && SkipBody->ShouldSkip)
9154 return SkipBody->Previous;
9155
9156 Specialization->setInvalidDecl(Invalid);
9157 inferGslOwnerPointerAttribute(Record: Specialization);
9158 return Specialization;
9159}
9160
9161Decl *Sema::ActOnTemplateDeclarator(Scope *S,
9162 MultiTemplateParamsArg TemplateParameterLists,
9163 Declarator &D) {
9164 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9165 ActOnDocumentableDecl(D: NewDecl);
9166 return NewDecl;
9167}
9168
9169ConceptDecl *Sema::ActOnStartConceptDefinition(
9170 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9171 const IdentifierInfo *Name, SourceLocation NameLoc) {
9172 DeclContext *DC = CurContext;
9173
9174 if (!DC->getRedeclContext()->isFileContext()) {
9175 Diag(Loc: NameLoc,
9176 DiagID: diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9177 return nullptr;
9178 }
9179
9180 if (TemplateParameterLists.size() > 1) {
9181 Diag(Loc: NameLoc, DiagID: diag::err_concept_extra_headers);
9182 return nullptr;
9183 }
9184
9185 TemplateParameterList *Params = TemplateParameterLists.front();
9186
9187 if (Params->size() == 0) {
9188 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_parameters);
9189 return nullptr;
9190 }
9191
9192 // Ensure that the parameter pack, if present, is the last parameter in the
9193 // template.
9194 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9195 ParamEnd = Params->end();
9196 ParamIt != ParamEnd; ++ParamIt) {
9197 Decl const *Param = *ParamIt;
9198 if (Param->isParameterPack()) {
9199 if (++ParamIt == ParamEnd)
9200 break;
9201 Diag(Loc: Param->getLocation(),
9202 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
9203 return nullptr;
9204 }
9205 }
9206
9207 ConceptDecl *NewDecl =
9208 ConceptDecl::Create(C&: Context, DC, L: NameLoc, Name, Params);
9209
9210 if (NewDecl->hasAssociatedConstraints()) {
9211 // C++2a [temp.concept]p4:
9212 // A concept shall not have associated constraints.
9213 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_associated_constraints);
9214 NewDecl->setInvalidDecl();
9215 }
9216
9217 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9218 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9219 forRedeclarationInCurContext());
9220 LookupName(R&: Previous, S);
9221 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9222 /*AllowInlineNamespace*/ false);
9223
9224 // We cannot properly handle redeclarations until we parse the constraint
9225 // expression, so only inject the name if we are sure we are not redeclaring a
9226 // symbol
9227 if (Previous.empty())
9228 PushOnScopeChains(D: NewDecl, S, AddToContext: true);
9229
9230 return NewDecl;
9231}
9232
9233static bool RemoveLookupResult(LookupResult &R, NamedDecl *C) {
9234 bool Found = false;
9235 LookupResult::Filter F = R.makeFilter();
9236 while (F.hasNext()) {
9237 NamedDecl *D = F.next();
9238 if (D == C) {
9239 F.erase();
9240 Found = true;
9241 break;
9242 }
9243 }
9244 F.done();
9245 return Found;
9246}
9247
9248ConceptDecl *
9249Sema::ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
9250 Expr *ConstraintExpr,
9251 const ParsedAttributesView &Attrs) {
9252 assert(!C->hasDefinition() && "Concept already defined");
9253 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr)) {
9254 C->setInvalidDecl();
9255 return nullptr;
9256 }
9257 C->setDefinition(ConstraintExpr);
9258 ProcessDeclAttributeList(S, D: C, AttrList: Attrs);
9259
9260 // Check for conflicting previous declaration.
9261 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9262 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9263 forRedeclarationInCurContext());
9264 LookupName(R&: Previous, S);
9265 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9266 /*AllowInlineNamespace*/ false);
9267 bool WasAlreadyAdded = RemoveLookupResult(R&: Previous, C);
9268 bool AddToScope = true;
9269 CheckConceptRedefinition(NewDecl: C, Previous, AddToScope);
9270
9271 ActOnDocumentableDecl(D: C);
9272 if (!WasAlreadyAdded && AddToScope)
9273 PushOnScopeChains(D: C, S);
9274
9275 return C;
9276}
9277
9278void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
9279 LookupResult &Previous, bool &AddToScope) {
9280 AddToScope = true;
9281
9282 if (Previous.empty())
9283 return;
9284
9285 auto *OldConcept = dyn_cast<ConceptDecl>(Val: Previous.getRepresentativeDecl()->getUnderlyingDecl());
9286 if (!OldConcept) {
9287 auto *Old = Previous.getRepresentativeDecl();
9288 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_kind)
9289 << NewDecl->getDeclName();
9290 notePreviousDefinition(Old, New: NewDecl->getLocation());
9291 AddToScope = false;
9292 return;
9293 }
9294 // Check if we can merge with a concept declaration.
9295 bool IsSame = Context.isSameEntity(X: NewDecl, Y: OldConcept);
9296 if (!IsSame) {
9297 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_concept)
9298 << NewDecl->getDeclName();
9299 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9300 AddToScope = false;
9301 return;
9302 }
9303 if (hasReachableDefinition(D: OldConcept) &&
9304 IsRedefinitionInModule(New: NewDecl, Old: OldConcept)) {
9305 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition)
9306 << NewDecl->getDeclName();
9307 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9308 AddToScope = false;
9309 return;
9310 }
9311 if (!Previous.isSingleResult()) {
9312 // FIXME: we should produce an error in case of ambig and failed lookups.
9313 // Other decls (e.g. namespaces) also have this shortcoming.
9314 return;
9315 }
9316 // We unwrap canonical decl late to check for module visibility.
9317 Context.setPrimaryMergedDecl(D: NewDecl, Primary: OldConcept->getCanonicalDecl());
9318}
9319
9320bool Sema::CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc) {
9321 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Val: Concept);
9322 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9323 Diag(Loc, DiagID: diag::err_recursive_concept) << CE;
9324 Diag(Loc: CE->getLocation(), DiagID: diag::note_declared_at);
9325 CE->setInvalidDecl();
9326 return true;
9327 }
9328 // Concept template parameters don't have a definition and can't
9329 // be defined recursively.
9330 return false;
9331}
9332
9333/// \brief Strips various properties off an implicit instantiation
9334/// that has just been explicitly specialized.
9335static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9336 if (MinGW || (isa<FunctionDecl>(Val: D) &&
9337 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization()))
9338 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9339
9340 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D))
9341 FD->setInlineSpecified(false);
9342}
9343
9344/// Create an ExplicitInstantiationDecl to record source-location info for an
9345/// explicit template instantiation statement, and add it to \p CurContext.
9346///
9347/// For class templates / nested classes, the caller should build a
9348/// TypeSourceInfo that encodes the tag keyword, qualifier, name, and template
9349/// arguments, and pass empty QualifierLoc / null ArgsAsWritten.
9350///
9351/// For function / variable templates, the caller should pass TypeAsWritten for
9352/// the declared type, and separate QualifierLoc / ArgsAsWritten.
9353static void addExplicitInstantiationDecl(
9354 ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec,
9355 SourceLocation ExternLoc, SourceLocation TemplateLoc,
9356 NestedNameSpecifierLoc QualifierLoc,
9357 const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc,
9358 TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK) {
9359 auto *EID = ExplicitInstantiationDecl::Create(
9360 C&: Context, DC: CurContext, Specialization: Spec, ExternLoc, TemplateLoc, QualifierLoc,
9361 ArgsAsWritten, NameLoc, TypeAsWritten, TSK);
9362 Context.addExplicitInstantiationDecl(Spec, EID);
9363 CurContext->addDecl(D: EID);
9364}
9365
9366/// Compute the diagnostic location for an explicit instantiation
9367// declaration or definition.
9368static SourceLocation
9369DiagLocForExplicitInstantiation(NamedDecl *D,
9370 SourceLocation PointOfInstantiation) {
9371 for (auto *EID : D->getASTContext().getExplicitInstantiationDecls(Spec: D))
9372 if (EID->getTemplateSpecializationKind() ==
9373 TSK_ExplicitInstantiationDefinition)
9374 return EID->getTemplateLoc();
9375
9376 // Explicit instantiations following a specialization have no effect and
9377 // hence no PointOfInstantiation. In that case, walk decl backwards
9378 // until a valid name loc is found.
9379 SourceLocation PrevDiagLoc = PointOfInstantiation;
9380 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9381 Prev = Prev->getPreviousDecl()) {
9382 PrevDiagLoc = Prev->getLocation();
9383 }
9384 assert(PrevDiagLoc.isValid() &&
9385 "Explicit instantiation without point of instantiation?");
9386 return PrevDiagLoc;
9387}
9388
9389bool
9390Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
9391 TemplateSpecializationKind NewTSK,
9392 NamedDecl *PrevDecl,
9393 TemplateSpecializationKind PrevTSK,
9394 SourceLocation PrevPointOfInstantiation,
9395 bool &HasNoEffect) {
9396 HasNoEffect = false;
9397
9398 switch (NewTSK) {
9399 case TSK_Undeclared:
9400 case TSK_ImplicitInstantiation:
9401 assert(
9402 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9403 "previous declaration must be implicit!");
9404 return false;
9405
9406 case TSK_ExplicitSpecialization:
9407 switch (PrevTSK) {
9408 case TSK_Undeclared:
9409 case TSK_ExplicitSpecialization:
9410 // Okay, we're just specializing something that is either already
9411 // explicitly specialized or has merely been mentioned without any
9412 // instantiation.
9413 return false;
9414
9415 case TSK_ImplicitInstantiation:
9416 if (PrevPointOfInstantiation.isInvalid()) {
9417 // The declaration itself has not actually been instantiated, so it is
9418 // still okay to specialize it.
9419 StripImplicitInstantiation(
9420 D: PrevDecl, MinGW: Context.getTargetInfo().getTriple().isOSCygMing());
9421 return false;
9422 }
9423 // Fall through
9424 [[fallthrough]];
9425
9426 case TSK_ExplicitInstantiationDeclaration:
9427 case TSK_ExplicitInstantiationDefinition:
9428 assert((PrevTSK == TSK_ImplicitInstantiation ||
9429 PrevPointOfInstantiation.isValid()) &&
9430 "Explicit instantiation without point of instantiation?");
9431
9432 // C++ [temp.expl.spec]p6:
9433 // If a template, a member template or the member of a class template
9434 // is explicitly specialized then that specialization shall be declared
9435 // before the first use of that specialization that would cause an
9436 // implicit instantiation to take place, in every translation unit in
9437 // which such a use occurs; no diagnostic is required.
9438 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9439 // Is there any previous explicit specialization declaration?
9440 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization)
9441 return false;
9442 }
9443
9444 Diag(Loc: NewLoc, DiagID: diag::err_specialization_after_instantiation)
9445 << PrevDecl;
9446 Diag(Loc: PrevPointOfInstantiation, DiagID: diag::note_instantiation_required_here)
9447 << (PrevTSK != TSK_ImplicitInstantiation);
9448
9449 return true;
9450 }
9451 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9452
9453 case TSK_ExplicitInstantiationDeclaration:
9454 switch (PrevTSK) {
9455 case TSK_ExplicitInstantiationDeclaration:
9456 // This explicit instantiation declaration is redundant (that's okay).
9457 HasNoEffect = true;
9458 return false;
9459
9460 case TSK_Undeclared:
9461 case TSK_ImplicitInstantiation:
9462 // We're explicitly instantiating something that may have already been
9463 // implicitly instantiated; that's fine.
9464 return false;
9465
9466 case TSK_ExplicitSpecialization:
9467 // C++0x [temp.explicit]p4:
9468 // For a given set of template parameters, if an explicit instantiation
9469 // of a template appears after a declaration of an explicit
9470 // specialization for that template, the explicit instantiation has no
9471 // effect.
9472 HasNoEffect = true;
9473 return false;
9474
9475 case TSK_ExplicitInstantiationDefinition:
9476 // C++0x [temp.explicit]p10:
9477 // If an entity is the subject of both an explicit instantiation
9478 // declaration and an explicit instantiation definition in the same
9479 // translation unit, the definition shall follow the declaration.
9480 Diag(Loc: NewLoc,
9481 DiagID: diag::err_explicit_instantiation_declaration_after_definition);
9482
9483 // Explicit instantiations following a specialization have no effect and
9484 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9485 // until a valid name loc is found.
9486 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9487 DiagID: diag::note_explicit_instantiation_definition_here);
9488 HasNoEffect = true;
9489 return false;
9490 }
9491 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9492
9493 case TSK_ExplicitInstantiationDefinition:
9494 switch (PrevTSK) {
9495 case TSK_Undeclared:
9496 case TSK_ImplicitInstantiation:
9497 // We're explicitly instantiating something that may have already been
9498 // implicitly instantiated; that's fine.
9499 return false;
9500
9501 case TSK_ExplicitSpecialization:
9502 // C++ DR 259, C++0x [temp.explicit]p4:
9503 // For a given set of template parameters, if an explicit
9504 // instantiation of a template appears after a declaration of
9505 // an explicit specialization for that template, the explicit
9506 // instantiation has no effect.
9507 Diag(Loc: NewLoc, DiagID: diag::warn_explicit_instantiation_after_specialization)
9508 << PrevDecl;
9509 Diag(Loc: PrevDecl->getLocation(),
9510 DiagID: diag::note_previous_template_specialization);
9511 HasNoEffect = true;
9512 return false;
9513
9514 case TSK_ExplicitInstantiationDeclaration:
9515 // We're explicitly instantiating a definition for something for which we
9516 // were previously asked to suppress instantiations. That's fine.
9517
9518 // C++0x [temp.explicit]p4:
9519 // For a given set of template parameters, if an explicit instantiation
9520 // of a template appears after a declaration of an explicit
9521 // specialization for that template, the explicit instantiation has no
9522 // effect.
9523 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9524 // Is there any previous explicit specialization declaration?
9525 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9526 HasNoEffect = true;
9527 break;
9528 }
9529 }
9530
9531 return false;
9532
9533 case TSK_ExplicitInstantiationDefinition:
9534 // C++0x [temp.spec]p5:
9535 // For a given template and a given set of template-arguments,
9536 // - an explicit instantiation definition shall appear at most once
9537 // in a program,
9538
9539 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9540 Diag(Loc: NewLoc, DiagID: (getLangOpts().MSVCCompat)
9541 ? diag::ext_explicit_instantiation_duplicate
9542 : diag::err_explicit_instantiation_duplicate)
9543 << PrevDecl;
9544 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9545 DiagID: diag::note_previous_explicit_instantiation);
9546 HasNoEffect = true;
9547 return false;
9548 }
9549 }
9550
9551 llvm_unreachable("Missing specialization/instantiation case?");
9552}
9553
9554bool Sema::CheckDependentFunctionTemplateSpecialization(
9555 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9556 LookupResult &Previous) {
9557 // Remove anything from Previous that isn't a function template in
9558 // the correct context.
9559 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9560 LookupResult::Filter F = Previous.makeFilter();
9561 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9562 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9563 while (F.hasNext()) {
9564 NamedDecl *D = F.next()->getUnderlyingDecl();
9565 if (!isa<FunctionTemplateDecl>(Val: D)) {
9566 F.erase();
9567 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAFunctionTemplate, y&: D));
9568 continue;
9569 }
9570
9571 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9572 NS: D->getDeclContext()->getRedeclContext())) {
9573 F.erase();
9574 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAMemberOfEnclosing, y&: D));
9575 continue;
9576 }
9577 }
9578 F.done();
9579
9580 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9581 if (Previous.empty()) {
9582 NestedNameSpecifier FriendQualifier = FD->getQualifier();
9583 if (IsFriend && FriendQualifier.isDependent() &&
9584 FriendQualifier.getKind() == NestedNameSpecifier::Kind::Type &&
9585 FriendQualifier.getAsType()->getAs<TemplateSpecializationType>()) {
9586 FD->setDependentTemplateSpecialization(
9587 Context, Templates: Previous.asUnresolvedSet(), TemplateArgs: ExplicitTemplateArgs);
9588 return false;
9589 }
9590
9591 Diag(Loc: FD->getLocation(), DiagID: diag::err_dependent_function_template_spec_no_match)
9592 << IsFriend;
9593 for (auto &P : DiscardedCandidates)
9594 Diag(Loc: P.second->getLocation(),
9595 DiagID: diag::note_dependent_function_template_spec_discard_reason)
9596 << P.first << IsFriend;
9597 return true;
9598 }
9599
9600 FD->setDependentTemplateSpecialization(Context, Templates: Previous.asUnresolvedSet(),
9601 TemplateArgs: ExplicitTemplateArgs);
9602 return false;
9603}
9604
9605bool Sema::CheckFunctionTemplateSpecialization(
9606 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9607 LookupResult &Previous, bool QualifiedFriend) {
9608 // The set of function template specializations that could match this
9609 // explicit function template specialization.
9610 UnresolvedSet<8> Candidates;
9611 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9612 /*ForTakingAddress=*/false);
9613
9614 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9615 ConvertedTemplateArgs;
9616
9617 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9618 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9619 I != E; ++I) {
9620 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9621 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Ovl)) {
9622 // Only consider templates found within the same semantic lookup scope as
9623 // FD.
9624 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9625 NS: Ovl->getDeclContext()->getRedeclContext()))
9626 continue;
9627
9628 QualType FT = FD->getType();
9629 // C++11 [dcl.constexpr]p8:
9630 // A constexpr specifier for a non-static member function that is not
9631 // a constructor declares that member function to be const.
9632 //
9633 // When matching a constexpr member function template specialization
9634 // against the primary template, we don't yet know whether the
9635 // specialization has an implicit 'const' (because we don't know whether
9636 // it will be a static member function until we know which template it
9637 // specializes). This rule was removed in C++14.
9638 if (auto *NewMD = dyn_cast<CXXMethodDecl>(Val: FD);
9639 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9640 !isa<CXXConstructorDecl, CXXDestructorDecl>(Val: NewMD)) {
9641 auto *OldMD = dyn_cast<CXXMethodDecl>(Val: FunTmpl->getTemplatedDecl());
9642 if (OldMD && OldMD->isConst()) {
9643 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9644 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9645 EPI.TypeQuals.addConst();
9646 FT = Context.getFunctionType(ResultTy: FPT->getReturnType(),
9647 Args: FPT->getParamTypes(), EPI);
9648 }
9649 }
9650
9651 TemplateArgumentListInfo Args;
9652 if (ExplicitTemplateArgs)
9653 Args = *ExplicitTemplateArgs;
9654
9655 // C++ [temp.expl.spec]p11:
9656 // A trailing template-argument can be left unspecified in the
9657 // template-id naming an explicit function template specialization
9658 // provided it can be deduced from the function argument type.
9659 // Perform template argument deduction to determine whether we may be
9660 // specializing this template.
9661 // FIXME: It is somewhat wasteful to build
9662 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9663 FunctionDecl *Specialization = nullptr;
9664 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9665 FunctionTemplate: cast<FunctionTemplateDecl>(Val: FunTmpl->getFirstDecl()),
9666 ExplicitTemplateArgs: ExplicitTemplateArgs ? &Args : nullptr, ArgFunctionType: FT, Specialization, Info);
9667 TDK != TemplateDeductionResult::Success) {
9668 // Template argument deduction failed; record why it failed, so
9669 // that we can provide nifty diagnostics.
9670 FailedCandidates.addCandidate().set(
9671 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9672 Info: MakeDeductionFailureInfo(Context, TDK, Info));
9673 (void)TDK;
9674 continue;
9675 }
9676
9677 // Target attributes are part of the cuda function signature, so
9678 // the deduced template's cuda target must match that of the
9679 // specialization. Given that C++ template deduction does not
9680 // take target attributes into account, we reject candidates
9681 // here that have a different target.
9682 if (LangOpts.CUDA &&
9683 CUDA().IdentifyTarget(D: Specialization,
9684 /* IgnoreImplicitHDAttr = */ true) !=
9685 CUDA().IdentifyTarget(D: FD, /* IgnoreImplicitHDAttr = */ true)) {
9686 FailedCandidates.addCandidate().set(
9687 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9688 Info: MakeDeductionFailureInfo(
9689 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
9690 continue;
9691 }
9692
9693 // Record this candidate.
9694 if (ExplicitTemplateArgs)
9695 ConvertedTemplateArgs[Specialization] = std::move(Args);
9696 Candidates.addDecl(D: Specialization, AS: I.getAccess());
9697 }
9698 }
9699
9700 // For a qualified friend declaration (with no explicit marker to indicate
9701 // that a template specialization was intended), note all (template and
9702 // non-template) candidates.
9703 if (QualifiedFriend && Candidates.empty()) {
9704 Diag(Loc: FD->getLocation(), DiagID: diag::err_qualified_friend_no_match)
9705 << FD->getDeclName() << FDLookupContext;
9706 // FIXME: We should form a single candidate list and diagnose all
9707 // candidates at once, to get proper sorting and limiting.
9708 for (auto *OldND : Previous) {
9709 if (auto *OldFD = dyn_cast<FunctionDecl>(Val: OldND->getUnderlyingDecl()))
9710 NoteOverloadCandidate(Found: OldND, Fn: OldFD, RewriteKind: CRK_None, DestType: FD->getType(), TakingAddress: false);
9711 }
9712 FailedCandidates.NoteCandidates(S&: *this, Loc: FD->getLocation());
9713 return true;
9714 }
9715
9716 // Find the most specialized function template.
9717 UnresolvedSetIterator Result = getMostSpecialized(
9718 SBegin: Candidates.begin(), SEnd: Candidates.end(), FailedCandidates, Loc: FD->getLocation(),
9719 NoneDiag: PDiag(DiagID: diag::err_function_template_spec_no_match) << FD->getDeclName(),
9720 AmbigDiag: PDiag(DiagID: diag::err_function_template_spec_ambiguous)
9721 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9722 CandidateDiag: PDiag(DiagID: diag::note_function_template_spec_matched));
9723
9724 if (Result == Candidates.end())
9725 return true;
9726
9727 // Ignore access information; it doesn't figure into redeclaration checking.
9728 FunctionDecl *Specialization = cast<FunctionDecl>(Val: *Result);
9729
9730 if (const auto *PT = Specialization->getPrimaryTemplate();
9731 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9732 auto Message = DSA->getMessage();
9733 Diag(Loc: FD->getLocation(), DiagID: diag::warn_invalid_specialization)
9734 << PT << !Message.empty() << Message;
9735 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
9736 }
9737
9738 // C++23 [except.spec]p13:
9739 // An exception specification is considered to be needed when:
9740 // - [...]
9741 // - the exception specification is compared to that of another declaration
9742 // (e.g., an explicit specialization or an overriding virtual function);
9743 // - [...]
9744 //
9745 // The exception specification of a defaulted function is evaluated as
9746 // described above only when needed; similarly, the noexcept-specifier of a
9747 // specialization of a function template or member function of a class
9748 // template is instantiated only when needed.
9749 //
9750 // The standard doesn't specify what the "comparison with another declaration"
9751 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9752 // not state which properties of an explicit specialization must match the
9753 // primary template.
9754 //
9755 // We assume that an explicit specialization must correspond with (per
9756 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9757 // the declaration produced by substitution into the function template.
9758 //
9759 // Since the determination whether two function declarations correspond does
9760 // not consider exception specification, we only need to instantiate it once
9761 // we determine the primary template when comparing types per
9762 // [basic.link]p11.1.
9763 auto *SpecializationFPT =
9764 Specialization->getType()->castAs<FunctionProtoType>();
9765 // If the function has a dependent exception specification, resolve it after
9766 // we have selected the primary template so we can check whether it matches.
9767 if (getLangOpts().CPlusPlus17 &&
9768 isUnresolvedExceptionSpec(ESpecType: SpecializationFPT->getExceptionSpecType()) &&
9769 !ResolveExceptionSpec(Loc: FD->getLocation(), FPT: SpecializationFPT))
9770 return true;
9771
9772 FunctionTemplateSpecializationInfo *SpecInfo
9773 = Specialization->getTemplateSpecializationInfo();
9774 assert(SpecInfo && "Function template specialization info missing?");
9775
9776 // Note: do not overwrite location info if previous template
9777 // specialization kind was explicit.
9778 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9779 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9780 Specialization->setLocation(FD->getLocation());
9781 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9782 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9783 // function can differ from the template declaration with respect to
9784 // the constexpr specifier.
9785 // FIXME: We need an update record for this AST mutation.
9786 // FIXME: What if there are multiple such prior declarations (for instance,
9787 // from different modules)?
9788 Specialization->setConstexprKind(FD->getConstexprKind());
9789 }
9790
9791 // FIXME: Check if the prior specialization has a point of instantiation.
9792 // If so, we have run afoul of .
9793
9794 // If this is a friend declaration, then we're not really declaring
9795 // an explicit specialization.
9796 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9797
9798 // Check the scope of this explicit specialization.
9799 if (!isFriend &&
9800 CheckTemplateSpecializationScope(S&: *this,
9801 Specialized: Specialization->getPrimaryTemplate(),
9802 PrevDecl: Specialization, Loc: FD->getLocation(),
9803 IsPartialSpecialization: false))
9804 return true;
9805
9806 // C++ [temp.expl.spec]p6:
9807 // If a template, a member template or the member of a class template is
9808 // explicitly specialized then that specialization shall be declared
9809 // before the first use of that specialization that would cause an implicit
9810 // instantiation to take place, in every translation unit in which such a
9811 // use occurs; no diagnostic is required.
9812 bool HasNoEffect = false;
9813 if (!isFriend &&
9814 CheckSpecializationInstantiationRedecl(NewLoc: FD->getLocation(),
9815 NewTSK: TSK_ExplicitSpecialization,
9816 PrevDecl: Specialization,
9817 PrevTSK: SpecInfo->getTemplateSpecializationKind(),
9818 PrevPointOfInstantiation: SpecInfo->getPointOfInstantiation(),
9819 HasNoEffect))
9820 return true;
9821
9822 // Mark the prior declaration as an explicit specialization, so that later
9823 // clients know that this is an explicit specialization.
9824 // A dependent friend specialization which has a definition should be treated
9825 // as explicit specialization, despite being invalid.
9826 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9827 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9828 // Since explicit specializations do not inherit '=delete' from their
9829 // primary function template - check if the 'specialization' that was
9830 // implicitly generated (during template argument deduction for partial
9831 // ordering) from the most specialized of all the function templates that
9832 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9833 // first check that it was implicitly generated during template argument
9834 // deduction by making sure it wasn't referenced, and then reset the deleted
9835 // flag to not-deleted, so that we can inherit that information from 'FD'.
9836 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9837 !Specialization->getCanonicalDecl()->isReferenced()) {
9838 // FIXME: This assert will not hold in the presence of modules.
9839 assert(
9840 Specialization->getCanonicalDecl() == Specialization &&
9841 "This must be the only existing declaration of this specialization");
9842 // FIXME: We need an update record for this AST mutation.
9843 Specialization->setDeletedAsWritten(D: false);
9844 }
9845 // FIXME: We need an update record for this AST mutation.
9846 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9847 MarkUnusedFileScopedDecl(D: Specialization);
9848 }
9849
9850 // Turn the given function declaration into a function template
9851 // specialization, with the template arguments from the previous
9852 // specialization.
9853 // Take copies of (semantic and syntactic) template argument lists.
9854 TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy(
9855 Context, Args: Specialization->getTemplateSpecializationArgs()->asArray());
9856 FD->setFunctionTemplateSpecialization(
9857 Template: Specialization->getPrimaryTemplate(), TemplateArgs: TemplArgs, /*InsertToken=*/{},
9858 TSK: SpecInfo->getTemplateSpecializationKind(),
9859 TemplateArgsAsWritten: ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9860
9861 // A function template specialization inherits the target attributes
9862 // of its template. (We require the attributes explicitly in the
9863 // code to match, but a template may have implicit attributes by
9864 // virtue e.g. of being constexpr, and it passes these implicit
9865 // attributes on to its specializations.)
9866 if (LangOpts.CUDA)
9867 CUDA().inheritTargetAttrs(FD, TD: *Specialization->getPrimaryTemplate());
9868
9869 // The "previous declaration" for this function template specialization is
9870 // the prior function template specialization.
9871 Previous.clear();
9872 Previous.addDecl(D: Specialization);
9873 return false;
9874}
9875
9876bool
9877Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9878 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9879 "Only for non-template members");
9880
9881 // Try to find the member we are instantiating.
9882 NamedDecl *FoundInstantiation = nullptr;
9883 NamedDecl *Instantiation = nullptr;
9884 NamedDecl *InstantiatedFrom = nullptr;
9885 MemberSpecializationInfo *MSInfo = nullptr;
9886
9887 if (Previous.empty()) {
9888 // Nowhere to look anyway.
9889 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Member)) {
9890 UnresolvedSet<8> Candidates;
9891 for (NamedDecl *Candidate : Previous) {
9892 auto *Method = dyn_cast<CXXMethodDecl>(Val: Candidate->getUnderlyingDecl());
9893 // Ignore any candidates that aren't member functions.
9894 if (!Method)
9895 continue;
9896
9897 QualType Adjusted = Function->getType();
9898 if (!hasExplicitCallingConv(T: Adjusted))
9899 Adjusted = adjustCCAndNoReturn(ArgFunctionType: Adjusted, FunctionType: Method->getType());
9900 // Ignore any candidates with the wrong type.
9901 // This doesn't handle deduced return types, but both function
9902 // declarations should be undeduced at this point.
9903 // FIXME: The exception specification should probably be ignored when
9904 // comparing the types.
9905 if (!Context.hasSameType(T1: Adjusted, T2: Method->getType()))
9906 continue;
9907
9908 // Ignore any candidates with unsatisfied constraints.
9909 if (ConstraintSatisfaction Satisfaction;
9910 Method->getTrailingRequiresClause() &&
9911 (CheckFunctionConstraints(FD: Method, Satisfaction,
9912 /*UsageLoc=*/Member->getLocation(),
9913 /*ForOverloadResolution=*/true) ||
9914 !Satisfaction.IsSatisfied))
9915 continue;
9916
9917 Candidates.addDecl(D: Candidate);
9918 }
9919
9920 // If we have no viable candidates left after filtering, we are done.
9921 if (Candidates.empty())
9922 return false;
9923
9924 // Find the function that is more constrained than every other function it
9925 // has been compared to.
9926 UnresolvedSetIterator Best = Candidates.begin();
9927 CXXMethodDecl *BestMethod = nullptr;
9928 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9929 I != E; ++I) {
9930 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9931 if (I == Best ||
9932 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) == Method) {
9933 Best = I;
9934 BestMethod = Method;
9935 }
9936 }
9937
9938 FoundInstantiation = *Best;
9939 Instantiation = BestMethod;
9940 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9941 MSInfo = BestMethod->getMemberSpecializationInfo();
9942
9943 // Make sure the best candidate is more constrained than all of the others.
9944 bool Ambiguous = false;
9945 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9946 I != E; ++I) {
9947 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9948 if (I != Best &&
9949 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) != BestMethod) {
9950 Ambiguous = true;
9951 break;
9952 }
9953 }
9954
9955 if (Ambiguous) {
9956 Diag(Loc: Member->getLocation(), DiagID: diag::err_function_member_spec_ambiguous)
9957 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9958 for (NamedDecl *Candidate : Candidates) {
9959 Candidate = Candidate->getUnderlyingDecl();
9960 Diag(Loc: Candidate->getLocation(), DiagID: diag::note_function_member_spec_matched)
9961 << Candidate;
9962 }
9963 return true;
9964 }
9965 } else if (isa<VarDecl>(Val: Member)) {
9966 VarDecl *PrevVar;
9967 if (Previous.isSingleResult() &&
9968 (PrevVar = dyn_cast<VarDecl>(Val: Previous.getFoundDecl())))
9969 if (PrevVar->isStaticDataMember()) {
9970 FoundInstantiation = Previous.getRepresentativeDecl();
9971 Instantiation = PrevVar;
9972 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9973 MSInfo = PrevVar->getMemberSpecializationInfo();
9974 }
9975 } else if (isa<RecordDecl>(Val: Member)) {
9976 CXXRecordDecl *PrevRecord;
9977 if (Previous.isSingleResult() &&
9978 (PrevRecord = dyn_cast<CXXRecordDecl>(Val: Previous.getFoundDecl()))) {
9979 FoundInstantiation = Previous.getRepresentativeDecl();
9980 Instantiation = PrevRecord;
9981 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9982 MSInfo = PrevRecord->getMemberSpecializationInfo();
9983 }
9984 } else if (isa<EnumDecl>(Val: Member)) {
9985 EnumDecl *PrevEnum;
9986 if (Previous.isSingleResult() &&
9987 (PrevEnum = dyn_cast<EnumDecl>(Val: Previous.getFoundDecl()))) {
9988 FoundInstantiation = Previous.getRepresentativeDecl();
9989 Instantiation = PrevEnum;
9990 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9991 MSInfo = PrevEnum->getMemberSpecializationInfo();
9992 }
9993 }
9994
9995 if (!Instantiation) {
9996 // There is no previous declaration that matches. Since member
9997 // specializations are always out-of-line, the caller will complain about
9998 // this mismatch later.
9999 return false;
10000 }
10001
10002 // A member specialization in a friend declaration isn't really declaring
10003 // an explicit specialization, just identifying a specific (possibly implicit)
10004 // specialization. Don't change the template specialization kind.
10005 //
10006 // FIXME: Is this really valid? Other compilers reject.
10007 if (Member->getFriendObjectKind() != Decl::FOK_None) {
10008 // Preserve instantiation information.
10009 if (InstantiatedFrom && isa<CXXMethodDecl>(Val: Member)) {
10010 cast<CXXMethodDecl>(Val: Member)->setInstantiationOfMemberFunction(
10011 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom),
10012 TSK: cast<CXXMethodDecl>(Val: Instantiation)->getTemplateSpecializationKind());
10013 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Val: Member)) {
10014 cast<CXXRecordDecl>(Val: Member)->setInstantiationOfMemberClass(
10015 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom),
10016 TSK: cast<CXXRecordDecl>(Val: Instantiation)->getTemplateSpecializationKind());
10017 }
10018
10019 Previous.clear();
10020 Previous.addDecl(D: FoundInstantiation);
10021 return false;
10022 }
10023
10024 // Make sure that this is a specialization of a member.
10025 if (!InstantiatedFrom) {
10026 Diag(Loc: Member->getLocation(), DiagID: diag::err_spec_member_not_instantiated)
10027 << Member;
10028 Diag(Loc: Instantiation->getLocation(), DiagID: diag::note_specialized_decl);
10029 return true;
10030 }
10031
10032 // C++ [temp.expl.spec]p6:
10033 // If a template, a member template or the member of a class template is
10034 // explicitly specialized then that specialization shall be declared
10035 // before the first use of that specialization that would cause an implicit
10036 // instantiation to take place, in every translation unit in which such a
10037 // use occurs; no diagnostic is required.
10038 assert(MSInfo && "Member specialization info missing?");
10039
10040 bool HasNoEffect = false;
10041 if (CheckSpecializationInstantiationRedecl(NewLoc: Member->getLocation(),
10042 NewTSK: TSK_ExplicitSpecialization,
10043 PrevDecl: Instantiation,
10044 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10045 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10046 HasNoEffect))
10047 return true;
10048
10049 // Check the scope of this explicit specialization.
10050 if (CheckTemplateSpecializationScope(S&: *this,
10051 Specialized: InstantiatedFrom,
10052 PrevDecl: Instantiation, Loc: Member->getLocation(),
10053 IsPartialSpecialization: false))
10054 return true;
10055
10056 // Note that this member specialization is an "instantiation of" the
10057 // corresponding member of the original template.
10058 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Val: Member)) {
10059 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Val: Instantiation);
10060 if (InstantiationFunction->getTemplateSpecializationKind() ==
10061 TSK_ImplicitInstantiation) {
10062 // Explicit specializations of member functions of class templates do not
10063 // inherit '=delete' from the member function they are specializing.
10064 if (InstantiationFunction->isDeleted()) {
10065 // FIXME: This assert will not hold in the presence of modules.
10066 assert(InstantiationFunction->getCanonicalDecl() ==
10067 InstantiationFunction);
10068 // FIXME: We need an update record for this AST mutation.
10069 InstantiationFunction->setDeletedAsWritten(D: false);
10070 }
10071 }
10072
10073 MemberFunction->setInstantiationOfMemberFunction(
10074 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10075 } else if (auto *MemberVar = dyn_cast<VarDecl>(Val: Member)) {
10076 MemberVar->setInstantiationOfStaticDataMember(
10077 VD: cast<VarDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10078 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Val: Member)) {
10079 MemberClass->setInstantiationOfMemberClass(
10080 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10081 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Val: Member)) {
10082 MemberEnum->setInstantiationOfMemberEnum(
10083 ED: cast<EnumDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10084 } else {
10085 llvm_unreachable("unknown member specialization kind");
10086 }
10087
10088 // Save the caller the trouble of having to figure out which declaration
10089 // this specialization matches.
10090 Previous.clear();
10091 Previous.addDecl(D: FoundInstantiation);
10092 return false;
10093}
10094
10095/// Complete the explicit specialization of a member of a class template by
10096/// updating the instantiated member to be marked as an explicit specialization.
10097///
10098/// \param OrigD The member declaration instantiated from the template.
10099/// \param Loc The location of the explicit specialization of the member.
10100template<typename DeclT>
10101static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10102 SourceLocation Loc) {
10103 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10104 return;
10105
10106 // FIXME: Inform AST mutation listeners of this AST mutation.
10107 // FIXME: If there are multiple in-class declarations of the member (from
10108 // multiple modules, or a declaration and later definition of a member type),
10109 // should we update all of them?
10110 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10111 OrigD->setLocation(Loc);
10112}
10113
10114void Sema::CompleteMemberSpecialization(NamedDecl *Member,
10115 LookupResult &Previous) {
10116 NamedDecl *Instantiation = cast<NamedDecl>(Val: Member->getCanonicalDecl());
10117 if (Instantiation == Member)
10118 return;
10119
10120 if (auto *Function = dyn_cast<CXXMethodDecl>(Val: Instantiation))
10121 completeMemberSpecializationImpl(S&: *this, OrigD: Function, Loc: Member->getLocation());
10122 else if (auto *Var = dyn_cast<VarDecl>(Val: Instantiation))
10123 completeMemberSpecializationImpl(S&: *this, OrigD: Var, Loc: Member->getLocation());
10124 else if (auto *Record = dyn_cast<CXXRecordDecl>(Val: Instantiation))
10125 completeMemberSpecializationImpl(S&: *this, OrigD: Record, Loc: Member->getLocation());
10126 else if (auto *Enum = dyn_cast<EnumDecl>(Val: Instantiation))
10127 completeMemberSpecializationImpl(S&: *this, OrigD: Enum, Loc: Member->getLocation());
10128 else
10129 llvm_unreachable("unknown member specialization kind");
10130}
10131
10132/// Check the scope of an explicit instantiation.
10133///
10134/// \returns true if a serious error occurs, false otherwise.
10135static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
10136 SourceLocation InstLoc,
10137 bool WasQualifiedName) {
10138 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
10139 DeclContext *CurContext = S.CurContext->getRedeclContext();
10140
10141 if (CurContext->isRecord()) {
10142 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_in_class)
10143 << D;
10144 return true;
10145 }
10146
10147 // C++11 [temp.explicit]p3:
10148 // An explicit instantiation shall appear in an enclosing namespace of its
10149 // template. If the name declared in the explicit instantiation is an
10150 // unqualified name, the explicit instantiation shall appear in the
10151 // namespace where its template is declared or, if that namespace is inline
10152 // (7.3.1), any namespace from its enclosing namespace set.
10153 //
10154 // This is DR275, which we do not retroactively apply to C++98/03.
10155 if (WasQualifiedName) {
10156 if (CurContext->Encloses(DC: OrigContext))
10157 return false;
10158 } else {
10159 if (CurContext->InEnclosingNamespaceSetOf(NS: OrigContext))
10160 return false;
10161 }
10162
10163 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: OrigContext)) {
10164 if (WasQualifiedName)
10165 S.Diag(Loc: InstLoc,
10166 DiagID: S.getLangOpts().CPlusPlus11?
10167 diag::err_explicit_instantiation_out_of_scope :
10168 diag::warn_explicit_instantiation_out_of_scope_0x)
10169 << D << NS;
10170 else
10171 S.Diag(Loc: InstLoc,
10172 DiagID: S.getLangOpts().CPlusPlus11?
10173 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10174 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10175 << D << NS;
10176 } else
10177 S.Diag(Loc: InstLoc,
10178 DiagID: S.getLangOpts().CPlusPlus11?
10179 diag::err_explicit_instantiation_must_be_global :
10180 diag::warn_explicit_instantiation_must_be_global_0x)
10181 << D;
10182 S.Diag(Loc: D->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10183 return false;
10184}
10185
10186/// Common checks for whether an explicit instantiation of \p D is valid.
10187static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
10188 SourceLocation InstLoc,
10189 bool WasQualifiedName,
10190 TemplateSpecializationKind TSK) {
10191 // C++ [temp.explicit]p13:
10192 // An explicit instantiation declaration shall not name a specialization of
10193 // a template with internal linkage.
10194 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10195 D->getFormalLinkage() == Linkage::Internal) {
10196 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_internal_linkage) << D;
10197 return true;
10198 }
10199
10200 // C++11 [temp.explicit]p3: [DR 275]
10201 // An explicit instantiation shall appear in an enclosing namespace of its
10202 // template.
10203 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10204 return true;
10205
10206 return false;
10207}
10208
10209/// Determine whether the given scope specifier has a template-id in it.
10210static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
10211 // C++11 [temp.explicit]p3:
10212 // If the explicit instantiation is for a member function, a member class
10213 // or a static data member of a class template specialization, the name of
10214 // the class template specialization in the qualified-id for the member
10215 // name shall be a simple-template-id.
10216 //
10217 // C++98 has the same restriction, just worded differently.
10218 for (NestedNameSpecifier NNS = SS.getScopeRep();
10219 NNS.getKind() == NestedNameSpecifier::Kind::Type;
10220 /**/) {
10221 const Type *T = NNS.getAsType();
10222 if (isa<TemplateSpecializationType>(Val: T))
10223 return true;
10224 NNS = T->getPrefix();
10225 }
10226 return false;
10227}
10228
10229/// Make a dllexport or dllimport attr on a class template specialization take
10230/// effect.
10231static void dllExportImportClassTemplateSpecialization(
10232 Sema &S, ClassTemplateSpecializationDecl *Def) {
10233 auto *A = cast_or_null<InheritableAttr>(Val: getDLLAttr(D: Def));
10234 assert(A && "dllExportImportClassTemplateSpecialization called "
10235 "on Def without dllexport or dllimport");
10236
10237 // We reject explicit instantiations in class scope, so there should
10238 // never be any delayed exported classes to worry about.
10239 assert(S.DelayedDllExportClasses.empty() &&
10240 "delayed exports present at explicit instantiation");
10241 S.checkClassLevelDLLAttribute(Class: Def);
10242
10243 // Propagate attribute to base class templates.
10244 for (auto &B : Def->bases()) {
10245 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10246 Val: B.getType()->getAsCXXRecordDecl()))
10247 S.propagateDLLAttrToBaseClassTemplate(Class: Def, ClassAttr: A, BaseTemplateSpec: BT, BaseLoc: B.getBeginLoc());
10248 }
10249
10250 S.referenceDLLExportedClassMethods();
10251}
10252
10253DeclResult Sema::ActOnExplicitInstantiation(
10254 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10255 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10256 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10257 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10258 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10259 // Find the class template we're specializing
10260 TemplateName Name = TemplateD.get();
10261 TemplateDecl *TD = Name.getAsTemplateDecl();
10262 // Check that the specialization uses the same tag kind as the
10263 // original template.
10264 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10265 assert(Kind != TagTypeKind::Enum &&
10266 "Invalid enum tag in class template explicit instantiation!");
10267
10268 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: TD);
10269
10270 if (!ClassTemplate) {
10271 NonTagKind NTK = getNonTagTypeDeclKind(D: TD, TTK: Kind);
10272 Diag(Loc: TemplateNameLoc, DiagID: diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10273 Diag(Loc: TD->getLocation(), DiagID: diag::note_previous_use);
10274 return true;
10275 }
10276
10277 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(),
10278 NewTag: Kind, /*isDefinition*/false, NewTagLoc: KWLoc,
10279 Name: ClassTemplate->getIdentifier())) {
10280 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
10281 << ClassTemplate
10282 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
10283 Code: ClassTemplate->getTemplatedDecl()->getKindName());
10284 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
10285 DiagID: diag::note_previous_use);
10286 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10287 }
10288
10289 // C++0x [temp.explicit]p2:
10290 // There are two forms of explicit instantiation: an explicit instantiation
10291 // definition and an explicit instantiation declaration. An explicit
10292 // instantiation declaration begins with the extern keyword. [...]
10293 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10294 ? TSK_ExplicitInstantiationDefinition
10295 : TSK_ExplicitInstantiationDeclaration;
10296
10297 bool DLLAttrAffected = false;
10298 const ParsedAttr *AttachedExportAttr = nullptr;
10299 const ParsedAttr *AttachedImportAttr = nullptr;
10300 for (const ParsedAttr &AL : Attr) {
10301 if (AL.getKind() == ParsedAttr::AT_DLLExport)
10302 AttachedExportAttr = &AL;
10303 else if (AL.getKind() == ParsedAttr::AT_DLLImport)
10304 AttachedImportAttr = &AL;
10305 }
10306
10307 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10308 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10309 // Check for dllexport class template instantiation declarations,
10310 // except for MinGW mode.
10311 if (AttachedExportAttr) {
10312 Diag(Loc: ExternLoc,
10313 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10314 Diag(Loc: AttachedExportAttr->getLoc(), DiagID: diag::note_attribute);
10315 DLLAttrAffected = true;
10316 }
10317
10318 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10319 Diag(Loc: ExternLoc,
10320 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10321 Diag(Loc: A->getLocation(), DiagID: diag::note_attribute);
10322 DLLAttrAffected = true;
10323 }
10324 }
10325
10326 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10327 // instantiation declarations for most purposes.
10328 bool DLLImportExplicitInstantiationDef = false;
10329 if (TSK == TSK_ExplicitInstantiationDefinition &&
10330 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10331 // Check for dllimport class template instantiation definitions.
10332 bool DLLImport =
10333 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10334 // dllexport trumps dllimport.
10335 if ((DLLImport || AttachedImportAttr) && !AttachedExportAttr) {
10336 TSK = TSK_ExplicitInstantiationDeclaration;
10337 DLLImportExplicitInstantiationDef = true;
10338 }
10339 }
10340
10341 // Translate the parser's template argument list in our AST format.
10342 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10343 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10344
10345 // Check that the template argument list is well-formed for this
10346 // template.
10347 CheckTemplateArgumentInfo CTAI;
10348 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
10349 /*DefaultArgs=*/{}, PartialTemplateArgs: false, CTAI,
10350 /*UpdateArgsWithConversions=*/true,
10351 /*ConstraintsNotSatisfied=*/nullptr))
10352 return true;
10353
10354 // Find the class template specialization declaration that
10355 // corresponds to these arguments.
10356 llvm::FoldingSetInsertToken InsertToken;
10357 ClassTemplateSpecializationDecl *PrevDecl =
10358 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertToken);
10359
10360 TemplateSpecializationKind PrevDecl_TSK
10361 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10362
10363 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10364 Context.getTargetInfo().getTriple().isOSCygMing()) {
10365 // Check for dllexport class template instantiation definitions in MinGW
10366 // mode, if a previous declaration of the instantiation was seen.
10367 if (AttachedExportAttr) {
10368 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10369 Diag(Loc: AttachedExportAttr->getLoc(),
10370 DiagID: diag::warn_attr_dllexport_explicit_inst_def);
10371 } else {
10372 Diag(Loc: AttachedExportAttr->getLoc(),
10373 DiagID: diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10374 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_prev_decl_missing_dllexport);
10375 }
10376 DLLAttrAffected = true;
10377 } else if (AttachedImportAttr) {
10378 Diag(Loc: AttachedImportAttr->getLoc(),
10379 DiagID: diag::warn_attribute_dllimport_explicit_instantiation_def);
10380 DLLAttrAffected = true;
10381 }
10382 }
10383
10384 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10385 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10386 !AttachedExportAttr) {
10387 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10388 Diag(Loc: TemplateLoc, DiagID: diag::warn_dllexport_on_decl_ignored);
10389 Diag(Loc: DEA->getLoc(), DiagID: diag::note_dllexport_on_decl);
10390 DLLAttrAffected = true;
10391 }
10392 }
10393
10394 if (CheckExplicitInstantiation(S&: *this, D: ClassTemplate, InstLoc: TemplateNameLoc,
10395 WasQualifiedName: SS.isSet(), TSK))
10396 return true;
10397
10398 ClassTemplateSpecializationDecl *Specialization = nullptr;
10399
10400 bool HasNoEffect = false;
10401 if (PrevDecl) {
10402 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateNameLoc, NewTSK: TSK,
10403 PrevDecl, PrevTSK: PrevDecl_TSK,
10404 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
10405 HasNoEffect))
10406 return PrevDecl;
10407
10408 // Even though HasNoEffect == true means that this explicit instantiation
10409 // has no effect on semantics, we go on to put its syntax in the AST.
10410
10411 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10412 PrevDecl_TSK == TSK_Undeclared) {
10413 // Since the only prior class template specialization with these
10414 // arguments was referenced but not declared, reuse that
10415 // declaration node as our own, updating the source location
10416 // for the template name to reflect our new declaration.
10417 // (Other source locations will be updated later.)
10418 Specialization = PrevDecl;
10419 Specialization->setLocation(TemplateNameLoc);
10420 PrevDecl = nullptr;
10421 }
10422
10423 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10424 DLLImportExplicitInstantiationDef) {
10425 // The new specialization might add a dllimport attribute.
10426 HasNoEffect = false;
10427 }
10428 }
10429
10430 if (!Specialization) {
10431 // Create a new class template specialization declaration node for
10432 // this explicit specialization.
10433 Specialization = ClassTemplateSpecializationDecl::Create(
10434 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
10435 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
10436 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
10437
10438 // A MSInheritanceAttr attached to the previous declaration must be
10439 // propagated to the new node prior to instantiation.
10440 if (PrevDecl) {
10441 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10442 auto *Clone = A->clone(C&: getASTContext());
10443 Clone->setInherited(true);
10444 Specialization->addAttr(A: Clone);
10445 Consumer.AssignInheritanceModel(RD: Specialization);
10446 }
10447 }
10448
10449 if (!HasNoEffect && !PrevDecl) {
10450 // Insert the new specialization.
10451 ClassTemplate->AddSpecialization(D: Specialization, InsertToken);
10452 }
10453 }
10454
10455 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10456
10457 // Set source locations for keywords.
10458 Specialization->setExternKeywordLoc(ExternLoc);
10459 Specialization->setTemplateKeywordLoc(TemplateLoc);
10460 Specialization->setBraceRange(SourceRange());
10461
10462 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>() ||
10463 (PrevDecl && PrevDecl->hasAttr<DLLExportAttr>());
10464 bool PreviouslyDLLImported = Specialization->hasAttr<DLLImportAttr>() ||
10465 (PrevDecl && PrevDecl->hasAttr<DLLImportAttr>());
10466 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
10467 ProcessAPINotes(D: Specialization);
10468
10469 // Add the explicit instantiation into its lexical context. However,
10470 // since explicit instantiations are never found by name lookup, we
10471 // just put it into the declaration context directly.
10472 Specialization->setLexicalDeclContext(CurContext);
10473 CurContext->addDecl(D: Specialization);
10474
10475 // Syntax is now OK, so return if it has no other effect on semantics.
10476 if (HasNoEffect) {
10477 // Set the template specialization kind.
10478 Specialization->setTemplateSpecializationKind(TSK);
10479
10480 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
10481 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10482 Keyword: KW, ElaboratedKeywordLoc: KWLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: SourceLocation(), T: Name,
10483 TLoc: TemplateNameLoc, SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted,
10484 Canon: Context.getCanonicalTagType(TD: Specialization));
10485 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
10486 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10487 NameLoc: TemplateNameLoc, TypeAsWritten: TSI, TSK);
10488 return Specialization;
10489 }
10490
10491 // C++ [temp.explicit]p3:
10492 // A definition of a class template or class member template
10493 // shall be in scope at the point of the explicit instantiation of
10494 // the class template or class member template.
10495 //
10496 // This check comes when we actually try to perform the
10497 // instantiation.
10498 ClassTemplateSpecializationDecl *Def
10499 = cast_or_null<ClassTemplateSpecializationDecl>(
10500 Val: Specialization->getDefinition());
10501 if (!Def) {
10502 InstantiateClassTemplateSpecialization(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Specialization, TSK,
10503 /*Complain=*/true,
10504 PrimaryStrictPackMatch: CTAI.StrictPackMatch);
10505 DLLAttrAffected = true;
10506 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
10507 MarkVTableUsed(Loc: TemplateNameLoc, Class: Specialization, DefinitionRequired: true);
10508 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10509 }
10510
10511 // Instantiate the members of this class template specialization.
10512 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10513 Val: Specialization->getDefinition());
10514 if (Def) {
10515 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
10516 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10517 // TSK_ExplicitInstantiationDefinition
10518 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10519 (TSK == TSK_ExplicitInstantiationDefinition ||
10520 DLLImportExplicitInstantiationDef)) {
10521 // FIXME: Need to notify the ASTMutationListener that we did this.
10522 Def->setTemplateSpecializationKind(TSK);
10523
10524 if (!getDLLAttr(D: Def) && getDLLAttr(D: Specialization) &&
10525 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10526 // An explicit instantiation definition can add a dll attribute to a
10527 // template with a previous instantiation declaration. MinGW doesn't
10528 // allow this.
10529 auto *A = cast<InheritableAttr>(
10530 Val: getDLLAttr(D: Specialization)->clone(C&: getASTContext()));
10531 A->setInherited(true);
10532 Def->addAttr(A);
10533 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10534 DLLAttrAffected = true;
10535 }
10536 }
10537
10538 // Fix a TSK_ImplicitInstantiation followed by a
10539 // TSK_ExplicitInstantiationDefinition
10540 bool NewlyDLLExported = !PreviouslyDLLExported && AttachedExportAttr &&
10541 Specialization->hasAttr<DLLExportAttr>();
10542 bool NewlyDLLImported = !PreviouslyDLLImported && AttachedImportAttr &&
10543 Specialization->hasAttr<DLLImportAttr>();
10544 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10545 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10546 // An explicit instantiation definition can add a dll attribute to a
10547 // template with a previous implicit instantiation. MinGW doesn't allow
10548 // this. We limit clang to only adding dllexport, to avoid potentially
10549 // strange codegen behavior. For example, if we extend this conditional
10550 // to dllimport, and we have a source file calling a method on an
10551 // implicitly instantiated template class instance and then declaring a
10552 // dllimport explicit instantiation definition for the same template
10553 // class, the codegen for the method call will not respect the dllimport,
10554 // while it will with cl. The Def will already have the DLL attribute,
10555 // since the Def and Specialization will be the same in the case of
10556 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10557 // attribute to the Specialization; we just need to make it take effect.
10558 assert(Def == Specialization &&
10559 "Def and Specialization should match for implicit instantiation");
10560 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10561 DLLAttrAffected = true;
10562 }
10563
10564 // In MinGW mode, export the template instantiation if the declaration
10565 // was marked dllexport.
10566 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10567 Context.getTargetInfo().getTriple().isOSCygMing() &&
10568 PrevDecl->hasAttr<DLLExportAttr>()) {
10569 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10570 DLLAttrAffected = true;
10571 }
10572
10573 if (!DLLAttrAffected && (NewlyDLLExported || NewlyDLLImported)) {
10574 if (Context.getTargetInfo().getTriple().isOSCygMing() &&
10575 TSK == TSK_ExplicitInstantiationDeclaration && NewlyDLLImported) {
10576 // In MinGW mode, all undefined symbols are also searched from DLLs
10577 // even if they were not declared with dllimport, so doesn't warn
10578 // about ignoring dllimport.
10579 } else {
10580 const ParsedAttr *A =
10581 AttachedExportAttr ? AttachedExportAttr : AttachedImportAttr;
10582 Diag(Loc: A->getLoc(), DiagID: diag::warn_dllattr_ignored_already_instantiated) << A;
10583 Diag(Loc: Def->getPointOfInstantiation(),
10584 DiagID: diag::note_instantiation_required_here)
10585 << /*implicit|explicit=*/0;
10586 }
10587 }
10588
10589 // Set the template specialization kind. Make sure it is set before
10590 // instantiating the members which will trigger ASTConsumer callbacks.
10591 Specialization->setTemplateSpecializationKind(TSK);
10592 InstantiateClassTemplateSpecializationMembers(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Def, TSK);
10593 } else {
10594
10595 // Set the template specialization kind.
10596 Specialization->setTemplateSpecializationKind(TSK);
10597 }
10598
10599 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
10600 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10601 Keyword: KW, ElaboratedKeywordLoc: KWLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: SourceLocation(), T: Name,
10602 TLoc: TemplateNameLoc, SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted,
10603 Canon: Context.getCanonicalTagType(TD: Specialization));
10604 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
10605 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10606 NameLoc: TemplateNameLoc, TypeAsWritten: TSI, TSK);
10607 return Specialization;
10608}
10609
10610DeclResult
10611Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10612 SourceLocation TemplateLoc, unsigned TagSpec,
10613 SourceLocation KWLoc, CXXScopeSpec &SS,
10614 IdentifierInfo *Name, SourceLocation NameLoc,
10615 const ParsedAttributesView &Attr) {
10616
10617 bool Owned = false;
10618 bool IsDependent = false;
10619 Decl *TagD =
10620 ActOnTag(S, TagSpec, TUK: TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10621 Attr, AS: AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10622 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent, ScopedEnumKWLoc: SourceLocation(),
10623 ScopedEnumUsesClassTag: false, UnderlyingType: TypeResult(), /*IsTypeSpecifier*/ false,
10624 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10625 .get();
10626 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10627
10628 if (!TagD)
10629 return true;
10630
10631 TagDecl *Tag = cast<TagDecl>(Val: TagD);
10632 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10633
10634 if (Tag->isInvalidDecl())
10635 return true;
10636
10637 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: Tag);
10638 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10639 if (!Pattern) {
10640 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_nontemplate_type)
10641 << Context.getCanonicalTagType(TD: Record);
10642 Diag(Loc: Record->getLocation(), DiagID: diag::note_nontemplate_decl_here);
10643 return true;
10644 }
10645
10646 // C++0x [temp.explicit]p2:
10647 // If the explicit instantiation is for a class or member class, the
10648 // elaborated-type-specifier in the declaration shall include a
10649 // simple-template-id.
10650 //
10651 // C++98 has the same restriction, just worded differently.
10652 if (!ScopeSpecifierHasTemplateId(SS))
10653 Diag(Loc: TemplateLoc, DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10654 << Record << SS.getRange();
10655
10656 // C++0x [temp.explicit]p2:
10657 // There are two forms of explicit instantiation: an explicit instantiation
10658 // definition and an explicit instantiation declaration. An explicit
10659 // instantiation declaration begins with the extern keyword. [...]
10660 TemplateSpecializationKind TSK
10661 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10662 : TSK_ExplicitInstantiationDeclaration;
10663
10664 CheckExplicitInstantiation(S&: *this, D: Record, InstLoc: NameLoc, WasQualifiedName: true, TSK);
10665
10666 // Verify that it is okay to explicitly instantiate here.
10667 CXXRecordDecl *PrevDecl
10668 = cast_or_null<CXXRecordDecl>(Val: Record->getPreviousDecl());
10669 if (!PrevDecl && Record->getDefinition())
10670 PrevDecl = Record;
10671 if (PrevDecl) {
10672 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10673 bool HasNoEffect = false;
10674 assert(MSInfo && "No member specialization information?");
10675 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateLoc, NewTSK: TSK,
10676 PrevDecl,
10677 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10678 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10679 HasNoEffect))
10680 return true;
10681 if (HasNoEffect) {
10682 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10683 ElaboratedTypeKeyword KW =
10684 TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
10685 QualType TagTy = Context.getTagType(Keyword: KW, Qualifier: SS.getScopeRep(), TD: Record, OwnsTag: false);
10686 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T: TagTy);
10687 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10688 TL.setElaboratedKeywordLoc(KWLoc);
10689 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10690 TL.setNameLoc(NameLoc);
10691 addExplicitInstantiationDecl(Context, CurContext, Spec: Record, ExternLoc,
10692 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(),
10693 ArgsAsWritten: nullptr, NameLoc, TypeAsWritten: TSI, TSK);
10694 return TagD;
10695 }
10696 }
10697
10698 CXXRecordDecl *RecordDef
10699 = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10700 if (!RecordDef) {
10701 // C++ [temp.explicit]p3:
10702 // A definition of a member class of a class template shall be in scope
10703 // at the point of an explicit instantiation of the member class.
10704 CXXRecordDecl *Def
10705 = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition());
10706 if (!Def) {
10707 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_undefined_member)
10708 << 0 << Record->getDeclName() << Record->getDeclContext();
10709 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_forward_declaration)
10710 << Pattern;
10711 return true;
10712 } else {
10713 if (InstantiateClass(PointOfInstantiation: NameLoc, Instantiation: Record, Pattern: Def,
10714 TemplateArgs: getTemplateInstantiationArgs(D: Record),
10715 TSK))
10716 return true;
10717
10718 RecordDef = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10719 if (!RecordDef)
10720 return true;
10721 }
10722 }
10723
10724 // Instantiate all of the members of the class.
10725 InstantiateClassMembers(PointOfInstantiation: NameLoc, Instantiation: RecordDef,
10726 TemplateArgs: getTemplateInstantiationArgs(D: Record), TSK);
10727
10728 if (TSK == TSK_ExplicitInstantiationDefinition)
10729 MarkVTableUsed(Loc: NameLoc, Class: RecordDef, DefinitionRequired: true);
10730
10731 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10732 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
10733 QualType TagTy = Context.getTagType(Keyword: KW, Qualifier: SS.getScopeRep(), TD: Record, OwnsTag: false);
10734 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T: TagTy);
10735 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10736 TL.setElaboratedKeywordLoc(KWLoc);
10737 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10738 TL.setNameLoc(NameLoc);
10739 addExplicitInstantiationDecl(Context, CurContext, Spec: Record, ExternLoc,
10740 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10741 NameLoc, TypeAsWritten: TSI, TSK);
10742 return TagD;
10743}
10744
10745DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10746 SourceLocation ExternLoc,
10747 SourceLocation TemplateLoc,
10748 Declarator &D) {
10749 // Explicit instantiations always require a name.
10750 // TODO: check if/when DNInfo should replace Name.
10751 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10752 DeclarationName Name = NameInfo.getName();
10753 if (!Name) {
10754 if (!D.isInvalidType())
10755 Diag(Loc: D.getDeclSpec().getBeginLoc(),
10756 DiagID: diag::err_explicit_instantiation_requires_name)
10757 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10758
10759 return true;
10760 }
10761
10762 // Get the innermost enclosing declaration scope.
10763 S = S->getDeclParent();
10764
10765 // Determine the type of the declaration.
10766 TypeSourceInfo *T = GetTypeForDeclarator(D);
10767 QualType R = T->getType();
10768 if (R.isNull())
10769 return true;
10770
10771 // C++ [dcl.stc]p1:
10772 // A storage-class-specifier shall not be specified in [...] an explicit
10773 // instantiation (14.7.2) directive.
10774 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10775 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_of_typedef)
10776 << Name;
10777 return true;
10778 } else if (D.getDeclSpec().getStorageClassSpec()
10779 != DeclSpec::SCS_unspecified) {
10780 // Complain about then remove the storage class specifier.
10781 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_storage_class)
10782 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10783
10784 D.getMutableDeclSpec().ClearStorageClassSpecs();
10785 }
10786
10787 // C++0x [temp.explicit]p1:
10788 // [...] An explicit instantiation of a function template shall not use the
10789 // inline or constexpr specifiers.
10790 // Presumably, this also applies to member functions of class templates as
10791 // well.
10792 if (D.getDeclSpec().isInlineSpecified())
10793 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10794 DiagID: getLangOpts().CPlusPlus11 ?
10795 diag::err_explicit_instantiation_inline :
10796 diag::warn_explicit_instantiation_inline_0x)
10797 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10798 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10799 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10800 // not already specified.
10801 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10802 DiagID: diag::err_explicit_instantiation_constexpr);
10803
10804 // A deduction guide is not on the list of entities that can be explicitly
10805 // instantiated.
10806 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10807 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
10808 << /*explicit instantiation*/ 0;
10809 return true;
10810 }
10811
10812 // C++0x [temp.explicit]p2:
10813 // There are two forms of explicit instantiation: an explicit instantiation
10814 // definition and an explicit instantiation declaration. An explicit
10815 // instantiation declaration begins with the extern keyword. [...]
10816 TemplateSpecializationKind TSK
10817 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10818 : TSK_ExplicitInstantiationDeclaration;
10819
10820 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10821 LookupParsedName(R&: Previous, S, SS: &D.getCXXScopeSpec(),
10822 /*ObjectType=*/QualType());
10823
10824 if (!R->isFunctionType()) {
10825 // C++ [temp.explicit]p1:
10826 // A [...] static data member of a class template can be explicitly
10827 // instantiated from the member definition associated with its class
10828 // template.
10829 // C++1y [temp.explicit]p1:
10830 // A [...] variable [...] template specialization can be explicitly
10831 // instantiated from its template.
10832 if (Previous.isAmbiguous())
10833 return true;
10834
10835 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10836 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10837 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
10838
10839 if (!PrevTemplate) {
10840 if (!Prev || !Prev->isStaticDataMember()) {
10841 // We expect to see a static data member here.
10842 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_not_known)
10843 << Name;
10844 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10845 P != PEnd; ++P)
10846 Diag(Loc: (*P)->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10847 return true;
10848 }
10849
10850 if (!Prev->getInstantiatedFromStaticDataMember()) {
10851 // FIXME: Check for explicit specialization?
10852 Diag(Loc: D.getIdentifierLoc(),
10853 DiagID: diag::err_explicit_instantiation_data_member_not_instantiated)
10854 << Prev;
10855 Diag(Loc: Prev->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10856 // FIXME: Can we provide a note showing where this was declared?
10857 return true;
10858 }
10859 } else {
10860 // Explicitly instantiate a variable template.
10861
10862 // C++1y [dcl.spec.auto]p6:
10863 // ... A program that uses auto or decltype(auto) in a context not
10864 // explicitly allowed in this section is ill-formed.
10865 //
10866 // This includes auto-typed variable template instantiations.
10867 if (R->isUndeducedType()) {
10868 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10869 DiagID: diag::err_auto_not_allowed_var_inst);
10870 return true;
10871 }
10872
10873 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10874 // C++1y [temp.explicit]p3:
10875 // If the explicit instantiation is for a variable, the unqualified-id
10876 // in the declaration shall be a template-id.
10877 Diag(Loc: D.getIdentifierLoc(),
10878 DiagID: diag::err_explicit_instantiation_without_template_id)
10879 << PrevTemplate;
10880 Diag(Loc: PrevTemplate->getLocation(),
10881 DiagID: diag::note_explicit_instantiation_here);
10882 return true;
10883 }
10884
10885 // Translate the parser's template argument list into our AST format.
10886 TemplateArgumentListInfo TemplateArgs =
10887 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10888
10889 DeclResult Res =
10890 CheckVarTemplateId(Template: PrevTemplate, TemplateLoc, TemplateNameLoc: D.getIdentifierLoc(),
10891 TemplateArgs, /*SetWrittenArgs=*/true);
10892 if (Res.isInvalid())
10893 return true;
10894
10895 if (!Res.isUsable()) {
10896 // We somehow specified dependent template arguments in an explicit
10897 // instantiation. This should probably only happen during error
10898 // recovery.
10899 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_dependent);
10900 return true;
10901 }
10902
10903 // Ignore access control bits, we don't need them for redeclaration
10904 // checking.
10905 Prev = cast<VarDecl>(Val: Res.get());
10906 ArgsAsWritten =
10907 ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
10908 }
10909
10910 // C++0x [temp.explicit]p2:
10911 // If the explicit instantiation is for a member function, a member class
10912 // or a static data member of a class template specialization, the name of
10913 // the class template specialization in the qualified-id for the member
10914 // name shall be a simple-template-id.
10915 //
10916 // C++98 has the same restriction, just worded differently.
10917 //
10918 // This does not apply to variable template specializations, where the
10919 // template-id is in the unqualified-id instead.
10920 if (!ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()) && !PrevTemplate)
10921 Diag(Loc: D.getIdentifierLoc(),
10922 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10923 << Prev << D.getCXXScopeSpec().getRange();
10924
10925 CheckExplicitInstantiation(S&: *this, D: Prev, InstLoc: D.getIdentifierLoc(), WasQualifiedName: true, TSK);
10926
10927 // Verify that it is okay to explicitly instantiate here.
10928 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10929 SourceLocation POI = Prev->getPointOfInstantiation();
10930 bool HasNoEffect = false;
10931 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK, PrevDecl: Prev,
10932 PrevTSK, PrevPointOfInstantiation: POI, HasNoEffect))
10933 return true;
10934
10935 if (!HasNoEffect) {
10936 // Instantiate static data member or variable template.
10937 Prev->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
10938 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: Prev)) {
10939 VTSD->setExternKeywordLoc(ExternLoc);
10940 VTSD->setTemplateKeywordLoc(TemplateLoc);
10941 }
10942
10943 // Merge attributes.
10944 ProcessDeclAttributeList(S, D: Prev, AttrList: D.getDeclSpec().getAttributes());
10945 if (PrevTemplate)
10946 ProcessAPINotes(D: Prev);
10947
10948 if (TSK == TSK_ExplicitInstantiationDefinition)
10949 InstantiateVariableDefinition(PointOfInstantiation: D.getIdentifierLoc(), Var: Prev);
10950 }
10951
10952 // Check the new variable specialization against the parsed input.
10953 if (PrevTemplate && !Context.hasSameType(T1: Prev->getType(), T2: R)) {
10954 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10955 DiagID: diag::err_invalid_var_template_spec_type)
10956 << 0 << PrevTemplate << R << Prev->getType();
10957 Diag(Loc: PrevTemplate->getLocation(), DiagID: diag::note_template_declared_here)
10958 << 2 << PrevTemplate->getDeclName();
10959 return true;
10960 }
10961
10962 addExplicitInstantiationDecl(
10963 Context, CurContext, Spec: Prev, ExternLoc, TemplateLoc,
10964 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
10965 NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
10966 return (Decl *)nullptr;
10967 }
10968
10969 // If the declarator is a template-id, translate the parser's template
10970 // argument list into our AST format.
10971 bool HasExplicitTemplateArgs = false;
10972 TemplateArgumentListInfo TemplateArgs;
10973 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10974 TemplateArgs = makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10975 HasExplicitTemplateArgs = true;
10976 }
10977
10978 // C++ [temp.explicit]p1:
10979 // A [...] function [...] can be explicitly instantiated from its template.
10980 // A member function [...] of a class template can be explicitly
10981 // instantiated from the member definition associated with its class
10982 // template.
10983 UnresolvedSet<8> TemplateMatches;
10984 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10985 OverloadCandidateSet::CSK_Normal);
10986 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10987 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10988 P != PEnd; ++P) {
10989 NamedDecl *Prev = *P;
10990 if (!HasExplicitTemplateArgs) {
10991 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Prev)) {
10992 QualType Adjusted = adjustCCAndNoReturn(ArgFunctionType: R, FunctionType: Method->getType(),
10993 /*AdjustExceptionSpec*/true);
10994 if (Context.hasSameUnqualifiedType(T1: Method->getType(), T2: Adjusted)) {
10995 if (Method->getPrimaryTemplate()) {
10996 TemplateMatches.addDecl(D: Method, AS: P.getAccess());
10997 } else {
10998 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10999 C.FoundDecl = P.getPair();
11000 C.Function = Method;
11001 C.Viable = true;
11002 ConstraintSatisfaction S;
11003 if (Method->getTrailingRequiresClause() &&
11004 (CheckFunctionConstraints(FD: Method, Satisfaction&: S, UsageLoc: D.getIdentifierLoc(),
11005 /*ForOverloadResolution=*/true) ||
11006 !S.IsSatisfied)) {
11007 C.Viable = false;
11008 C.FailureKind = ovl_fail_constraints_not_satisfied;
11009 }
11010 }
11011 }
11012 }
11013 }
11014
11015 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Prev);
11016 if (!FunTmpl)
11017 continue;
11018
11019 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
11020 FunctionDecl *Specialization = nullptr;
11021 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
11022 FunctionTemplate: FunTmpl, ExplicitTemplateArgs: (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), ArgFunctionType: R,
11023 Specialization, Info);
11024 TDK != TemplateDeductionResult::Success) {
11025 // Keep track of almost-matches.
11026 FailedTemplateCandidates.addCandidate().set(
11027 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
11028 Info: MakeDeductionFailureInfo(Context, TDK, Info));
11029 (void)TDK;
11030 continue;
11031 }
11032
11033 // Target attributes are part of the cuda function signature, so
11034 // the cuda target of the instantiated function must match that of its
11035 // template. Given that C++ template deduction does not take
11036 // target attributes into account, we reject candidates here that
11037 // have a different target.
11038 if (LangOpts.CUDA &&
11039 CUDA().IdentifyTarget(D: Specialization,
11040 /* IgnoreImplicitHDAttr = */ true) !=
11041 CUDA().IdentifyTarget(Attrs: D.getDeclSpec().getAttributes())) {
11042 FailedTemplateCandidates.addCandidate().set(
11043 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
11044 Info: MakeDeductionFailureInfo(
11045 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
11046 continue;
11047 }
11048
11049 TemplateMatches.addDecl(D: Specialization, AS: P.getAccess());
11050 }
11051
11052 FunctionDecl *Specialization = nullptr;
11053 if (!NonTemplateMatches.empty()) {
11054 unsigned Msg = 0;
11055 OverloadCandidateDisplayKind DisplayKind;
11056 OverloadCandidateSet::iterator Best;
11057 switch (NonTemplateMatches.BestViableFunction(S&: *this, Loc: D.getIdentifierLoc(),
11058 Best)) {
11059 case OR_Success:
11060 case OR_Deleted:
11061 Specialization = cast<FunctionDecl>(Val: Best->Function);
11062 break;
11063 case OR_Ambiguous:
11064 Msg = diag::err_explicit_instantiation_ambiguous;
11065 DisplayKind = OCD_AmbiguousCandidates;
11066 break;
11067 case OR_No_Viable_Function:
11068 Msg = diag::err_explicit_instantiation_no_candidate;
11069 DisplayKind = OCD_AllCandidates;
11070 break;
11071 }
11072 if (Msg) {
11073 PartialDiagnostic Diag = PDiag(DiagID: Msg) << Name;
11074 NonTemplateMatches.NoteCandidates(
11075 PA: PartialDiagnosticAt(D.getIdentifierLoc(), Diag), S&: *this, OCD: DisplayKind,
11076 Args: {});
11077 return true;
11078 }
11079 }
11080
11081 if (!Specialization) {
11082 // Find the most specialized function template specialization.
11083 UnresolvedSetIterator Result = getMostSpecialized(
11084 SBegin: TemplateMatches.begin(), SEnd: TemplateMatches.end(),
11085 FailedCandidates&: FailedTemplateCandidates, Loc: D.getIdentifierLoc(),
11086 NoneDiag: PDiag(DiagID: diag::err_explicit_instantiation_not_known) << Name,
11087 AmbigDiag: PDiag(DiagID: diag::err_explicit_instantiation_ambiguous) << Name,
11088 CandidateDiag: PDiag(DiagID: diag::note_explicit_instantiation_candidate));
11089
11090 if (Result == TemplateMatches.end())
11091 return true;
11092
11093 // Ignore access control bits, we don't need them for redeclaration checking.
11094 Specialization = cast<FunctionDecl>(Val: *Result);
11095 }
11096
11097 // C++11 [except.spec]p4
11098 // In an explicit instantiation an exception-specification may be specified,
11099 // but is not required.
11100 // If an exception-specification is specified in an explicit instantiation
11101 // directive, it shall be compatible with the exception-specifications of
11102 // other declarations of that function.
11103 if (auto *FPT = R->getAs<FunctionProtoType>())
11104 if (FPT->hasExceptionSpec()) {
11105 unsigned DiagID =
11106 diag::err_mismatched_exception_spec_explicit_instantiation;
11107 if (getLangOpts().MicrosoftExt)
11108 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11109 bool Result = CheckEquivalentExceptionSpec(
11110 DiagID: PDiag(DiagID) << Specialization->getType(),
11111 NoteID: PDiag(DiagID: diag::note_explicit_instantiation_here),
11112 Old: Specialization->getType()->getAs<FunctionProtoType>(),
11113 OldLoc: Specialization->getLocation(), New: FPT, NewLoc: D.getBeginLoc());
11114 // In Microsoft mode, mismatching exception specifications just cause a
11115 // warning.
11116 if (!getLangOpts().MicrosoftExt && Result)
11117 return true;
11118 }
11119
11120 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11121 Diag(Loc: D.getIdentifierLoc(),
11122 DiagID: diag::err_explicit_instantiation_member_function_not_instantiated)
11123 << Specialization
11124 << (Specialization->getTemplateSpecializationKind() ==
11125 TSK_ExplicitSpecialization);
11126 Diag(Loc: Specialization->getLocation(), DiagID: diag::note_explicit_instantiation_here);
11127 return true;
11128 }
11129
11130 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11131 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11132 PrevDecl = Specialization;
11133
11134 if (PrevDecl) {
11135 bool HasNoEffect = false;
11136 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK,
11137 PrevDecl,
11138 PrevTSK: PrevDecl->getTemplateSpecializationKind(),
11139 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
11140 HasNoEffect))
11141 return true;
11142
11143 if (HasNoEffect) {
11144 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11145 if (HasExplicitTemplateArgs)
11146 ArgsAsWritten =
11147 ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
11148 addExplicitInstantiationDecl(
11149 Context, CurContext, Spec: Specialization, ExternLoc, TemplateLoc,
11150 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11151 NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
11152 return (Decl *)nullptr;
11153 }
11154 }
11155
11156 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11157 // functions
11158 // valarray<size_t>::valarray(size_t) and
11159 // valarray<size_t>::~valarray()
11160 // that it declared to have internal linkage with the internal_linkage
11161 // attribute. Ignore the explicit instantiation declaration in this case.
11162 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11163 TSK == TSK_ExplicitInstantiationDeclaration) {
11164 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Specialization->getDeclContext()))
11165 if (RD->getIdentifier() && RD->getIdentifier()->isStr(Str: "valarray") &&
11166 RD->isInStdNamespace())
11167 return (Decl*) nullptr;
11168 }
11169
11170 ProcessDeclAttributeList(S, D: Specialization, AttrList: D.getDeclSpec().getAttributes());
11171 ProcessAPINotes(D: Specialization);
11172
11173 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11174 // instantiation declarations.
11175 if (TSK == TSK_ExplicitInstantiationDefinition &&
11176 Specialization->hasAttr<DLLImportAttr>() &&
11177 Context.getTargetInfo().getCXXABI().isMicrosoft())
11178 TSK = TSK_ExplicitInstantiationDeclaration;
11179
11180 Specialization->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
11181 if (Specialization->isDefined()) {
11182 // Let the ASTConsumer know that this function has been explicitly
11183 // instantiated now, and its linkage might have changed.
11184 Consumer.HandleTopLevelDecl(D: DeclGroupRef(Specialization));
11185 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
11186 // C++2c [expr.prim.lambda.closure]/19 A member of a closure type shall not
11187 // be explicitly instantiated.
11188 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Specialization->getParent());
11189 RD && RD->isLambda()) {
11190 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_lambda_explicit_temp_spec)
11191 << /*instantiation*/ 1;
11192 Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here) << RD;
11193 return (Decl *)nullptr;
11194 }
11195 InstantiateFunctionDefinition(PointOfInstantiation: D.getIdentifierLoc(), Function: Specialization);
11196 }
11197
11198 // C++0x [temp.explicit]p2:
11199 // If the explicit instantiation is for a member function, a member class
11200 // or a static data member of a class template specialization, the name of
11201 // the class template specialization in the qualified-id for the member
11202 // name shall be a simple-template-id.
11203 //
11204 // C++98 has the same restriction, just worded differently.
11205 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11206 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11207 D.getCXXScopeSpec().isSet() &&
11208 !ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()))
11209 Diag(Loc: D.getIdentifierLoc(),
11210 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
11211 << Specialization << D.getCXXScopeSpec().getRange();
11212
11213 CheckExplicitInstantiation(
11214 S&: *this,
11215 D: FunTmpl ? (NamedDecl *)FunTmpl
11216 : Specialization->getInstantiatedFromMemberFunction(),
11217 InstLoc: D.getIdentifierLoc(), WasQualifiedName: D.getCXXScopeSpec().isSet(), TSK);
11218
11219 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11220 if (HasExplicitTemplateArgs)
11221 ArgsAsWritten = ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
11222 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
11223 TemplateLoc,
11224 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context),
11225 ArgsAsWritten, NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
11226 return (Decl *)nullptr;
11227}
11228
11229TypeResult Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11230 const CXXScopeSpec &SS,
11231 const IdentifierInfo *Name,
11232 SourceLocation TagLoc,
11233 SourceLocation NameLoc) {
11234 // This has to hold, because SS is expected to be defined.
11235 assert(Name && "Expected a name in a dependent tag");
11236
11237 NestedNameSpecifier NNS = SS.getScopeRep();
11238 if (!NNS)
11239 return true;
11240
11241 if (TUK == TagUseKind::Friend &&
11242 DiagnosePackIndexingInFriendNNS(Loc: NameLoc, NNSLoc: SS.getWithLocInContext(Context)))
11243 return true;
11244
11245 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
11246
11247 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11248 Diag(Loc: NameLoc, DiagID: diag::err_dependent_tag_decl)
11249 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11250 return true;
11251 }
11252
11253 // Create the resulting type.
11254 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
11255 QualType Result = Context.getDependentNameType(Keyword: Kwd, NNS, Name);
11256
11257 // Create type-source location information for this type.
11258 TypeLocBuilder TLB;
11259 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: Result);
11260 TL.setElaboratedKeywordLoc(TagLoc);
11261 TL.setQualifierLoc(SS.getWithLocInContext(Context));
11262 TL.setNameLoc(NameLoc);
11263 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
11264}
11265
11266TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11267 const CXXScopeSpec &SS,
11268 const IdentifierInfo &II,
11269 SourceLocation IdLoc,
11270 ImplicitTypenameContext IsImplicitTypename) {
11271 if (SS.isInvalid())
11272 return true;
11273
11274 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11275 DiagCompat(Loc: TypenameLoc, CompatDiagId: diag_compat::typename_outside_of_template)
11276 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11277
11278 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11279 TypeSourceInfo *TSI = nullptr;
11280 QualType T =
11281 CheckTypenameType(Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11282 : ElaboratedTypeKeyword::None,
11283 KeywordLoc: TypenameLoc, QualifierLoc, II, IILoc: IdLoc, TSI: &TSI,
11284 /*DeducedTSTContext=*/true);
11285 if (T.isNull())
11286 return true;
11287 return CreateParsedType(T, TInfo: TSI);
11288}
11289
11290TypeResult
11291Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11292 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11293 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11294 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11295 ASTTemplateArgsPtr TemplateArgsIn,
11296 SourceLocation RAngleLoc) {
11297 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11298 Diag(Loc: TypenameLoc, DiagID: getLangOpts().CPlusPlus11
11299 ? diag::compat_cxx11_typename_outside_of_template
11300 : diag::compat_pre_cxx11_typename_outside_of_template)
11301 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11302
11303 // Strangely, non-type results are not ignored by this lookup, so the
11304 // program is ill-formed if it finds an injected-class-name.
11305 if (TypenameLoc.isValid()) {
11306 auto *LookupRD =
11307 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: false));
11308 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11309 Diag(Loc: TemplateIILoc,
11310 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
11311 << TemplateII << 0 /*injected-class-name used as template name*/
11312 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11313 }
11314 }
11315
11316 // Translate the parser's template argument list in our AST format.
11317 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11318 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11319
11320 QualType T = CheckTemplateIdType(
11321 Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11322 : ElaboratedTypeKeyword::None,
11323 Name: TemplateIn.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
11324 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11325 if (T.isNull())
11326 return true;
11327
11328 // Provide source-location information for the template specialization type.
11329 TypeLocBuilder Builder;
11330 TemplateSpecializationTypeLoc SpecTL
11331 = Builder.push<TemplateSpecializationTypeLoc>(T);
11332 SpecTL.set(ElaboratedKeywordLoc: TypenameLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
11333 NameLoc: TemplateIILoc, TAL: TemplateArgs);
11334 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11335 return CreateParsedType(T, TInfo: TSI);
11336}
11337
11338/// Determine whether this failed name lookup should be treated as being
11339/// disabled by a usage of std::enable_if.
11340static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
11341 SourceRange &CondRange, Expr *&Cond) {
11342 // We must be looking for a ::type...
11343 if (!II.isStr(Str: "type"))
11344 return false;
11345
11346 // ... within an explicitly-written template specialization...
11347 if (NNS.getNestedNameSpecifier().getKind() != NestedNameSpecifier::Kind::Type)
11348 return false;
11349
11350 // FIXME: Look through sugar.
11351 auto EnableIfTSTLoc =
11352 NNS.castAsTypeLoc().getAs<TemplateSpecializationTypeLoc>();
11353 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11354 return false;
11355 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11356
11357 // ... which names a complete class template declaration...
11358 const TemplateDecl *EnableIfDecl =
11359 EnableIfTST->getTemplateName().getAsTemplateDecl();
11360 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11361 return false;
11362
11363 // ... called "enable_if".
11364 const IdentifierInfo *EnableIfII =
11365 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11366 if (!EnableIfII || !EnableIfII->isStr(Str: "enable_if"))
11367 return false;
11368
11369 // Assume the first template argument is the condition.
11370 CondRange = EnableIfTSTLoc.getArgLoc(i: 0).getSourceRange();
11371
11372 // Dig out the condition.
11373 Cond = nullptr;
11374 if (EnableIfTSTLoc.getArgLoc(i: 0).getArgument().getKind()
11375 != TemplateArgument::Expression)
11376 return true;
11377
11378 Cond = EnableIfTSTLoc.getArgLoc(i: 0).getSourceExpression();
11379
11380 // Ignore Boolean literals; they add no value.
11381 if (isa<CXXBoolLiteralExpr>(Val: Cond->IgnoreParenCasts()))
11382 Cond = nullptr;
11383
11384 return true;
11385}
11386
11387QualType
11388Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11389 SourceLocation KeywordLoc,
11390 NestedNameSpecifierLoc QualifierLoc,
11391 const IdentifierInfo &II,
11392 SourceLocation IILoc,
11393 TypeSourceInfo **TSI,
11394 bool DeducedTSTContext) {
11395 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11396 DeducedTSTContext);
11397 if (T.isNull())
11398 return QualType();
11399
11400 TypeLocBuilder TLB;
11401 if (isa<DependentNameType>(Val: T)) {
11402 auto TL = TLB.push<DependentNameTypeLoc>(T);
11403 TL.setElaboratedKeywordLoc(KeywordLoc);
11404 TL.setQualifierLoc(QualifierLoc);
11405 TL.setNameLoc(IILoc);
11406 } else if (isa<DeducedTemplateSpecializationType>(Val: T)) {
11407 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
11408 TL.setElaboratedKeywordLoc(KeywordLoc);
11409 TL.setQualifierLoc(QualifierLoc);
11410 TL.setNameLoc(IILoc);
11411 } else if (isa<TemplateTypeParmType>(Val: T)) {
11412 // FIXME: There might be a 'typename' keyword here, but we just drop it
11413 // as it can't be represented.
11414 assert(!QualifierLoc);
11415 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11416 } else if (isa<TagType>(Val: T)) {
11417 auto TL = TLB.push<TagTypeLoc>(T);
11418 TL.setElaboratedKeywordLoc(KeywordLoc);
11419 TL.setQualifierLoc(QualifierLoc);
11420 TL.setNameLoc(IILoc);
11421 } else if (isa<TypedefType>(Val: T)) {
11422 TLB.push<TypedefTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11423 } else {
11424 TLB.push<UnresolvedUsingTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11425 }
11426 *TSI = TLB.getTypeSourceInfo(Context, T);
11427 return T;
11428}
11429
11430/// Build the type that describes a C++ typename specifier,
11431/// e.g., "typename T::type".
11432QualType
11433Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11434 SourceLocation KeywordLoc,
11435 NestedNameSpecifierLoc QualifierLoc,
11436 const IdentifierInfo &II,
11437 SourceLocation IILoc, bool DeducedTSTContext) {
11438 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11439
11440 CXXScopeSpec SS;
11441 SS.Adopt(Other: QualifierLoc);
11442
11443 DeclContext *Ctx = nullptr;
11444 if (QualifierLoc) {
11445 Ctx = computeDeclContext(SS);
11446 if (!Ctx) {
11447 // If the nested-name-specifier is dependent and couldn't be
11448 // resolved to a type, build a typename type.
11449 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11450 return Context.getDependentNameType(Keyword,
11451 NNS: QualifierLoc.getNestedNameSpecifier(),
11452 Name: &II);
11453 }
11454
11455 // If the nested-name-specifier refers to the current instantiation,
11456 // the "typename" keyword itself is superfluous. In C++03, the
11457 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11458 // allows such extraneous "typename" keywords, and we retroactively
11459 // apply this DR to C++03 code with only a warning. In any case we continue.
11460
11461 if (RequireCompleteDeclContext(SS, DC: Ctx))
11462 return QualType();
11463 }
11464
11465 DeclarationName Name(&II);
11466 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11467 if (Ctx)
11468 LookupQualifiedName(R&: Result, LookupCtx: Ctx, SS);
11469 else
11470 LookupName(R&: Result, S: CurScope);
11471 unsigned DiagID = 0;
11472 Decl *Referenced = nullptr;
11473 switch (Result.getResultKind()) {
11474 case LookupResultKind::NotFound: {
11475 // If we're looking up 'type' within a template named 'enable_if', produce
11476 // a more specific diagnostic.
11477 SourceRange CondRange;
11478 Expr *Cond = nullptr;
11479 if (Ctx && isEnableIf(NNS: QualifierLoc, II, CondRange, Cond)) {
11480 // If we have a condition, narrow it down to the specific failed
11481 // condition.
11482 if (Cond) {
11483 Expr *FailedCond;
11484 std::string FailedDescription;
11485 std::tie(args&: FailedCond, args&: FailedDescription) =
11486 findFailedBooleanCondition(Cond);
11487
11488 Diag(Loc: FailedCond->getExprLoc(),
11489 DiagID: diag::err_typename_nested_not_found_requirement)
11490 << FailedDescription
11491 << FailedCond->getSourceRange();
11492 return QualType();
11493 }
11494
11495 Diag(Loc: CondRange.getBegin(),
11496 DiagID: diag::err_typename_nested_not_found_enable_if)
11497 << Ctx << CondRange;
11498 return QualType();
11499 }
11500
11501 DiagID = Ctx ? diag::err_typename_nested_not_found
11502 : diag::err_unknown_typename;
11503 break;
11504 }
11505
11506 case LookupResultKind::FoundUnresolvedValue: {
11507 // We found a using declaration that is a value. Most likely, the using
11508 // declaration itself is meant to have the 'typename' keyword.
11509 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11510 IILoc);
11511 Diag(Loc: IILoc, DiagID: diag::err_typename_refers_to_using_value_decl)
11512 << Name << Ctx << FullRange;
11513 if (UnresolvedUsingValueDecl *Using
11514 = dyn_cast<UnresolvedUsingValueDecl>(Val: Result.getRepresentativeDecl())){
11515 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11516 Diag(Loc, DiagID: diag::note_using_value_decl_missing_typename)
11517 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
11518 }
11519 }
11520 // Fall through to create a dependent typename type, from which we can
11521 // recover better.
11522 [[fallthrough]];
11523
11524 case LookupResultKind::NotFoundInCurrentInstantiation:
11525 // Okay, it's a member of an unknown instantiation.
11526 return Context.getDependentNameType(Keyword,
11527 NNS: QualifierLoc.getNestedNameSpecifier(),
11528 Name: &II);
11529
11530 case LookupResultKind::Found:
11531 // FXIME: Missing support for UsingShadowDecl on this path?
11532 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: Result.getFoundDecl())) {
11533 // C++ [class.qual]p2:
11534 // In a lookup in which function names are not ignored and the
11535 // nested-name-specifier nominates a class C, if the name specified
11536 // after the nested-name-specifier, when looked up in C, is the
11537 // injected-class-name of C [...] then the name is instead considered
11538 // to name the constructor of class C.
11539 //
11540 // Unlike in an elaborated-type-specifier, function names are not ignored
11541 // in typename-specifier lookup. However, they are ignored in all the
11542 // contexts where we form a typename type with no keyword (that is, in
11543 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11544 //
11545 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11546 // ignore functions, but that appears to be an oversight.
11547 checkTypeDeclType(LookupCtx: Ctx,
11548 DCK: Keyword == ElaboratedTypeKeyword::Typename
11549 ? DiagCtorKind::Typename
11550 : DiagCtorKind::None,
11551 TD: Type, NameLoc: IILoc);
11552 // FIXME: This appears to be the only case where a template type parameter
11553 // can have an elaborated keyword. We should preserve it somehow.
11554 if (isa<TemplateTypeParmDecl>(Val: Type)) {
11555 assert(Keyword == ElaboratedTypeKeyword::Typename);
11556 assert(!QualifierLoc);
11557 Keyword = ElaboratedTypeKeyword::None;
11558 }
11559 return Context.getTypeDeclType(
11560 Keyword, Qualifier: QualifierLoc.getNestedNameSpecifier(), Decl: Type);
11561 }
11562
11563 // C++ [dcl.type.simple]p2:
11564 // A type-specifier of the form
11565 // typename[opt] nested-name-specifier[opt] template-name
11566 // is a placeholder for a deduced class type [...].
11567 if (getLangOpts().CPlusPlus17) {
11568 if (auto *TD = getAsTypeTemplateDecl(D: Result.getFoundDecl())) {
11569 if (!DeducedTSTContext) {
11570 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11571 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11572 Diag(Loc: IILoc, DiagID: diag::err_dependent_deduced_tst)
11573 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
11574 << QualType(Qualifier.getAsType(), 0);
11575 else
11576 Diag(Loc: IILoc, DiagID: diag::err_deduced_tst)
11577 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD));
11578 NoteTemplateLocation(Decl: *TD);
11579 return QualType();
11580 }
11581 TemplateName Name = Context.getQualifiedTemplateName(
11582 Qualifier: QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11583 Template: TemplateName(TD));
11584 return Context.getDeducedTemplateSpecializationType(
11585 DK: DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11586 Template: Name);
11587 }
11588 }
11589
11590 DiagID = Ctx ? diag::err_typename_nested_not_type
11591 : diag::err_typename_not_type;
11592 Referenced = Result.getFoundDecl();
11593 break;
11594
11595 case LookupResultKind::FoundOverloaded:
11596 DiagID = Ctx ? diag::err_typename_nested_not_type
11597 : diag::err_typename_not_type;
11598 Referenced = *Result.begin();
11599 break;
11600
11601 case LookupResultKind::Ambiguous:
11602 return QualType();
11603 }
11604
11605 // If we get here, it's because name lookup did not find a
11606 // type. Emit an appropriate diagnostic and return an error.
11607 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11608 IILoc);
11609 if (Ctx)
11610 Diag(Loc: IILoc, DiagID) << FullRange << Name << Ctx;
11611 else
11612 Diag(Loc: IILoc, DiagID) << FullRange << Name;
11613 if (Referenced)
11614 Diag(Loc: Referenced->getLocation(),
11615 DiagID: Ctx ? diag::note_typename_member_refers_here
11616 : diag::note_typename_refers_here)
11617 << Name;
11618 return QualType();
11619}
11620
11621namespace {
11622 // See Sema::RebuildTypeInCurrentInstantiation
11623 class CurrentInstantiationRebuilder
11624 : public TreeTransform<CurrentInstantiationRebuilder> {
11625 SourceLocation Loc;
11626 DeclarationName Entity;
11627
11628 public:
11629 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11630
11631 CurrentInstantiationRebuilder(Sema &SemaRef,
11632 SourceLocation Loc,
11633 DeclarationName Entity)
11634 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11635 Loc(Loc), Entity(Entity) { }
11636
11637 /// Determine whether the given type \p T has already been
11638 /// transformed.
11639 ///
11640 /// For the purposes of type reconstruction, a type has already been
11641 /// transformed if it is NULL or if it is not dependent.
11642 bool AlreadyTransformed(QualType T) {
11643 return T.isNull() || !T->isInstantiationDependentType();
11644 }
11645
11646 /// Returns the location of the entity whose type is being
11647 /// rebuilt.
11648 SourceLocation getBaseLocation() { return Loc; }
11649
11650 /// Returns the name of the entity whose type is being rebuilt.
11651 DeclarationName getBaseEntity() { return Entity; }
11652
11653 /// Sets the "base" location and entity when that
11654 /// information is known based on another transformation.
11655 void setBase(SourceLocation Loc, DeclarationName Entity) {
11656 this->Loc = Loc;
11657 this->Entity = Entity;
11658 }
11659
11660 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11661 // Lambdas never need to be transformed.
11662 return E;
11663 }
11664 };
11665} // end anonymous namespace
11666
11667TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11668 SourceLocation Loc,
11669 DeclarationName Name) {
11670 if (!T || !T->getType()->isInstantiationDependentType())
11671 return T;
11672
11673 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11674 return Rebuilder.TransformType(TSI: T);
11675}
11676
11677ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11678 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11679 DeclarationName());
11680 return Rebuilder.TransformExpr(E);
11681}
11682
11683bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11684 if (SS.isInvalid())
11685 return true;
11686
11687 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11688 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11689 DeclarationName());
11690 NestedNameSpecifierLoc Rebuilt
11691 = Rebuilder.TransformNestedNameSpecifierLoc(NNS: QualifierLoc);
11692 if (!Rebuilt)
11693 return true;
11694
11695 SS.Adopt(Other: Rebuilt);
11696 return false;
11697}
11698
11699bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11700 TemplateParameterList *Params) {
11701 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11702 Decl *Param = Params->getParam(Idx: I);
11703
11704 // There is nothing to rebuild in a type parameter.
11705 if (isa<TemplateTypeParmDecl>(Val: Param))
11706 continue;
11707
11708 // Rebuild the template parameter list of a template template parameter.
11709 if (TemplateTemplateParmDecl *TTP
11710 = dyn_cast<TemplateTemplateParmDecl>(Val: Param)) {
11711 if (RebuildTemplateParamsInCurrentInstantiation(
11712 Params: TTP->getTemplateParameters()))
11713 return true;
11714
11715 continue;
11716 }
11717
11718 // Rebuild the type of a non-type template parameter.
11719 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Val: Param);
11720 TypeSourceInfo *NewTSI
11721 = RebuildTypeInCurrentInstantiation(T: NTTP->getTypeSourceInfo(),
11722 Loc: NTTP->getLocation(),
11723 Name: NTTP->getDeclName());
11724 if (!NewTSI)
11725 return true;
11726
11727 if (NewTSI->getType()->isUndeducedType()) {
11728 // C++17 [temp.dep.expr]p3:
11729 // An id-expression is type-dependent if it contains
11730 // - an identifier associated by name lookup with a non-type
11731 // template-parameter declared with a type that contains a
11732 // placeholder type (7.1.7.4),
11733 NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: NewTSI);
11734 }
11735
11736 if (NewTSI != NTTP->getTypeSourceInfo()) {
11737 NTTP->setTypeSourceInfo(NewTSI);
11738 NTTP->setType(NewTSI->getType());
11739 }
11740 }
11741
11742 return false;
11743}
11744
11745std::string
11746Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11747 const TemplateArgumentList &Args) {
11748 return getTemplateArgumentBindingsText(Params, Args: Args.data(), NumArgs: Args.size());
11749}
11750
11751std::string
11752Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11753 const TemplateArgument *Args,
11754 unsigned NumArgs) {
11755 SmallString<128> Str;
11756 llvm::raw_svector_ostream Out(Str);
11757
11758 if (!Params || Params->size() == 0 || NumArgs == 0)
11759 return std::string();
11760
11761 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11762 if (I >= NumArgs)
11763 break;
11764
11765 if (I == 0)
11766 Out << "[with ";
11767 else
11768 Out << ", ";
11769
11770 if (const IdentifierInfo *Id = Params->getParam(Idx: I)->getIdentifier()) {
11771 Out << Id->getName();
11772 } else {
11773 Out << '$' << I;
11774 }
11775
11776 Out << " = ";
11777 Args[I].print(Policy: getPrintingPolicy(), Out,
11778 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
11779 Policy: getPrintingPolicy(), TPL: Params, Idx: I));
11780 }
11781
11782 Out << ']';
11783 return std::string(Out.str());
11784}
11785
11786void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11787 CachedTokens &Toks) {
11788 if (!FD)
11789 return;
11790
11791 auto LPT = std::make_unique<LateParsedTemplate>();
11792
11793 // Take tokens to avoid allocations
11794 LPT->Toks.swap(RHS&: Toks);
11795 LPT->D = FnD;
11796 LPT->FPO = getCurFPFeatures();
11797 LateParsedTemplateMap.insert(KV: std::make_pair(x&: FD, y: std::move(LPT)));
11798
11799 FD->setLateTemplateParsed(true);
11800}
11801
11802void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11803 if (!FD)
11804 return;
11805 FD->setLateTemplateParsed(false);
11806}
11807
11808bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11809 DeclContext *DC = CurContext;
11810
11811 while (DC) {
11812 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
11813 const FunctionDecl *FD = RD->isLocalClass();
11814 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11815 } else if (DC->isTranslationUnit() || DC->isNamespace())
11816 return false;
11817
11818 DC = DC->getParent();
11819 }
11820 return false;
11821}
11822
11823namespace {
11824/// Walk the path from which a declaration was instantiated, and check
11825/// that every explicit specialization along that path is visible. This enforces
11826/// C++ [temp.expl.spec]/6:
11827///
11828/// If a template, a member template or a member of a class template is
11829/// explicitly specialized then that specialization shall be declared before
11830/// the first use of that specialization that would cause an implicit
11831/// instantiation to take place, in every translation unit in which such a
11832/// use occurs; no diagnostic is required.
11833///
11834/// and also C++ [temp.class.spec]/1:
11835///
11836/// A partial specialization shall be declared before the first use of a
11837/// class template specialization that would make use of the partial
11838/// specialization as the result of an implicit or explicit instantiation
11839/// in every translation unit in which such a use occurs; no diagnostic is
11840/// required.
11841class ExplicitSpecializationVisibilityChecker {
11842 Sema &S;
11843 SourceLocation Loc;
11844 llvm::SmallVector<Module *, 8> Modules;
11845 Sema::AcceptableKind Kind;
11846
11847public:
11848 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11849 Sema::AcceptableKind Kind)
11850 : S(S), Loc(Loc), Kind(Kind) {}
11851
11852 void check(NamedDecl *ND) {
11853 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
11854 return checkImpl(Spec: FD);
11855 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
11856 return checkImpl(Spec: RD);
11857 if (auto *VD = dyn_cast<VarDecl>(Val: ND))
11858 return checkImpl(Spec: VD);
11859 if (auto *ED = dyn_cast<EnumDecl>(Val: ND))
11860 return checkImpl(Spec: ED);
11861 }
11862
11863private:
11864 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11865 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11866 : Sema::MissingImportKind::ExplicitSpecialization;
11867 const bool Recover = true;
11868
11869 // If we got a custom set of modules (because only a subset of the
11870 // declarations are interesting), use them, otherwise let
11871 // diagnoseMissingImport intelligently pick some.
11872 if (Modules.empty())
11873 S.diagnoseMissingImport(Loc, Decl: D, MIK: Kind, Recover);
11874 else
11875 S.diagnoseMissingImport(Loc, Decl: D, DeclLoc: D->getLocation(), Modules, MIK: Kind, Recover);
11876 }
11877
11878 bool CheckMemberSpecialization(const NamedDecl *D) {
11879 return Kind == Sema::AcceptableKind::Visible
11880 ? S.hasVisibleMemberSpecialization(D)
11881 : S.hasReachableMemberSpecialization(D);
11882 }
11883
11884 bool CheckExplicitSpecialization(const NamedDecl *D) {
11885 return Kind == Sema::AcceptableKind::Visible
11886 ? S.hasVisibleExplicitSpecialization(D)
11887 : S.hasReachableExplicitSpecialization(D);
11888 }
11889
11890 bool CheckDeclaration(const NamedDecl *D) {
11891 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11892 : S.hasReachableDeclaration(D);
11893 }
11894
11895 // Check a specific declaration. There are three problematic cases:
11896 //
11897 // 1) The declaration is an explicit specialization of a template
11898 // specialization.
11899 // 2) The declaration is an explicit specialization of a member of an
11900 // templated class.
11901 // 3) The declaration is an instantiation of a template, and that template
11902 // is an explicit specialization of a member of a templated class.
11903 //
11904 // We don't need to go any deeper than that, as the instantiation of the
11905 // surrounding class / etc is not triggered by whatever triggered this
11906 // instantiation, and thus should be checked elsewhere.
11907 template<typename SpecDecl>
11908 void checkImpl(SpecDecl *Spec) {
11909 bool IsHiddenExplicitSpecialization = false;
11910 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11911 // Some invalid friend declarations are written as specializations but are
11912 // instantiated implicitly.
11913 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11914 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11915 if (SpecKind == TSK_ExplicitSpecialization) {
11916 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11917 ? !CheckMemberSpecialization(D: Spec)
11918 : !CheckExplicitSpecialization(D: Spec);
11919 } else {
11920 checkInstantiated(Spec);
11921 }
11922
11923 if (IsHiddenExplicitSpecialization)
11924 diagnose(D: Spec->getMostRecentDecl(), IsPartialSpec: false);
11925 }
11926
11927 void checkInstantiated(FunctionDecl *FD) {
11928 if (auto *TD = FD->getPrimaryTemplate())
11929 checkTemplate(TD);
11930 }
11931
11932 void checkInstantiated(CXXRecordDecl *RD) {
11933 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD);
11934 if (!SD)
11935 return;
11936
11937 auto From = SD->getSpecializedTemplateOrPartial();
11938 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11939 checkTemplate(TD);
11940 else if (auto *TD =
11941 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11942 if (!CheckDeclaration(D: TD))
11943 diagnose(D: TD, IsPartialSpec: true);
11944 checkTemplate(TD);
11945 }
11946 }
11947
11948 void checkInstantiated(VarDecl *RD) {
11949 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(Val: RD);
11950 if (!SD)
11951 return;
11952
11953 auto From = SD->getSpecializedTemplateOrPartial();
11954 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11955 checkTemplate(TD);
11956 else if (auto *TD =
11957 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11958 if (!CheckDeclaration(D: TD))
11959 diagnose(D: TD, IsPartialSpec: true);
11960 checkTemplate(TD);
11961 }
11962 }
11963
11964 void checkInstantiated(EnumDecl *FD) {}
11965
11966 template<typename TemplDecl>
11967 void checkTemplate(TemplDecl *TD) {
11968 if (TD->isMemberSpecialization()) {
11969 if (!CheckMemberSpecialization(D: TD))
11970 diagnose(D: TD->getMostRecentDecl(), IsPartialSpec: false);
11971 }
11972 }
11973};
11974} // end anonymous namespace
11975
11976void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
11977 if (!getLangOpts().Modules)
11978 return;
11979
11980 ExplicitSpecializationVisibilityChecker(*this, Loc,
11981 Sema::AcceptableKind::Visible)
11982 .check(ND: Spec);
11983}
11984
11985void Sema::checkSpecializationReachability(SourceLocation Loc,
11986 NamedDecl *Spec) {
11987 if (!getLangOpts().CPlusPlusModules)
11988 return checkSpecializationVisibility(Loc, Spec);
11989
11990 ExplicitSpecializationVisibilityChecker(*this, Loc,
11991 Sema::AcceptableKind::Reachable)
11992 .check(ND: Spec);
11993}
11994
11995SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
11996 if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
11997 return N->getLocation();
11998 if (const auto *FD = dyn_cast<FunctionDecl>(Val: N)) {
11999 if (!FD->isFunctionTemplateSpecialization())
12000 return FD->getLocation();
12001 } else if (!isa<ClassTemplateSpecializationDecl,
12002 VarTemplateSpecializationDecl>(Val: N)) {
12003 return N->getLocation();
12004 }
12005 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
12006 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
12007 continue;
12008 return CSC.PointOfInstantiation;
12009 }
12010 return N->getLocation();
12011}
12012