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/Mangle.h"
23#include "clang/AST/TemplateName.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeOrdering.h"
26#include "clang/AST/TypeVisitor.h"
27#include "clang/Basic/Builtins.h"
28#include "clang/Basic/DiagnosticSema.h"
29#include "clang/Basic/LangOptions.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/SourceLocation.h"
32#include "clang/Basic/TargetInfo.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/EnterExpressionEvaluationContext.h"
35#include "clang/Sema/Initialization.h"
36#include "clang/Sema/Lookup.h"
37#include "clang/Sema/Overload.h"
38#include "clang/Sema/ParsedTemplate.h"
39#include "clang/Sema/Scope.h"
40#include "clang/Sema/SemaCUDA.h"
41#include "clang/Sema/SemaInternal.h"
42#include "clang/Sema/Template.h"
43#include "clang/Sema/TemplateDeduction.h"
44#include "llvm/ADT/STLExtras.h"
45#include "llvm/ADT/SmallBitVector.h"
46#include "llvm/ADT/StringExtras.h"
47#include "llvm/Support/Casting.h"
48#include "llvm/Support/SaveAndRestore.h"
49
50#include <optional>
51using namespace clang;
52using namespace sema;
53
54// Exported for use by Parser.
55SourceRange
56clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
57 unsigned N) {
58 if (!N) return SourceRange();
59 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
60}
61
62unsigned Sema::getTemplateDepth(Scope *S) const {
63 unsigned Depth = 0;
64
65 // Each template parameter scope represents one level of template parameter
66 // depth.
67 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
68 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
69 ++Depth;
70 }
71
72 // Note that there are template parameters with the given depth.
73 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(a: Depth, b: D + 1); };
74
75 // Look for parameters of an enclosing generic lambda. We don't create a
76 // template parameter scope for these.
77 for (FunctionScopeInfo *FSI : getFunctionScopes()) {
78 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FSI)) {
79 if (!LSI->TemplateParams.empty()) {
80 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
81 break;
82 }
83 if (LSI->GLTemplateParameterList) {
84 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
85 break;
86 }
87 }
88 }
89
90 // Look for parameters of an enclosing terse function template. We don't
91 // create a template parameter scope for these either.
92 for (const InventedTemplateParameterInfo &Info :
93 getInventedParameterInfos()) {
94 if (!Info.TemplateParams.empty()) {
95 ParamsAtDepth(Info.AutoTemplateParameterDepth);
96 break;
97 }
98 }
99
100 return Depth;
101}
102
103/// \brief Determine whether the declaration found is acceptable as the name
104/// of a template and, if so, return that template declaration. Otherwise,
105/// returns null.
106///
107/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
108/// is true. In all other cases it will return a TemplateDecl (or null).
109NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
110 bool AllowFunctionTemplates,
111 bool AllowDependent) {
112 D = D->getUnderlyingDecl();
113
114 if (isa<TemplateDecl>(Val: D)) {
115 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(Val: D))
116 return nullptr;
117
118 return D;
119 }
120
121 if (const auto *Record = dyn_cast<CXXRecordDecl>(Val: D)) {
122 // C++ [temp.local]p1:
123 // Like normal (non-template) classes, class templates have an
124 // injected-class-name (Clause 9). The injected-class-name
125 // can be used with or without a template-argument-list. When
126 // it is used without a template-argument-list, it is
127 // equivalent to the injected-class-name followed by the
128 // template-parameters of the class template enclosed in
129 // <>. When it is used with a template-argument-list, it
130 // refers to the specified class template specialization,
131 // which could be the current specialization or another
132 // specialization.
133 if (Record->isInjectedClassName()) {
134 Record = cast<CXXRecordDecl>(Val: Record->getDeclContext());
135 if (Record->getDescribedClassTemplate())
136 return Record->getDescribedClassTemplate();
137
138 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record))
139 return Spec->getSpecializedTemplate();
140 }
141
142 return nullptr;
143 }
144
145 // 'using Dependent::foo;' can resolve to a template name.
146 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
147 // injected-class-name).
148 if (AllowDependent && isa<UnresolvedUsingValueDecl>(Val: D))
149 return D;
150
151 return nullptr;
152}
153
154void Sema::FilterAcceptableTemplateNames(LookupResult &R,
155 bool AllowFunctionTemplates,
156 bool AllowDependent) {
157 LookupResult::Filter filter = R.makeFilter();
158 while (filter.hasNext()) {
159 NamedDecl *Orig = filter.next();
160 if (!getAsTemplateNameDecl(D: Orig, AllowFunctionTemplates, AllowDependent))
161 filter.erase();
162 }
163 filter.done();
164}
165
166bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
167 bool AllowFunctionTemplates,
168 bool AllowDependent,
169 bool AllowNonTemplateFunctions) {
170 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
171 if (getAsTemplateNameDecl(D: *I, AllowFunctionTemplates, AllowDependent))
172 return true;
173 if (AllowNonTemplateFunctions &&
174 isa<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
175 return true;
176 }
177
178 return false;
179}
180
181TemplateNameKind
182Sema::isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword,
183 const UnqualifiedId &Name, ParsedType ObjectTypePtr,
184 bool EnteringContext, TemplateTy &TemplateResult,
185 bool &MemberOfUnknownSpecialization,
186 bool AllowTypoCorrection) {
187 assert(getLangOpts().CPlusPlus && "No template names in C!");
188
189 DeclarationName TName;
190 MemberOfUnknownSpecialization = false;
191
192 switch (Name.getKind()) {
193 case UnqualifiedIdKind::IK_Identifier:
194 TName = DeclarationName(Name.Identifier);
195 break;
196
197 case UnqualifiedIdKind::IK_OperatorFunctionId:
198 TName = Context.DeclarationNames.getCXXOperatorName(
199 Op: Name.OperatorFunctionId.Operator);
200 break;
201
202 case UnqualifiedIdKind::IK_LiteralOperatorId:
203 TName = Context.DeclarationNames.getCXXLiteralOperatorName(II: Name.Identifier);
204 break;
205
206 default:
207 return TNK_Non_template;
208 }
209
210 QualType ObjectType = ObjectTypePtr.get();
211
212 AssumedTemplateKind AssumedTemplate;
213 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
214 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
215 /*RequiredTemplate=*/SourceLocation(),
216 ATK: &AssumedTemplate, AllowTypoCorrection))
217 return TNK_Non_template;
218 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
219
220 if (AssumedTemplate != AssumedTemplateKind::None) {
221 TemplateResult = TemplateTy::make(P: Context.getAssumedTemplateName(Name: TName));
222 // Let the parser know whether we found nothing or found functions; if we
223 // found nothing, we want to more carefully check whether this is actually
224 // a function template name versus some other kind of undeclared identifier.
225 return AssumedTemplate == AssumedTemplateKind::FoundNothing
226 ? TNK_Undeclared_template
227 : TNK_Function_template;
228 }
229
230 if (R.empty())
231 return TNK_Non_template;
232
233 NamedDecl *D = nullptr;
234 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *R.begin());
235 if (R.isAmbiguous()) {
236 // If we got an ambiguity involving a non-function template, treat this
237 // as a template name, and pick an arbitrary template for error recovery.
238 bool AnyFunctionTemplates = false;
239 for (NamedDecl *FoundD : R) {
240 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(D: FoundD)) {
241 if (isa<FunctionTemplateDecl>(Val: FoundTemplate))
242 AnyFunctionTemplates = true;
243 else {
244 D = FoundTemplate;
245 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: FoundD);
246 break;
247 }
248 }
249 }
250
251 // If we didn't find any templates at all, this isn't a template name.
252 // Leave the ambiguity for a later lookup to diagnose.
253 if (!D && !AnyFunctionTemplates) {
254 R.suppressDiagnostics();
255 return TNK_Non_template;
256 }
257
258 // If the only templates were function templates, filter out the rest.
259 // We'll diagnose the ambiguity later.
260 if (!D)
261 FilterAcceptableTemplateNames(R);
262 }
263
264 // At this point, we have either picked a single template name declaration D
265 // or we have a non-empty set of results R containing either one template name
266 // declaration or a set of function templates.
267
268 TemplateName Template;
269 TemplateNameKind TemplateKind;
270
271 unsigned ResultCount = R.end() - R.begin();
272 if (!D && ResultCount > 1) {
273 // We assume that we'll preserve the qualifier from a function
274 // template name in other ways.
275 Template = Context.getOverloadedTemplateName(Begin: R.begin(), End: R.end());
276 TemplateKind = TNK_Function_template;
277
278 // We'll do this lookup again later.
279 R.suppressDiagnostics();
280 } else {
281 if (!D) {
282 D = getAsTemplateNameDecl(D: *R.begin());
283 assert(D && "unambiguous result is not a template name");
284 }
285
286 if (isa<UnresolvedUsingValueDecl>(Val: D)) {
287 // We don't yet know whether this is a template-name or not.
288 MemberOfUnknownSpecialization = true;
289 return TNK_Non_template;
290 }
291
292 TemplateDecl *TD = cast<TemplateDecl>(Val: D);
293 Template =
294 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
295 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
296 if (!SS.isInvalid()) {
297 NestedNameSpecifier Qualifier = SS.getScopeRep();
298 Template = Context.getQualifiedTemplateName(Qualifier, TemplateKeyword: hasTemplateKeyword,
299 Template);
300 }
301
302 if (isa<FunctionTemplateDecl>(Val: TD)) {
303 TemplateKind = TNK_Function_template;
304
305 // We'll do this lookup again later.
306 R.suppressDiagnostics();
307 } else {
308 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
309 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
310 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
311 TemplateKind =
312 isa<TemplateTemplateParmDecl>(Val: TD)
313 ? dyn_cast<TemplateTemplateParmDecl>(Val: TD)->templateParameterKind()
314 : isa<VarTemplateDecl>(Val: TD) ? TNK_Var_template
315 : isa<ConceptDecl>(Val: TD) ? TNK_Concept_template
316 : TNK_Type_template;
317 }
318 }
319
320 if (isPackProducingBuiltinTemplateName(N: Template) && S &&
321 S->getTemplateParamParent() == nullptr)
322 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_builtin_pack_outside_template) << TName;
323 // Recover by returning the template, even though we would never be able to
324 // substitute it.
325
326 TemplateResult = TemplateTy::make(P: Template);
327 return TemplateKind;
328}
329
330bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
331 SourceLocation NameLoc, CXXScopeSpec &SS,
332 ParsedTemplateTy *Template /*=nullptr*/) {
333 // We could use redeclaration lookup here, but we don't need to: the
334 // syntactic form of a deduction guide is enough to identify it even
335 // if we can't look up the template name at all.
336 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
337 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
338 /*EnteringContext*/ false))
339 return false;
340
341 if (R.empty()) return false;
342 if (R.isAmbiguous()) {
343 // FIXME: Diagnose an ambiguity if we find at least one template.
344 R.suppressDiagnostics();
345 return false;
346 }
347
348 // We only treat template-names that name type templates as valid deduction
349 // guide names.
350 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
351 if (!TD || !getAsTypeTemplateDecl(D: TD))
352 return false;
353
354 if (Template) {
355 TemplateName Name = Context.getQualifiedTemplateName(
356 Qualifier: SS.getScopeRep(), /*TemplateKeyword=*/false, Template: TemplateName(TD));
357 *Template = TemplateTy::make(P: Name);
358 }
359 return true;
360}
361
362bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
363 SourceLocation IILoc,
364 Scope *S,
365 const CXXScopeSpec *SS,
366 TemplateTy &SuggestedTemplate,
367 TemplateNameKind &SuggestedKind) {
368 // We can't recover unless there's a dependent scope specifier preceding the
369 // template name.
370 // FIXME: Typo correction?
371 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(SS: *SS) ||
372 computeDeclContext(SS: *SS))
373 return false;
374
375 // The code is missing a 'template' keyword prior to the dependent template
376 // name.
377 SuggestedTemplate = TemplateTy::make(P: Context.getDependentTemplateName(
378 Name: {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
379 Diag(Loc: IILoc, DiagID: diag::err_template_kw_missing)
380 << SuggestedTemplate.get()
381 << FixItHint::CreateInsertion(InsertionLoc: IILoc, Code: "template ");
382 SuggestedKind = TNK_Dependent_template_name;
383 return true;
384}
385
386bool Sema::LookupTemplateName(LookupResult &Found, Scope *S, CXXScopeSpec &SS,
387 QualType ObjectType, bool EnteringContext,
388 RequiredTemplateKind RequiredTemplate,
389 AssumedTemplateKind *ATK,
390 bool AllowTypoCorrection) {
391 if (ATK)
392 *ATK = AssumedTemplateKind::None;
393
394 if (SS.isInvalid())
395 return true;
396
397 Found.setTemplateNameLookup(true);
398
399 // Determine where to perform name lookup
400 DeclContext *LookupCtx = nullptr;
401 bool IsDependent = false;
402 if (!ObjectType.isNull()) {
403 // This nested-name-specifier occurs in a member access expression, e.g.,
404 // x->B::f, and we are looking into the type of the object.
405 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
406 LookupCtx = computeDeclContext(T: ObjectType);
407 IsDependent = !LookupCtx && ObjectType->isDependentType();
408 assert((IsDependent || !ObjectType->isIncompleteType() ||
409 !ObjectType->getAs<TagType>() ||
410 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&
411 "Caller should have completed object type");
412
413 // Template names cannot appear inside an Objective-C class or object type
414 // or a vector type.
415 //
416 // FIXME: This is wrong. For example:
417 //
418 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
419 // Vec<int> vi;
420 // vi.Vec<int>::~Vec<int>();
421 //
422 // ... should be accepted but we will not treat 'Vec' as a template name
423 // here. The right thing to do would be to check if the name is a valid
424 // vector component name, and look up a template name if not. And similarly
425 // for lookups into Objective-C class and object types, where the same
426 // problem can arise.
427 if (ObjectType->isObjCObjectOrInterfaceType() ||
428 ObjectType->isVectorType()) {
429 Found.clear();
430 return false;
431 }
432 } else if (SS.isNotEmpty()) {
433 // This nested-name-specifier occurs after another nested-name-specifier,
434 // so long into the context associated with the prior nested-name-specifier.
435 LookupCtx = computeDeclContext(SS, EnteringContext);
436 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
437
438 // The declaration context must be complete.
439 if (LookupCtx && RequireCompleteDeclContext(SS, DC: LookupCtx))
440 return true;
441 }
442
443 bool ObjectTypeSearchedInScope = false;
444 bool AllowFunctionTemplatesInLookup = true;
445 if (LookupCtx) {
446 // Perform "qualified" name lookup into the declaration context we
447 // computed, which is either the type of the base of a member access
448 // expression or the declaration context associated with a prior
449 // nested-name-specifier.
450 LookupQualifiedName(R&: Found, LookupCtx);
451
452 // FIXME: The C++ standard does not clearly specify what happens in the
453 // case where the object type is dependent, and implementations vary. In
454 // Clang, we treat a name after a . or -> as a template-name if lookup
455 // finds a non-dependent member or member of the current instantiation that
456 // is a type template, or finds no such members and lookup in the context
457 // of the postfix-expression finds a type template. In the latter case, the
458 // name is nonetheless dependent, and we may resolve it to a member of an
459 // unknown specialization when we come to instantiate the template.
460 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
461 }
462
463 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
464 // C++ [basic.lookup.classref]p1:
465 // In a class member access expression (5.2.5), if the . or -> token is
466 // immediately followed by an identifier followed by a <, the
467 // identifier must be looked up to determine whether the < is the
468 // beginning of a template argument list (14.2) or a less-than operator.
469 // The identifier is first looked up in the class of the object
470 // expression. If the identifier is not found, it is then looked up in
471 // the context of the entire postfix-expression and shall name a class
472 // template.
473 if (S)
474 LookupName(R&: Found, S);
475
476 if (!ObjectType.isNull()) {
477 // FIXME: We should filter out all non-type templates here, particularly
478 // variable templates and concepts. But the exclusion of alias templates
479 // and template template parameters is a wording defect.
480 AllowFunctionTemplatesInLookup = false;
481 ObjectTypeSearchedInScope = true;
482 }
483
484 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
485 }
486
487 if (Found.isAmbiguous())
488 return false;
489
490 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
491 !RequiredTemplate.hasTemplateKeyword()) {
492 // C++2a [temp.names]p2:
493 // A name is also considered to refer to a template if it is an
494 // unqualified-id followed by a < and name lookup finds either one or more
495 // functions or finds nothing.
496 //
497 // To keep our behavior consistent, we apply the "finds nothing" part in
498 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
499 // successfully form a call to an undeclared template-id.
500 bool AllFunctions =
501 getLangOpts().CPlusPlus20 && llvm::all_of(Range&: Found, P: [](NamedDecl *ND) {
502 return isa<FunctionDecl>(Val: ND->getUnderlyingDecl());
503 });
504 if (AllFunctions || (Found.empty() && !IsDependent)) {
505 // If lookup found any functions, or if this is a name that can only be
506 // used for a function, then strongly assume this is a function
507 // template-id.
508 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
509 ? AssumedTemplateKind::FoundNothing
510 : AssumedTemplateKind::FoundFunctions;
511 Found.clear();
512 return false;
513 }
514 }
515
516 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
517 // If we did not find any names, and this is not a disambiguation, attempt
518 // to correct any typos.
519 DeclarationName Name = Found.getLookupName();
520 Found.clear();
521
522 class TemplateNameLookupValidatorCCC final
523 : public QualifiedLookupValidatorCCC {
524 public:
525 using QualifiedLookupValidatorCCC::QualifiedLookupValidatorCCC;
526
527 bool ValidateCandidate(const TypoCorrection &Candidate) final {
528 if (const NamedDecl *ND = Candidate.getCorrectionDecl();
529 !ND || !isa<TemplateDecl>(Val: ND))
530 return false;
531 return QualifiedLookupValidatorCCC::ValidateCandidate(Candidate);
532 }
533
534 std::unique_ptr<CorrectionCandidateCallback> clone() final {
535 return std::make_unique<TemplateNameLookupValidatorCCC>(args&: *this);
536 }
537 };
538
539 TemplateNameLookupValidatorCCC FilterCCC(!SS.isEmpty());
540 FilterCCC.WantTypeSpecifiers = false;
541 FilterCCC.WantExpressionKeywords = false;
542 FilterCCC.WantRemainingKeywords = false;
543 FilterCCC.WantCXXNamedCasts = true;
544 if (TypoCorrection Corrected = CorrectTypo(
545 Typo: Found.getLookupNameInfo(), LookupKind: Found.getLookupKind(), S, SS: &SS, CCC&: FilterCCC,
546 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
547 if (auto *ND = Corrected.getFoundDecl())
548 Found.addDecl(D: ND);
549 FilterAcceptableTemplateNames(R&: Found);
550 if (Found.isAmbiguous()) {
551 Found.clear();
552 } else if (!Found.empty()) {
553 // Do not erase the typo-corrected result to avoid duplicated
554 // diagnostics.
555 AllowFunctionTemplatesInLookup = true;
556 Found.setLookupName(Corrected.getCorrection());
557 if (LookupCtx) {
558 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
559 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
560 Name.getAsString() == CorrectedStr;
561 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_template_suggest)
562 << Name << LookupCtx << DroppedSpecifier
563 << SS.getRange());
564 } else {
565 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_template_suggest) << Name);
566 }
567
568 if (Corrected.WillReplaceSpecifier()) {
569 NestedNameSpecifier NNS = Corrected.getCorrectionSpecifier();
570 // In order to be valid, a non-empty CXXScopeSpec needs a source
571 // range.
572 SS.MakeTrivial(Context, Qualifier: NNS,
573 R: NNS ? Found.getNameLoc() : SourceRange());
574 }
575 }
576 }
577 }
578
579 NamedDecl *ExampleLookupResult =
580 Found.empty() ? nullptr : Found.getRepresentativeDecl();
581 FilterAcceptableTemplateNames(R&: Found, AllowFunctionTemplates: AllowFunctionTemplatesInLookup);
582 if (Found.empty()) {
583 if (IsDependent) {
584 Found.setNotFoundInCurrentInstantiation();
585 return false;
586 }
587
588 // If a 'template' keyword was used, a lookup that finds only non-template
589 // names is an error.
590 if (ExampleLookupResult && RequiredTemplate) {
591 Diag(Loc: Found.getNameLoc(), DiagID: diag::err_template_kw_refers_to_non_template)
592 << Found.getLookupName() << SS.getRange()
593 << RequiredTemplate.hasTemplateKeyword()
594 << RequiredTemplate.getTemplateKeywordLoc();
595 Diag(Loc: ExampleLookupResult->getUnderlyingDecl()->getLocation(),
596 DiagID: diag::note_template_kw_refers_to_non_template)
597 << Found.getLookupName();
598 return true;
599 }
600
601 return false;
602 }
603
604 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
605 !getLangOpts().CPlusPlus11) {
606 // C++03 [basic.lookup.classref]p1:
607 // [...] If the lookup in the class of the object expression finds a
608 // template, the name is also looked up in the context of the entire
609 // postfix-expression and [...]
610 //
611 // Note: C++11 does not perform this second lookup.
612 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
613 LookupOrdinaryName);
614 FoundOuter.setTemplateNameLookup(true);
615 LookupName(R&: FoundOuter, S);
616 // FIXME: We silently accept an ambiguous lookup here, in violation of
617 // [basic.lookup]/1.
618 FilterAcceptableTemplateNames(R&: FoundOuter, /*AllowFunctionTemplates=*/false);
619
620 NamedDecl *OuterTemplate;
621 if (FoundOuter.empty()) {
622 // - if the name is not found, the name found in the class of the
623 // object expression is used, otherwise
624 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
625 !(OuterTemplate =
626 getAsTemplateNameDecl(D: FoundOuter.getFoundDecl()))) {
627 // - if the name is found in the context of the entire
628 // postfix-expression and does not name a class template, the name
629 // found in the class of the object expression is used, otherwise
630 FoundOuter.clear();
631 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
632 // - if the name found is a class template, it must refer to the same
633 // entity as the one found in the class of the object expression,
634 // otherwise the program is ill-formed.
635 if (!Found.isSingleResult() ||
636 getAsTemplateNameDecl(D: Found.getFoundDecl())->getCanonicalDecl() !=
637 OuterTemplate->getCanonicalDecl()) {
638 Diag(Loc: Found.getNameLoc(),
639 DiagID: diag::ext_nested_name_member_ref_lookup_ambiguous)
640 << Found.getLookupName()
641 << ObjectType;
642 Diag(Loc: Found.getRepresentativeDecl()->getLocation(),
643 DiagID: diag::note_ambig_member_ref_object_type)
644 << ObjectType;
645 Diag(Loc: FoundOuter.getFoundDecl()->getLocation(),
646 DiagID: diag::note_ambig_member_ref_scope);
647
648 // Recover by taking the template that we found in the object
649 // expression's type.
650 }
651 }
652 }
653
654 return false;
655}
656
657void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
658 SourceLocation Less,
659 SourceLocation Greater) {
660 if (TemplateName.isInvalid())
661 return;
662
663 DeclarationNameInfo NameInfo;
664 CXXScopeSpec SS;
665 LookupNameKind LookupKind;
666
667 DeclContext *LookupCtx = nullptr;
668 NamedDecl *Found = nullptr;
669 bool MissingTemplateKeyword = false;
670
671 // Figure out what name we looked up.
672 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: TemplateName.get())) {
673 NameInfo = DRE->getNameInfo();
674 SS.Adopt(Other: DRE->getQualifierLoc());
675 LookupKind = LookupOrdinaryName;
676 Found = DRE->getFoundDecl();
677 } else if (auto *ME = dyn_cast<MemberExpr>(Val: TemplateName.get())) {
678 NameInfo = ME->getMemberNameInfo();
679 SS.Adopt(Other: ME->getQualifierLoc());
680 LookupKind = LookupMemberName;
681 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
682 Found = ME->getMemberDecl();
683 } else if (auto *DSDRE =
684 dyn_cast<DependentScopeDeclRefExpr>(Val: TemplateName.get())) {
685 NameInfo = DSDRE->getNameInfo();
686 SS.Adopt(Other: DSDRE->getQualifierLoc());
687 MissingTemplateKeyword = true;
688 } else if (auto *DSME =
689 dyn_cast<CXXDependentScopeMemberExpr>(Val: TemplateName.get())) {
690 NameInfo = DSME->getMemberNameInfo();
691 SS.Adopt(Other: DSME->getQualifierLoc());
692 MissingTemplateKeyword = true;
693 } else {
694 llvm_unreachable("unexpected kind of potential template name");
695 }
696
697 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
698 // was missing.
699 if (MissingTemplateKeyword) {
700 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_template_kw_missing)
701 << NameInfo.getName() << SourceRange(Less, Greater);
702 return;
703 }
704
705 // Try to correct the name by looking for templates and C++ named casts.
706 struct TemplateCandidateFilter : CorrectionCandidateCallback {
707 Sema &S;
708 TemplateCandidateFilter(Sema &S) : S(S) {
709 WantTypeSpecifiers = false;
710 WantExpressionKeywords = false;
711 WantRemainingKeywords = false;
712 WantCXXNamedCasts = true;
713 };
714 bool ValidateCandidate(const TypoCorrection &Candidate) override {
715 if (auto *ND = Candidate.getCorrectionDecl())
716 return S.getAsTemplateNameDecl(D: ND);
717 return Candidate.isKeyword();
718 }
719
720 std::unique_ptr<CorrectionCandidateCallback> clone() override {
721 return std::make_unique<TemplateCandidateFilter>(args&: *this);
722 }
723 };
724
725 DeclarationName Name = NameInfo.getName();
726 TemplateCandidateFilter CCC(*this);
727 if (TypoCorrection Corrected =
728 CorrectTypo(Typo: NameInfo, LookupKind, S, SS: &SS, CCC,
729 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
730 auto *ND = Corrected.getFoundDecl();
731 if (ND)
732 ND = getAsTemplateNameDecl(D: ND);
733 if (ND || Corrected.isKeyword()) {
734 if (LookupCtx) {
735 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
736 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
737 Name.getAsString() == CorrectedStr;
738 diagnoseTypo(Correction: Corrected,
739 TypoDiag: PDiag(DiagID: diag::err_non_template_in_member_template_id_suggest)
740 << Name << LookupCtx << DroppedSpecifier
741 << SS.getRange(), ErrorRecovery: false);
742 } else {
743 diagnoseTypo(Correction: Corrected,
744 TypoDiag: PDiag(DiagID: diag::err_non_template_in_template_id_suggest)
745 << Name, ErrorRecovery: false);
746 }
747 if (Found)
748 Diag(Loc: Found->getLocation(),
749 DiagID: diag::note_non_template_in_template_id_found);
750 return;
751 }
752 }
753
754 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_non_template_in_template_id)
755 << Name << SourceRange(Less, Greater);
756 if (Found)
757 Diag(Loc: Found->getLocation(), DiagID: diag::note_non_template_in_template_id_found);
758}
759
760ExprResult
761Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
762 SourceLocation TemplateKWLoc,
763 const DeclarationNameInfo &NameInfo,
764 bool isAddressOfOperand,
765 const TemplateArgumentListInfo *TemplateArgs) {
766 if (SS.isEmpty()) {
767 // FIXME: This codepath is only used by dependent unqualified names
768 // (e.g. a dependent conversion-function-id, or operator= once we support
769 // it). It doesn't quite do the right thing, and it will silently fail if
770 // getCurrentThisType() returns null.
771 QualType ThisType = getCurrentThisType();
772 if (ThisType.isNull())
773 return ExprError();
774
775 return CXXDependentScopeMemberExpr::Create(
776 Ctx: Context, /*Base=*/nullptr, BaseType: ThisType,
777 /*IsArrow=*/!Context.getLangOpts().HLSL,
778 /*OperatorLoc=*/SourceLocation(),
779 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
780 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
781 }
782 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
783}
784
785ExprResult
786Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
787 SourceLocation TemplateKWLoc,
788 const DeclarationNameInfo &NameInfo,
789 const TemplateArgumentListInfo *TemplateArgs) {
790 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
791 if (!SS.isValid())
792 return CreateRecoveryExpr(
793 Begin: SS.getBeginLoc(),
794 End: TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), SubExprs: {});
795
796 return DependentScopeDeclRefExpr::Create(
797 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
798 TemplateArgs);
799}
800
801ExprResult
802Sema::BuildSubstNonTypeTemplateParmExpr(Decl *AssociatedDecl, unsigned Index,
803 QualType ParamType, SourceLocation Loc,
804 TemplateArgument Arg,
805 UnsignedOrNone PackIndex, bool Final) {
806 // The template argument itself might be an expression, in which case we just
807 // return that expression. This happens when substituting into an alias
808 // template.
809 Expr *Replacement;
810 if (Arg.getKind() == TemplateArgument::Expression) {
811 Replacement = Arg.getAsExpr();
812 } else {
813 ExprResult result =
814 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
815 if (result.isInvalid())
816 return ExprError();
817 Replacement = result.get();
818 }
819 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
820 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
821 AssociatedDecl, ParamType, Index, PackIndex, Final);
822}
823
824bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
825 NamedDecl *Instantiation,
826 bool InstantiatedFromMember,
827 const NamedDecl *Pattern,
828 const NamedDecl *PatternDef,
829 TemplateSpecializationKind TSK,
830 bool Complain, bool *Unreachable) {
831 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
832 isa<VarDecl>(Instantiation));
833
834 bool IsEntityBeingDefined = false;
835 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(Val: PatternDef))
836 IsEntityBeingDefined = TD->isBeingDefined();
837
838 if (PatternDef && !IsEntityBeingDefined) {
839 NamedDecl *SuggestedDef = nullptr;
840 if (!hasReachableDefinition(D: const_cast<NamedDecl *>(PatternDef),
841 Suggested: &SuggestedDef,
842 /*OnlyNeedComplete*/ false)) {
843 if (Unreachable)
844 *Unreachable = true;
845 // If we're allowed to diagnose this and recover, do so.
846 bool Recover = Complain && !isSFINAEContext();
847 if (Complain)
848 diagnoseMissingImport(Loc: PointOfInstantiation, Decl: SuggestedDef,
849 MIK: Sema::MissingImportKind::Definition, Recover);
850 return !Recover;
851 }
852 return false;
853 }
854
855 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
856 return true;
857
858 CanQualType InstantiationTy;
859 if (TagDecl *TD = dyn_cast<TagDecl>(Val: Instantiation))
860 InstantiationTy = Context.getCanonicalTagType(TD);
861 if (PatternDef) {
862 Diag(Loc: PointOfInstantiation,
863 DiagID: diag::err_template_instantiate_within_definition)
864 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
865 << InstantiationTy;
866 // Not much point in noting the template declaration here, since
867 // we're lexically inside it.
868 Instantiation->setInvalidDecl();
869 } else if (InstantiatedFromMember) {
870 if (isa<FunctionDecl>(Val: Instantiation)) {
871 Diag(Loc: PointOfInstantiation,
872 DiagID: diag::err_explicit_instantiation_undefined_member)
873 << /*member function*/ 1 << Instantiation->getDeclName()
874 << Instantiation->getDeclContext();
875 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
876 } else {
877 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
878 Diag(Loc: PointOfInstantiation,
879 DiagID: diag::err_implicit_instantiate_member_undefined)
880 << InstantiationTy;
881 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_member_declared_at);
882 }
883 } else {
884 if (isa<FunctionDecl>(Val: Instantiation)) {
885 Diag(Loc: PointOfInstantiation,
886 DiagID: diag::err_explicit_instantiation_undefined_func_template)
887 << Pattern;
888 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
889 } else if (isa<TagDecl>(Val: Instantiation)) {
890 Diag(Loc: PointOfInstantiation, DiagID: diag::err_template_instantiate_undefined)
891 << (TSK != TSK_ImplicitInstantiation)
892 << InstantiationTy;
893 NoteTemplateLocation(Decl: *Pattern);
894 } else {
895 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
896 if (isa<VarTemplateSpecializationDecl>(Val: Instantiation)) {
897 Diag(Loc: PointOfInstantiation,
898 DiagID: diag::err_explicit_instantiation_undefined_var_template)
899 << Instantiation;
900 Instantiation->setInvalidDecl();
901 } else
902 Diag(Loc: PointOfInstantiation,
903 DiagID: diag::err_explicit_instantiation_undefined_member)
904 << /*static data member*/ 2 << Instantiation->getDeclName()
905 << Instantiation->getDeclContext();
906 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
907 }
908 }
909
910 // In general, Instantiation isn't marked invalid to get more than one
911 // error for multiple undefined instantiations. But the code that does
912 // explicit declaration -> explicit definition conversion can't handle
913 // invalid declarations, so mark as invalid in that case.
914 if (TSK == TSK_ExplicitInstantiationDeclaration)
915 Instantiation->setInvalidDecl();
916 return true;
917}
918
919void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
920 bool SupportedForCompatibility) {
921 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
922
923 // C++23 [temp.local]p6:
924 // The name of a template-parameter shall not be bound to any following.
925 // declaration whose locus is contained by the scope to which the
926 // template-parameter belongs.
927 //
928 // When MSVC compatibility is enabled, the diagnostic is always a warning
929 // by default. Otherwise, it an error unless SupportedForCompatibility is
930 // true, in which case it is a default-to-error warning.
931 unsigned DiagId =
932 getLangOpts().MSVCCompat
933 ? diag::ext_template_param_shadow
934 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
935 : diag::err_template_param_shadow);
936 const auto *ND = cast<NamedDecl>(Val: PrevDecl);
937 Diag(Loc, DiagID: DiagId) << ND->getDeclName();
938 NoteTemplateParameterLocation(Decl: *ND);
939}
940
941TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
942 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(Val: D)) {
943 D = Temp->getTemplatedDecl();
944 return Temp;
945 }
946 return nullptr;
947}
948
949ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
950 SourceLocation EllipsisLoc) const {
951 assert(Kind == Template &&
952 "Only template template arguments can be pack expansions here");
953 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
954 "Template template argument pack expansion without packs");
955 ParsedTemplateArgument Result(*this);
956 Result.EllipsisLoc = EllipsisLoc;
957 return Result;
958}
959
960static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
961 const ParsedTemplateArgument &Arg) {
962
963 switch (Arg.getKind()) {
964 case ParsedTemplateArgument::Type: {
965 TypeSourceInfo *TSI;
966 QualType T = SemaRef.GetTypeFromParser(Ty: Arg.getAsType(), TInfo: &TSI);
967 if (!TSI)
968 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc: Arg.getNameLoc());
969 return TemplateArgumentLoc(TemplateArgument(T), TSI);
970 }
971
972 case ParsedTemplateArgument::NonType: {
973 Expr *E = Arg.getAsExpr();
974 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
975 }
976
977 case ParsedTemplateArgument::Template: {
978 TemplateName Template = Arg.getAsTemplate().get();
979 TemplateArgument TArg;
980 if (Arg.getEllipsisLoc().isValid())
981 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
982 else
983 TArg = Template;
984 return TemplateArgumentLoc(
985 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
986 Arg.getScopeSpec().getWithLocInContext(Context&: SemaRef.Context),
987 Arg.getNameLoc(), Arg.getEllipsisLoc());
988 }
989 }
990
991 llvm_unreachable("Unhandled parsed template argument");
992}
993
994void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
995 TemplateArgumentListInfo &TemplateArgs) {
996 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
997 TemplateArgs.addArgument(Loc: translateTemplateArgument(SemaRef&: *this,
998 Arg: TemplateArgsIn[I]));
999}
1000
1001static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
1002 SourceLocation Loc,
1003 const IdentifierInfo *Name) {
1004 NamedDecl *PrevDecl =
1005 SemaRef.LookupSingleName(S, Name, Loc, NameKind: Sema::LookupOrdinaryName,
1006 Redecl: RedeclarationKind::ForVisibleRedeclaration);
1007 if (PrevDecl && PrevDecl->isTemplateParameter())
1008 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
1009}
1010
1011ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
1012 TypeSourceInfo *TInfo;
1013 QualType T = GetTypeFromParser(Ty: ParsedType.get(), TInfo: &TInfo);
1014 if (T.isNull())
1015 return ParsedTemplateArgument();
1016 assert(TInfo && "template argument with no location");
1017
1018 // If we might have formed a deduced template specialization type, convert
1019 // it to a template template argument.
1020 if (getLangOpts().CPlusPlus17) {
1021 TypeLoc TL = TInfo->getTypeLoc();
1022 SourceLocation EllipsisLoc;
1023 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1024 EllipsisLoc = PET.getEllipsisLoc();
1025 TL = PET.getPatternLoc();
1026 }
1027
1028 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1029 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1030 CXXScopeSpec SS;
1031 SS.Adopt(Other: DTST.getQualifierLoc());
1032 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1033 TemplateTy::make(P: Name),
1034 DTST.getTemplateNameLoc());
1035 if (EllipsisLoc.isValid())
1036 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1037 return Result;
1038 }
1039 }
1040
1041 // This is a normal type template argument. Note, if the type template
1042 // argument is an injected-class-name for a template, it has a dual nature
1043 // and can be used as either a type or a template. We handle that in
1044 // convertTypeTemplateArgumentToTemplate.
1045 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1046 ParsedType.get().getAsOpaquePtr(),
1047 TInfo->getTypeLoc().getBeginLoc());
1048}
1049
1050NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
1051 SourceLocation EllipsisLoc,
1052 SourceLocation KeyLoc,
1053 IdentifierInfo *ParamName,
1054 SourceLocation ParamNameLoc,
1055 unsigned Depth, unsigned Position,
1056 SourceLocation EqualLoc,
1057 ParsedType DefaultArg,
1058 bool HasTypeConstraint) {
1059 assert(S->isTemplateParamScope() &&
1060 "Template type parameter not in template parameter scope!");
1061
1062 bool IsParameterPack = EllipsisLoc.isValid();
1063 TemplateTypeParmDecl *Param
1064 = TemplateTypeParmDecl::Create(C: Context, DC: Context.getTranslationUnitDecl(),
1065 KeyLoc, NameLoc: ParamNameLoc, D: Depth, P: Position,
1066 Id: ParamName, Typename, ParameterPack: IsParameterPack,
1067 HasTypeConstraint);
1068 Param->setAccess(AS_public);
1069
1070 if (Param->isParameterPack())
1071 if (auto *CSI = getEnclosingLambdaOrBlock())
1072 CSI->LocalPacks.push_back(Elt: Param);
1073
1074 if (ParamName) {
1075 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: ParamNameLoc, Name: ParamName);
1076
1077 // Add the template parameter into the current scope.
1078 S->AddDecl(D: Param);
1079 IdResolver.AddDecl(D: Param);
1080 }
1081
1082 // C++0x [temp.param]p9:
1083 // A default template-argument may be specified for any kind of
1084 // template-parameter that is not a template parameter pack.
1085 if (DefaultArg && IsParameterPack) {
1086 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1087 DefaultArg = nullptr;
1088 }
1089
1090 // Handle the default argument, if provided.
1091 if (DefaultArg) {
1092 TypeSourceInfo *DefaultTInfo;
1093 GetTypeFromParser(Ty: DefaultArg, TInfo: &DefaultTInfo);
1094
1095 assert(DefaultTInfo && "expected source information for type");
1096
1097 // Check for unexpanded parameter packs.
1098 if (DiagnoseUnexpandedParameterPack(Loc: ParamNameLoc, T: DefaultTInfo,
1099 UPPC: UPPC_DefaultArgument))
1100 return Param;
1101
1102 // Check the template argument itself.
1103 if (CheckTemplateArgument(Arg: DefaultTInfo)) {
1104 Param->setInvalidDecl();
1105 return Param;
1106 }
1107
1108 Param->setDefaultArgument(
1109 C: Context, DefArg: TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1110 }
1111
1112 return Param;
1113}
1114
1115/// Convert the parser's template argument list representation into our form.
1116static TemplateArgumentListInfo
1117makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1118 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1119 TemplateId.RAngleLoc);
1120 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1121 TemplateId.NumArgs);
1122 S.translateTemplateArguments(TemplateArgsIn: TemplateArgsPtr, TemplateArgs);
1123 return TemplateArgs;
1124}
1125
1126bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {
1127
1128 TemplateName TN = TypeConstr->Template.get();
1129 NamedDecl *CD = nullptr;
1130 bool IsTypeConcept = false;
1131 bool RequiresArguments = false;
1132 if (auto *TTP = TN.getAsTemplateTemplateParmDecl()) {
1133 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1134 RequiresArguments =
1135 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1136 CD = TTP;
1137 } else {
1138 CD = TN.getAsTemplateDecl();
1139 IsTypeConcept = cast<ConceptDecl>(Val: CD)->isTypeConcept();
1140 RequiresArguments = cast<ConceptDecl>(Val: CD)
1141 ->getTemplateParameters()
1142 ->getMinRequiredArguments() > 1;
1143 }
1144
1145 // C++2a [temp.param]p4:
1146 // [...] The concept designated by a type-constraint shall be a type
1147 // concept ([temp.concept]).
1148 if (!IsTypeConcept) {
1149 Diag(Loc: TypeConstr->TemplateNameLoc,
1150 DiagID: diag::err_type_constraint_non_type_concept);
1151 return true;
1152 }
1153
1154 if (CheckConceptUseInDefinition(Concept: CD, Loc: TypeConstr->TemplateNameLoc))
1155 return true;
1156
1157 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1158
1159 if (!WereArgsSpecified && RequiresArguments) {
1160 Diag(Loc: TypeConstr->TemplateNameLoc,
1161 DiagID: diag::err_type_constraint_missing_arguments)
1162 << CD;
1163 return true;
1164 }
1165 return false;
1166}
1167
1168bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1169 TemplateIdAnnotation *TypeConstr,
1170 TemplateTypeParmDecl *ConstrainedParameter,
1171 SourceLocation EllipsisLoc) {
1172 return BuildTypeConstraint(SS, TypeConstraint: TypeConstr, ConstrainedParameter, EllipsisLoc,
1173 AllowUnexpandedPack: false);
1174}
1175
1176bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1177 TemplateIdAnnotation *TypeConstr,
1178 TemplateTypeParmDecl *ConstrainedParameter,
1179 SourceLocation EllipsisLoc,
1180 bool AllowUnexpandedPack) {
1181
1182 if (CheckTypeConstraint(TypeConstr))
1183 return true;
1184
1185 TemplateName TN = TypeConstr->Template.get();
1186 UsingShadowDecl *USD = TN.getAsUsingShadowDecl();
1187 TemplateDecl *CD = TN.getAsTemplateDecl();
1188
1189 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1190 TypeConstr->TemplateNameLoc);
1191
1192 TemplateArgumentListInfo TemplateArgs;
1193 if (TypeConstr->LAngleLoc.isValid()) {
1194 TemplateArgs =
1195 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TypeConstr);
1196
1197 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1198 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1199 if (DiagnoseUnexpandedParameterPack(Arg, UPPC: UPPC_TypeConstraint))
1200 return true;
1201 }
1202 }
1203 }
1204 return AttachTypeConstraint(
1205 NS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1206 NameInfo: ConceptName, NamedConcept: TN,
1207 /*FoundDecl=*/USD ? cast<NamedDecl>(Val: USD) : cast_if_present<NamedDecl>(Val: CD),
1208 TemplateArgs: TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1209 ConstrainedParameter, EllipsisLoc);
1210}
1211
1212template <typename ArgumentLocAppender>
1213static ExprResult formImmediatelyDeclaredConstraint(
1214 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1215 TemplateName NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1216 SourceLocation RAngleLoc, QualType ConstrainedType,
1217 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1218 SourceLocation EllipsisLoc) {
1219
1220 TemplateArgumentListInfo ConstraintArgs;
1221 ConstraintArgs.addArgument(
1222 Loc: S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(ConstrainedType),
1223 /*NTTPType=*/QualType(), Loc: ParamNameLoc));
1224
1225 ConstraintArgs.setRAngleLoc(RAngleLoc);
1226 ConstraintArgs.setLAngleLoc(LAngleLoc);
1227 Appender(ConstraintArgs);
1228
1229 // C++2a [temp.param]p4:
1230 // [...] This constraint-expression E is called the immediately-declared
1231 // constraint of T. [...]
1232 CXXScopeSpec SS;
1233 SS.Adopt(Other: NS);
1234 ExprResult ImmediatelyDeclaredConstraint;
1235 if (auto *CD =
1236 dyn_cast_if_present<ConceptDecl>(Val: NamedConcept.getAsTemplateDecl())) {
1237 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1238 SS, /*TemplateKWLoc=*/SourceLocation(), ConceptNameInfo: NameInfo,
1239 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, NamedConcept: CD, TemplateArgs: &ConstraintArgs,
1240 /*DoCheckConstraintSatisfaction=*/
1241 !S.inParameterMappingSubstitution());
1242 }
1243 // We have a template template parameter
1244 else {
1245 assert(SS.isEmpty() && "template parameter with a scope specifier?");
1246 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1247 NameInfo, Template: NamedConcept, TemplateArgs: &ConstraintArgs);
1248 }
1249 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1250 return ImmediatelyDeclaredConstraint;
1251
1252 // C++2a [temp.param]p4:
1253 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1254 //
1255 // We have the following case:
1256 //
1257 // template<typename T> concept C1 = true;
1258 // template<C1... T> struct s1;
1259 //
1260 // The constraint: (C1<T> && ...)
1261 //
1262 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1263 // any unqualified lookups for 'operator&&' here.
1264 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/Callee: nullptr,
1265 /*LParenLoc=*/SourceLocation(),
1266 LHS: ImmediatelyDeclaredConstraint.get(), Operator: BO_LAnd,
1267 EllipsisLoc, /*RHS=*/nullptr,
1268 /*RParenLoc=*/SourceLocation(),
1269 /*NumExpansions=*/std::nullopt);
1270}
1271
1272bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1273 DeclarationNameInfo NameInfo,
1274 TemplateName NamedConcept, NamedDecl *FoundDecl,
1275 const TemplateArgumentListInfo *TemplateArgs,
1276 TemplateTypeParmDecl *ConstrainedParameter,
1277 SourceLocation EllipsisLoc) {
1278 // C++2a [temp.param]p4:
1279 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1280 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1281 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1282 TemplateArgs ? ASTTemplateArgumentListInfo::Create(C: Context,
1283 List: *TemplateArgs) : nullptr;
1284
1285 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1286
1287 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1288 S&: *this, NS, NameInfo, NamedConcept, FoundDecl,
1289 LAngleLoc: TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1290 RAngleLoc: TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1291 ConstrainedType: ParamAsArgument, ParamNameLoc: ConstrainedParameter->getLocation(),
1292 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1293 if (TemplateArgs)
1294 for (const auto &ArgLoc : TemplateArgs->arguments())
1295 ConstraintArgs.addArgument(Loc: ArgLoc);
1296 },
1297 EllipsisLoc);
1298 if (ImmediatelyDeclaredConstraint.isInvalid())
1299 return true;
1300
1301 auto *CL = ConceptReference::Create(C: Context, /*NNS=*/NS,
1302 /*TemplateKWLoc=*/SourceLocation{},
1303 /*ConceptNameInfo=*/NameInfo,
1304 /*FoundDecl=*/FoundDecl,
1305 /*NamedConcept=*/NamedConcept,
1306 /*ArgsWritten=*/ArgsAsWritten);
1307 ConstrainedParameter->setTypeConstraint(
1308 CR: CL, ImmediatelyDeclaredConstraint: ImmediatelyDeclaredConstraint.get(), ArgPackSubstIndex: std::nullopt);
1309 return false;
1310}
1311
1312bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
1313 NonTypeTemplateParmDecl *NewConstrainedParm,
1314 NonTypeTemplateParmDecl *OrigConstrainedParm,
1315 SourceLocation EllipsisLoc) {
1316 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1317 TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1318 Diag(Loc: NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1319 DiagID: diag::err_unsupported_placeholder_constraint)
1320 << NewConstrainedParm->getTypeSourceInfo()
1321 ->getTypeLoc()
1322 .getSourceRange();
1323 NewConstrainedParm->setType(TL.getType());
1324 return true;
1325 }
1326 // FIXME: Concepts: This should be the type of the placeholder, but this is
1327 // unclear in the wording right now.
1328 DeclRefExpr *Ref =
1329 BuildDeclRefExpr(D: OrigConstrainedParm, Ty: OrigConstrainedParm->getType(),
1330 VK: VK_PRValue, Loc: OrigConstrainedParm->getLocation());
1331 if (!Ref)
1332 return true;
1333 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1334 S&: *this, NS: TL.getNestedNameSpecifierLoc(), NameInfo: TL.getConceptNameInfo(),
1335 NamedConcept: TL.getNamedConcept(),
1336 /*FoundDecl=*/TL.getFoundDecl(), LAngleLoc: TL.getLAngleLoc(), RAngleLoc: TL.getRAngleLoc(),
1337 ConstrainedType: BuildDecltypeType(E: Ref), ParamNameLoc: OrigConstrainedParm->getLocation(),
1338 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1339 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1340 ConstraintArgs.addArgument(Loc: TL.getArgLoc(i: I));
1341 },
1342 EllipsisLoc);
1343 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1344 !ImmediatelyDeclaredConstraint.isUsable())
1345 return true;
1346
1347 NewConstrainedParm->setPlaceholderTypeConstraint(
1348 ImmediatelyDeclaredConstraint.get());
1349 return false;
1350}
1351
1352QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1353 SourceLocation Loc) {
1354 if (TSI->getType()->isUndeducedType()) {
1355 // C++17 [temp.dep.expr]p3:
1356 // An id-expression is type-dependent if it contains
1357 // - an identifier associated by name lookup with a non-type
1358 // template-parameter declared with a type that contains a
1359 // placeholder type (7.1.7.4),
1360 TypeSourceInfo *NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSI);
1361 if (!NewTSI)
1362 return QualType();
1363 TSI = NewTSI;
1364 }
1365
1366 return CheckNonTypeTemplateParameterType(T: TSI->getType(), Loc);
1367}
1368
1369bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1370 if (T->isDependentType())
1371 return false;
1372
1373 if (RequireCompleteType(Loc, T, DiagID: diag::err_template_nontype_parm_incomplete))
1374 return true;
1375
1376 if (T->isStructuralType())
1377 return false;
1378
1379 // Structural types are required to be object types or lvalue references.
1380 if (T->isRValueReferenceType()) {
1381 Diag(Loc, DiagID: diag::err_template_nontype_parm_rvalue_ref) << T;
1382 return true;
1383 }
1384
1385 // Don't mention structural types in our diagnostic prior to C++20. Also,
1386 // there's not much more we can say about non-scalar non-class types --
1387 // because we can't see functions or arrays here, those can only be language
1388 // extensions.
1389 if (!getLangOpts().CPlusPlus20 ||
1390 (!T->isScalarType() && !T->isRecordType())) {
1391 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_type) << T;
1392 return true;
1393 }
1394
1395 // Structural types are required to be literal types.
1396 if (RequireLiteralType(Loc, T, DiagID: diag::err_template_nontype_parm_not_literal))
1397 return true;
1398
1399 Diag(Loc, DiagID: diag::err_template_nontype_parm_not_structural) << T;
1400
1401 // Drill down into the reason why the class is non-structural.
1402 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1403 // All members are required to be public and non-mutable, and can't be of
1404 // rvalue reference type. Check these conditions first to prefer a "local"
1405 // reason over a more distant one.
1406 for (const FieldDecl *FD : RD->fields()) {
1407 if (FD->getAccess() != AS_public) {
1408 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_non_public) << T << 0;
1409 return true;
1410 }
1411 if (FD->isMutable()) {
1412 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_mutable_field) << T;
1413 return true;
1414 }
1415 if (FD->getType()->isRValueReferenceType()) {
1416 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_rvalue_ref_field)
1417 << T;
1418 return true;
1419 }
1420 }
1421
1422 // All bases are required to be public.
1423 for (const auto &BaseSpec : RD->bases()) {
1424 if (BaseSpec.getAccessSpecifier() != AS_public) {
1425 Diag(Loc: BaseSpec.getBaseTypeLoc(), DiagID: diag::note_not_structural_non_public)
1426 << T << 1;
1427 return true;
1428 }
1429 }
1430
1431 // All subobjects are required to be of structural types.
1432 SourceLocation SubLoc;
1433 QualType SubType;
1434 int Kind = -1;
1435
1436 for (const FieldDecl *FD : RD->fields()) {
1437 QualType T = Context.getBaseElementType(QT: FD->getType());
1438 if (!T->isStructuralType()) {
1439 SubLoc = FD->getLocation();
1440 SubType = T;
1441 Kind = 0;
1442 break;
1443 }
1444 }
1445
1446 if (Kind == -1) {
1447 for (const auto &BaseSpec : RD->bases()) {
1448 QualType T = BaseSpec.getType();
1449 if (!T->isStructuralType()) {
1450 SubLoc = BaseSpec.getBaseTypeLoc();
1451 SubType = T;
1452 Kind = 1;
1453 break;
1454 }
1455 }
1456 }
1457
1458 assert(Kind != -1 && "couldn't find reason why type is not structural");
1459 Diag(Loc: SubLoc, DiagID: diag::note_not_structural_subobject)
1460 << T << Kind << SubType;
1461 T = SubType;
1462 RD = T->getAsCXXRecordDecl();
1463 }
1464
1465 return true;
1466}
1467
1468QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1469 SourceLocation Loc) {
1470 // We don't allow variably-modified types as the type of non-type template
1471 // parameters.
1472 if (T->isVariablyModifiedType()) {
1473 Diag(Loc, DiagID: diag::err_variably_modified_nontype_template_param)
1474 << T;
1475 return QualType();
1476 }
1477
1478 if (T->isBlockPointerType()) {
1479 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_type) << T;
1480 return QualType();
1481 }
1482
1483 // C++ [temp.param]p4:
1484 //
1485 // A non-type template-parameter shall have one of the following
1486 // (optionally cv-qualified) types:
1487 //
1488 // -- integral or enumeration type,
1489 if (T->isIntegralOrEnumerationType() ||
1490 // -- pointer to object or pointer to function,
1491 T->isPointerType() ||
1492 // -- lvalue reference to object or lvalue reference to function,
1493 T->isLValueReferenceType() ||
1494 // -- pointer to member,
1495 T->isMemberPointerType() ||
1496 // -- std::nullptr_t, or
1497 T->isNullPtrType() ||
1498 // -- a type that contains a placeholder type.
1499 T->isUndeducedType()) {
1500 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1501 // are ignored when determining its type.
1502 return T.getUnqualifiedType();
1503 }
1504
1505 // C++ [temp.param]p8:
1506 //
1507 // A non-type template-parameter of type "array of T" or
1508 // "function returning T" is adjusted to be of type "pointer to
1509 // T" or "pointer to function returning T", respectively.
1510 if (T->isArrayType() || T->isFunctionType())
1511 return Context.getDecayedType(T);
1512
1513 // If T is a dependent type, we can't do the check now, so we
1514 // assume that it is well-formed. Note that stripping off the
1515 // qualifiers here is not really correct if T turns out to be
1516 // an array type, but we'll recompute the type everywhere it's
1517 // used during instantiation, so that should be OK. (Using the
1518 // qualified type is equally wrong.)
1519 if (T->isDependentType())
1520 return T.getUnqualifiedType();
1521
1522 // C++20 [temp.param]p6:
1523 // -- a structural type
1524 if (RequireStructuralType(T, Loc))
1525 return QualType();
1526
1527 if (!getLangOpts().CPlusPlus20) {
1528 // FIXME: Consider allowing structural types as an extension in C++17. (In
1529 // earlier language modes, the template argument evaluation rules are too
1530 // inflexible.)
1531 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_structural_type) << T;
1532 return QualType();
1533 }
1534
1535 Diag(Loc, DiagID: diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1536 return T.getUnqualifiedType();
1537}
1538
1539NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1540 unsigned Depth,
1541 unsigned Position,
1542 SourceLocation EqualLoc,
1543 Expr *Default) {
1544 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
1545
1546 // Check that we have valid decl-specifiers specified.
1547 auto CheckValidDeclSpecifiers = [this, &D] {
1548 // C++ [temp.param]
1549 // p1
1550 // template-parameter:
1551 // ...
1552 // parameter-declaration
1553 // p2
1554 // ... A storage class shall not be specified in a template-parameter
1555 // declaration.
1556 // [dcl.typedef]p1:
1557 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1558 // of a parameter-declaration
1559 const DeclSpec &DS = D.getDeclSpec();
1560 auto EmitDiag = [this](SourceLocation Loc) {
1561 Diag(Loc, DiagID: diag::err_invalid_decl_specifier_in_nontype_parm)
1562 << FixItHint::CreateRemoval(RemoveRange: Loc);
1563 };
1564 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1565 EmitDiag(DS.getStorageClassSpecLoc());
1566
1567 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1568 EmitDiag(DS.getThreadStorageClassSpecLoc());
1569
1570 // [dcl.inline]p1:
1571 // The inline specifier can be applied only to the declaration or
1572 // definition of a variable or function.
1573
1574 if (DS.isInlineSpecified())
1575 EmitDiag(DS.getInlineSpecLoc());
1576
1577 // [dcl.constexpr]p1:
1578 // The constexpr specifier shall be applied only to the definition of a
1579 // variable or variable template or the declaration of a function or
1580 // function template.
1581
1582 if (DS.hasConstexprSpecifier())
1583 EmitDiag(DS.getConstexprSpecLoc());
1584
1585 // [dcl.fct.spec]p1:
1586 // Function-specifiers can be used only in function declarations.
1587
1588 if (DS.isVirtualSpecified())
1589 EmitDiag(DS.getVirtualSpecLoc());
1590
1591 if (DS.hasExplicitSpecifier())
1592 EmitDiag(DS.getExplicitSpecLoc());
1593
1594 if (DS.isNoreturnSpecified())
1595 EmitDiag(DS.getNoreturnSpecLoc());
1596 };
1597
1598 CheckValidDeclSpecifiers();
1599
1600 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1601 if (isa<AutoType>(Val: T))
1602 Diag(Loc: D.getIdentifierLoc(),
1603 DiagID: diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1604 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1605
1606 assert(S->isTemplateParamScope() &&
1607 "Non-type template parameter not in template parameter scope!");
1608 bool Invalid = false;
1609
1610 QualType T = CheckNonTypeTemplateParameterType(TSI&: TInfo, Loc: D.getIdentifierLoc());
1611 if (T.isNull()) {
1612 T = Context.IntTy; // Recover with an 'int' type.
1613 Invalid = true;
1614 }
1615
1616 CheckFunctionOrTemplateParamDeclarator(S, D);
1617
1618 const IdentifierInfo *ParamName = D.getIdentifier();
1619 bool IsParameterPack = D.hasEllipsis();
1620 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1621 C: Context, DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
1622 IdLoc: D.getIdentifierLoc(), D: Depth, P: Position, Id: ParamName, T, ParameterPack: IsParameterPack,
1623 TInfo);
1624 Param->setAccess(AS_public);
1625
1626 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1627 if (TL.isConstrained()) {
1628 if (D.getEllipsisLoc().isInvalid() &&
1629 T->containsUnexpandedParameterPack()) {
1630 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1631 for (auto &Loc :
1632 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1633 Invalid |= DiagnoseUnexpandedParameterPack(
1634 Arg: Loc, UPPC: UnexpandedParameterPackContext::UPPC_TypeConstraint);
1635 }
1636 if (!Invalid &&
1637 AttachTypeConstraint(TL, NewConstrainedParm: Param, OrigConstrainedParm: Param, EllipsisLoc: D.getEllipsisLoc()))
1638 Invalid = true;
1639 }
1640
1641 if (Invalid)
1642 Param->setInvalidDecl();
1643
1644 if (Param->isParameterPack())
1645 if (auto *CSI = getEnclosingLambdaOrBlock())
1646 CSI->LocalPacks.push_back(Elt: Param);
1647
1648 if (ParamName) {
1649 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: D.getIdentifierLoc(),
1650 Name: ParamName);
1651
1652 // Add the template parameter into the current scope.
1653 S->AddDecl(D: Param);
1654 IdResolver.AddDecl(D: Param);
1655 }
1656
1657 // C++0x [temp.param]p9:
1658 // A default template-argument may be specified for any kind of
1659 // template-parameter that is not a template parameter pack.
1660 if (Default && IsParameterPack) {
1661 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1662 Default = nullptr;
1663 }
1664
1665 // Check the well-formedness of the default template argument, if provided.
1666 if (Default) {
1667 // Check for unexpanded parameter packs.
1668 if (DiagnoseUnexpandedParameterPack(E: Default, UPPC: UPPC_DefaultArgument))
1669 return Param;
1670
1671 Param->setDefaultArgument(
1672 C: Context, DefArg: getTrivialTemplateArgumentLoc(
1673 Arg: TemplateArgument(Default, /*IsCanonical=*/false),
1674 NTTPType: QualType(), Loc: SourceLocation()));
1675 }
1676
1677 return Param;
1678}
1679
1680/// ActOnTemplateTemplateParameter - Called when a C++ template template
1681/// parameter (e.g. T in template <template \<typename> class T> class array)
1682/// has been parsed. S is the current scope.
1683NamedDecl *Sema::ActOnTemplateTemplateParameter(
1684 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1685 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1686 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1687 unsigned Position, SourceLocation EqualLoc,
1688 ParsedTemplateArgument Default) {
1689 assert(S->isTemplateParamScope() &&
1690 "Template template parameter not in template parameter scope!");
1691
1692 bool IsParameterPack = EllipsisLoc.isValid();
1693
1694 SourceLocation Loc = NameLoc.isInvalid() ? TmpLoc : NameLoc;
1695 if (Params->size() == 0) {
1696 Diag(Loc, DiagID: diag::err_template_template_parm_no_parms)
1697 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1698
1699 // Recover as if there was a type template parameter pack.
1700 SmallVector<NamedDecl *, 4> ParamDecls;
1701 ParamDecls.push_back(Elt: TemplateTypeParmDecl::Create(
1702 C: Context, DC: Context.getTranslationUnitDecl(), KeyLoc: Loc, NameLoc: SourceLocation(),
1703 D: Depth + 1, P: 0, /*Id=*/nullptr,
1704 /*Typename=*/false, /*ParameterPack=*/true));
1705 Params = TemplateParameterList::Create(
1706 C: Context, TemplateLoc: Params->getTemplateLoc(), LAngleLoc: Params->getLAngleLoc(), Params: ParamDecls,
1707 RAngleLoc: Params->getRAngleLoc(), RequiresClause: Params->getRequiresClause());
1708 }
1709
1710 bool Invalid = false;
1711 if (CheckTemplateParameterList(
1712 NewParams: Params,
1713 /*OldParams=*/nullptr,
1714 TPC: IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1715 Invalid = true;
1716
1717 // Construct the parameter object.
1718 TemplateTemplateParmDecl *Param = TemplateTemplateParmDecl::Create(
1719 C: Context, DC: Context.getTranslationUnitDecl(), L: Loc, D: Depth, P: Position,
1720 ParameterPack: IsParameterPack, Id: Name, ParameterKind: Kind, Typename, Params);
1721 Param->setAccess(AS_public);
1722
1723 if (Param->isParameterPack())
1724 if (auto *LSI = getEnclosingLambdaOrBlock())
1725 LSI->LocalPacks.push_back(Elt: Param);
1726
1727 // If the template template parameter has a name, then link the identifier
1728 // into the scope and lookup mechanisms.
1729 if (Name) {
1730 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: NameLoc, Name);
1731
1732 S->AddDecl(D: Param);
1733 IdResolver.AddDecl(D: Param);
1734 }
1735
1736 if (Invalid)
1737 Param->setInvalidDecl();
1738
1739 // C++0x [temp.param]p9:
1740 // A default template-argument may be specified for any kind of
1741 // template-parameter that is not a template parameter pack.
1742 if (IsParameterPack && !Default.isInvalid()) {
1743 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1744 Default = ParsedTemplateArgument();
1745 }
1746
1747 if (!Default.isInvalid()) {
1748 // Check only that we have a template template argument. We don't want to
1749 // try to check well-formedness now, because our template template parameter
1750 // might have dependent types in its template parameters, which we wouldn't
1751 // be able to match now.
1752 //
1753 // If none of the template template parameter's template arguments mention
1754 // other template parameters, we could actually perform more checking here.
1755 // However, it isn't worth doing.
1756 TemplateArgumentLoc DefaultArg = translateTemplateArgument(SemaRef&: *this, Arg: Default);
1757 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1758 Diag(Loc: DefaultArg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
1759 << DefaultArg.getSourceRange();
1760 return Param;
1761 }
1762
1763 TemplateName Name =
1764 DefaultArg.getArgument().getAsTemplateOrTemplatePattern();
1765 TemplateDecl *Template = Name.getAsTemplateDecl();
1766 if (Template &&
1767 !CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg: DefaultArg)) {
1768 return Param;
1769 }
1770
1771 // Check for unexpanded parameter packs.
1772 if (DiagnoseUnexpandedParameterPack(Loc: DefaultArg.getLocation(),
1773 Template: DefaultArg.getArgument().getAsTemplate(),
1774 UPPC: UPPC_DefaultArgument))
1775 return Param;
1776
1777 Param->setDefaultArgument(C: Context, DefArg: DefaultArg);
1778 }
1779
1780 return Param;
1781}
1782
1783namespace {
1784class ConstraintRefersToContainingTemplateChecker
1785 : public ConstDynamicRecursiveASTVisitor {
1786 using inherited = ConstDynamicRecursiveASTVisitor;
1787 bool Result = false;
1788 const FunctionDecl *Friend = nullptr;
1789 unsigned TemplateDepth = 0;
1790
1791 // Check a record-decl that we've seen to see if it is a lexical parent of the
1792 // Friend, likely because it was referred to without its template arguments.
1793 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1794 CheckingRD = CheckingRD->getMostRecentDecl();
1795 if (!CheckingRD->isTemplated())
1796 return true;
1797
1798 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1799 DC && !DC->isFileContext(); DC = DC->getParent())
1800 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
1801 if (CheckingRD == RD->getMostRecentDecl()) {
1802 Result = true;
1803 return false;
1804 }
1805
1806 return true;
1807 }
1808
1809 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1810 if (D->getDepth() < TemplateDepth)
1811 Result = true;
1812
1813 // Necessary because the type of the NTTP might be what refers to the parent
1814 // constriant.
1815 return TraverseType(T: D->getType());
1816 }
1817
1818public:
1819 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1820 unsigned TemplateDepth)
1821 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1822
1823 bool getResult() const { return Result; }
1824
1825 // This should be the only template parm type that we have to deal with.
1826 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1827 // FunctionParmPackExpr are all partially substituted, which cannot happen
1828 // with concepts at this point in translation.
1829 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1830 if (Type->getDecl()->getDepth() < TemplateDepth) {
1831 Result = true;
1832 return false;
1833 }
1834 return true;
1835 }
1836
1837 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1838 return TraverseDecl(D: E->getDecl());
1839 }
1840
1841 bool TraverseTypedefType(const TypedefType *TT,
1842 bool /*TraverseQualifier*/) override {
1843 return TraverseType(T: TT->desugar());
1844 }
1845
1846 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1847 // We don't care about TypeLocs. So traverse Types instead.
1848 return TraverseType(T: TL.getType(), TraverseQualifier);
1849 }
1850
1851 bool VisitTagType(const TagType *T) override {
1852 return TraverseDecl(D: T->getDecl());
1853 }
1854
1855 bool TraverseDecl(const Decl *D) override {
1856 assert(D);
1857 // FIXME : This is possibly an incomplete list, but it is unclear what other
1858 // Decl kinds could be used to refer to the template parameters. This is a
1859 // best guess so far based on examples currently available, but the
1860 // unreachable should catch future instances/cases.
1861 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
1862 return TraverseType(T: TD->getUnderlyingType());
1863 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Val: D))
1864 return CheckNonTypeTemplateParmDecl(D: NTTPD);
1865 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
1866 return TraverseType(T: VD->getType());
1867 if (isa<TemplateDecl>(Val: D))
1868 return true;
1869 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1870 return CheckIfContainingRecord(CheckingRD: RD);
1871
1872 if (isa<NamedDecl, RequiresExprBodyDecl>(Val: D)) {
1873 // No direct types to visit here I believe.
1874 } else
1875 llvm_unreachable("Don't know how to handle this declaration type yet");
1876 return true;
1877 }
1878};
1879} // namespace
1880
1881bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1882 const FunctionDecl *Friend, unsigned TemplateDepth,
1883 const Expr *Constraint) {
1884 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1885 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1886 Checker.TraverseStmt(S: Constraint);
1887 return Checker.getResult();
1888}
1889
1890TemplateParameterList *
1891Sema::ActOnTemplateParameterList(unsigned Depth,
1892 SourceLocation ExportLoc,
1893 SourceLocation TemplateLoc,
1894 SourceLocation LAngleLoc,
1895 ArrayRef<NamedDecl *> Params,
1896 SourceLocation RAngleLoc,
1897 Expr *RequiresClause) {
1898 if (ExportLoc.isValid())
1899 Diag(Loc: ExportLoc, DiagID: diag::warn_template_export_unsupported);
1900
1901 for (NamedDecl *P : Params)
1902 warnOnReservedIdentifier(D: P);
1903
1904 return TemplateParameterList::Create(C: Context, TemplateLoc, LAngleLoc,
1905 Params: llvm::ArrayRef(Params), RAngleLoc,
1906 RequiresClause);
1907}
1908
1909static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1910 const CXXScopeSpec &SS) {
1911 if (SS.isSet())
1912 T->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
1913}
1914
1915// Returns the template parameter list with all default template argument
1916// information.
1917TemplateParameterList *Sema::GetTemplateParameterList(TemplateDecl *TD) {
1918 // Make sure we get the template parameter list from the most
1919 // recent declaration, since that is the only one that is guaranteed to
1920 // have all the default template argument information.
1921 Decl *D = TD->getMostRecentDecl();
1922 // C++11 N3337 [temp.param]p12:
1923 // A default template argument shall not be specified in a friend class
1924 // template declaration.
1925 //
1926 // Skip past friend *declarations* because they are not supposed to contain
1927 // default template arguments. Moreover, these declarations may introduce
1928 // template parameters living in different template depths than the
1929 // corresponding template parameters in TD, causing unmatched constraint
1930 // substitution.
1931 //
1932 // FIXME: Diagnose such cases within a class template:
1933 // template <class T>
1934 // struct S {
1935 // template <class = void> friend struct C;
1936 // };
1937 // template struct S<int>;
1938 while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
1939 D->getPreviousDecl())
1940 D = D->getPreviousDecl();
1941 return cast<TemplateDecl>(Val: D)->getTemplateParameters();
1942}
1943
1944DeclResult Sema::CheckClassTemplate(
1945 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1946 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1947 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1948 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1949 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1950 TemplateParameterList **OuterTemplateParamLists,
1951 bool IsMemberSpecialization, SkipBodyInfo *SkipBody) {
1952 assert(TemplateParams && TemplateParams->size() > 0 &&
1953 "No template parameters");
1954 assert(TUK != TagUseKind::Reference &&
1955 "Can only declare or define class templates");
1956 bool Invalid = false;
1957
1958 // Check that we can declare a template here.
1959 if (CheckTemplateDeclScope(S, TemplateParams))
1960 return true;
1961
1962 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
1963 assert(Kind != TagTypeKind::Enum &&
1964 "can't build template of enumerated type");
1965
1966 // There is no such thing as an unnamed class template.
1967 if (!Name) {
1968 Diag(Loc: KWLoc, DiagID: diag::err_template_unnamed_class);
1969 return true;
1970 }
1971
1972 // Find any previous declaration with this name. For a friend with no
1973 // scope explicitly specified, we only look for tag declarations (per
1974 // C++11 [basic.lookup.elab]p2).
1975 DeclContext *SemanticContext;
1976 LookupResult Previous(*this, Name, NameLoc,
1977 (SS.isEmpty() && TUK == TagUseKind::Friend)
1978 ? LookupTagName
1979 : LookupOrdinaryName,
1980 forRedeclarationInCurContext());
1981 if (SS.isNotEmpty() && !SS.isInvalid()) {
1982 SemanticContext = computeDeclContext(SS, EnteringContext: true);
1983 if (!SemanticContext) {
1984 Diag(Loc: NameLoc, DiagID: diag::err_template_qualified_declarator_no_match)
1985 << SS.getScopeRep() << SS.getRange();
1986 return true;
1987 }
1988
1989 if (RequireCompleteDeclContext(SS, DC: SemanticContext))
1990 return true;
1991
1992 // If we're adding a template to a dependent context, we may need to
1993 // rebuilding some of the types used within the template parameter list,
1994 // now that we know what the current instantiation is.
1995 if (SemanticContext->isDependentContext()) {
1996 ContextRAII SavedContext(*this, SemanticContext);
1997 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
1998 Invalid = true;
1999 }
2000
2001 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference &&
2002 diagnoseQualifiedDeclaration(SS, DC: SemanticContext, Name, Loc: NameLoc,
2003 /*TemplateId=*/nullptr,
2004 IsMemberSpecialization))
2005 return true;
2006
2007 LookupQualifiedName(R&: Previous, LookupCtx: SemanticContext);
2008 } else {
2009 SemanticContext = CurContext;
2010
2011 // C++14 [class.mem]p14:
2012 // If T is the name of a class, then each of the following shall have a
2013 // name different from T:
2014 // -- every member template of class T
2015 if (TUK != TagUseKind::Friend &&
2016 DiagnoseClassNameShadow(DC: SemanticContext,
2017 Info: DeclarationNameInfo(Name, NameLoc)))
2018 return true;
2019
2020 LookupName(R&: Previous, S);
2021 }
2022
2023 if (Previous.isAmbiguous())
2024 return true;
2025
2026 // Let the template parameter scope enter the lookup chain of the current
2027 // class template. For example, given
2028 //
2029 // namespace ns {
2030 // template <class> bool Param = false;
2031 // template <class T> struct N;
2032 // }
2033 //
2034 // template <class Param> struct ns::N { void foo(Param); };
2035 //
2036 // When we reference Param inside the function parameter list, our name lookup
2037 // chain for it should be like:
2038 // FunctionScope foo
2039 // -> RecordScope N
2040 // -> TemplateParamScope (where we will find Param)
2041 // -> NamespaceScope ns
2042 //
2043 // See also CppLookupName().
2044 if (S->isTemplateParamScope())
2045 EnterTemplatedContext(S, DC: SemanticContext);
2046
2047 NamedDecl *PrevDecl = nullptr;
2048 if (Previous.begin() != Previous.end())
2049 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2050
2051 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2052 // Maybe we will complain about the shadowed template parameter.
2053 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl);
2054 // Just pretend that we didn't see the previous declaration.
2055 PrevDecl = nullptr;
2056 }
2057
2058 // If there is a previous declaration with the same name, check
2059 // whether this is a valid redeclaration.
2060 ClassTemplateDecl *PrevClassTemplate =
2061 dyn_cast_or_null<ClassTemplateDecl>(Val: PrevDecl);
2062
2063 // We may have found the injected-class-name of a class template,
2064 // class template partial specialization, or class template specialization.
2065 // In these cases, grab the template that is being defined or specialized.
2066 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(Val: PrevDecl) &&
2067 cast<CXXRecordDecl>(Val: PrevDecl)->isInjectedClassName()) {
2068 PrevDecl = cast<CXXRecordDecl>(Val: PrevDecl->getDeclContext());
2069 PrevClassTemplate
2070 = cast<CXXRecordDecl>(Val: PrevDecl)->getDescribedClassTemplate();
2071 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(Val: PrevDecl)) {
2072 PrevClassTemplate
2073 = cast<ClassTemplateSpecializationDecl>(Val: PrevDecl)
2074 ->getSpecializedTemplate();
2075 }
2076 }
2077
2078 if (TUK == TagUseKind::Friend) {
2079 // C++ [namespace.memdef]p3:
2080 // [...] When looking for a prior declaration of a class or a function
2081 // declared as a friend, and when the name of the friend class or
2082 // function is neither a qualified name nor a template-id, scopes outside
2083 // the innermost enclosing namespace scope are not considered.
2084 if (!SS.isSet()) {
2085 DeclContext *OutermostContext = CurContext;
2086 while (!OutermostContext->isFileContext())
2087 OutermostContext = OutermostContext->getLookupParent();
2088
2089 if (PrevDecl &&
2090 (OutermostContext->Equals(DC: PrevDecl->getDeclContext()) ||
2091 OutermostContext->Encloses(DC: PrevDecl->getDeclContext()))) {
2092 SemanticContext = PrevDecl->getDeclContext();
2093 } else {
2094 // Declarations in outer scopes don't matter. However, the outermost
2095 // context we computed is the semantic context for our new
2096 // declaration.
2097 PrevDecl = PrevClassTemplate = nullptr;
2098 SemanticContext = OutermostContext;
2099
2100 // Check that the chosen semantic context doesn't already contain a
2101 // declaration of this name as a non-tag type.
2102 Previous.clear(Kind: LookupOrdinaryName);
2103 DeclContext *LookupContext = SemanticContext;
2104 while (LookupContext->isTransparentContext())
2105 LookupContext = LookupContext->getLookupParent();
2106 LookupQualifiedName(R&: Previous, LookupCtx: LookupContext);
2107
2108 if (Previous.isAmbiguous())
2109 return true;
2110
2111 if (Previous.begin() != Previous.end())
2112 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2113 }
2114 }
2115 } else if (PrevDecl &&
2116 !isTagRedeclarationInScope(D: Previous.getRepresentativeDecl(),
2117 Ctx: SemanticContext, S, AllowInlineNamespace: SS.isValid()))
2118 PrevDecl = PrevClassTemplate = nullptr;
2119
2120 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2121 Val: PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2122 if (SS.isEmpty() &&
2123 !(PrevClassTemplate &&
2124 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2125 DC: SemanticContext->getRedeclContext()))) {
2126 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
2127 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
2128 DiagID: diag::note_using_decl_target);
2129 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
2130 // Recover by ignoring the old declaration.
2131 PrevDecl = PrevClassTemplate = nullptr;
2132 }
2133 }
2134
2135 if (PrevClassTemplate) {
2136 // Ensure that the template parameter lists are compatible. Skip this check
2137 // for a friend in a dependent context: the template parameter list itself
2138 // could be dependent.
2139 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2140 !TemplateParameterListsAreEqual(
2141 NewInstFrom: TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2142 : CurContext,
2143 CurContext, KWLoc),
2144 New: TemplateParams, OldInstFrom: PrevClassTemplate,
2145 Old: PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2146 Kind: TPL_TemplateMatch))
2147 return true;
2148
2149 // C++ [temp.class]p4:
2150 // In a redeclaration, partial specialization, explicit
2151 // specialization or explicit instantiation of a class template,
2152 // the class-key shall agree in kind with the original class
2153 // template declaration (7.1.5.3).
2154 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2155 if (!isAcceptableTagRedeclaration(
2156 Previous: PrevRecordDecl, NewTag: Kind, isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc, Name)) {
2157 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
2158 << Name
2159 << FixItHint::CreateReplacement(RemoveRange: KWLoc, Code: PrevRecordDecl->getKindName());
2160 Diag(Loc: PrevRecordDecl->getLocation(), DiagID: diag::note_previous_use);
2161 Kind = PrevRecordDecl->getTagKind();
2162 }
2163
2164 // Check for redefinition of this class template.
2165 if (TUK == TagUseKind::Definition) {
2166 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2167 // If we have a prior definition that is not visible, treat this as
2168 // simply making that previous definition visible.
2169 NamedDecl *Hidden = nullptr;
2170 bool HiddenDefVisible = false;
2171 if (SkipBody &&
2172 isRedefinitionAllowedFor(D: Def, NewDefinitionLoc: NameLoc, Suggested: &Hidden, Visible&: HiddenDefVisible)) {
2173 SkipBody->ShouldSkip = true;
2174 SkipBody->Previous = Def;
2175 if (!HiddenDefVisible && Hidden) {
2176 auto *Tmpl =
2177 cast<CXXRecordDecl>(Val: Hidden)->getDescribedClassTemplate();
2178 assert(Tmpl && "original definition of a class template is not a "
2179 "class template?");
2180 makeMergedDefinitionVisible(ND: Hidden);
2181 makeMergedDefinitionVisible(ND: Tmpl);
2182 }
2183 } else {
2184 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
2185 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
2186 // FIXME: Would it make sense to try to "forget" the previous
2187 // definition, as part of error recovery?
2188 return true;
2189 }
2190 }
2191 }
2192 } else if (PrevDecl) {
2193 // C++ [temp]p5:
2194 // A class template shall not have the same name as any other
2195 // template, class, function, object, enumeration, enumerator,
2196 // namespace, or type in the same scope (3.3), except as specified
2197 // in (14.5.4).
2198 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
2199 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
2200 return true;
2201 }
2202
2203 // Check the template parameter list of this declaration, possibly
2204 // merging in the template parameter list from the previous class
2205 // template declaration. Skip this check for a friend in a dependent
2206 // context, because the template parameter list might be dependent.
2207 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2208 CheckTemplateParameterList(
2209 NewParams: TemplateParams,
2210 OldParams: PrevClassTemplate ? GetTemplateParameterList(TD: PrevClassTemplate)
2211 : nullptr,
2212 TPC: (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2213 SemanticContext->isDependentContext())
2214 ? TPC_ClassTemplateMember
2215 : TUK == TagUseKind::Friend ? TPC_FriendClassTemplate
2216 : TPC_Other,
2217 SkipBody))
2218 Invalid = true;
2219
2220 if (SS.isSet()) {
2221 // If the name of the template was qualified, we must be defining the
2222 // template out-of-line.
2223 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate)
2224 return Diag(Loc: NameLoc, DiagID: TUK == TagUseKind::Friend
2225 ? diag::err_friend_decl_does_not_match
2226 : diag::err_member_decl_does_not_match)
2227 << Name << SemanticContext << /*IsDefinition*/ true
2228 << SS.getRange();
2229 }
2230
2231 // If this is a templated friend in a dependent context we should not put it
2232 // on the redecl chain. In some cases, the templated friend can be the most
2233 // recent declaration tricking the template instantiator to make substitutions
2234 // there.
2235 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2236 bool ShouldAddRedecl =
2237 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2238
2239 CXXRecordDecl *NewClass = CXXRecordDecl::Create(
2240 C: Context, TK: Kind, DC: SemanticContext, StartLoc: KWLoc, IdLoc: NameLoc, Id: Name,
2241 PrevDecl: PrevClassTemplate && ShouldAddRedecl
2242 ? PrevClassTemplate->getTemplatedDecl()
2243 : nullptr);
2244 SetNestedNameSpecifier(S&: *this, T: NewClass, SS);
2245 if (NumOuterTemplateParamLists > 0)
2246 NewClass->setTemplateParameterListsInfo(
2247 Context,
2248 TPLists: llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2249
2250 // Add alignment attributes if necessary; these attributes are checked when
2251 // the ASTContext lays out the structure.
2252 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2253 if (LangOpts.HLSL)
2254 NewClass->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
2255 AddAlignmentAttributesForRecord(RD: NewClass);
2256 AddMsStructLayoutForRecord(RD: NewClass);
2257 }
2258
2259 ClassTemplateDecl *NewTemplate
2260 = ClassTemplateDecl::Create(C&: Context, DC: SemanticContext, L: NameLoc,
2261 Name: DeclarationName(Name), Params: TemplateParams,
2262 Decl: NewClass);
2263
2264 if (ShouldAddRedecl)
2265 NewTemplate->setPreviousDecl(PrevClassTemplate);
2266
2267 NewClass->setDescribedClassTemplate(NewTemplate);
2268
2269 if (ModulePrivateLoc.isValid())
2270 NewTemplate->setModulePrivate();
2271
2272 if (IsMemberSpecialization) {
2273 assert(PrevClassTemplate &&
2274 "Member specialization without a primary template?");
2275 NewTemplate->setMemberSpecialization();
2276 }
2277
2278 // Set the access specifier.
2279 if (!Invalid && TUK != TagUseKind::Friend &&
2280 NewTemplate->getDeclContext()->isRecord())
2281 SetMemberAccessSpecifier(MemberDecl: NewTemplate, PrevMemberDecl: PrevClassTemplate, LexicalAS: AS);
2282
2283 // Set the lexical context of these templates
2284 NewClass->setLexicalDeclContext(CurContext);
2285 NewTemplate->setLexicalDeclContext(CurContext);
2286
2287 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2288 NewClass->startDefinition();
2289
2290 ProcessDeclAttributeList(S, D: NewClass, AttrList: Attr);
2291
2292 if (PrevClassTemplate) {
2293 mergeDeclAttributes(New: NewTemplate, Old: PrevClassTemplate);
2294 mergeDeclAttributes(New: NewClass, Old: PrevClassTemplate->getTemplatedDecl());
2295 }
2296
2297 AddPushedVisibilityAttribute(RD: NewClass);
2298 inferGslOwnerPointerAttribute(Record: NewClass);
2299 inferNullableClassAttribute(CRD: NewClass);
2300
2301 if (TUK != TagUseKind::Friend) {
2302 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2303 Scope *Outer = S;
2304 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2305 Outer = Outer->getParent();
2306 PushOnScopeChains(D: NewTemplate, S: Outer);
2307 } else {
2308 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2309 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2310 NewClass->setAccess(PrevClassTemplate->getAccess());
2311 }
2312
2313 NewTemplate->setObjectOfFriendDecl();
2314
2315 // Friend templates are visible in fairly strange ways.
2316 if (!CurContext->isDependentContext()) {
2317 DeclContext *DC = SemanticContext->getRedeclContext();
2318 DC->makeDeclVisibleInContext(D: NewTemplate);
2319 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2320 PushOnScopeChains(D: NewTemplate, S: EnclosingScope,
2321 /* AddToContext = */ false);
2322 }
2323
2324 FriendDecl *Friend = FriendDecl::Create(
2325 C&: Context, DC: CurContext, L: NewClass->getLocation(), Friend: NewTemplate, FriendL: FriendLoc);
2326 Friend->setAccess(AS_public);
2327 CurContext->addDecl(D: Friend);
2328 }
2329
2330 if (PrevClassTemplate)
2331 CheckRedeclarationInModule(New: NewTemplate, Old: PrevClassTemplate);
2332
2333 if (Invalid) {
2334 NewTemplate->setInvalidDecl();
2335 NewClass->setInvalidDecl();
2336 }
2337
2338 ActOnDocumentableDecl(D: NewTemplate);
2339
2340 if (SkipBody && SkipBody->ShouldSkip)
2341 return SkipBody->Previous;
2342
2343 return NewTemplate;
2344}
2345
2346/// Diagnose the presence of a default template argument on a
2347/// template parameter, which is ill-formed in certain contexts.
2348///
2349/// \returns true if the default template argument should be dropped.
2350static bool DiagnoseDefaultTemplateArgument(Sema &S,
2351 Sema::TemplateParamListContext TPC,
2352 SourceLocation ParamLoc,
2353 SourceRange DefArgRange) {
2354 switch (TPC) {
2355 case Sema::TPC_Other:
2356 case Sema::TPC_TemplateTemplateParameterPack:
2357 return false;
2358
2359 case Sema::TPC_FunctionTemplate:
2360 case Sema::TPC_FriendFunctionTemplateDefinition:
2361 // C++ [temp.param]p9:
2362 // A default template-argument shall not be specified in a
2363 // function template declaration or a function template
2364 // definition [...]
2365 // If a friend function template declaration specifies a default
2366 // template-argument, that declaration shall be a definition and shall be
2367 // the only declaration of the function template in the translation unit.
2368 // (C++98/03 doesn't have this wording; see DR226).
2369 S.DiagCompat(Loc: ParamLoc, CompatDiagId: diag_compat::templ_default_in_function_templ)
2370 << DefArgRange;
2371 return false;
2372
2373 case Sema::TPC_ClassTemplateMember:
2374 // C++0x [temp.param]p9:
2375 // A default template-argument shall not be specified in the
2376 // template-parameter-lists of the definition of a member of a
2377 // class template that appears outside of the member's class.
2378 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_template_member)
2379 << DefArgRange;
2380 return true;
2381
2382 case Sema::TPC_FriendClassTemplate:
2383 case Sema::TPC_FriendFunctionTemplate:
2384 // C++ [temp.param]p9:
2385 // A default template-argument shall not be specified in a
2386 // friend template declaration.
2387 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_friend_template)
2388 << DefArgRange;
2389 return true;
2390
2391 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2392 // for friend function templates if there is only a single
2393 // declaration (and it is a definition). Strange!
2394 }
2395
2396 llvm_unreachable("Invalid TemplateParamListContext!");
2397}
2398
2399/// Check for unexpanded parameter packs within the template parameters
2400/// of a template template parameter, recursively.
2401static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2402 TemplateTemplateParmDecl *TTP) {
2403 // A template template parameter which is a parameter pack is also a pack
2404 // expansion.
2405 if (TTP->isParameterPack())
2406 return false;
2407
2408 TemplateParameterList *Params = TTP->getTemplateParameters();
2409 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2410 NamedDecl *P = Params->getParam(Idx: I);
2411 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: P)) {
2412 if (!TTP->isParameterPack())
2413 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2414 if (TC->hasExplicitTemplateArgs())
2415 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2416 if (S.DiagnoseUnexpandedParameterPack(Arg: ArgLoc,
2417 UPPC: Sema::UPPC_TypeConstraint))
2418 return true;
2419 continue;
2420 }
2421
2422 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: P)) {
2423 if (!NTTP->isParameterPack() &&
2424 S.DiagnoseUnexpandedParameterPack(Loc: NTTP->getLocation(),
2425 T: NTTP->getTypeSourceInfo(),
2426 UPPC: Sema::UPPC_NonTypeTemplateParameterType))
2427 return true;
2428
2429 continue;
2430 }
2431
2432 if (TemplateTemplateParmDecl *InnerTTP
2433 = dyn_cast<TemplateTemplateParmDecl>(Val: P))
2434 if (DiagnoseUnexpandedParameterPacks(S, TTP: InnerTTP))
2435 return true;
2436 }
2437
2438 return false;
2439}
2440
2441bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2442 TemplateParameterList *OldParams,
2443 TemplateParamListContext TPC,
2444 SkipBodyInfo *SkipBody) {
2445 bool Invalid = false;
2446
2447 // C++ [temp.param]p10:
2448 // The set of default template-arguments available for use with a
2449 // template declaration or definition is obtained by merging the
2450 // default arguments from the definition (if in scope) and all
2451 // declarations in scope in the same way default function
2452 // arguments are (8.3.6).
2453 bool SawDefaultArgument = false;
2454 SourceLocation PreviousDefaultArgLoc;
2455
2456 // Dummy initialization to avoid warnings.
2457 TemplateParameterList::iterator OldParam = NewParams->end();
2458 if (OldParams)
2459 OldParam = OldParams->begin();
2460
2461 bool RemoveDefaultArguments = false;
2462 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2463 NewParamEnd = NewParams->end();
2464 NewParam != NewParamEnd; ++NewParam) {
2465 // Whether we've seen a duplicate default argument in the same translation
2466 // unit.
2467 bool RedundantDefaultArg = false;
2468 // Whether we've found inconsis inconsitent default arguments in different
2469 // translation unit.
2470 bool InconsistentDefaultArg = false;
2471 // The name of the module which contains the inconsistent default argument.
2472 std::string PrevModuleName;
2473
2474 SourceLocation OldDefaultLoc;
2475 SourceLocation NewDefaultLoc;
2476
2477 // Variable used to diagnose missing default arguments
2478 bool MissingDefaultArg = false;
2479
2480 // Variable used to diagnose non-final parameter packs
2481 bool SawParameterPack = false;
2482
2483 if (TemplateTypeParmDecl *NewTypeParm
2484 = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam)) {
2485 // Check the presence of a default argument here.
2486 if (NewTypeParm->hasDefaultArgument() &&
2487 DiagnoseDefaultTemplateArgument(
2488 S&: *this, TPC, ParamLoc: NewTypeParm->getLocation(),
2489 DefArgRange: NewTypeParm->getDefaultArgument().getSourceRange()))
2490 NewTypeParm->removeDefaultArgument();
2491
2492 // Merge default arguments for template type parameters.
2493 TemplateTypeParmDecl *OldTypeParm
2494 = OldParams? cast<TemplateTypeParmDecl>(Val: *OldParam) : nullptr;
2495 if (NewTypeParm->isParameterPack()) {
2496 assert(!NewTypeParm->hasDefaultArgument() &&
2497 "Parameter packs can't have a default argument!");
2498 SawParameterPack = true;
2499 } else if (OldTypeParm && hasVisibleDefaultArgument(D: OldTypeParm) &&
2500 NewTypeParm->hasDefaultArgument() &&
2501 (!SkipBody || !SkipBody->ShouldSkip)) {
2502 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2503 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2504 SawDefaultArgument = true;
2505
2506 if (!OldTypeParm->getOwningModule())
2507 RedundantDefaultArg = true;
2508 else if (!getASTContext().isSameDefaultTemplateArgument(X: OldTypeParm,
2509 Y: NewTypeParm)) {
2510 InconsistentDefaultArg = true;
2511 PrevModuleName =
2512 OldTypeParm->getImportedOwningModule()->getFullModuleName();
2513 }
2514 PreviousDefaultArgLoc = NewDefaultLoc;
2515 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2516 // Merge the default argument from the old declaration to the
2517 // new declaration.
2518 NewTypeParm->setInheritedDefaultArgument(C: Context, Prev: OldTypeParm);
2519 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2520 } else if (NewTypeParm->hasDefaultArgument()) {
2521 SawDefaultArgument = true;
2522 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2523 } else if (SawDefaultArgument)
2524 MissingDefaultArg = true;
2525 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2526 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam)) {
2527 // Check for unexpanded parameter packs, except in a template template
2528 // parameter pack, as in those any unexpanded packs should be expanded
2529 // along with the parameter itself.
2530 if (TPC != TPC_TemplateTemplateParameterPack &&
2531 !NewNonTypeParm->isParameterPack() &&
2532 DiagnoseUnexpandedParameterPack(Loc: NewNonTypeParm->getLocation(),
2533 T: NewNonTypeParm->getTypeSourceInfo(),
2534 UPPC: UPPC_NonTypeTemplateParameterType)) {
2535 Invalid = true;
2536 continue;
2537 }
2538
2539 // Check the presence of a default argument here.
2540 if (NewNonTypeParm->hasDefaultArgument() &&
2541 DiagnoseDefaultTemplateArgument(
2542 S&: *this, TPC, ParamLoc: NewNonTypeParm->getLocation(),
2543 DefArgRange: NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2544 NewNonTypeParm->removeDefaultArgument();
2545 }
2546
2547 // Merge default arguments for non-type template parameters
2548 NonTypeTemplateParmDecl *OldNonTypeParm
2549 = OldParams? cast<NonTypeTemplateParmDecl>(Val: *OldParam) : nullptr;
2550 if (NewNonTypeParm->isParameterPack()) {
2551 assert(!NewNonTypeParm->hasDefaultArgument() &&
2552 "Parameter packs can't have a default argument!");
2553 if (!NewNonTypeParm->isPackExpansion())
2554 SawParameterPack = true;
2555 } else if (OldNonTypeParm && hasVisibleDefaultArgument(D: OldNonTypeParm) &&
2556 NewNonTypeParm->hasDefaultArgument() &&
2557 (!SkipBody || !SkipBody->ShouldSkip)) {
2558 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2559 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2560 SawDefaultArgument = true;
2561 if (!OldNonTypeParm->getOwningModule())
2562 RedundantDefaultArg = true;
2563 else if (!getASTContext().isSameDefaultTemplateArgument(
2564 X: OldNonTypeParm, Y: NewNonTypeParm)) {
2565 InconsistentDefaultArg = true;
2566 PrevModuleName =
2567 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2568 }
2569 PreviousDefaultArgLoc = NewDefaultLoc;
2570 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2571 // Merge the default argument from the old declaration to the
2572 // new declaration.
2573 NewNonTypeParm->setInheritedDefaultArgument(C: Context, Parm: OldNonTypeParm);
2574 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2575 } else if (NewNonTypeParm->hasDefaultArgument()) {
2576 SawDefaultArgument = true;
2577 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2578 } else if (SawDefaultArgument)
2579 MissingDefaultArg = true;
2580 } else {
2581 TemplateTemplateParmDecl *NewTemplateParm
2582 = cast<TemplateTemplateParmDecl>(Val: *NewParam);
2583
2584 // Check for unexpanded parameter packs, recursively.
2585 if (::DiagnoseUnexpandedParameterPacks(S&: *this, TTP: NewTemplateParm)) {
2586 Invalid = true;
2587 continue;
2588 }
2589
2590 // Check the presence of a default argument here.
2591 if (NewTemplateParm->hasDefaultArgument() &&
2592 DiagnoseDefaultTemplateArgument(S&: *this, TPC,
2593 ParamLoc: NewTemplateParm->getLocation(),
2594 DefArgRange: NewTemplateParm->getDefaultArgument().getSourceRange()))
2595 NewTemplateParm->removeDefaultArgument();
2596
2597 // Merge default arguments for template template parameters
2598 TemplateTemplateParmDecl *OldTemplateParm
2599 = OldParams? cast<TemplateTemplateParmDecl>(Val: *OldParam) : nullptr;
2600 if (NewTemplateParm->isParameterPack()) {
2601 assert(!NewTemplateParm->hasDefaultArgument() &&
2602 "Parameter packs can't have a default argument!");
2603 if (!NewTemplateParm->isPackExpansion())
2604 SawParameterPack = true;
2605 } else if (OldTemplateParm &&
2606 hasVisibleDefaultArgument(D: OldTemplateParm) &&
2607 NewTemplateParm->hasDefaultArgument() &&
2608 (!SkipBody || !SkipBody->ShouldSkip)) {
2609 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2610 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2611 SawDefaultArgument = true;
2612 if (!OldTemplateParm->getOwningModule())
2613 RedundantDefaultArg = true;
2614 else if (!getASTContext().isSameDefaultTemplateArgument(
2615 X: OldTemplateParm, Y: NewTemplateParm)) {
2616 InconsistentDefaultArg = true;
2617 PrevModuleName =
2618 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2619 }
2620 PreviousDefaultArgLoc = NewDefaultLoc;
2621 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2622 // Merge the default argument from the old declaration to the
2623 // new declaration.
2624 NewTemplateParm->setInheritedDefaultArgument(C: Context, Prev: OldTemplateParm);
2625 PreviousDefaultArgLoc
2626 = OldTemplateParm->getDefaultArgument().getLocation();
2627 } else if (NewTemplateParm->hasDefaultArgument()) {
2628 SawDefaultArgument = true;
2629 PreviousDefaultArgLoc
2630 = NewTemplateParm->getDefaultArgument().getLocation();
2631 } else if (SawDefaultArgument)
2632 MissingDefaultArg = true;
2633 }
2634
2635 // C++11 [temp.param]p11:
2636 // If a template parameter of a primary class template or alias template
2637 // is a template parameter pack, it shall be the last template parameter.
2638 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2639 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2640 Diag(Loc: (*NewParam)->getLocation(),
2641 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
2642 Invalid = true;
2643 }
2644
2645 // [basic.def.odr]/13:
2646 // There can be more than one definition of a
2647 // ...
2648 // default template argument
2649 // ...
2650 // in a program provided that each definition appears in a different
2651 // translation unit and the definitions satisfy the [same-meaning
2652 // criteria of the ODR].
2653 //
2654 // Simply, the design of modules allows the definition of template default
2655 // argument to be repeated across translation unit. Note that the ODR is
2656 // checked elsewhere. But it is still not allowed to repeat template default
2657 // argument in the same translation unit.
2658 if (RedundantDefaultArg) {
2659 Diag(Loc: NewDefaultLoc, DiagID: diag::err_template_param_default_arg_redefinition);
2660 Diag(Loc: OldDefaultLoc, DiagID: diag::note_template_param_prev_default_arg);
2661 Invalid = true;
2662 } else if (InconsistentDefaultArg) {
2663 // We could only diagnose about the case that the OldParam is imported.
2664 // The case NewParam is imported should be handled in ASTReader.
2665 Diag(Loc: NewDefaultLoc,
2666 DiagID: diag::err_template_param_default_arg_inconsistent_redefinition);
2667 Diag(Loc: OldDefaultLoc,
2668 DiagID: diag::note_template_param_prev_default_arg_in_other_module)
2669 << PrevModuleName;
2670 Invalid = true;
2671 } else if (MissingDefaultArg &&
2672 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2673 TPC == TPC_FriendClassTemplate)) {
2674 // C++ 23[temp.param]p14:
2675 // If a template-parameter of a class template, variable template, or
2676 // alias template has a default template argument, each subsequent
2677 // template-parameter shall either have a default template argument
2678 // supplied or be a template parameter pack.
2679 Diag(Loc: (*NewParam)->getLocation(),
2680 DiagID: diag::err_template_param_default_arg_missing);
2681 Diag(Loc: PreviousDefaultArgLoc, DiagID: diag::note_template_param_prev_default_arg);
2682 Invalid = true;
2683 RemoveDefaultArguments = true;
2684 }
2685
2686 // If we have an old template parameter list that we're merging
2687 // in, move on to the next parameter.
2688 if (OldParams)
2689 ++OldParam;
2690 }
2691
2692 // We were missing some default arguments at the end of the list, so remove
2693 // all of the default arguments.
2694 if (RemoveDefaultArguments) {
2695 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2696 NewParamEnd = NewParams->end();
2697 NewParam != NewParamEnd; ++NewParam) {
2698 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam))
2699 TTP->removeDefaultArgument();
2700 else if (NonTypeTemplateParmDecl *NTTP
2701 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam))
2702 NTTP->removeDefaultArgument();
2703 else
2704 cast<TemplateTemplateParmDecl>(Val: *NewParam)->removeDefaultArgument();
2705 }
2706 }
2707
2708 return Invalid;
2709}
2710
2711namespace {
2712
2713/// A class which looks for a use of a certain level of template
2714/// parameter.
2715struct DependencyChecker : DynamicRecursiveASTVisitor {
2716 unsigned Depth;
2717
2718 // Whether we're looking for a use of a template parameter that makes the
2719 // overall construct type-dependent / a dependent type. This is strictly
2720 // best-effort for now; we may fail to match at all for a dependent type
2721 // in some cases if this is set.
2722 bool IgnoreNonTypeDependent;
2723
2724 bool Match;
2725 SourceLocation MatchLoc;
2726
2727 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2728 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2729 Match(false) {}
2730
2731 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2732 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2733 NamedDecl *ND = Params->getParam(Idx: 0);
2734 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(Val: ND)) {
2735 Depth = PD->getDepth();
2736 } else if (NonTypeTemplateParmDecl *PD =
2737 dyn_cast<NonTypeTemplateParmDecl>(Val: ND)) {
2738 Depth = PD->getDepth();
2739 } else {
2740 Depth = cast<TemplateTemplateParmDecl>(Val: ND)->getDepth();
2741 }
2742 }
2743
2744 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2745 if (ParmDepth >= Depth) {
2746 Match = true;
2747 MatchLoc = Loc;
2748 return true;
2749 }
2750 return false;
2751 }
2752
2753 bool TraverseStmt(Stmt *S) override {
2754 // Prune out non-type-dependent expressions if requested. This can
2755 // sometimes result in us failing to find a template parameter reference
2756 // (if a value-dependent expression creates a dependent type), but this
2757 // mode is best-effort only.
2758 if (auto *E = dyn_cast_or_null<Expr>(Val: S))
2759 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2760 return true;
2761 return DynamicRecursiveASTVisitor::TraverseStmt(S);
2762 }
2763
2764 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2765 if (IgnoreNonTypeDependent && !TL.isNull() &&
2766 !TL.getType()->isDependentType())
2767 return true;
2768 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2769 }
2770
2771 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2772 return !Matches(ParmDepth: TL.getTypePtr()->getDepth(), Loc: TL.getNameLoc());
2773 }
2774
2775 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2776 // For a best-effort search, keep looking until we find a location.
2777 return IgnoreNonTypeDependent || !Matches(ParmDepth: T->getDepth());
2778 }
2779
2780 bool TraverseTemplateName(TemplateName N, bool TraverseQualifier) override {
2781 if (TemplateTemplateParmDecl *PD =
2782 dyn_cast_or_null<TemplateTemplateParmDecl>(Val: N.getAsTemplateDecl()))
2783 if (Matches(ParmDepth: PD->getDepth()))
2784 return false;
2785 return DynamicRecursiveASTVisitor::TraverseTemplateName(Template: N,
2786 TraverseQualifier);
2787 }
2788
2789 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2790 if (NonTypeTemplateParmDecl *PD =
2791 dyn_cast<NonTypeTemplateParmDecl>(Val: E->getDecl()))
2792 if (Matches(ParmDepth: PD->getDepth(), Loc: E->getExprLoc()))
2793 return false;
2794 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(S: E);
2795 }
2796
2797 bool VisitDependentTemplateIdExpr(DependentTemplateIdExpr *E) override {
2798 if (Matches(ParmDepth: E->getParameter()->getDepth(), Loc: E->getExprLoc()))
2799 return false;
2800 return DynamicRecursiveASTVisitor::VisitDependentTemplateIdExpr(S: E);
2801 }
2802
2803 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2804 return TraverseType(T: T->getReplacementType());
2805 }
2806
2807 bool VisitSubstTemplateTypeParmPackType(
2808 SubstTemplateTypeParmPackType *T) override {
2809 return TraverseTemplateArgument(Arg: T->getArgumentPack());
2810 }
2811
2812 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2813 bool TraverseQualifier) override {
2814 // An InjectedClassNameType will never have a dependent template name,
2815 // so no need to traverse it.
2816 return TraverseTemplateArguments(
2817 Args: T->getTemplateArgs(Ctx: T->getDecl()->getASTContext()));
2818 }
2819};
2820} // end anonymous namespace
2821
2822/// Determines whether a given type depends on the given parameter
2823/// list.
2824static bool
2825DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2826 if (!Params->size())
2827 return false;
2828
2829 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2830 Checker.TraverseType(T);
2831 return Checker.Match;
2832}
2833
2834// Find the source range corresponding to the named type in the given
2835// nested-name-specifier, if any.
2836static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2837 QualType T,
2838 const CXXScopeSpec &SS) {
2839 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2840 for (;;) {
2841 NestedNameSpecifier NNS = NNSLoc.getNestedNameSpecifier();
2842 if (NNS.getKind() != NestedNameSpecifier::Kind::Type)
2843 break;
2844 if (Context.hasSameUnqualifiedType(T1: T, T2: QualType(NNS.getAsType(), 0)))
2845 return NNSLoc.castAsTypeLoc().getSourceRange();
2846 // FIXME: This will always be empty.
2847 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2848 }
2849
2850 return SourceRange();
2851}
2852
2853TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2854 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2855 TemplateIdAnnotation *TemplateId,
2856 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2857 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2858 IsMemberSpecialization = false;
2859 Invalid = false;
2860
2861 // The sequence of nested types to which we will match up the template
2862 // parameter lists. We first build this list by starting with the type named
2863 // by the nested-name-specifier and walking out until we run out of types.
2864 SmallVector<QualType, 4> NestedTypes;
2865 QualType T;
2866 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2867 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2868 if (CXXRecordDecl *Record =
2869 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: true)))
2870 T = Context.getCanonicalTagType(TD: Record);
2871 else
2872 T = QualType(Qualifier.getAsType(), 0);
2873 }
2874
2875 // If we found an explicit specialization that prevents us from needing
2876 // 'template<>' headers, this will be set to the location of that
2877 // explicit specialization.
2878 SourceLocation ExplicitSpecLoc;
2879
2880 while (!T.isNull()) {
2881 NestedTypes.push_back(Elt: T);
2882
2883 // Retrieve the parent of a record type.
2884 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2885 // If this type is an explicit specialization, we're done.
2886 if (ClassTemplateSpecializationDecl *Spec
2887 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
2888 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Spec) &&
2889 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2890 ExplicitSpecLoc = Spec->getLocation();
2891 break;
2892 }
2893 } else if (Record->getTemplateSpecializationKind()
2894 == TSK_ExplicitSpecialization) {
2895 ExplicitSpecLoc = Record->getLocation();
2896 break;
2897 }
2898
2899 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Record->getParent()))
2900 T = Context.getTypeDeclType(Decl: Parent);
2901 else
2902 T = QualType();
2903 continue;
2904 }
2905
2906 if (const TemplateSpecializationType *TST
2907 = T->getAs<TemplateSpecializationType>()) {
2908 TemplateName Name = TST->getTemplateName();
2909 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2910 // Look one step prior in a dependent template specialization type.
2911 if (NestedNameSpecifier NNS = DTS->getQualifier();
2912 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2913 T = QualType(NNS.getAsType(), 0);
2914 else
2915 T = QualType();
2916 continue;
2917 }
2918 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2919 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Template->getDeclContext()))
2920 T = Context.getTypeDeclType(Decl: Parent);
2921 else
2922 T = QualType();
2923 continue;
2924 }
2925 }
2926
2927 // Look one step prior in a dependent name type.
2928 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2929 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2930 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2931 T = QualType(NNS.getAsType(), 0);
2932 else
2933 T = QualType();
2934 continue;
2935 }
2936
2937 // Retrieve the parent of an enumeration type.
2938 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2939 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2940 // check here.
2941 EnumDecl *Enum = EnumT->getDecl();
2942
2943 // Get to the parent type.
2944 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Enum->getParent()))
2945 T = Context.getCanonicalTypeDeclType(TD: Parent);
2946 else
2947 T = QualType();
2948 continue;
2949 }
2950
2951 T = QualType();
2952 }
2953 // Reverse the nested types list, since we want to traverse from the outermost
2954 // to the innermost while checking template-parameter-lists.
2955 std::reverse(first: NestedTypes.begin(), last: NestedTypes.end());
2956
2957 // C++0x [temp.expl.spec]p17:
2958 // A member or a member template may be nested within many
2959 // enclosing class templates. In an explicit specialization for
2960 // such a member, the member declaration shall be preceded by a
2961 // template<> for each enclosing class template that is
2962 // explicitly specialized.
2963 bool SawNonEmptyTemplateParameterList = false;
2964
2965 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2966 if (SawNonEmptyTemplateParameterList) {
2967 if (!SuppressDiagnostic)
2968 Diag(Loc: DeclLoc, DiagID: diag::err_specialize_member_of_template)
2969 << !Recovery << Range;
2970 Invalid = true;
2971 IsMemberSpecialization = false;
2972 return true;
2973 }
2974
2975 return false;
2976 };
2977
2978 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2979 // Check that we can have an explicit specialization here.
2980 if (CheckExplicitSpecialization(Range, true))
2981 return true;
2982
2983 // We don't have a template header, but we should.
2984 SourceLocation ExpectedTemplateLoc;
2985 if (!ParamLists.empty())
2986 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2987 else
2988 ExpectedTemplateLoc = DeclStartLoc;
2989
2990 if (!SuppressDiagnostic)
2991 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_header)
2992 << Range
2993 << FixItHint::CreateInsertion(InsertionLoc: ExpectedTemplateLoc, Code: "template<> ");
2994 return false;
2995 };
2996
2997 unsigned ParamIdx = 0;
2998 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2999 ++TypeIdx) {
3000 T = NestedTypes[TypeIdx];
3001
3002 // Whether we expect a 'template<>' header.
3003 bool NeedEmptyTemplateHeader = false;
3004
3005 // Whether we expect a template header with parameters.
3006 bool NeedNonemptyTemplateHeader = false;
3007
3008 // For a dependent type, the set of template parameters that we
3009 // expect to see.
3010 TemplateParameterList *ExpectedTemplateParams = nullptr;
3011
3012 // C++0x [temp.expl.spec]p15:
3013 // A member or a member template may be nested within many enclosing
3014 // class templates. In an explicit specialization for such a member, the
3015 // member declaration shall be preceded by a template<> for each
3016 // enclosing class template that is explicitly specialized.
3017 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3018 if (ClassTemplatePartialSpecializationDecl *Partial
3019 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Record)) {
3020 ExpectedTemplateParams = Partial->getTemplateParameters();
3021 NeedNonemptyTemplateHeader = true;
3022 } else if (Record->isDependentType()) {
3023 if (Record->getDescribedClassTemplate()) {
3024 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3025 ->getTemplateParameters();
3026 NeedNonemptyTemplateHeader = true;
3027 }
3028 } else if (ClassTemplateSpecializationDecl *Spec
3029 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
3030 // C++0x [temp.expl.spec]p4:
3031 // Members of an explicitly specialized class template are defined
3032 // in the same manner as members of normal classes, and not using
3033 // the template<> syntax.
3034 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3035 NeedEmptyTemplateHeader = true;
3036 else
3037 continue;
3038 } else if (Record->getTemplateSpecializationKind()) {
3039 if (Record->getTemplateSpecializationKind()
3040 != TSK_ExplicitSpecialization &&
3041 TypeIdx == NumTypes - 1)
3042 IsMemberSpecialization = true;
3043
3044 continue;
3045 }
3046 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3047 TemplateName Name = TST->getTemplateName();
3048 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3049 ExpectedTemplateParams = Template->getTemplateParameters();
3050 NeedNonemptyTemplateHeader = true;
3051 } else if (Name.getAsDependentTemplateName()) {
3052 NeedNonemptyTemplateHeader = true;
3053 } else if (Name.getAsDeducedTemplateName()) {
3054 // FIXME: We actually could/should check the template arguments here
3055 // against the corresponding template parameter list.
3056 NeedNonemptyTemplateHeader = false;
3057 }
3058 }
3059
3060 // C++ [temp.expl.spec]p16:
3061 // In an explicit specialization declaration for a member of a class
3062 // template or a member template that appears in namespace scope, the
3063 // member template and some of its enclosing class templates may remain
3064 // unspecialized, except that the declaration shall not explicitly
3065 // specialize a class member template if its enclosing class templates
3066 // are not explicitly specialized as well.
3067 if (ParamIdx < ParamLists.size()) {
3068 if (ParamLists[ParamIdx]->size() == 0) {
3069 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3070 false))
3071 return nullptr;
3072 } else
3073 SawNonEmptyTemplateParameterList = true;
3074 }
3075
3076 if (NeedEmptyTemplateHeader) {
3077 // If we're on the last of the types, and we need a 'template<>' header
3078 // here, then it's a member specialization.
3079 if (TypeIdx == NumTypes - 1)
3080 IsMemberSpecialization = true;
3081
3082 if (ParamIdx < ParamLists.size()) {
3083 if (ParamLists[ParamIdx]->size() > 0) {
3084 // The header has template parameters when it shouldn't. Complain.
3085 if (!SuppressDiagnostic)
3086 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3087 DiagID: diag::err_template_param_list_matches_nontemplate)
3088 << T
3089 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3090 ParamLists[ParamIdx]->getRAngleLoc())
3091 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3092 Invalid = true;
3093 return nullptr;
3094 }
3095
3096 // Consume this template header.
3097 ++ParamIdx;
3098 continue;
3099 }
3100
3101 if (!IsFriend)
3102 if (DiagnoseMissingExplicitSpecialization(
3103 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3104 return nullptr;
3105
3106 continue;
3107 }
3108
3109 if (NeedNonemptyTemplateHeader) {
3110 // In friend declarations we can have template-ids which don't
3111 // depend on the corresponding template parameter lists. But
3112 // assume that empty parameter lists are supposed to match this
3113 // template-id.
3114 if (IsFriend && T->isDependentType()) {
3115 if (ParamIdx < ParamLists.size() &&
3116 DependsOnTemplateParameters(T, Params: ParamLists[ParamIdx]))
3117 ExpectedTemplateParams = nullptr;
3118 else
3119 continue;
3120 }
3121
3122 if (ParamIdx < ParamLists.size()) {
3123 // Check the template parameter list, if we can.
3124 if (ExpectedTemplateParams &&
3125 !TemplateParameterListsAreEqual(New: ParamLists[ParamIdx],
3126 Old: ExpectedTemplateParams,
3127 Complain: !SuppressDiagnostic, Kind: TPL_TemplateMatch))
3128 Invalid = true;
3129
3130 if (!Invalid &&
3131 CheckTemplateParameterList(NewParams: ParamLists[ParamIdx], OldParams: nullptr,
3132 TPC: TPC_ClassTemplateMember))
3133 Invalid = true;
3134
3135 ++ParamIdx;
3136 continue;
3137 }
3138
3139 if (!SuppressDiagnostic)
3140 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_template_parameters)
3141 << T
3142 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3143 Invalid = true;
3144 continue;
3145 }
3146 }
3147
3148 // If there were at least as many template-ids as there were template
3149 // parameter lists, then there are no template parameter lists remaining for
3150 // the declaration itself.
3151 if (ParamIdx >= ParamLists.size()) {
3152 if (TemplateId && !IsFriend) {
3153 // We don't have a template header for the declaration itself, but we
3154 // should.
3155 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3156 TemplateId->RAngleLoc));
3157
3158 // Fabricate an empty template parameter list for the invented header.
3159 return TemplateParameterList::Create(C: Context, TemplateLoc: SourceLocation(),
3160 LAngleLoc: SourceLocation(), Params: {},
3161 RAngleLoc: SourceLocation(), RequiresClause: nullptr);
3162 }
3163
3164 return nullptr;
3165 }
3166
3167 // If there were too many template parameter lists, complain about that now.
3168 if (ParamIdx < ParamLists.size() - 1) {
3169 bool HasAnyExplicitSpecHeader = false;
3170 bool AllExplicitSpecHeaders = true;
3171 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3172 if (ParamLists[I]->size() == 0)
3173 HasAnyExplicitSpecHeader = true;
3174 else
3175 AllExplicitSpecHeaders = false;
3176 }
3177
3178 if (!SuppressDiagnostic)
3179 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3180 DiagID: AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3181 : diag::err_template_spec_extra_headers)
3182 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3183 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3184
3185 // If there was a specialization somewhere, such that 'template<>' is
3186 // not required, and there were any 'template<>' headers, note where the
3187 // specialization occurred.
3188 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3189 !SuppressDiagnostic)
3190 Diag(Loc: ExplicitSpecLoc,
3191 DiagID: diag::note_explicit_template_spec_does_not_need_header)
3192 << NestedTypes.back();
3193
3194 // We have a template parameter list with no corresponding scope, which
3195 // means that the resulting template declaration can't be instantiated
3196 // properly (we'll end up with dependent nodes when we shouldn't).
3197 if (!AllExplicitSpecHeaders)
3198 Invalid = true;
3199 }
3200
3201 // C++ [temp.expl.spec]p16:
3202 // In an explicit specialization declaration for a member of a class
3203 // template or a member template that ap- pears in namespace scope, the
3204 // member template and some of its enclosing class templates may remain
3205 // unspecialized, except that the declaration shall not explicitly
3206 // specialize a class member template if its en- closing class templates
3207 // are not explicitly specialized as well.
3208 if (ParamLists.back()->size() == 0 &&
3209 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3210 false))
3211 return nullptr;
3212
3213 // Return the last template parameter list, which corresponds to the
3214 // entity being declared.
3215 return ParamLists.back();
3216}
3217
3218void Sema::NoteAllFoundTemplates(TemplateName Name) {
3219 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3220 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_declared_here)
3221 << (isa<FunctionTemplateDecl>(Val: Template)
3222 ? 0
3223 : isa<ClassTemplateDecl>(Val: Template)
3224 ? 1
3225 : isa<VarTemplateDecl>(Val: Template)
3226 ? 2
3227 : isa<TypeAliasTemplateDecl>(Val: Template) ? 3 : 4)
3228 << Template->getDeclName();
3229 return;
3230 }
3231
3232 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3233 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3234 IEnd = OST->end();
3235 I != IEnd; ++I)
3236 Diag(Loc: (*I)->getLocation(), DiagID: diag::note_template_declared_here)
3237 << 0 << (*I)->getDeclName();
3238
3239 return;
3240 }
3241}
3242
3243static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword,
3244 TemplateName BaseTemplate,
3245 SourceLocation TemplateLoc,
3246 ArrayRef<TemplateArgument> Ts) {
3247 auto lookUpCommonType = [&](TemplateArgument T1,
3248 TemplateArgument T2) -> QualType {
3249 // Don't bother looking for other specializations if both types are
3250 // builtins - users aren't allowed to specialize for them
3251 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3252 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3253 Ts: {T1, T2});
3254
3255 TemplateArgumentListInfo Args;
3256 Args.addArgument(Loc: TemplateArgumentLoc(
3257 T1, S.Context.getTrivialTypeSourceInfo(T: T1.getAsType())));
3258 Args.addArgument(Loc: TemplateArgumentLoc(
3259 T2, S.Context.getTrivialTypeSourceInfo(T: T2.getAsType())));
3260
3261 EnterExpressionEvaluationContext UnevaluatedContext(
3262 S, Sema::ExpressionEvaluationContext::Unevaluated);
3263 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3264 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3265
3266 QualType BaseTemplateInst = S.CheckTemplateIdType(
3267 Keyword, Template: BaseTemplate, TemplateLoc, TemplateArgs&: Args,
3268 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3269
3270 if (SFINAE.hasErrorOccurred())
3271 return QualType();
3272
3273 return BaseTemplateInst;
3274 };
3275
3276 // Note A: For the common_type trait applied to a template parameter pack T of
3277 // types, the member type shall be either defined or not present as follows:
3278 switch (Ts.size()) {
3279
3280 // If sizeof...(T) is zero, there shall be no member type.
3281 case 0:
3282 return QualType();
3283
3284 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3285 // pack T. The member typedef-name type shall denote the same type, if any, as
3286 // common_type_t<T0, T0>; otherwise there shall be no member type.
3287 case 1:
3288 return lookUpCommonType(Ts[0], Ts[0]);
3289
3290 // If sizeof...(T) is two, let the first and second types constituting T be
3291 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3292 // as decay_t<T1> and decay_t<T2>, respectively.
3293 case 2: {
3294 QualType T1 = Ts[0].getAsType();
3295 QualType T2 = Ts[1].getAsType();
3296 QualType D1 = S.BuiltinDecay(BaseType: T1, Loc: {});
3297 QualType D2 = S.BuiltinDecay(BaseType: T2, Loc: {});
3298
3299 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3300 // the same type, if any, as common_type_t<D1, D2>.
3301 if (!S.Context.hasSameType(T1, T2: D1) || !S.Context.hasSameType(T1: T2, T2: D2))
3302 return lookUpCommonType(D1, D2);
3303
3304 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3305 // denotes a valid type, let C denote that type.
3306 {
3307 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3308 EnterExpressionEvaluationContext UnevaluatedContext(
3309 S, Sema::ExpressionEvaluationContext::Unevaluated);
3310 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3311 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3312
3313 // false
3314 OpaqueValueExpr CondExpr(SourceLocation(), S.Context.BoolTy,
3315 VK_PRValue);
3316 ExprResult Cond = &CondExpr;
3317
3318 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3319 if (ConstRefQual) {
3320 D1.addConst();
3321 D2.addConst();
3322 }
3323
3324 // declval<D1>()
3325 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3326 ExprResult LHS = &LHSExpr;
3327
3328 // declval<D2>()
3329 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3330 ExprResult RHS = &RHSExpr;
3331
3332 ExprValueKind VK = VK_PRValue;
3333 ExprObjectKind OK = OK_Ordinary;
3334
3335 // decltype(false ? declval<D1>() : declval<D2>())
3336 QualType Result =
3337 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc: TemplateLoc);
3338
3339 if (Result.isNull() || SFINAE.hasErrorOccurred())
3340 return QualType();
3341
3342 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3343 return S.BuiltinDecay(BaseType: Result, Loc: TemplateLoc);
3344 };
3345
3346 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3347 return Res;
3348
3349 // Let:
3350 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3351 // COND-RES(X, Y) be
3352 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3353
3354 // C++20 only
3355 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3356 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3357 if (!S.Context.getLangOpts().CPlusPlus20)
3358 return QualType();
3359 return CheckConditionalOperands(true);
3360 }
3361 }
3362
3363 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3364 // denote the first, second, and (pack of) remaining types constituting T. Let
3365 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3366 // a type C, the member typedef-name type shall denote the same type, if any,
3367 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3368 default: {
3369 QualType Result = Ts.front().getAsType();
3370 for (auto T : llvm::drop_begin(RangeOrContainer&: Ts)) {
3371 Result = lookUpCommonType(Result, T.getAsType());
3372 if (Result.isNull())
3373 return QualType();
3374 }
3375 return Result;
3376 }
3377 }
3378}
3379
3380static bool isInVkNamespace(const RecordType *RT) {
3381 DeclContext *DC = RT->getDecl()->getDeclContext();
3382 if (!DC)
3383 return false;
3384
3385 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Val: DC);
3386 if (!ND)
3387 return false;
3388
3389 return ND->getQualifiedNameAsString() == "hlsl::vk";
3390}
3391
3392static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3393 QualType OperandArg,
3394 SourceLocation Loc) {
3395 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3396 bool Literal = false;
3397 SourceLocation LiteralLoc;
3398 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3399 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3400 assert(SpecDecl);
3401
3402 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3403 QualType ConstantType = LiteralArgs[0].getAsType();
3404 RT = ConstantType->getAsCanonical<RecordType>();
3405 Literal = true;
3406 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3407 }
3408
3409 if (RT && isInVkNamespace(RT) &&
3410 RT->getDecl()->getName() == "integral_constant") {
3411 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3412 assert(SpecDecl);
3413
3414 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3415
3416 QualType ConstantType = ConstantArgs[0].getAsType();
3417 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3418
3419 if (Literal)
3420 return SpirvOperand::createLiteral(Val: Value);
3421 return SpirvOperand::createConstant(ResultType: ConstantType, Val: Value);
3422 } else if (Literal) {
3423 SemaRef.Diag(Loc: LiteralLoc, DiagID: diag::err_hlsl_vk_literal_must_contain_constant);
3424 return SpirvOperand();
3425 }
3426 }
3427 if (SemaRef.RequireCompleteType(Loc, T: OperandArg,
3428 DiagID: diag::err_call_incomplete_argument))
3429 return SpirvOperand();
3430 return SpirvOperand::createType(T: OperandArg);
3431}
3432
3433static QualType sortBuiltinTemplatePack(ASTContext &Context,
3434 ArrayRef<TemplateArgument> InputArgs) {
3435 // FIXME: cache mangling globally?
3436 std::unique_ptr<MangleContext> MC(Context.createMangleContext());
3437 SmallVector<std::pair<std::string, TemplateArgument>> SortedArgs(
3438 InputArgs.size());
3439 llvm::transform(Range&: InputArgs, d_first: SortedArgs.begin(),
3440 F: [&](const TemplateArgument &Arg) {
3441 assert(Arg.getKind() == TemplateArgument::Type);
3442 std::string MangledName;
3443 llvm::raw_string_ostream OS(MangledName);
3444 MC->mangleCanonicalTypeName(T: Arg.getAsType(), OS);
3445 return std::pair<std::string, TemplateArgument>(
3446 std::move(MangledName), Arg);
3447 });
3448 llvm::stable_sort(Range&: SortedArgs, C: llvm::less_first());
3449
3450 auto OutArgs = llvm::to_vector(Range: llvm::make_second_range(c&: SortedArgs));
3451 return Context.getSubstBuiltinTemplatePack(
3452 ArgPack: TemplateArgument::CreatePackCopy(Context, Args: OutArgs));
3453}
3454
3455static QualType checkBuiltinTemplateIdType(
3456 Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD,
3457 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3458 TemplateArgumentListInfo &TemplateArgs) {
3459 ASTContext &Context = SemaRef.getASTContext();
3460
3461 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3462 "Builtin template arguments do not match its parameters");
3463
3464 switch (BTD->getBuiltinTemplateKind()) {
3465 case BTK__make_integer_seq: {
3466 // Specializations of __make_integer_seq<S, T, N> are treated like
3467 // S<T, 0, ..., N-1>.
3468
3469 QualType OrigType = Converted[1].getAsType();
3470 // C++14 [inteseq.intseq]p1:
3471 // T shall be an integer type.
3472 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Ctx: Context)) {
3473 SemaRef.Diag(Loc: TemplateArgs[1].getLocation(),
3474 DiagID: diag::err_integer_sequence_integral_element_type);
3475 return QualType();
3476 }
3477
3478 TemplateArgument NumArgsArg = Converted[2];
3479 if (NumArgsArg.isDependent())
3480 return QualType();
3481
3482 TemplateArgumentListInfo SyntheticTemplateArgs;
3483 // The type argument, wrapped in substitution sugar, gets reused as the
3484 // first template argument in the synthetic template argument list.
3485 SyntheticTemplateArgs.addArgument(
3486 Loc: TemplateArgumentLoc(TemplateArgument(OrigType),
3487 SemaRef.Context.getTrivialTypeSourceInfo(
3488 T: OrigType, Loc: TemplateArgs[1].getLocation())));
3489
3490 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3491 // Expand N into 0 ... N-1.
3492 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3493 I < NumArgs; ++I) {
3494 TemplateArgument TA(Context, I, OrigType);
3495 SyntheticTemplateArgs.addArgument(Loc: SemaRef.getTrivialTemplateArgumentLoc(
3496 Arg: TA, NTTPType: OrigType, Loc: TemplateArgs[2].getLocation()));
3497 }
3498 } else {
3499 // C++14 [inteseq.make]p1:
3500 // If N is negative the program is ill-formed.
3501 SemaRef.Diag(Loc: TemplateArgs[2].getLocation(),
3502 DiagID: diag::err_integer_sequence_negative_length);
3503 return QualType();
3504 }
3505
3506 // The first template argument will be reused as the template decl that
3507 // our synthetic template arguments will be applied to.
3508 return SemaRef.CheckTemplateIdType(Keyword, Template: Converted[0].getAsTemplate(),
3509 TemplateLoc, TemplateArgs&: SyntheticTemplateArgs,
3510 /*Scope=*/nullptr,
3511 /*ForNestedNameSpecifier=*/false);
3512 }
3513
3514 case BTK__type_pack_element: {
3515 // Specializations of
3516 // __type_pack_element<Index, T_1, ..., T_N>
3517 // are treated like T_Index.
3518 assert(Converted.size() == 2 &&
3519 "__type_pack_element should be given an index and a parameter pack");
3520
3521 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3522 if (IndexArg.isDependent() || Ts.isDependent())
3523 return QualType();
3524
3525 llvm::APSInt Index = IndexArg.getAsIntegral();
3526 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3527 "type std::size_t, and hence be non-negative");
3528 // If the Index is out of bounds, the program is ill-formed.
3529 if (Index >= Ts.pack_size()) {
3530 SemaRef.Diag(Loc: TemplateArgs[0].getLocation(),
3531 DiagID: diag::err_type_pack_element_out_of_bounds);
3532 return QualType();
3533 }
3534
3535 // We simply return the type at index `Index`.
3536 int64_t N = Index.getExtValue();
3537 return Ts.getPackAsArray()[N].getAsType();
3538 }
3539
3540 case BTK__builtin_common_type: {
3541 assert(Converted.size() == 4);
3542 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3543 return QualType();
3544
3545 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3546 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3547 if (auto CT = builtinCommonTypeImpl(S&: SemaRef, Keyword, BaseTemplate,
3548 TemplateLoc, Ts);
3549 !CT.isNull()) {
3550 TemplateArgumentListInfo TAs;
3551 TAs.addArgument(Loc: TemplateArgumentLoc(
3552 TemplateArgument(CT), SemaRef.Context.getTrivialTypeSourceInfo(
3553 T: CT, Loc: TemplateArgs[1].getLocation())));
3554 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3555 return SemaRef.CheckTemplateIdType(Keyword, Template: HasTypeMember, TemplateLoc,
3556 TemplateArgs&: TAs, /*Scope=*/nullptr,
3557 /*ForNestedNameSpecifier=*/false);
3558 }
3559 QualType HasNoTypeMember = Converted[2].getAsType();
3560 return HasNoTypeMember;
3561 }
3562
3563 case BTK__hlsl_spirv_type: {
3564 assert(Converted.size() == 4);
3565
3566 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3567 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_hlsl_spirv_only) << BTD;
3568 }
3569
3570 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3571 return QualType();
3572
3573 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3574 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3575 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3576
3577 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3578
3579 llvm::SmallVector<SpirvOperand> Operands;
3580
3581 for (auto &OperandTA : OperandArgs) {
3582 QualType OperandArg = OperandTA.getAsType();
3583 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3584 Loc: TemplateArgs[3].getLocation());
3585 if (!Operand.isValid())
3586 return QualType();
3587 Operands.push_back(Elt: Operand);
3588 }
3589
3590 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3591 }
3592 case BTK__builtin_dedup_pack: {
3593 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3594 "a parameter pack");
3595 TemplateArgument Ts = Converted[0];
3596 // Delay the computation until we can compute the final result. We choose
3597 // not to remove the duplicates upfront before substitution to keep the code
3598 // simple.
3599 if (Ts.isDependent())
3600 return QualType();
3601 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3602 llvm::SmallVector<TemplateArgument> OutArgs;
3603 llvm::SmallDenseSet<QualType> Seen;
3604 // Synthesize a new template argument list, removing duplicates.
3605 for (auto T : Ts.getPackAsArray()) {
3606 assert(T.getKind() == clang::TemplateArgument::Type);
3607 if (!Seen.insert(V: T.getAsType().getCanonicalType()).second)
3608 continue;
3609 OutArgs.push_back(Elt: T);
3610 }
3611 return Context.getSubstBuiltinTemplatePack(
3612 ArgPack: TemplateArgument::CreatePackCopy(Context, Args: OutArgs));
3613 }
3614 case BTK__builtin_sort_pack: {
3615 assert(Converted.size() == 1 &&
3616 "__builtin_sort_pack should be given a parameter pack");
3617 TemplateArgument Ts = Converted[0];
3618 if (Ts.isDependent())
3619 return QualType();
3620 assert(Ts.getKind() == TemplateArgument::Pack);
3621 return sortBuiltinTemplatePack(Context, InputArgs: Ts.getPackAsArray());
3622 }
3623 }
3624 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3625}
3626
3627/// Determine whether this alias template is "enable_if_t".
3628/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3629static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3630 return AliasTemplate->getName() == "enable_if_t" ||
3631 AliasTemplate->getName() == "__enable_if_t";
3632}
3633
3634/// Collect all of the separable terms in the given condition, which
3635/// might be a conjunction.
3636///
3637/// FIXME: The right answer is to convert the logical expression into
3638/// disjunctive normal form, so we can find the first failed term
3639/// within each possible clause.
3640static void collectConjunctionTerms(Expr *Clause,
3641 SmallVectorImpl<Expr *> &Terms) {
3642 if (auto BinOp = dyn_cast<BinaryOperator>(Val: Clause->IgnoreParenImpCasts())) {
3643 if (BinOp->getOpcode() == BO_LAnd) {
3644 collectConjunctionTerms(Clause: BinOp->getLHS(), Terms);
3645 collectConjunctionTerms(Clause: BinOp->getRHS(), Terms);
3646 return;
3647 }
3648 }
3649
3650 Terms.push_back(Elt: Clause);
3651}
3652
3653// The ranges-v3 library uses an odd pattern of a top-level "||" with
3654// a left-hand side that is value-dependent but never true. Identify
3655// the idiom and ignore that term.
3656static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3657 // Top-level '||'.
3658 auto *BinOp = dyn_cast<BinaryOperator>(Val: Cond->IgnoreParenImpCasts());
3659 if (!BinOp) return Cond;
3660
3661 if (BinOp->getOpcode() != BO_LOr) return Cond;
3662
3663 // With an inner '==' that has a literal on the right-hand side.
3664 Expr *LHS = BinOp->getLHS();
3665 auto *InnerBinOp = dyn_cast<BinaryOperator>(Val: LHS->IgnoreParenImpCasts());
3666 if (!InnerBinOp) return Cond;
3667
3668 if (InnerBinOp->getOpcode() != BO_EQ ||
3669 !isa<IntegerLiteral>(Val: InnerBinOp->getRHS()))
3670 return Cond;
3671
3672 // If the inner binary operation came from a macro expansion named
3673 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3674 // of the '||', which is the real, user-provided condition.
3675 SourceLocation Loc = InnerBinOp->getExprLoc();
3676 if (!Loc.isMacroID()) return Cond;
3677
3678 StringRef MacroName = PP.getImmediateMacroName(Loc);
3679 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3680 return BinOp->getRHS();
3681
3682 return Cond;
3683}
3684
3685namespace {
3686
3687// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3688// within failing boolean expression, such as substituting template parameters
3689// for actual types.
3690class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3691public:
3692 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3693 : Policy(P) {}
3694
3695 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3696 const auto *DR = dyn_cast<DeclRefExpr>(Val: E);
3697 if (DR && DR->getQualifier()) {
3698 // If this is a qualified name, expand the template arguments in nested
3699 // qualifiers.
3700 DR->getQualifier().print(OS, Policy, ResolveTemplateArguments: true);
3701 // Then print the decl itself.
3702 const ValueDecl *VD = DR->getDecl();
3703 OS << *VD;
3704 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) {
3705 // This is a template variable, print the expanded template arguments.
3706 printTemplateArgumentList(
3707 OS, Args: IV->getTemplateArgs().asArray(), Policy,
3708 TPL: IV->getSpecializedTemplate()->getTemplateParameters());
3709 }
3710 return true;
3711 }
3712 return false;
3713 }
3714
3715private:
3716 const PrintingPolicy Policy;
3717};
3718
3719} // end anonymous namespace
3720
3721std::pair<Expr *, std::string>
3722Sema::findFailedBooleanCondition(Expr *Cond) {
3723 Cond = lookThroughRangesV3Condition(PP, Cond);
3724
3725 // Separate out all of the terms in a conjunction.
3726 SmallVector<Expr *, 4> Terms;
3727 collectConjunctionTerms(Clause: Cond, Terms);
3728
3729 // Determine which term failed.
3730 Expr *FailedCond = nullptr;
3731 for (Expr *Term : Terms) {
3732 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3733
3734 // Literals are uninteresting.
3735 if (isa<CXXBoolLiteralExpr>(Val: TermAsWritten) ||
3736 isa<IntegerLiteral>(Val: TermAsWritten))
3737 continue;
3738
3739 // The initialization of the parameter from the argument is
3740 // a constant-evaluated context.
3741 EnterExpressionEvaluationContext ConstantEvaluated(
3742 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3743
3744 bool Succeeded;
3745 if (Term->EvaluateAsBooleanCondition(Result&: Succeeded, Ctx: Context) &&
3746 !Succeeded) {
3747 FailedCond = TermAsWritten;
3748 break;
3749 }
3750 }
3751 if (!FailedCond)
3752 FailedCond = Cond->IgnoreParenImpCasts();
3753
3754 std::string Description;
3755 {
3756 llvm::raw_string_ostream Out(Description);
3757 PrintingPolicy Policy = getPrintingPolicy();
3758 Policy.PrintAsCanonical = true;
3759 FailedBooleanConditionPrinterHelper Helper(Policy);
3760 FailedCond->printPretty(OS&: Out, Helper: &Helper, Policy, Indentation: 0, NewlineSymbol: "\n", Context: nullptr);
3761 }
3762 return { FailedCond, Description };
3763}
3764
3765static TemplateName
3766resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope,
3767 const AssumedTemplateStorage *ATN,
3768 SourceLocation NameLoc) {
3769 // We assumed this undeclared identifier to be an (ADL-only) function
3770 // template name, but it was used in a context where a type was required.
3771 // Try to typo-correct it now.
3772 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3773 struct CandidateCallback : CorrectionCandidateCallback {
3774 bool ValidateCandidate(const TypoCorrection &TC) override {
3775 return TC.getCorrectionDecl() &&
3776 getAsTypeTemplateDecl(D: TC.getCorrectionDecl());
3777 }
3778 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3779 return std::make_unique<CandidateCallback>(args&: *this);
3780 }
3781 } FilterCCC;
3782
3783 TypoCorrection Corrected =
3784 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Scope,
3785 /*SS=*/nullptr, CCC&: FilterCCC, Mode: CorrectTypoKind::ErrorRecovery);
3786 if (Corrected && Corrected.getFoundDecl()) {
3787 S.diagnoseTypo(Correction: Corrected, TypoDiag: S.PDiag(DiagID: diag::err_no_template_suggest)
3788 << ATN->getDeclName());
3789 return S.Context.getQualifiedTemplateName(
3790 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3791 Template: TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()));
3792 }
3793
3794 return TemplateName();
3795}
3796
3797QualType Sema::CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
3798 TemplateName Name,
3799 SourceLocation TemplateLoc,
3800 TemplateArgumentListInfo &TemplateArgs,
3801 Scope *Scope, bool ForNestedNameSpecifier) {
3802 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3803
3804 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3805 if (!Template) {
3806 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3807 Template = S->getParameterPack();
3808 } else if (const auto *PI = UnderlyingName.getAsPackIndexingTemplate()) {
3809 Template = PI->getParameterPack();
3810 if (!Template)
3811 Template = PI->getPattern().getAsTemplateDecl();
3812 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3813 if (DTN->getName().getIdentifier())
3814 // When building a template-id where the template-name is dependent,
3815 // assume the template is a type template. Either our assumption is
3816 // correct, or the code is ill-formed and will be diagnosed when the
3817 // dependent name is substituted.
3818 return Context.getTemplateSpecializationType(Keyword, T: Name,
3819 SpecifiedArgs: TemplateArgs.arguments(),
3820 /*CanonicalArgs=*/{});
3821 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3822 if (TemplateName CorrectedName = ::resolveAssumedTemplateNameAsType(
3823 S&: *this, Scope, ATN, NameLoc: TemplateLoc);
3824 CorrectedName.isNull()) {
3825 Diag(Loc: TemplateLoc, DiagID: diag::err_no_template) << ATN->getDeclName();
3826 return QualType();
3827 } else {
3828 Name = CorrectedName;
3829 Template = Name.getAsTemplateDecl();
3830 }
3831 }
3832 }
3833 if (!Template ||
3834 isa<FunctionTemplateDecl, VarTemplateDecl, ConceptDecl>(Val: Template)) {
3835 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3836 if (ForNestedNameSpecifier)
3837 Diag(Loc: TemplateLoc, DiagID: diag::err_non_type_template_in_nested_name_specifier)
3838 << isa_and_nonnull<VarTemplateDecl>(Val: Template) << Name << R;
3839 else
3840 Diag(Loc: TemplateLoc, DiagID: diag::err_template_id_not_a_type) << Name << R;
3841 NoteAllFoundTemplates(Name);
3842 return QualType();
3843 }
3844
3845 // Check that the template argument list is well-formed for this
3846 // template.
3847 CheckTemplateArgumentInfo CTAI;
3848 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3849 DefaultArgs, /*PartialTemplateArgs=*/false,
3850 CTAI,
3851 /*UpdateArgsWithConversions=*/true))
3852 return QualType();
3853
3854 // FIXME: Diagnose uses of this template. DiagnoseUseOfDecl is quite slow,
3855 // and there are no diagnsotics currently implemented for TemplateDecls,
3856 // so avoid doing it for now.
3857 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Template, /*OdrUse=*/MightBeOdrUse: false);
3858
3859 QualType CanonType;
3860
3861 if (isa<TemplateTemplateParmDecl>(Val: Template)) {
3862 // We might have a substituted template template parameter pack. If so,
3863 // build a template specialization type for it.
3864 } else if (TypeAliasTemplateDecl *AliasTemplate =
3865 dyn_cast<TypeAliasTemplateDecl>(Val: Template)) {
3866
3867 // C++0x [dcl.type.elab]p2:
3868 // If the identifier resolves to a typedef-name or the simple-template-id
3869 // resolves to an alias template specialization, the
3870 // elaborated-type-specifier is ill-formed.
3871 if (Keyword != ElaboratedTypeKeyword::None &&
3872 Keyword != ElaboratedTypeKeyword::Typename) {
3873 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_tag_reference_non_tag)
3874 << AliasTemplate << NonTagKind::TypeAliasTemplate
3875 << KeywordHelpers::getTagTypeKindForKeyword(Keyword);
3876 SemaRef.Diag(Loc: AliasTemplate->getLocation(), DiagID: diag::note_declared_at);
3877 }
3878
3879 // Find the canonical type for this type alias template specialization.
3880 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3881
3882 // Diagnose uses of the pattern of this template.
3883 (void)DiagnoseUseOfDecl(D: Pattern, Locs: TemplateLoc);
3884 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Pattern, /*OdrUse=*/MightBeOdrUse: false);
3885
3886 if (Pattern->isInvalidDecl())
3887 return QualType();
3888
3889 // Only substitute for the innermost template argument list.
3890 MultiLevelTemplateArgumentList TemplateArgLists;
3891 TemplateArgLists.addOuterTemplateArguments(AssociatedDecl: Template, Args: CTAI.SugaredConverted,
3892 /*Final=*/true);
3893 TemplateArgLists.addOuterRetainedLevels(
3894 Num: AliasTemplate->getTemplateParameters()->getDepth());
3895
3896 LocalInstantiationScope Scope(*this);
3897
3898 // FIXME: The TemplateArgs passed here are not used for the context note,
3899 // nor they should, because this note will be pointing to the specialization
3900 // anyway. These arguments are needed for a hack for instantiating lambdas
3901 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3902 // arguments will be used for collating the template arguments needed to
3903 // instantiate the lambda.
3904 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3905 /*Entity=*/AliasTemplate,
3906 /*TemplateArgs=*/CTAI.SugaredConverted);
3907 if (Inst.isInvalid())
3908 return QualType();
3909
3910 std::optional<ContextRAII> SavedContext;
3911 if (!AliasTemplate->getDeclContext()->isFileContext())
3912 SavedContext.emplace(args&: *this, args: AliasTemplate->getDeclContext());
3913
3914 CanonType =
3915 SubstType(T: Pattern->getUnderlyingType(), TemplateArgs: TemplateArgLists,
3916 Loc: AliasTemplate->getLocation(), Entity: AliasTemplate->getDeclName());
3917 if (CanonType.isNull()) {
3918 // If this was enable_if and we failed to find the nested type
3919 // within enable_if in a SFINAE context, dig out the specific
3920 // enable_if condition that failed and present that instead.
3921 if (isEnableIfAliasTemplate(AliasTemplate)) {
3922 if (SFINAETrap *Trap = getSFINAEContext();
3923 TemplateDeductionInfo *DeductionInfo =
3924 Trap ? Trap->getDeductionInfo() : nullptr) {
3925 if (DeductionInfo->hasSFINAEDiagnostic() &&
3926 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3927 diag::err_typename_nested_not_found_enable_if &&
3928 TemplateArgs[0].getArgument().getKind() ==
3929 TemplateArgument::Expression) {
3930 Expr *FailedCond;
3931 std::string FailedDescription;
3932 std::tie(args&: FailedCond, args&: FailedDescription) =
3933 findFailedBooleanCondition(Cond: TemplateArgs[0].getSourceExpression());
3934
3935 // Remove the old SFINAE diagnostic.
3936 PartialDiagnosticAt OldDiag =
3937 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3938 DeductionInfo->takeSFINAEDiagnostic(PD&: OldDiag);
3939
3940 // Add a new SFINAE diagnostic specifying which condition
3941 // failed.
3942 DeductionInfo->addSFINAEDiagnostic(
3943 Loc: OldDiag.first,
3944 PD: PDiag(DiagID: diag::err_typename_nested_not_found_requirement)
3945 << FailedDescription << FailedCond->getSourceRange());
3946 }
3947 }
3948 }
3949
3950 return QualType();
3951 }
3952 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Val: Template)) {
3953 CanonType = checkBuiltinTemplateIdType(
3954 SemaRef&: *this, Keyword, BTD, Converted: CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3955 } else if (Name.isDependent() ||
3956 TemplateSpecializationType::anyDependentTemplateArguments(
3957 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
3958 // This class template specialization is a dependent
3959 // type. Therefore, its canonical type is another class template
3960 // specialization type that contains all of the converted
3961 // arguments in canonical form. This ensures that, e.g., A<T> and
3962 // A<T, T> have identical types when A is declared as:
3963 //
3964 // template<typename T, typename U = T> struct A;
3965 CanonType = Context.getCanonicalTemplateSpecializationType(
3966 Keyword: ElaboratedTypeKeyword::None,
3967 T: Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3968 CanonicalArgs: CTAI.CanonicalConverted);
3969 assert(CanonType->isCanonicalUnqualified());
3970
3971 // This might work out to be a current instantiation, in which
3972 // case the canonical type needs to be the InjectedClassNameType.
3973 //
3974 // TODO: in theory this could be a simple hashtable lookup; most
3975 // changes to CurContext don't change the set of current
3976 // instantiations.
3977 if (isa<ClassTemplateDecl>(Val: Template)) {
3978 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3979 // If we get out to a namespace, we're done.
3980 if (Ctx->isFileContext()) break;
3981
3982 // If this isn't a record, keep looking.
3983 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Ctx);
3984 if (!Record) continue;
3985
3986 // Look for one of the two cases with InjectedClassNameTypes
3987 // and check whether it's the same template.
3988 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Record) &&
3989 !Record->getDescribedClassTemplate())
3990 continue;
3991
3992 // Fetch the injected class name type and check whether its
3993 // injected type is equal to the type we just built.
3994 CanQualType ICNT = Context.getCanonicalTagType(TD: Record);
3995 CanQualType Injected =
3996 Record->getCanonicalTemplateSpecializationType(Ctx: Context);
3997
3998 if (CanonType != Injected)
3999 continue;
4000
4001 (void)DiagnoseUseOfDecl(D: Record, Locs: TemplateLoc);
4002 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Record, /*OdrUse=*/MightBeOdrUse: false);
4003
4004 // If so, the canonical type of this TST is the injected
4005 // class name type of the record we just found.
4006 CanonType = ICNT;
4007 break;
4008 }
4009 }
4010 } else if (ClassTemplateDecl *ClassTemplate =
4011 dyn_cast<ClassTemplateDecl>(Val: Template)) {
4012 // Find the class template specialization declaration that
4013 // corresponds to these arguments.
4014 llvm::FoldingSetInsertToken InsertToken;
4015 ClassTemplateSpecializationDecl *Decl =
4016 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertToken);
4017 if (!Decl) {
4018 // This is the first time we have referenced this class template
4019 // specialization. Create the canonical declaration and add it to
4020 // the set of specializations.
4021 Decl = ClassTemplateSpecializationDecl::Create(
4022 Context, TK: ClassTemplate->getTemplatedDecl()->getTagKind(),
4023 DC: ClassTemplate->getDeclContext(),
4024 StartLoc: ClassTemplate->getTemplatedDecl()->getBeginLoc(),
4025 IdLoc: ClassTemplate->getLocation(), SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted,
4026 StrictPackMatch: CTAI.StrictPackMatch, PrevDecl: nullptr);
4027 ClassTemplate->AddSpecialization(D: Decl, InsertToken);
4028 if (ClassTemplate->isOutOfLine())
4029 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
4030 }
4031
4032 if (Decl->getSpecializationKind() == TSK_Undeclared &&
4033 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4034 NonSFINAEContext _(*this);
4035 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4036 if (!Inst.isInvalid()) {
4037 MultiLevelTemplateArgumentList TemplateArgLists(Template,
4038 CTAI.CanonicalConverted,
4039 /*Final=*/false);
4040 InstantiateAttrsForDecl(TemplateArgs: TemplateArgLists,
4041 Pattern: ClassTemplate->getTemplatedDecl(), Inst: Decl);
4042 }
4043 }
4044
4045 // Diagnose uses of this specialization.
4046 (void)DiagnoseUseOfDecl(D: Decl, Locs: TemplateLoc);
4047 MarkAnyDeclReferenced(Loc: TemplateLoc, D: Decl, /*OdrUse=*/MightBeOdrUse: false);
4048
4049 CanonType = Context.getCanonicalTagType(TD: Decl);
4050 assert(isa<RecordType>(CanonType) &&
4051 "type of non-dependent specialization is not a RecordType");
4052 } else {
4053 llvm_unreachable("Unhandled template kind");
4054 }
4055
4056 // Build the fully-sugared type for this class template
4057 // specialization, which refers back to the class template
4058 // specialization we created or found.
4059 return Context.getTemplateSpecializationType(
4060 Keyword, T: Name, SpecifiedArgs: TemplateArgs.arguments(), CanonicalArgs: CTAI.CanonicalConverted,
4061 Canon: CanonType);
4062}
4063
4064void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
4065 TemplateNameKind &TNK,
4066 SourceLocation NameLoc,
4067 IdentifierInfo *&II) {
4068 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4069
4070 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4071 assert(ATN && "not an assumed template name");
4072 II = ATN->getDeclName().getAsIdentifierInfo();
4073
4074 if (TemplateName Name =
4075 ::resolveAssumedTemplateNameAsType(S&: *this, Scope: S, ATN, NameLoc);
4076 !Name.isNull()) {
4077 // Resolved to a type template name.
4078 ParsedName = TemplateTy::make(P: Name);
4079 TNK = TNK_Type_template;
4080 }
4081}
4082
4083TypeResult Sema::ActOnTemplateIdType(
4084 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4085 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4086 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4087 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4088 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4089 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4090 ImplicitTypenameContext AllowImplicitTypename) {
4091 if (SS.isInvalid())
4092 return true;
4093
4094 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4095 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4096
4097 // C++ [temp.res]p3:
4098 // A qualified-id that refers to a type and in which the
4099 // nested-name-specifier depends on a template-parameter (14.6.2)
4100 // shall be prefixed by the keyword typename to indicate that the
4101 // qualified-id denotes a type, forming an
4102 // elaborated-type-specifier (7.1.5.3).
4103 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4104 // C++2a relaxes some of those restrictions in [temp.res]p5.
4105 QualType DNT = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
4106 NNS: SS.getScopeRep(), Name: TemplateII);
4107 NestedNameSpecifier NNS(DNT.getTypePtr());
4108 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4109 auto DB = DiagCompat(Loc: SS.getBeginLoc(), CompatDiagId: diag_compat::implicit_typename)
4110 << NNS;
4111 if (!getLangOpts().CPlusPlus20)
4112 DB << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "typename ");
4113 } else
4114 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_typename_missing_template) << NNS;
4115
4116 // FIXME: This is not quite correct recovery as we don't transform SS
4117 // into the corresponding dependent form (and we don't diagnose missing
4118 // 'template' keywords within SS as a result).
4119 return ActOnTypenameType(S: nullptr, TypenameLoc: SourceLocation(), SS, TemplateLoc: TemplateKWLoc,
4120 TemplateName: TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4121 TemplateArgs: TemplateArgsIn, RAngleLoc);
4122 }
4123
4124 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4125 // it's not actually allowed to be used as a type in most cases. Because
4126 // we annotate it before we know whether it's valid, we have to check for
4127 // this case here.
4128 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
4129 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4130 Diag(Loc: TemplateIILoc,
4131 DiagID: TemplateKWLoc.isInvalid()
4132 ? diag::err_out_of_line_qualified_id_type_names_constructor
4133 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4134 << TemplateII << 0 /*injected-class-name used as template name*/
4135 << 1 /*if any keyword was present, it was 'template'*/;
4136 }
4137 }
4138
4139 // Translate the parser's template argument list in our AST format.
4140 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4141 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4142
4143 QualType SpecTy = CheckTemplateIdType(
4144 Keyword: ElaboratedKeyword, Name: TemplateD.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
4145 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4146 if (SpecTy.isNull())
4147 return true;
4148
4149 // Build type-source information.
4150 TypeLocBuilder TLB;
4151 TLB.push<TemplateSpecializationTypeLoc>(T: SpecTy).set(
4152 ElaboratedKeywordLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
4153 NameLoc: TemplateIILoc, TAL: TemplateArgs);
4154 return CreateParsedType(T: SpecTy, TInfo: TLB.getTypeSourceInfo(Context, T: SpecTy));
4155}
4156
4157TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
4158 TypeSpecifierType TagSpec,
4159 SourceLocation TagLoc,
4160 CXXScopeSpec &SS,
4161 SourceLocation TemplateKWLoc,
4162 TemplateTy TemplateD,
4163 SourceLocation TemplateLoc,
4164 SourceLocation LAngleLoc,
4165 ASTTemplateArgsPtr TemplateArgsIn,
4166 SourceLocation RAngleLoc) {
4167 if (SS.isInvalid())
4168 return TypeResult(true);
4169
4170 // Translate the parser's template argument list in our AST format.
4171 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4172 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4173
4174 // Determine the tag kind
4175 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
4176 ElaboratedTypeKeyword Keyword
4177 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
4178
4179 QualType Result =
4180 CheckTemplateIdType(Keyword, Name: TemplateD.get(), TemplateLoc, TemplateArgs,
4181 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4182 if (Result.isNull())
4183 return TypeResult(true);
4184
4185 // Check the tag kind
4186 if (const RecordType *RT = Result->getAs<RecordType>()) {
4187 RecordDecl *D = RT->getDecl();
4188
4189 IdentifierInfo *Id = D->getIdentifier();
4190 assert(Id && "templated class must have an identifier");
4191
4192 if (!isAcceptableTagRedeclaration(Previous: D, NewTag: TagKind, isDefinition: TUK == TagUseKind::Definition,
4193 NewTagLoc: TagLoc, Name: Id)) {
4194 Diag(Loc: TagLoc, DiagID: diag::err_use_with_wrong_tag)
4195 << Result
4196 << FixItHint::CreateReplacement(RemoveRange: SourceRange(TagLoc), Code: D->getKindName());
4197 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_use);
4198 }
4199 }
4200
4201 // Provide source-location information for the template specialization.
4202 TypeLocBuilder TLB;
4203 TLB.push<TemplateSpecializationTypeLoc>(T: Result).set(
4204 ElaboratedKeywordLoc: TagLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc, NameLoc: TemplateLoc,
4205 TAL: TemplateArgs);
4206 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
4207}
4208
4209static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4210 NamedDecl *PrevDecl,
4211 SourceLocation Loc,
4212 bool IsPartialSpecialization);
4213
4214static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4215
4216static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg,
4217 unsigned Depth,
4218 unsigned Index) {
4219 switch (Arg.getKind()) {
4220 case TemplateArgument::Null:
4221 case TemplateArgument::NullPtr:
4222 case TemplateArgument::Integral:
4223 case TemplateArgument::Declaration:
4224 case TemplateArgument::StructuralValue:
4225 case TemplateArgument::Pack:
4226 case TemplateArgument::TemplateExpansion:
4227 return false;
4228
4229 case TemplateArgument::Type: {
4230 QualType Type = Arg.getAsType();
4231 const TemplateTypeParmType *TPT =
4232 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4233 return TPT && !Type.hasQualifiers() &&
4234 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4235 }
4236
4237 case TemplateArgument::Expression: {
4238 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg.getAsExpr());
4239 if (!DRE || !DRE->getDecl())
4240 return false;
4241 const NonTypeTemplateParmDecl *NTTP =
4242 dyn_cast<NonTypeTemplateParmDecl>(Val: DRE->getDecl());
4243 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4244 }
4245
4246 case TemplateArgument::Template:
4247 const TemplateTemplateParmDecl *TTP =
4248 dyn_cast_or_null<TemplateTemplateParmDecl>(
4249 Val: Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4250 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4251 }
4252 llvm_unreachable("unexpected kind of template argument");
4253}
4254
4255static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4256 TemplateParameterList *SpecParams,
4257 ArrayRef<TemplateArgument> Args) {
4258 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4259 return false;
4260
4261 unsigned Depth = Params->getDepth();
4262
4263 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4264 TemplateArgument Arg = Args[I];
4265
4266 // If the parameter is a pack expansion, the argument must be a pack
4267 // whose only element is a pack expansion.
4268 if (Params->getParam(Idx: I)->isParameterPack()) {
4269 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4270 !Arg.pack_begin()->isPackExpansion())
4271 return false;
4272 Arg = Arg.pack_begin()->getPackExpansionPattern();
4273 }
4274
4275 if (!isTemplateArgumentTemplateParameter(Arg, Depth, Index: I))
4276 return false;
4277
4278 // For NTTPs further specialization is allowed via deduced types, so
4279 // we need to make sure to only reject here if primary template and
4280 // specialization use the same type for the NTTP.
4281 if (auto *SpecNTTP =
4282 dyn_cast<NonTypeTemplateParmDecl>(Val: SpecParams->getParam(Idx: I))) {
4283 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: I));
4284 if (!NTTP || NTTP->getType().getCanonicalType() !=
4285 SpecNTTP->getType().getCanonicalType())
4286 return false;
4287 }
4288 }
4289
4290 return true;
4291}
4292
4293template<typename PartialSpecDecl>
4294static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4295 if (Partial->getDeclContext()->isDependentContext())
4296 return;
4297
4298 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4299 // for non-substitution-failure issues?
4300 TemplateDeductionInfo Info(Partial->getLocation());
4301 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4302 return;
4303
4304 auto *Template = Partial->getSpecializedTemplate();
4305 S.Diag(Partial->getLocation(),
4306 diag::ext_partial_spec_not_more_specialized_than_primary)
4307 << isa<VarTemplateDecl>(Template);
4308
4309 if (Info.hasSFINAEDiagnostic()) {
4310 PartialDiagnosticAt Diag = {SourceLocation(),
4311 PartialDiagnostic::NullDiagnostic()};
4312 Info.takeSFINAEDiagnostic(PD&: Diag);
4313 SmallString<128> SFINAEArgString;
4314 Diag.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
4315 S.Diag(Loc: Diag.first,
4316 DiagID: diag::note_partial_spec_not_more_specialized_than_primary)
4317 << SFINAEArgString;
4318 }
4319
4320 S.NoteTemplateLocation(Decl: *Template);
4321 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4322 Template->getAssociatedConstraints(TemplateAC);
4323 Partial->getAssociatedConstraints(PartialAC);
4324 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Partial, AC1: PartialAC, D2: Template,
4325 AC2: TemplateAC);
4326}
4327
4328static void
4329noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4330 const llvm::SmallBitVector &DeducibleParams) {
4331 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4332 if (!DeducibleParams[I]) {
4333 NamedDecl *Param = TemplateParams->getParam(Idx: I);
4334 if (Param->getDeclName())
4335 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4336 << Param->getDeclName();
4337 else
4338 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4339 << "(anonymous)";
4340 }
4341 }
4342}
4343
4344
4345template<typename PartialSpecDecl>
4346static void checkTemplatePartialSpecialization(Sema &S,
4347 PartialSpecDecl *Partial) {
4348 // C++1z [temp.class.spec]p8: (DR1495)
4349 // - The specialization shall be more specialized than the primary
4350 // template (14.5.5.2).
4351 checkMoreSpecializedThanPrimary(S, Partial);
4352
4353 // C++ [temp.class.spec]p8: (DR1315)
4354 // - Each template-parameter shall appear at least once in the
4355 // template-id outside a non-deduced context.
4356 // C++1z [temp.class.spec.match]p3 (P0127R2)
4357 // If the template arguments of a partial specialization cannot be
4358 // deduced because of the structure of its template-parameter-list
4359 // and the template-id, the program is ill-formed.
4360 auto *TemplateParams = Partial->getTemplateParameters();
4361 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4362 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4363 TemplateParams->getDepth(), DeducibleParams);
4364
4365 if (!DeducibleParams.all()) {
4366 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4367 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4368 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4369 << (NumNonDeducible > 1)
4370 << SourceRange(Partial->getLocation(),
4371 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4372 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4373 }
4374}
4375
4376void Sema::CheckTemplatePartialSpecialization(
4377 ClassTemplatePartialSpecializationDecl *Partial) {
4378 checkTemplatePartialSpecialization(S&: *this, Partial);
4379}
4380
4381void Sema::CheckTemplatePartialSpecialization(
4382 VarTemplatePartialSpecializationDecl *Partial) {
4383 checkTemplatePartialSpecialization(S&: *this, Partial);
4384}
4385
4386void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4387 // C++1z [temp.param]p11:
4388 // A template parameter of a deduction guide template that does not have a
4389 // default-argument shall be deducible from the parameter-type-list of the
4390 // deduction guide template.
4391 auto *TemplateParams = TD->getTemplateParameters();
4392 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4393 MarkDeducedTemplateParameters(FunctionTemplate: TD, Deduced&: DeducibleParams);
4394 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4395 // A parameter pack is deducible (to an empty pack).
4396 auto *Param = TemplateParams->getParam(Idx: I);
4397 if (Param->isParameterPack() || hasVisibleDefaultArgument(D: Param))
4398 DeducibleParams[I] = true;
4399 }
4400
4401 if (!DeducibleParams.all()) {
4402 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4403 Diag(Loc: TD->getLocation(), DiagID: diag::err_deduction_guide_template_not_deducible)
4404 << (NumNonDeducible > 1);
4405 noteNonDeducibleParameters(S&: *this, TemplateParams, DeducibleParams);
4406 }
4407}
4408
4409DeclResult Sema::ActOnVarTemplateSpecialization(
4410 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
4411 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4412 StorageClass SC, bool IsPartialSpecialization) {
4413 // D must be variable template id.
4414 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4415 "Variable template specialization is declared with a template id.");
4416
4417 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4418 TemplateArgumentListInfo TemplateArgs =
4419 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TemplateId);
4420 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4421 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4422 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4423
4424 TemplateName Name = TemplateId->Template.get();
4425
4426 // The template-id must name a variable template.
4427 VarTemplateDecl *VarTemplate =
4428 dyn_cast_or_null<VarTemplateDecl>(Val: Name.getAsTemplateDecl());
4429 if (!VarTemplate) {
4430 NamedDecl *FnTemplate;
4431 if (auto *OTS = Name.getAsOverloadedTemplate())
4432 FnTemplate = *OTS->begin();
4433 else
4434 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Val: Name.getAsTemplateDecl());
4435 if (FnTemplate)
4436 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template_but_method)
4437 << FnTemplate->getDeclName();
4438 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template)
4439 << IsPartialSpecialization;
4440 }
4441
4442 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4443 auto Message = DSA->getMessage();
4444 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
4445 << VarTemplate << !Message.empty() << Message;
4446 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
4447 }
4448
4449 // Check for unexpanded parameter packs in any of the template arguments.
4450 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4451 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
4452 UPPC: IsPartialSpecialization
4453 ? UPPC_PartialSpecialization
4454 : UPPC_ExplicitSpecialization))
4455 return true;
4456
4457 // Check that the template argument list is well-formed for this
4458 // template.
4459 CheckTemplateArgumentInfo CTAI;
4460 if (CheckTemplateArgumentList(Template: VarTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
4461 /*DefaultArgs=*/{},
4462 /*PartialTemplateArgs=*/false, CTAI,
4463 /*UpdateArgsWithConversions=*/true))
4464 return true;
4465
4466 // Find the variable template (partial) specialization declaration that
4467 // corresponds to these arguments.
4468 if (IsPartialSpecialization) {
4469 if (CheckTemplatePartialSpecializationArgs(Loc: TemplateNameLoc, PrimaryTemplate: VarTemplate,
4470 NumExplicitArgs: TemplateArgs.size(),
4471 Args: CTAI.CanonicalConverted))
4472 return true;
4473
4474 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4475 // we also do them during instantiation.
4476 if (!Name.isDependent() &&
4477 !TemplateSpecializationType::anyDependentTemplateArguments(
4478 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4479 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
4480 << VarTemplate->getDeclName();
4481 IsPartialSpecialization = false;
4482 }
4483
4484 if (isSameAsPrimaryTemplate(Params: VarTemplate->getTemplateParameters(),
4485 SpecParams: TemplateParams, Args: CTAI.CanonicalConverted) &&
4486 (!Context.getLangOpts().CPlusPlus20 ||
4487 !TemplateParams->hasAssociatedConstraints())) {
4488 // C++ [temp.class.spec]p9b3:
4489 //
4490 // -- The argument list of the specialization shall not be identical
4491 // to the implicit argument list of the primary template.
4492 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
4493 << /*variable template*/ 1
4494 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4495 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
4496 // FIXME: Recover from this by treating the declaration as a
4497 // redeclaration of the primary template.
4498 return true;
4499 }
4500 }
4501
4502 llvm::FoldingSetInsertToken InsertToken;
4503 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4504
4505 if (IsPartialSpecialization)
4506 PrevDecl = VarTemplate->findPartialSpecialization(
4507 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertToken);
4508 else
4509 PrevDecl =
4510 VarTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertToken);
4511
4512 VarTemplateSpecializationDecl *Specialization = nullptr;
4513
4514 // Check whether we can declare a variable template specialization in
4515 // the current scope.
4516 if (CheckTemplateSpecializationScope(S&: *this, Specialized: VarTemplate, PrevDecl,
4517 Loc: TemplateNameLoc,
4518 IsPartialSpecialization))
4519 return true;
4520
4521 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4522 // Since the only prior variable template specialization with these
4523 // arguments was referenced but not declared, reuse that
4524 // declaration node as our own, updating its source location and
4525 // the list of outer template parameters to reflect our new declaration.
4526 Specialization = PrevDecl;
4527 Specialization->setLocation(TemplateNameLoc);
4528 PrevDecl = nullptr;
4529 } else if (IsPartialSpecialization) {
4530 // Create a new class template partial specialization declaration node.
4531 VarTemplatePartialSpecializationDecl *PrevPartial =
4532 cast_or_null<VarTemplatePartialSpecializationDecl>(Val: PrevDecl);
4533 VarTemplatePartialSpecializationDecl *Partial =
4534 VarTemplatePartialSpecializationDecl::Create(
4535 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc,
4536 IdLoc: TemplateNameLoc, Params: TemplateParams, SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI,
4537 S: SC, Args: CTAI.CanonicalConverted);
4538 Partial->setTemplateArgsAsWritten(TemplateArgs);
4539
4540 if (!PrevPartial)
4541 VarTemplate->AddPartialSpecialization(D: Partial, InsertToken);
4542 Specialization = Partial;
4543
4544 CheckTemplatePartialSpecialization(Partial);
4545 } else {
4546 // Create a new class template specialization declaration node for
4547 // this explicit specialization or friend declaration.
4548 Specialization = VarTemplateSpecializationDecl::Create(
4549 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc, IdLoc: TemplateNameLoc,
4550 SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI, S: SC, Args: CTAI.CanonicalConverted);
4551 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4552
4553 if (!PrevDecl)
4554 VarTemplate->AddSpecialization(D: Specialization, InsertToken);
4555 }
4556
4557 // C++ [temp.expl.spec]p6:
4558 // If a template, a member template or the member of a class template is
4559 // explicitly specialized then that specialization shall be declared
4560 // before the first use of that specialization that would cause an implicit
4561 // instantiation to take place, in every translation unit in which such a
4562 // use occurs; no diagnostic is required.
4563 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4564 bool Okay = false;
4565 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4566 // Is there any previous explicit specialization declaration?
4567 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
4568 Okay = true;
4569 break;
4570 }
4571 }
4572
4573 if (!Okay) {
4574 SourceRange Range(TemplateNameLoc, RAngleLoc);
4575 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
4576 << Name << Range;
4577
4578 Diag(Loc: PrevDecl->getPointOfInstantiation(),
4579 DiagID: diag::note_instantiation_required_here)
4580 << (PrevDecl->getTemplateSpecializationKind() !=
4581 TSK_ImplicitInstantiation);
4582 return true;
4583 }
4584 }
4585
4586 Specialization->setLexicalDeclContext(CurContext);
4587
4588 // Add the specialization into its lexical context, so that it can
4589 // be seen when iterating through the list of declarations in that
4590 // context. However, specializations are not found by name lookup.
4591 CurContext->addDecl(D: Specialization);
4592
4593 // Note that this is an explicit specialization.
4594 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4595
4596 Previous.clear();
4597 if (PrevDecl)
4598 Previous.addDecl(D: PrevDecl);
4599 else if (Specialization->isStaticDataMember() &&
4600 Specialization->isOutOfLine())
4601 Specialization->setAccess(VarTemplate->getAccess());
4602
4603 return Specialization;
4604}
4605
4606namespace {
4607/// A partial specialization whose template arguments have matched
4608/// a given template-id.
4609struct PartialSpecMatchResult {
4610 VarTemplatePartialSpecializationDecl *Partial;
4611 TemplateArgumentList *Args;
4612};
4613
4614// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4615// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4616static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4617 if (Var->getName() != "format_kind" ||
4618 !Var->getDeclContext()->isStdNamespace())
4619 return false;
4620
4621 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4622 // release in which users can access std::format_kind.
4623 // We can use 20250520 as the final date, see the following commits.
4624 // GCC releases/gcc-15 branch:
4625 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4626 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4627 // GCC master branch:
4628 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4629 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4630 return PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2025'05'20);
4631}
4632} // end anonymous namespace
4633
4634DeclResult
4635Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4636 SourceLocation TemplateNameLoc,
4637 const TemplateArgumentListInfo &TemplateArgs,
4638 bool SetWrittenArgs) {
4639 assert(Template && "A variable template id without template?");
4640
4641 // Check that the template argument list is well-formed for this template.
4642 CheckTemplateArgumentInfo CTAI;
4643 if (CheckTemplateArgumentList(
4644 Template, TemplateLoc: TemplateNameLoc,
4645 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4646 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4647 /*UpdateArgsWithConversions=*/true))
4648 return true;
4649
4650 // Produce a placeholder value if the specialization is dependent.
4651 if (Template->getDeclContext()->isDependentContext() ||
4652 TemplateSpecializationType::anyDependentTemplateArguments(
4653 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4654 if (ParsingInitForAutoVars.empty())
4655 return DeclResult();
4656
4657 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4658 const TemplateArgument &Arg2) {
4659 return Context.isSameTemplateArgument(Arg1, Arg2);
4660 };
4661
4662 if (VarDecl *Var = Template->getTemplatedDecl();
4663 ParsingInitForAutoVars.count(Ptr: Var) &&
4664 // See comments on this function definition
4665 !IsLibstdcxxStdFormatKind(PP, Var) &&
4666 llvm::equal(
4667 LRange&: CTAI.CanonicalConverted,
4668 RRange: Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4669 P: IsSameTemplateArg)) {
4670 Diag(Loc: TemplateNameLoc,
4671 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4672 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4673 return true;
4674 }
4675
4676 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4677 Template->getPartialSpecializations(PS&: PartialSpecs);
4678 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4679 if (ParsingInitForAutoVars.count(Ptr: Partial) &&
4680 llvm::equal(LRange&: CTAI.CanonicalConverted,
4681 RRange: Partial->getTemplateArgs().asArray(),
4682 P: IsSameTemplateArg)) {
4683 Diag(Loc: TemplateNameLoc,
4684 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4685 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4686 << Partial->getType();
4687 return true;
4688 }
4689
4690 return DeclResult();
4691 }
4692
4693 // Find the variable template specialization declaration that
4694 // corresponds to these arguments.
4695 llvm::FoldingSetInsertToken InsertToken;
4696 if (VarTemplateSpecializationDecl *Spec =
4697 Template->findSpecialization(Args: CTAI.CanonicalConverted, InsertToken)) {
4698 checkSpecializationReachability(Loc: TemplateNameLoc, Spec);
4699 if (Spec->getType()->isUndeducedType()) {
4700 if (ParsingInitForAutoVars.count(Ptr: Spec))
4701 Diag(Loc: TemplateNameLoc,
4702 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4703 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4704 << Spec->getType();
4705 else
4706 // We are substituting the initializer of this variable template
4707 // specialization.
4708 Diag(Loc: TemplateNameLoc, DiagID: diag::err_var_template_spec_type_depends_on_self)
4709 << Spec << Spec->getType();
4710
4711 return true;
4712 }
4713 // If we already have a variable template specialization, return it.
4714 return Spec;
4715 }
4716
4717 // This is the first time we have referenced this variable template
4718 // specialization. Create the canonical declaration and add it to
4719 // the set of specializations, based on the closest partial specialization
4720 // that it represents. That is,
4721 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4722 const TemplateArgumentList *PartialSpecArgs = nullptr;
4723 bool AmbiguousPartialSpec = false;
4724 typedef PartialSpecMatchResult MatchResult;
4725 SmallVector<MatchResult, 4> Matched;
4726 SourceLocation PointOfInstantiation = TemplateNameLoc;
4727 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4728 /*ForTakingAddress=*/false);
4729
4730 // 1. Attempt to find the closest partial specialization that this
4731 // specializes, if any.
4732 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4733 // Perhaps better after unification of DeduceTemplateArguments() and
4734 // getMoreSpecializedPartialSpecialization().
4735 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4736 Template->getPartialSpecializations(PS&: PartialSpecs);
4737
4738 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4739 // C++ [temp.spec.partial.member]p2:
4740 // If the primary member template is explicitly specialized for a given
4741 // (implicit) specialization of the enclosing class template, the partial
4742 // specializations of the member template are ignored for this
4743 // specialization of the enclosing class template. If a partial
4744 // specialization of the member template is explicitly specialized for a
4745 // given (implicit) specialization of the enclosing class template, the
4746 // primary member template and its other partial specializations are still
4747 // considered for this specialization of the enclosing class template.
4748 if (Template->isMemberSpecialization() &&
4749 !Partial->isMemberSpecialization())
4750 continue;
4751
4752 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4753
4754 if (TemplateDeductionResult Result =
4755 DeduceTemplateArguments(Partial, TemplateArgs: CTAI.SugaredConverted, Info);
4756 Result != TemplateDeductionResult::Success) {
4757 // Store the failed-deduction information for use in diagnostics, later.
4758 // TODO: Actually use the failed-deduction info?
4759 FailedCandidates.addCandidate().set(
4760 Found: DeclAccessPair::make(D: Template, AS: AS_public), Spec: Partial,
4761 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
4762 (void)Result;
4763 } else {
4764 Matched.push_back(Elt: PartialSpecMatchResult());
4765 Matched.back().Partial = Partial;
4766 Matched.back().Args = Info.takeSugared();
4767 }
4768 }
4769
4770 if (Matched.size() >= 1) {
4771 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4772 if (Matched.size() == 1) {
4773 // -- If exactly one matching specialization is found, the
4774 // instantiation is generated from that specialization.
4775 // We don't need to do anything for this.
4776 } else {
4777 // -- If more than one matching specialization is found, the
4778 // partial order rules (14.5.4.2) are used to determine
4779 // whether one of the specializations is more specialized
4780 // than the others. If none of the specializations is more
4781 // specialized than all of the other matching
4782 // specializations, then the use of the variable template is
4783 // ambiguous and the program is ill-formed.
4784 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4785 PEnd = Matched.end();
4786 P != PEnd; ++P) {
4787 if (getMoreSpecializedPartialSpecialization(PS1: P->Partial, PS2: Best->Partial,
4788 Loc: PointOfInstantiation) ==
4789 P->Partial)
4790 Best = P;
4791 }
4792
4793 // Determine if the best partial specialization is more specialized than
4794 // the others.
4795 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4796 PEnd = Matched.end();
4797 P != PEnd; ++P) {
4798 if (P != Best && getMoreSpecializedPartialSpecialization(
4799 PS1: P->Partial, PS2: Best->Partial,
4800 Loc: PointOfInstantiation) != Best->Partial) {
4801 AmbiguousPartialSpec = true;
4802 break;
4803 }
4804 }
4805 }
4806
4807 // Instantiate using the best variable template partial specialization.
4808 InstantiationPattern = Best->Partial;
4809 PartialSpecArgs = Best->Args;
4810 } else {
4811 // -- If no match is found, the instantiation is generated
4812 // from the primary template.
4813 // InstantiationPattern = Template->getTemplatedDecl();
4814 }
4815
4816 // 2. Create the canonical declaration.
4817 // Note that we do not instantiate a definition until we see an odr-use
4818 // in DoMarkVarDeclReferenced().
4819 // FIXME: LateAttrs et al.?
4820 if (AmbiguousPartialSpec) {
4821 // Partial ordering did not produce a clear winner. Complain.
4822 Diag(Loc: PointOfInstantiation, DiagID: diag::err_partial_spec_ordering_ambiguous)
4823 << Template;
4824 // Print the matching partial specializations.
4825 for (MatchResult P : Matched)
4826 Diag(Loc: P.Partial->getLocation(), DiagID: diag::note_partial_spec_match)
4827 << getTemplateArgumentBindingsText(Params: P.Partial->getTemplateParameters(),
4828 Args: *P.Args);
4829 return true;
4830 }
4831
4832 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4833 VarTemplate: Template, FromVar: InstantiationPattern, PartialSpecArgs, Converted&: CTAI.CanonicalConverted,
4834 PointOfInstantiation: TemplateNameLoc /*, LateAttrs, StartingScope*/);
4835 if (!Decl)
4836 return true;
4837 if (SetWrittenArgs)
4838 Decl->setTemplateArgsAsWritten(TemplateArgs);
4839
4840 if (VarTemplatePartialSpecializationDecl *D =
4841 dyn_cast<VarTemplatePartialSpecializationDecl>(Val: InstantiationPattern))
4842 Decl->setInstantiationOf(PartialSpec: D, TemplateArgs: PartialSpecArgs);
4843
4844 checkSpecializationReachability(Loc: TemplateNameLoc, Spec: Decl);
4845
4846 assert(Decl && "No variable template specialization?");
4847 return Decl;
4848}
4849
4850ExprResult Sema::CheckVarTemplateId(
4851 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4852 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4853 const TemplateArgumentListInfo *TemplateArgs) {
4854
4855 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, TemplateNameLoc: NameInfo.getLoc(),
4856 TemplateArgs: *TemplateArgs, /*SetWrittenArgs=*/false);
4857 if (Decl.isInvalid())
4858 return ExprError();
4859
4860 if (!Decl.get())
4861 return ExprResult();
4862
4863 VarDecl *Var = cast<VarDecl>(Val: Decl.get());
4864 if (!Var->getTemplateSpecializationKind())
4865 Var->setTemplateSpecializationKind(TSK: TSK_ImplicitInstantiation,
4866 PointOfInstantiation: NameInfo.getLoc());
4867
4868 // Build an ordinary singleton decl ref.
4869 return BuildDeclarationNameExpr(SS, NameInfo, D: Var, FoundD, TemplateArgs);
4870}
4871
4872ExprResult Sema::CheckVarOrConceptTemplateTemplateId(
4873 const DeclarationNameInfo &NameInfo, TemplateName Template,
4874 const TemplateArgumentListInfo *TemplateArgs) {
4875 TemplateTemplateParmDecl *Parameter =
4876 Template.getAsTemplateTemplateParmDecl();
4877 assert(Parameter && "A variable template id without template?");
4878
4879 if (Parameter->templateParameterKind() !=
4880 TemplateNameKind::TNK_Var_template &&
4881 Parameter->templateParameterKind() !=
4882 TemplateNameKind::TNK_Concept_template)
4883 return ExprResult();
4884
4885 // Check that the template argument list is well-formed for this template.
4886 CheckTemplateArgumentInfo CTAI;
4887 if (CheckTemplateArgumentList(
4888 Template: Parameter, /*Template kw loc=*/TemplateLoc: {},
4889 // FIXME: TemplateArgs will not be modified because
4890 // UpdateArgsWithConversions is false, however, we should
4891 // CheckTemplateArgumentList to be const-correct.
4892 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4893 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4894 /*UpdateArgsWithConversions=*/false))
4895 return true;
4896
4897 return DependentTemplateIdExpr::Create(Context: getASTContext(), NameInfo, Name: Template,
4898 TemplateArgs: *TemplateArgs);
4899}
4900
4901void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4902 SourceLocation Loc) {
4903 Diag(Loc, DiagID: diag::err_template_missing_args)
4904 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4905 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4906 NoteTemplateLocation(Decl: *TD, ParamRange: TD->getTemplateParameters()->getSourceRange());
4907 }
4908}
4909
4910void Sema::diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
4911 bool TemplateKeyword,
4912 TemplateDecl *TD,
4913 SourceLocation Loc) {
4914 TemplateName Name = Context.getQualifiedTemplateName(
4915 Qualifier: SS.getScopeRep(), TemplateKeyword, Template: TemplateName(TD));
4916 diagnoseMissingTemplateArguments(Name, Loc);
4917}
4918
4919ExprResult Sema::CheckConceptTemplateId(
4920 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4921 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4922 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4923 bool DoCheckConstraintSatisfaction) {
4924 assert(NamedConcept && "A concept template id without a template?");
4925
4926 if (NamedConcept->isInvalidDecl())
4927 return ExprError();
4928
4929 CheckTemplateArgumentInfo CTAI;
4930 if (CheckTemplateArgumentList(
4931 Template: NamedConcept, TemplateLoc: ConceptNameInfo.getLoc(),
4932 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4933 /*DefaultArgs=*/{},
4934 /*PartialTemplateArgs=*/false, CTAI,
4935 /*UpdateArgsWithConversions=*/false))
4936 return ExprError();
4937
4938 DiagnoseUseOfDecl(D: NamedConcept, Locs: ConceptNameInfo.getLoc());
4939
4940 // There's a bug with CTAI.CanonicalConverted.
4941 // If the template argument contains a DependentDecltypeType that includes a
4942 // TypeAliasType, and the same written type had occurred previously in the
4943 // source, then the DependentDecltypeType would be canonicalized to that
4944 // previous type which would mess up the substitution.
4945 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4946 auto *CSD = ImplicitConceptSpecializationDecl::Create(
4947 C: Context, DC: NamedConcept->getDeclContext(), SL: NamedConcept->getLocation(),
4948 ConvertedArgs: CTAI.SugaredConverted);
4949 ConstraintSatisfaction Satisfaction;
4950 bool AreArgsDependent =
4951 TemplateSpecializationType::anyDependentTemplateArguments(
4952 *TemplateArgs, Converted: CTAI.SugaredConverted);
4953 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4954 /*Final=*/false);
4955 auto *CL = ConceptReference::Create(
4956 C: Context,
4957 NNS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4958 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept: TemplateName(NamedConcept),
4959 ArgsAsWritten: ASTTemplateArgumentListInfo::Create(C: Context, List: *TemplateArgs));
4960
4961 bool Error = false;
4962 if (const auto *Concept = dyn_cast<ConceptDecl>(Val: NamedConcept);
4963 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4964 DoCheckConstraintSatisfaction) {
4965
4966 LocalInstantiationScope Scope(*this);
4967
4968 EnterExpressionEvaluationContext EECtx{
4969 *this, ExpressionEvaluationContext::Unevaluated};
4970
4971 Error = CheckConstraintSatisfaction(
4972 Entity: NamedConcept, AssociatedConstraints: AssociatedConstraint(Concept->getConstraintExpr()), TemplateArgLists: MLTAL,
4973 TemplateIDRange: SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4974 TemplateArgs->getRAngleLoc()),
4975 Satisfaction, TopLevelConceptId: CL);
4976 Satisfaction.ContainsErrors = Error;
4977 }
4978
4979 if (Error)
4980 return ExprError();
4981
4982 return ConceptSpecializationExpr::Create(
4983 C: Context, ConceptRef: CL, SpecDecl: CSD, Satisfaction: AreArgsDependent ? nullptr : &Satisfaction);
4984}
4985
4986ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4987 SourceLocation TemplateKWLoc,
4988 LookupResult &R,
4989 bool RequiresADL,
4990 const TemplateArgumentListInfo *TemplateArgs) {
4991 // FIXME: Can we do any checking at this point? I guess we could check the
4992 // template arguments that we have against the template name, if the template
4993 // name refers to a single template. That's not a terribly common case,
4994 // though.
4995 // foo<int> could identify a single function unambiguously
4996 // This approach does NOT work, since f<int>(1);
4997 // gets resolved prior to resorting to overload resolution
4998 // i.e., template<class T> void f(double);
4999 // vs template<class T, class U> void f(U);
5000
5001 // These should be filtered out by our callers.
5002 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
5003
5004 // Non-function templates require a template argument list.
5005 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
5006 if (!TemplateArgs && !isa<FunctionTemplateDecl>(Val: TD)) {
5007 diagnoseMissingTemplateArguments(
5008 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, Loc: R.getNameLoc());
5009 return ExprError();
5010 }
5011 }
5012 bool KnownDependent = false;
5013 // In C++1y, check variable template ids.
5014 if (R.getAsSingle<VarTemplateDecl>()) {
5015 ExprResult Res = CheckVarTemplateId(
5016 SS, NameInfo: R.getLookupNameInfo(), Template: R.getAsSingle<VarTemplateDecl>(),
5017 FoundD: R.getRepresentativeDecl(), TemplateLoc: TemplateKWLoc, TemplateArgs);
5018 if (Res.isInvalid() || Res.isUsable())
5019 return Res;
5020 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
5021 KnownDependent = true;
5022 }
5023
5024 // We don't want lookup warnings at this point.
5025 R.suppressDiagnostics();
5026
5027 if (R.getAsSingle<ConceptDecl>()) {
5028 return CheckConceptTemplateId(SS, TemplateKWLoc, ConceptNameInfo: R.getLookupNameInfo(),
5029 FoundDecl: R.getRepresentativeDecl(),
5030 NamedConcept: R.getAsSingle<ConceptDecl>(), TemplateArgs);
5031 }
5032
5033 // Check variable template ids (C++17) and concept template parameters
5034 // (C++26).
5035 UnresolvedLookupExpr *ULE;
5036 if (R.getAsSingle<TemplateTemplateParmDecl>()) {
5037 assert(SS.isEmpty() && "template parameter with a scope specifier?");
5038 assert(TemplateKWLoc.isInvalid() &&
5039 "template keyword in front of a template parameter?");
5040 return CheckVarOrConceptTemplateTemplateId(
5041 NameInfo: R.getLookupNameInfo(),
5042 Template: TemplateName(R.getAsSingle<TemplateTemplateParmDecl>()), TemplateArgs);
5043 }
5044
5045 // Function templates
5046 ULE = UnresolvedLookupExpr::Create(
5047 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
5048 TemplateKWLoc, NameInfo: R.getLookupNameInfo(), RequiresADL, Args: TemplateArgs,
5049 Begin: R.begin(), End: R.end(), KnownDependent,
5050 /*KnownInstantiationDependent=*/false);
5051 // Model the templates with UnresolvedTemplateTy. The expression should then
5052 // either be transformed in an instantiation or be diagnosed in
5053 // CheckPlaceholderExpr.
5054 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
5055 !R.getFoundDecl()->getAsFunction())
5056 ULE->setType(Context.UnresolvedTemplateTy);
5057
5058 return ULE;
5059}
5060
5061ExprResult Sema::BuildQualifiedTemplateIdExpr(
5062 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5063 const DeclarationNameInfo &NameInfo,
5064 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5065 assert(TemplateArgs || TemplateKWLoc.isValid());
5066
5067 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5068 if (LookupTemplateName(Found&: R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5069 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc))
5070 return ExprError();
5071
5072 if (R.isAmbiguous())
5073 return ExprError();
5074
5075 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5076 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5077
5078 if (R.empty()) {
5079 DeclContext *DC = computeDeclContext(SS);
5080 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
5081 << NameInfo.getName() << DC << SS.getRange();
5082 return ExprError();
5083 }
5084
5085 // If necessary, build an implicit class member access.
5086 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5087 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5088 /*S=*/nullptr);
5089
5090 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/RequiresADL: false, TemplateArgs);
5091}
5092
5093TemplateNameKind Sema::ActOnTemplateName(Scope *S,
5094 CXXScopeSpec &SS,
5095 SourceLocation TemplateKWLoc,
5096 const UnqualifiedId &Name,
5097 ParsedType ObjectType,
5098 bool EnteringContext,
5099 TemplateTy &Result,
5100 bool AllowInjectedClassName) {
5101 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5102 DiagCompat(Loc: TemplateKWLoc, CompatDiagId: diag_compat::template_outside_of_template)
5103 << FixItHint::CreateRemoval(RemoveRange: TemplateKWLoc);
5104
5105 if (SS.isInvalid())
5106 return TNK_Non_template;
5107
5108 // Figure out where isTemplateName is going to look.
5109 DeclContext *LookupCtx = nullptr;
5110 if (SS.isNotEmpty())
5111 LookupCtx = computeDeclContext(SS, EnteringContext);
5112 else if (ObjectType)
5113 LookupCtx = computeDeclContext(T: GetTypeFromParser(Ty: ObjectType));
5114
5115 // C++0x [temp.names]p5:
5116 // If a name prefixed by the keyword template is not the name of
5117 // a template, the program is ill-formed. [Note: the keyword
5118 // template may not be applied to non-template members of class
5119 // templates. -end note ] [ Note: as is the case with the
5120 // typename prefix, the template prefix is allowed in cases
5121 // where it is not strictly necessary; i.e., when the
5122 // nested-name-specifier or the expression on the left of the ->
5123 // or . is not dependent on a template-parameter, or the use
5124 // does not appear in the scope of a template. -end note]
5125 //
5126 // Note: C++03 was more strict here, because it banned the use of
5127 // the "template" keyword prior to a template-name that was not a
5128 // dependent name. C++ DR468 relaxed this requirement (the
5129 // "template" keyword is now permitted). We follow the C++0x
5130 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5131 bool MemberOfUnknownSpecialization;
5132 TemplateNameKind TNK = isTemplateName(S, SS, hasTemplateKeyword: TemplateKWLoc.isValid(), Name,
5133 ObjectTypePtr: ObjectType, EnteringContext, TemplateResult&: Result,
5134 MemberOfUnknownSpecialization);
5135 if (TNK != TNK_Non_template) {
5136 // We resolved this to a (non-dependent) template name. Return it.
5137 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
5138 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5139 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5140 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5141 // C++14 [class.qual]p2:
5142 // In a lookup in which function names are not ignored and the
5143 // nested-name-specifier nominates a class C, if the name specified
5144 // [...] is the injected-class-name of C, [...] the name is instead
5145 // considered to name the constructor
5146 //
5147 // We don't get here if naming the constructor would be valid, so we
5148 // just reject immediately and recover by treating the
5149 // injected-class-name as naming the template.
5150 Diag(Loc: Name.getBeginLoc(),
5151 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
5152 << Name.Identifier
5153 << 0 /*injected-class-name used as template name*/
5154 << TemplateKWLoc.isValid();
5155 }
5156 return TNK;
5157 }
5158
5159 if (!MemberOfUnknownSpecialization) {
5160 // Didn't find a template name, and the lookup wasn't dependent.
5161 // Do the lookup again to determine if this is a "nothing found" case or
5162 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5163 // need to do this.
5164 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
5165 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5166 LookupOrdinaryName);
5167 // Tell LookupTemplateName that we require a template so that it diagnoses
5168 // cases where it finds a non-template.
5169 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5170 ? RequiredTemplateKind(TemplateKWLoc)
5171 : TemplateNameIsRequired;
5172 if (!LookupTemplateName(Found&: R, S, SS, ObjectType: ObjectType.get(), EnteringContext, RequiredTemplate: RTK,
5173 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5174 !R.isAmbiguous()) {
5175 if (LookupCtx)
5176 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_no_member)
5177 << DNI.getName() << LookupCtx << SS.getRange();
5178 else
5179 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_undeclared_use)
5180 << DNI.getName() << SS.getRange();
5181 }
5182 return TNK_Non_template;
5183 }
5184
5185 NestedNameSpecifier Qualifier = SS.getScopeRep();
5186
5187 switch (Name.getKind()) {
5188 case UnqualifiedIdKind::IK_Identifier:
5189 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5190 Name: {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5191 return TNK_Dependent_template_name;
5192
5193 case UnqualifiedIdKind::IK_OperatorFunctionId:
5194 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5195 Name: {Qualifier, Name.OperatorFunctionId.Operator,
5196 TemplateKWLoc.isValid()}));
5197 return TNK_Function_template;
5198
5199 case UnqualifiedIdKind::IK_LiteralOperatorId:
5200 // This is a kind of template name, but can never occur in a dependent
5201 // scope (literal operators can only be declared at namespace scope).
5202 break;
5203
5204 default:
5205 break;
5206 }
5207
5208 // This name cannot possibly name a dependent template. Diagnose this now
5209 // rather than building a dependent template name that can never be valid.
5210 Diag(Loc: Name.getBeginLoc(),
5211 DiagID: diag::err_template_kw_refers_to_dependent_non_template)
5212 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5213 << TemplateKWLoc.isValid() << TemplateKWLoc;
5214 return TNK_Non_template;
5215}
5216
5217bool Sema::CheckTemplateTypeArgument(
5218 TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
5219 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5220 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5221 const TemplateArgument &Arg = AL.getArgument();
5222 QualType ArgType;
5223 TypeSourceInfo *TSI = nullptr;
5224
5225 // Check template type parameter.
5226 switch(Arg.getKind()) {
5227 case TemplateArgument::Type:
5228 // C++ [temp.arg.type]p1:
5229 // A template-argument for a template-parameter which is a
5230 // type shall be a type-id.
5231 ArgType = Arg.getAsType();
5232 TSI = AL.getTypeSourceInfo();
5233 break;
5234 case TemplateArgument::Template:
5235 case TemplateArgument::TemplateExpansion: {
5236 // We have a template type parameter but the template argument
5237 // is a template without any arguments.
5238 SourceRange SR = AL.getSourceRange();
5239 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
5240 diagnoseMissingTemplateArguments(Name, Loc: SR.getEnd());
5241 return true;
5242 }
5243 case TemplateArgument::Expression: {
5244 // We have a template type parameter but the template argument is an
5245 // expression; see if maybe it is missing the "typename" keyword.
5246 CXXScopeSpec SS;
5247 DeclarationNameInfo NameInfo;
5248
5249 if (DependentScopeDeclRefExpr *ArgExpr =
5250 dyn_cast<DependentScopeDeclRefExpr>(Val: Arg.getAsExpr())) {
5251 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5252 NameInfo = ArgExpr->getNameInfo();
5253 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5254 dyn_cast<CXXDependentScopeMemberExpr>(Val: Arg.getAsExpr())) {
5255 if (ArgExpr->isImplicitAccess()) {
5256 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5257 NameInfo = ArgExpr->getMemberNameInfo();
5258 }
5259 }
5260
5261 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5262 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5263 LookupParsedName(R&: Result, S: CurScope, SS: &SS, /*ObjectType=*/QualType());
5264
5265 if (Result.getAsSingle<TypeDecl>() ||
5266 Result.wasNotFoundInCurrentInstantiation()) {
5267 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5268 // Suggest that the user add 'typename' before the NNS.
5269 SourceLocation Loc = AL.getSourceRange().getBegin();
5270 Diag(Loc, DiagID: getLangOpts().MSVCCompat
5271 ? diag::ext_ms_template_type_arg_missing_typename
5272 : diag::err_template_arg_must_be_type_suggest)
5273 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
5274 NoteTemplateParameterLocation(Decl: *Param);
5275
5276 // Recover by synthesizing a type using the location information that we
5277 // already have.
5278 ArgType = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
5279 NNS: SS.getScopeRep(), Name: II);
5280 TypeLocBuilder TLB;
5281 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: ArgType);
5282 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5283 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5284 TL.setNameLoc(NameInfo.getLoc());
5285 TSI = TLB.getTypeSourceInfo(Context, T: ArgType);
5286
5287 // Overwrite our input TemplateArgumentLoc so that we can recover
5288 // properly.
5289 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5290 TemplateArgumentLocInfo(TSI));
5291
5292 break;
5293 }
5294 }
5295 // fallthrough
5296 [[fallthrough]];
5297 }
5298 default: {
5299 // We allow instantiating a template with template argument packs when
5300 // building deduction guides or mapping constraint template parameters.
5301 if (Arg.getKind() == TemplateArgument::Pack &&
5302 (CodeSynthesisContexts.back().Kind ==
5303 Sema::CodeSynthesisContext::BuildingDeductionGuides ||
5304 inParameterMappingSubstitution())) {
5305 SugaredConverted.push_back(Elt: Arg);
5306 CanonicalConverted.push_back(Elt: Arg);
5307 return false;
5308 }
5309 // We have a template type parameter but the template argument
5310 // is not a type.
5311 SourceRange SR = AL.getSourceRange();
5312 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_type) << SR;
5313 NoteTemplateParameterLocation(Decl: *Param);
5314
5315 return true;
5316 }
5317 }
5318
5319 if (CheckTemplateArgument(Arg: TSI))
5320 return true;
5321
5322 // Objective-C ARC:
5323 // If an explicitly-specified template argument type is a lifetime type
5324 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5325 if (getLangOpts().ObjCAutoRefCount &&
5326 ArgType->isObjCLifetimeType() &&
5327 !ArgType.getObjCLifetime()) {
5328 Qualifiers Qs;
5329 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5330 ArgType = Context.getQualifiedType(T: ArgType, Qs);
5331 }
5332
5333 SugaredConverted.push_back(Elt: TemplateArgument(ArgType));
5334 CanonicalConverted.push_back(
5335 Elt: TemplateArgument(Context.getCanonicalType(T: ArgType)));
5336 return false;
5337}
5338
5339/// Substitute template arguments into the default template argument for
5340/// the given template type parameter.
5341///
5342/// \param SemaRef the semantic analysis object for which we are performing
5343/// the substitution.
5344///
5345/// \param Template the template that we are synthesizing template arguments
5346/// for.
5347///
5348/// \param TemplateLoc the location of the template name that started the
5349/// template-id we are checking.
5350///
5351/// \param RAngleLoc the location of the right angle bracket ('>') that
5352/// terminates the template-id.
5353///
5354/// \param Param the template template parameter whose default we are
5355/// substituting into.
5356///
5357/// \param Converted the list of template arguments provided for template
5358/// parameters that precede \p Param in the template parameter list.
5359///
5360/// \param Output the resulting substituted template argument.
5361///
5362/// \returns true if an error occurred.
5363static bool SubstDefaultTemplateArgument(
5364 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5365 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5366 ArrayRef<TemplateArgument> SugaredConverted,
5367 ArrayRef<TemplateArgument> CanonicalConverted,
5368 TemplateArgumentLoc &Output) {
5369 Output = Param->getDefaultArgument();
5370
5371 // If the argument type is dependent, instantiate it now based
5372 // on the previously-computed template arguments.
5373 if (Output.getArgument().isInstantiationDependent()) {
5374 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5375 SugaredConverted,
5376 SourceRange(TemplateLoc, RAngleLoc));
5377 if (Inst.isInvalid())
5378 return true;
5379
5380 // Only substitute for the innermost template argument list.
5381 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5382 /*Final=*/true);
5383 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5384 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5385
5386 bool ForLambdaCallOperator = false;
5387 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Val: Template->getDeclContext()))
5388 ForLambdaCallOperator = Rec->isLambda();
5389 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5390 !ForLambdaCallOperator);
5391
5392 if (SemaRef.SubstTemplateArgument(Input: Output, TemplateArgs: TemplateArgLists, Output,
5393 Loc: Param->getDefaultArgumentLoc(),
5394 Entity: Param->getDeclName()))
5395 return true;
5396 }
5397
5398 return false;
5399}
5400
5401/// Substitute template arguments into the default template argument for
5402/// the given non-type template parameter.
5403///
5404/// \param SemaRef the semantic analysis object for which we are performing
5405/// the substitution.
5406///
5407/// \param Template the template that we are synthesizing template arguments
5408/// for.
5409///
5410/// \param TemplateLoc the location of the template name that started the
5411/// template-id we are checking.
5412///
5413/// \param RAngleLoc the location of the right angle bracket ('>') that
5414/// terminates the template-id.
5415///
5416/// \param Param the non-type template parameter whose default we are
5417/// substituting into.
5418///
5419/// \param Converted the list of template arguments provided for template
5420/// parameters that precede \p Param in the template parameter list.
5421///
5422/// \returns the substituted template argument, or NULL if an error occurred.
5423static bool SubstDefaultTemplateArgument(
5424 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5425 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5426 ArrayRef<TemplateArgument> SugaredConverted,
5427 ArrayRef<TemplateArgument> CanonicalConverted,
5428 TemplateArgumentLoc &Output) {
5429 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5430 SugaredConverted,
5431 SourceRange(TemplateLoc, RAngleLoc));
5432 if (Inst.isInvalid())
5433 return true;
5434
5435 // Only substitute for the innermost template argument list.
5436 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5437 /*Final=*/true);
5438 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5439 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5440
5441 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5442 EnterExpressionEvaluationContext ConstantEvaluated(
5443 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5444 return SemaRef.SubstTemplateArgument(Input: Param->getDefaultArgument(),
5445 TemplateArgs: TemplateArgLists, Output);
5446}
5447
5448/// Substitute template arguments into the default template argument for
5449/// the given template template parameter.
5450///
5451/// \param SemaRef the semantic analysis object for which we are performing
5452/// the substitution.
5453///
5454/// \param Template the template that we are synthesizing template arguments
5455/// for.
5456///
5457/// \param TemplateLoc the location of the template name that started the
5458/// template-id we are checking.
5459///
5460/// \param RAngleLoc the location of the right angle bracket ('>') that
5461/// terminates the template-id.
5462///
5463/// \param Param the template template parameter whose default we are
5464/// substituting into.
5465///
5466/// \param Converted the list of template arguments provided for template
5467/// parameters that precede \p Param in the template parameter list.
5468///
5469/// \param QualifierLoc Will be set to the nested-name-specifier (with
5470/// source-location information) that precedes the template name.
5471///
5472/// \returns the substituted template argument, or NULL if an error occurred.
5473static TemplateName SubstDefaultTemplateArgument(
5474 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5475 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5476 TemplateTemplateParmDecl *Param,
5477 ArrayRef<TemplateArgument> SugaredConverted,
5478 ArrayRef<TemplateArgument> CanonicalConverted,
5479 NestedNameSpecifierLoc &QualifierLoc) {
5480 Sema::InstantiatingTemplate Inst(
5481 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5482 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5483 if (Inst.isInvalid())
5484 return TemplateName();
5485
5486 // Only substitute for the innermost template argument list.
5487 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5488 /*Final=*/true);
5489 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5490 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5491
5492 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5493
5494 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5495 QualifierLoc = A.getTemplateQualifierLoc();
5496 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5497 Name: A.getArgument().getAsTemplate(),
5498 NameLoc: A.getTemplateNameLoc(), TemplateArgs: TemplateArgLists);
5499}
5500
5501TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
5502 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5503 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5504 ArrayRef<TemplateArgument> SugaredConverted,
5505 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5506 HasDefaultArg = false;
5507
5508 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
5509 if (!hasReachableDefaultArgument(D: TypeParm))
5510 return TemplateArgumentLoc();
5511
5512 HasDefaultArg = true;
5513 TemplateArgumentLoc Output;
5514 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5515 RAngleLoc, Param: TypeParm, SugaredConverted,
5516 CanonicalConverted, Output))
5517 return TemplateArgumentLoc();
5518 return Output;
5519 }
5520
5521 if (NonTypeTemplateParmDecl *NonTypeParm
5522 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5523 if (!hasReachableDefaultArgument(D: NonTypeParm))
5524 return TemplateArgumentLoc();
5525
5526 HasDefaultArg = true;
5527 TemplateArgumentLoc Output;
5528 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5529 RAngleLoc, Param: NonTypeParm, SugaredConverted,
5530 CanonicalConverted, Output))
5531 return TemplateArgumentLoc();
5532 return Output;
5533 }
5534
5535 TemplateTemplateParmDecl *TempTempParm
5536 = cast<TemplateTemplateParmDecl>(Val: Param);
5537 if (!hasReachableDefaultArgument(D: TempTempParm))
5538 return TemplateArgumentLoc();
5539
5540 HasDefaultArg = true;
5541 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5542 NestedNameSpecifierLoc QualifierLoc;
5543 TemplateName TName = SubstDefaultTemplateArgument(
5544 SemaRef&: *this, Template, TemplateKWLoc, TemplateLoc: TemplateNameLoc, RAngleLoc, Param: TempTempParm,
5545 SugaredConverted, CanonicalConverted, QualifierLoc);
5546 if (TName.isNull())
5547 return TemplateArgumentLoc();
5548
5549 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5550 QualifierLoc, A.getTemplateNameLoc());
5551}
5552
5553/// Convert a template-argument that we parsed as a type into a template, if
5554/// possible. C++ permits injected-class-names to perform dual service as
5555/// template template arguments and as template type arguments.
5556static TemplateArgumentLoc
5557convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5558 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5559 if (!TagLoc)
5560 return TemplateArgumentLoc();
5561
5562 // If this type was written as an injected-class-name, it can be used as a
5563 // template template argument.
5564 // If this type was written as an injected-class-name, it may have been
5565 // converted to a RecordType during instantiation. If the RecordType is
5566 // *not* wrapped in a TemplateSpecializationType and denotes a class
5567 // template specialization, it must have come from an injected-class-name.
5568
5569 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Ctx: Context);
5570 if (Name.isNull())
5571 return TemplateArgumentLoc();
5572
5573 return TemplateArgumentLoc(Context, Name,
5574 /*TemplateKWLoc=*/SourceLocation(),
5575 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5576}
5577
5578bool Sema::CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &ArgLoc,
5579 NamedDecl *Template,
5580 SourceLocation TemplateLoc,
5581 SourceLocation RAngleLoc,
5582 unsigned ArgumentPackIndex,
5583 CheckTemplateArgumentInfo &CTAI,
5584 CheckTemplateArgumentKind CTAK) {
5585 // Check template type parameters.
5586 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param))
5587 return CheckTemplateTypeArgument(Param: TTP, AL&: ArgLoc, SugaredConverted&: CTAI.SugaredConverted,
5588 CanonicalConverted&: CTAI.CanonicalConverted);
5589
5590 const TemplateArgument &Arg = ArgLoc.getArgument();
5591 // Check non-type template parameters.
5592 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5593 // Do substitution on the type of the non-type template parameter
5594 // with the template arguments we've seen thus far. But if the
5595 // template has a dependent context then we cannot substitute yet.
5596 QualType NTTPType = NTTP->getType();
5597 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5598 NTTPType = NTTP->getExpansionType(I: ArgumentPackIndex);
5599
5600 if (NTTPType->isInstantiationDependentType()) {
5601 // Do substitution on the type of the non-type template parameter.
5602 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5603 CTAI.SugaredConverted,
5604 SourceRange(TemplateLoc, RAngleLoc));
5605 if (Inst.isInvalid())
5606 return true;
5607
5608 MultiLevelTemplateArgumentList MLTAL(Template, CTAI.SugaredConverted,
5609 /*Final=*/true);
5610 MLTAL.addOuterRetainedLevels(Num: NTTP->getDepth());
5611 // If the parameter is a pack expansion, expand this slice of the pack.
5612 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5613 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5614 NTTPType = SubstType(T: PET->getPattern(), TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5615 Entity: NTTP->getDeclName());
5616 } else {
5617 NTTPType = SubstType(T: NTTPType, TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5618 Entity: NTTP->getDeclName());
5619 }
5620
5621 // If that worked, check the non-type template parameter type
5622 // for validity.
5623 if (!NTTPType.isNull())
5624 NTTPType = CheckNonTypeTemplateParameterType(T: NTTPType,
5625 Loc: NTTP->getLocation());
5626 if (NTTPType.isNull())
5627 return true;
5628 }
5629
5630 auto checkExpr = [&](Expr *E) -> Expr * {
5631 TemplateArgument SugaredResult, CanonicalResult;
5632 ExprResult Res = CheckTemplateArgument(
5633 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E, SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5634 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5635 // If the current template argument causes an error, give up now.
5636 if (Res.isInvalid())
5637 return nullptr;
5638 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5639 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5640 return Res.get();
5641 };
5642
5643 switch (Arg.getKind()) {
5644 case TemplateArgument::Null:
5645 llvm_unreachable("Should never see a NULL template argument here");
5646
5647 case TemplateArgument::Expression: {
5648 Expr *E = Arg.getAsExpr();
5649 Expr *R = checkExpr(E);
5650 if (!R)
5651 return true;
5652 // If the resulting expression is new, then use it in place of the
5653 // old expression in the template argument.
5654 if (R != E) {
5655 TemplateArgument TA(R, /*IsCanonical=*/false);
5656 ArgLoc = TemplateArgumentLoc(TA, R);
5657 }
5658 break;
5659 }
5660
5661 // As for the converted NTTP kinds, they still might need another
5662 // conversion, as the new corresponding parameter might be different.
5663 // Ideally, we would always perform substitution starting with sugared types
5664 // and never need these, as we would still have expressions. Since these are
5665 // needed so rarely, it's probably a better tradeoff to just convert them
5666 // back to expressions.
5667 case TemplateArgument::Integral:
5668 case TemplateArgument::Declaration:
5669 case TemplateArgument::NullPtr:
5670 case TemplateArgument::StructuralValue: {
5671 // FIXME: StructuralValue is untested here.
5672 ExprResult R =
5673 BuildExpressionFromNonTypeTemplateArgument(Arg, Loc: SourceLocation());
5674 assert(R.isUsable());
5675 if (!checkExpr(R.get()))
5676 return true;
5677 break;
5678 }
5679
5680 case TemplateArgument::Template:
5681 case TemplateArgument::TemplateExpansion:
5682 // We were given a template template argument. It may not be ill-formed;
5683 // see below.
5684 if (DependentTemplateName *DTN = Arg.getAsTemplateOrTemplatePattern()
5685 .getAsDependentTemplateName()) {
5686 // We have a template argument such as \c T::template X, which we
5687 // parsed as a template template argument. However, since we now
5688 // know that we need a non-type template argument, convert this
5689 // template name into an expression.
5690
5691 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5692 ArgLoc.getTemplateNameLoc());
5693
5694 CXXScopeSpec SS;
5695 SS.Adopt(Other: ArgLoc.getTemplateQualifierLoc());
5696 // FIXME: the template-template arg was a DependentTemplateName,
5697 // so it was provided with a template keyword. However, its source
5698 // location is not stored in the template argument structure.
5699 SourceLocation TemplateKWLoc;
5700 ExprResult E = DependentScopeDeclRefExpr::Create(
5701 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5702 TemplateArgs: nullptr);
5703
5704 // If we parsed the template argument as a pack expansion, create a
5705 // pack expansion expression.
5706 if (Arg.getKind() == TemplateArgument::TemplateExpansion) {
5707 E = ActOnPackExpansion(Pattern: E.get(), EllipsisLoc: ArgLoc.getTemplateEllipsisLoc());
5708 if (E.isInvalid())
5709 return true;
5710 }
5711
5712 TemplateArgument SugaredResult, CanonicalResult;
5713 E = CheckTemplateArgument(
5714 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E.get(), SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5715 /*StrictCheck=*/CTAI.PartialOrdering, CTAK: CTAK_Specified);
5716 if (E.isInvalid())
5717 return true;
5718
5719 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5720 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5721 break;
5722 }
5723
5724 // We have a template argument that actually does refer to a class
5725 // template, alias template, or template template parameter, and
5726 // therefore cannot be a non-type template argument.
5727 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_expr)
5728 << ArgLoc.getSourceRange();
5729 NoteTemplateParameterLocation(Decl: *Param);
5730
5731 return true;
5732
5733 case TemplateArgument::Type: {
5734 // We have a non-type template parameter but the template
5735 // argument is a type.
5736
5737 // C++ [temp.arg]p2:
5738 // In a template-argument, an ambiguity between a type-id and
5739 // an expression is resolved to a type-id, regardless of the
5740 // form of the corresponding template-parameter.
5741 //
5742 // We warn specifically about this case, since it can be rather
5743 // confusing for users.
5744 QualType T = Arg.getAsType();
5745 SourceRange SR = ArgLoc.getSourceRange();
5746 if (T->isFunctionType())
5747 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_nontype_ambig) << SR << T;
5748 else
5749 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_expr) << SR;
5750 NoteTemplateParameterLocation(Decl: *Param);
5751 return true;
5752 }
5753
5754 case TemplateArgument::Pack:
5755 llvm_unreachable("Caller must expand template argument packs");
5756 }
5757
5758 return false;
5759 }
5760
5761
5762 // Check template template parameters.
5763 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Val: Param);
5764
5765 TemplateParameterList *Params = TempParm->getTemplateParameters();
5766 if (TempParm->isExpandedParameterPack())
5767 Params = TempParm->getExpansionTemplateParameters(I: ArgumentPackIndex);
5768
5769 // Substitute into the template parameter list of the template
5770 // template parameter, since previously-supplied template arguments
5771 // may appear within the template template parameter.
5772 //
5773 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5774 {
5775 // Set up a template instantiation context.
5776 LocalInstantiationScope Scope(*this);
5777 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5778 CTAI.SugaredConverted,
5779 SourceRange(TemplateLoc, RAngleLoc));
5780 if (Inst.isInvalid())
5781 return true;
5782
5783 Params = SubstTemplateParams(
5784 Params, Owner: CurContext,
5785 TemplateArgs: MultiLevelTemplateArgumentList(Template, CTAI.SugaredConverted,
5786 /*Final=*/true),
5787 /*EvaluateConstraints=*/false);
5788 if (!Params)
5789 return true;
5790 }
5791
5792 // C++1z [temp.local]p1: (DR1004)
5793 // When [the injected-class-name] is used [...] as a template-argument for
5794 // a template template-parameter [...] it refers to the class template
5795 // itself.
5796 if (Arg.getKind() == TemplateArgument::Type) {
5797 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5798 Context, TLoc: ArgLoc.getTypeSourceInfo()->getTypeLoc());
5799 if (!ConvertedArg.getArgument().isNull())
5800 ArgLoc = ConvertedArg;
5801 }
5802
5803 switch (Arg.getKind()) {
5804 case TemplateArgument::Null:
5805 llvm_unreachable("Should never see a NULL template argument here");
5806
5807 case TemplateArgument::Template:
5808 case TemplateArgument::TemplateExpansion:
5809 if (CheckTemplateTemplateArgument(Param: TempParm, Params, Arg&: ArgLoc,
5810 PartialOrdering: CTAI.PartialOrdering,
5811 StrictPackMatch: &CTAI.StrictPackMatch))
5812 return true;
5813
5814 CTAI.SugaredConverted.push_back(Elt: Arg);
5815 CTAI.CanonicalConverted.push_back(
5816 Elt: Context.getCanonicalTemplateArgument(Arg));
5817 break;
5818
5819 case TemplateArgument::Expression:
5820 case TemplateArgument::Type: {
5821 auto Kind = 0;
5822 switch (TempParm->templateParameterKind()) {
5823 case TemplateNameKind::TNK_Var_template:
5824 Kind = 1;
5825 break;
5826 case TemplateNameKind::TNK_Concept_template:
5827 Kind = 2;
5828 break;
5829 default:
5830 break;
5831 }
5832
5833 // We have a template template parameter but the template
5834 // argument does not refer to a template.
5835 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_template)
5836 << Kind << getLangOpts().CPlusPlus11;
5837 return true;
5838 }
5839
5840 case TemplateArgument::Declaration:
5841 case TemplateArgument::Integral:
5842 case TemplateArgument::StructuralValue:
5843 case TemplateArgument::NullPtr:
5844 llvm_unreachable("non-type argument with template template parameter");
5845
5846 case TemplateArgument::Pack:
5847 llvm_unreachable("Caller must expand template argument packs");
5848 }
5849
5850 return false;
5851}
5852
5853/// Diagnose a missing template argument.
5854template<typename TemplateParmDecl>
5855static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5856 TemplateDecl *TD,
5857 const TemplateParmDecl *D,
5858 TemplateArgumentListInfo &Args) {
5859 // Dig out the most recent declaration of the template parameter; there may be
5860 // declarations of the template that are more recent than TD.
5861 D = cast<TemplateParmDecl>(cast<TemplateDecl>(Val: TD->getMostRecentDecl())
5862 ->getTemplateParameters()
5863 ->getParam(D->getIndex()));
5864
5865 // If there's a default argument that's not reachable, diagnose that we're
5866 // missing a module import.
5867 llvm::SmallVector<Module*, 8> Modules;
5868 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, Modules: &Modules)) {
5869 S.diagnoseMissingImport(Loc, cast<NamedDecl>(Val: TD),
5870 D->getDefaultArgumentLoc(), Modules,
5871 Sema::MissingImportKind::DefaultArgument,
5872 /*Recover*/true);
5873 return true;
5874 }
5875
5876 // FIXME: If there's a more recent default argument that *is* visible,
5877 // diagnose that it was declared too late.
5878
5879 TemplateParameterList *Params = TD->getTemplateParameters();
5880
5881 S.Diag(Loc, DiagID: diag::err_template_arg_list_different_arity)
5882 << /*not enough args*/0
5883 << (int)S.getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
5884 << TD;
5885 S.NoteTemplateLocation(Decl: *TD, ParamRange: Params->getSourceRange());
5886 return true;
5887}
5888
5889/// Check that the given template argument list is well-formed
5890/// for specializing the given template.
5891bool Sema::CheckTemplateArgumentList(
5892 TemplateDecl *Template, SourceLocation TemplateLoc,
5893 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5894 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5895 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5896 return CheckTemplateArgumentList(
5897 Template, Params: GetTemplateParameterList(TD: Template), TemplateLoc, TemplateArgs,
5898 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5899 ConstraintsNotSatisfied);
5900}
5901
5902/// Check that the given template argument list is well-formed
5903/// for specializing the given template.
5904bool Sema::CheckTemplateArgumentList(
5905 TemplateDecl *Template, TemplateParameterList *Params,
5906 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5907 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5908 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5909 bool *ConstraintsNotSatisfied) {
5910
5911 if (ConstraintsNotSatisfied)
5912 *ConstraintsNotSatisfied = false;
5913
5914 // Make a copy of the template arguments for processing. Only make the
5915 // changes at the end when successful in matching the arguments to the
5916 // template.
5917 TemplateArgumentListInfo NewArgs = TemplateArgs;
5918
5919 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5920
5921 // C++23 [temp.arg.general]p1:
5922 // [...] The type and form of each template-argument specified in
5923 // a template-id shall match the type and form specified for the
5924 // corresponding parameter declared by the template in its
5925 // template-parameter-list.
5926 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Val: Template);
5927 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5928 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5929 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5930 LocalInstantiationScope InstScope(*this, true);
5931 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5932 ParamEnd = Params->end(),
5933 Param = ParamBegin;
5934 Param != ParamEnd;
5935 /* increment in loop */) {
5936 if (size_t ParamIdx = Param - ParamBegin;
5937 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5938 // All written arguments should have been consumed by this point.
5939 assert(ArgIdx == NumArgs && "bad default argument deduction");
5940 if (ParamIdx == DefaultArgs.StartPos) {
5941 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5942 // Default arguments from a DeducedTemplateName are already converted.
5943 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5944 CTAI.SugaredConverted.push_back(Elt: DefArg);
5945 CTAI.CanonicalConverted.push_back(
5946 Elt: Context.getCanonicalTemplateArgument(Arg: DefArg));
5947 ++Param;
5948 }
5949 continue;
5950 }
5951 }
5952
5953 // If we have an expanded parameter pack, make sure we don't have too
5954 // many arguments.
5955 if (UnsignedOrNone Expansions = getExpandedPackSize(Param: *Param)) {
5956 if (*Expansions == SugaredArgumentPack.size()) {
5957 // We're done with this parameter pack. Pack up its arguments and add
5958 // them to the list.
5959 CTAI.SugaredConverted.push_back(
5960 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
5961 SugaredArgumentPack.clear();
5962
5963 CTAI.CanonicalConverted.push_back(
5964 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
5965 CanonicalArgumentPack.clear();
5966
5967 // This argument is assigned to the next parameter.
5968 ++Param;
5969 continue;
5970 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5971 // Not enough arguments for this parameter pack.
5972 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
5973 << /*not enough args*/0
5974 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
5975 << Template;
5976 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
5977 return true;
5978 }
5979 }
5980
5981 // Check for builtins producing template packs in this context, we do not
5982 // support them yet.
5983 if (const NonTypeTemplateParmDecl *NTTP =
5984 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param);
5985 NTTP && NTTP->isPackExpansion()) {
5986 auto TL = NTTP->getTypeSourceInfo()
5987 ->getTypeLoc()
5988 .castAs<PackExpansionTypeLoc>();
5989 llvm::SmallVector<UnexpandedParameterPack> Unexpanded;
5990 collectUnexpandedParameterPacks(TL: TL.getPatternLoc(), Unexpanded);
5991 for (const auto &UPP : Unexpanded) {
5992 auto *TST = dyn_cast<const TemplateSpecializationType *>(Val: UPP.first);
5993 if (!TST)
5994 continue;
5995 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5996 // Expanding a built-in pack in this context is not yet supported.
5997 Diag(Loc: TL.getEllipsisLoc(),
5998 DiagID: diag::err_unsupported_builtin_template_pack_expansion)
5999 << TST->getTemplateName();
6000 return true;
6001 }
6002 }
6003
6004 if (ArgIdx < NumArgs) {
6005 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
6006 bool NonPackParameter =
6007 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(Param: *Param);
6008 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
6009
6010 if (ArgIsExpansion && CTAI.MatchingTTP) {
6011 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
6012 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
6013 ++Param) {
6014 TemplateArgument &Arg = Args[Param - First];
6015 Arg = ArgLoc.getArgument();
6016 if (!(*Param)->isTemplateParameterPack() ||
6017 getExpandedPackSize(Param: *Param))
6018 Arg = Arg.getPackExpansionPattern();
6019 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
6020 SaveAndRestore _1(CTAI.PartialOrdering, false);
6021 SaveAndRestore _2(CTAI.MatchingTTP, true);
6022 if (CheckTemplateArgument(Param: *Param, ArgLoc&: NewArgLoc, Template, TemplateLoc,
6023 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
6024 CTAK: CTAK_Specified))
6025 return true;
6026 Arg = NewArgLoc.getArgument();
6027 CTAI.CanonicalConverted.back().setIsDefaulted(
6028 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg, Param: *Param,
6029 Args: CTAI.CanonicalConverted,
6030 Depth: Params->getDepth()));
6031 }
6032 ArgLoc = TemplateArgumentLoc(
6033 TemplateArgument::CreatePackCopy(Context, Args),
6034 TemplateArgumentLocInfo(Context, ArgLoc.getLocation()));
6035 } else {
6036 SaveAndRestore _1(CTAI.PartialOrdering, false);
6037 if (CheckTemplateArgument(Param: *Param, ArgLoc, Template, TemplateLoc,
6038 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
6039 CTAK: CTAK_Specified))
6040 return true;
6041 CTAI.CanonicalConverted.back().setIsDefaulted(
6042 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg: ArgLoc.getArgument(),
6043 Param: *Param, Args: CTAI.CanonicalConverted,
6044 Depth: Params->getDepth()));
6045 if (ArgIsExpansion && NonPackParameter) {
6046 // CWG1430/CWG2686: we have a pack expansion as an argument to an
6047 // alias template, builtin template, or concept, and it's not part of
6048 // a parameter pack. This can't be canonicalized, so reject it now.
6049 if (isa<TypeAliasTemplateDecl, ConceptDecl, BuiltinTemplateDecl>(
6050 Val: Template)) {
6051 unsigned DiagSelect = isa<ConceptDecl>(Val: Template) ? 1
6052 : isa<BuiltinTemplateDecl>(Val: Template) ? 2
6053 : 0;
6054 Diag(Loc: ArgLoc.getLocation(),
6055 DiagID: diag::err_template_expansion_into_fixed_list)
6056 << DiagSelect << ArgLoc.getSourceRange();
6057 NoteTemplateParameterLocation(Decl: **Param);
6058 return true;
6059 }
6060 }
6061 }
6062
6063 // We're now done with this argument.
6064 ++ArgIdx;
6065
6066 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6067 // Directly convert the remaining arguments, because we don't know what
6068 // parameters they'll match up with.
6069
6070 if (!SugaredArgumentPack.empty()) {
6071 // If we were part way through filling in an expanded parameter pack,
6072 // fall back to just producing individual arguments.
6073 CTAI.SugaredConverted.insert(I: CTAI.SugaredConverted.end(),
6074 From: SugaredArgumentPack.begin(),
6075 To: SugaredArgumentPack.end());
6076 SugaredArgumentPack.clear();
6077
6078 CTAI.CanonicalConverted.insert(I: CTAI.CanonicalConverted.end(),
6079 From: CanonicalArgumentPack.begin(),
6080 To: CanonicalArgumentPack.end());
6081 CanonicalArgumentPack.clear();
6082 }
6083
6084 while (ArgIdx < NumArgs) {
6085 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6086 CTAI.SugaredConverted.push_back(Elt: Arg);
6087 CTAI.CanonicalConverted.push_back(
6088 Elt: Context.getCanonicalTemplateArgument(Arg));
6089 ++ArgIdx;
6090 }
6091
6092 return false;
6093 }
6094
6095 if ((*Param)->isTemplateParameterPack()) {
6096 // The template parameter was a template parameter pack, so take the
6097 // deduced argument and place it on the argument pack. Note that we
6098 // stay on the same template parameter so that we can deduce more
6099 // arguments.
6100 SugaredArgumentPack.push_back(Elt: CTAI.SugaredConverted.pop_back_val());
6101 CanonicalArgumentPack.push_back(Elt: CTAI.CanonicalConverted.pop_back_val());
6102 } else {
6103 // Move to the next template parameter.
6104 ++Param;
6105 }
6106 continue;
6107 }
6108
6109 // If we're checking a partial template argument list, we're done.
6110 if (PartialTemplateArgs) {
6111 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6112 CTAI.SugaredConverted.push_back(
6113 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6114 CTAI.CanonicalConverted.push_back(
6115 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6116 }
6117 return false;
6118 }
6119
6120 // If we have a template parameter pack with no more corresponding
6121 // arguments, just break out now and we'll fill in the argument pack below.
6122 if ((*Param)->isTemplateParameterPack()) {
6123 assert(!getExpandedPackSize(*Param) &&
6124 "Should have dealt with this already");
6125
6126 // A non-expanded parameter pack before the end of the parameter list
6127 // only occurs for an ill-formed template parameter list, unless we've
6128 // got a partial argument list for a function template, so just bail out.
6129 if (Param + 1 != ParamEnd) {
6130 assert(
6131 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6132 "Concept templates must have parameter packs at the end.");
6133 return true;
6134 }
6135
6136 CTAI.SugaredConverted.push_back(
6137 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6138 SugaredArgumentPack.clear();
6139
6140 CTAI.CanonicalConverted.push_back(
6141 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6142 CanonicalArgumentPack.clear();
6143
6144 ++Param;
6145 continue;
6146 }
6147
6148 // Check whether we have a default argument.
6149 bool HasDefaultArg;
6150
6151 // Retrieve the default template argument from the template
6152 // parameter. For each kind of template parameter, we substitute the
6153 // template arguments provided thus far and any "outer" template arguments
6154 // (when the template parameter was part of a nested template) into
6155 // the default argument.
6156 TemplateArgumentLoc Arg = SubstDefaultTemplateArgumentIfAvailable(
6157 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateNameLoc: TemplateLoc, RAngleLoc,
6158 Param: *Param, SugaredConverted: CTAI.SugaredConverted, CanonicalConverted: CTAI.CanonicalConverted, HasDefaultArg);
6159
6160 if (Arg.getArgument().isNull()) {
6161 if (!HasDefaultArg) {
6162 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *Param))
6163 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: TTP,
6164 Args&: NewArgs);
6165 if (NonTypeTemplateParmDecl *NTTP =
6166 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param))
6167 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: NTTP,
6168 Args&: NewArgs);
6169 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template,
6170 D: cast<TemplateTemplateParmDecl>(Val: *Param),
6171 Args&: NewArgs);
6172 }
6173 return true;
6174 }
6175
6176 // Introduce an instantiation record that describes where we are using
6177 // the default template argument. We're not actually instantiating a
6178 // template here, we just create this object to put a note into the
6179 // context stack.
6180 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6181 CTAI.SugaredConverted,
6182 SourceRange(TemplateLoc, RAngleLoc));
6183 if (Inst.isInvalid())
6184 return true;
6185
6186 SaveAndRestore _1(CTAI.PartialOrdering, false);
6187 SaveAndRestore _2(CTAI.MatchingTTP, false);
6188 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6189 // Check the default template argument.
6190 if (CheckTemplateArgument(Param: *Param, ArgLoc&: Arg, Template, TemplateLoc, RAngleLoc, ArgumentPackIndex: 0,
6191 CTAI, CTAK: CTAK_Specified))
6192 return true;
6193
6194 CTAI.SugaredConverted.back().setIsDefaulted(true);
6195 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6196
6197 // Core issue 150 (assumed resolution): if this is a template template
6198 // parameter, keep track of the default template arguments from the
6199 // template definition.
6200 if (isTemplateTemplateParameter)
6201 NewArgs.addArgument(Loc: Arg);
6202
6203 // Move to the next template parameter and argument.
6204 ++Param;
6205 ++ArgIdx;
6206 }
6207
6208 // If we're performing a partial argument substitution, allow any trailing
6209 // pack expansions; they might be empty. This can happen even if
6210 // PartialTemplateArgs is false (the list of arguments is complete but
6211 // still dependent).
6212 if (CTAI.MatchingTTP ||
6213 (CurrentInstantiationScope &&
6214 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6215 while (ArgIdx < NumArgs &&
6216 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6217 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6218 CTAI.SugaredConverted.push_back(Elt: Arg);
6219 CTAI.CanonicalConverted.push_back(
6220 Elt: Context.getCanonicalTemplateArgument(Arg));
6221 }
6222 }
6223
6224 // If we have any leftover arguments, then there were too many arguments.
6225 // Complain and fail.
6226 if (ArgIdx < NumArgs) {
6227 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
6228 << /*too many args*/1
6229 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
6230 << Template
6231 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6232 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
6233 return true;
6234 }
6235
6236 // No problems found with the new argument list, propagate changes back
6237 // to caller.
6238 if (UpdateArgsWithConversions)
6239 TemplateArgs = std::move(NewArgs);
6240
6241 if (!PartialTemplateArgs) {
6242 // Setup the context/ThisScope for the case where we are needing to
6243 // re-instantiate constraints outside of normal instantiation.
6244 DeclContext *NewContext = Template->getDeclContext();
6245
6246 // If this template is in a template, make sure we extract the templated
6247 // decl.
6248 if (auto *TD = dyn_cast<TemplateDecl>(Val: NewContext))
6249 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6250 auto *RD = dyn_cast<CXXRecordDecl>(Val: NewContext);
6251
6252 Qualifiers ThisQuals;
6253 if (const auto *Method =
6254 dyn_cast_or_null<CXXMethodDecl>(Val: Template->getTemplatedDecl()))
6255 ThisQuals = Method->getMethodQualifiers();
6256
6257 ContextRAII Context(*this, NewContext);
6258 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6259
6260 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
6261 D: Template, DC: NewContext, /*Final=*/true, Innermost: CTAI.SugaredConverted,
6262 /*RelativeToPrimary=*/true,
6263 /*Pattern=*/nullptr,
6264 /*ForConceptInstantiation=*/ForConstraintInstantiation: true);
6265 if (!isa<ConceptDecl>(Val: Template) &&
6266 EnsureTemplateArgumentListConstraints(
6267 Template, TemplateArgs: MLTAL,
6268 TemplateIDRange: SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6269 if (ConstraintsNotSatisfied)
6270 *ConstraintsNotSatisfied = true;
6271 return true;
6272 }
6273 }
6274
6275 return false;
6276}
6277
6278namespace {
6279 class UnnamedLocalNoLinkageFinder
6280 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6281 {
6282 Sema &S;
6283 SourceRange SR;
6284
6285 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
6286
6287 public:
6288 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6289
6290 bool Visit(QualType T) {
6291 return T.isNull() ? false : inherited::Visit(T: T.getTypePtr());
6292 }
6293
6294#define TYPE(Class, Parent) \
6295 bool Visit##Class##Type(const Class##Type *);
6296#define ABSTRACT_TYPE(Class, Parent) \
6297 bool Visit##Class##Type(const Class##Type *) { return false; }
6298#define NON_CANONICAL_TYPE(Class, Parent) \
6299 bool Visit##Class##Type(const Class##Type *) { return false; }
6300#include "clang/AST/TypeNodes.inc"
6301
6302 bool VisitTagDecl(const TagDecl *Tag);
6303 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6304 };
6305} // end anonymous namespace
6306
6307bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6308 return false;
6309}
6310
6311bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6312 return Visit(T: T->getElementType());
6313}
6314
6315bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6316 return Visit(T: T->getPointeeType());
6317}
6318
6319bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6320 const BlockPointerType* T) {
6321 return Visit(T: T->getPointeeType());
6322}
6323
6324bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6325 const LValueReferenceType* T) {
6326 return Visit(T: T->getPointeeType());
6327}
6328
6329bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6330 const RValueReferenceType* T) {
6331 return Visit(T: T->getPointeeType());
6332}
6333
6334bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6335 const MemberPointerType *T) {
6336 if (Visit(T: T->getPointeeType()))
6337 return true;
6338 if (auto *RD = T->getMostRecentCXXRecordDecl())
6339 return VisitTagDecl(Tag: RD);
6340 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6341}
6342
6343bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6344 const ConstantArrayType* T) {
6345 return Visit(T: T->getElementType());
6346}
6347
6348bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6349 const IncompleteArrayType* T) {
6350 return Visit(T: T->getElementType());
6351}
6352
6353bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6354 const VariableArrayType* T) {
6355 return Visit(T: T->getElementType());
6356}
6357
6358bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6359 const DependentSizedArrayType* T) {
6360 return Visit(T: T->getElementType());
6361}
6362
6363bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6364 const DependentSizedExtVectorType* T) {
6365 return Visit(T: T->getElementType());
6366}
6367
6368bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6369 const DependentSizedMatrixType *T) {
6370 return Visit(T: T->getElementType());
6371}
6372
6373bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6374 const DependentAddressSpaceType *T) {
6375 return Visit(T: T->getPointeeType());
6376}
6377
6378bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6379 return Visit(T: T->getElementType());
6380}
6381
6382bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6383 const DependentVectorType *T) {
6384 return Visit(T: T->getElementType());
6385}
6386
6387bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6388 return Visit(T: T->getElementType());
6389}
6390
6391bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6392 const ConstantMatrixType *T) {
6393 return Visit(T: T->getElementType());
6394}
6395
6396bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6397 const FunctionProtoType* T) {
6398 for (const auto &A : T->param_types()) {
6399 if (Visit(T: A))
6400 return true;
6401 }
6402
6403 return Visit(T: T->getReturnType());
6404}
6405
6406bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6407 const FunctionNoProtoType* T) {
6408 return Visit(T: T->getReturnType());
6409}
6410
6411bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6412 const UnresolvedUsingType*) {
6413 return false;
6414}
6415
6416bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6417 return false;
6418}
6419
6420bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6421 return Visit(T: T->getUnmodifiedType());
6422}
6423
6424bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6425 return false;
6426}
6427
6428bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6429 const PackIndexingType *) {
6430 return false;
6431}
6432
6433bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6434 const UnaryTransformType*) {
6435 return false;
6436}
6437
6438bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6439 return Visit(T: T->getDeducedType());
6440}
6441
6442bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6443 const DeducedTemplateSpecializationType *T) {
6444 return Visit(T: T->getDeducedType());
6445}
6446
6447bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6448 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6449}
6450
6451bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6452 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6453}
6454
6455bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6456 const TemplateTypeParmType*) {
6457 return false;
6458}
6459
6460bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6461 const SubstTemplateTypeParmPackType *) {
6462 return false;
6463}
6464
6465bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6466 const SubstBuiltinTemplatePackType *) {
6467 return false;
6468}
6469
6470bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6471 const TemplateSpecializationType*) {
6472 return false;
6473}
6474
6475bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6476 const InjectedClassNameType* T) {
6477 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6478}
6479
6480bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6481 const DependentNameType* T) {
6482 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6483}
6484
6485bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6486 const PackExpansionType* T) {
6487 return Visit(T: T->getPattern());
6488}
6489
6490bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6491 return false;
6492}
6493
6494bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6495 const ObjCInterfaceType *) {
6496 return false;
6497}
6498
6499bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6500 const ObjCObjectPointerType *) {
6501 return false;
6502}
6503
6504bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6505 return Visit(T: T->getValueType());
6506}
6507
6508bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6509 const OverflowBehaviorType *T) {
6510 return Visit(T: T->getUnderlyingType());
6511}
6512
6513bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6514 return false;
6515}
6516
6517bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6518 return false;
6519}
6520
6521bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6522 const ArrayParameterType *T) {
6523 return VisitConstantArrayType(T);
6524}
6525
6526bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6527 const DependentBitIntType *T) {
6528 return false;
6529}
6530
6531bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6532 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6533 S.Diag(Loc: SR.getBegin(), DiagID: S.getLangOpts().CPlusPlus11
6534 ? diag::warn_cxx98_compat_template_arg_local_type
6535 : diag::ext_template_arg_local_type)
6536 << S.Context.getCanonicalTagType(TD: Tag) << SR;
6537 return true;
6538 }
6539
6540 if (!Tag->hasNameForLinkage()) {
6541 S.Diag(Loc: SR.getBegin(),
6542 DiagID: S.getLangOpts().CPlusPlus11 ?
6543 diag::warn_cxx98_compat_template_arg_unnamed_type :
6544 diag::ext_template_arg_unnamed_type) << SR;
6545 S.Diag(Loc: Tag->getLocation(), DiagID: diag::note_template_unnamed_type_here);
6546 return true;
6547 }
6548
6549 return false;
6550}
6551
6552bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6553 NestedNameSpecifier NNS) {
6554 switch (NNS.getKind()) {
6555 case NestedNameSpecifier::Kind::Null:
6556 case NestedNameSpecifier::Kind::Namespace:
6557 case NestedNameSpecifier::Kind::Global:
6558 case NestedNameSpecifier::Kind::MicrosoftSuper:
6559 return false;
6560 case NestedNameSpecifier::Kind::Type:
6561 return Visit(T: QualType(NNS.getAsType(), 0));
6562 }
6563 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6564}
6565
6566bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6567 const HLSLAttributedResourceType *T) {
6568 if (T->hasContainedType() && Visit(T: T->getContainedType()))
6569 return true;
6570 return Visit(T: T->getWrappedType());
6571}
6572
6573bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6574 const HLSLInlineSpirvType *T) {
6575 for (auto &Operand : T->getOperands())
6576 if (Operand.isConstant() && Operand.isLiteral())
6577 if (Visit(T: Operand.getResultType()))
6578 return true;
6579 return false;
6580}
6581
6582bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6583 assert(ArgInfo && "invalid TypeSourceInfo");
6584 QualType Arg = ArgInfo->getType();
6585 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6586 QualType CanonArg = Context.getCanonicalType(T: Arg);
6587
6588 if (CanonArg->isVariablyModifiedType()) {
6589 return Diag(Loc: SR.getBegin(), DiagID: diag::err_variably_modified_template_arg) << Arg;
6590 } else if (Context.hasSameUnqualifiedType(T1: Arg, T2: Context.OverloadTy)) {
6591 return Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_overload_type) << SR;
6592 }
6593
6594 // C++03 [temp.arg.type]p2:
6595 // A local type, a type with no linkage, an unnamed type or a type
6596 // compounded from any of these types shall not be used as a
6597 // template-argument for a template type-parameter.
6598 //
6599 // C++11 allows these, and even in C++03 we allow them as an extension with
6600 // a warning.
6601 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6602 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6603 (void)Finder.Visit(T: CanonArg);
6604 }
6605
6606 return false;
6607}
6608
6609enum NullPointerValueKind {
6610 NPV_NotNullPointer,
6611 NPV_NullPointer,
6612 NPV_Error
6613};
6614
6615/// Determine whether the given template argument is a null pointer
6616/// value of the appropriate type.
6617static NullPointerValueKind
6618isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param,
6619 QualType ParamType, Expr *Arg,
6620 Decl *Entity = nullptr) {
6621 if (Arg->isValueDependent() || Arg->isTypeDependent())
6622 return NPV_NotNullPointer;
6623
6624 // dllimport'd entities aren't constant but are available inside of template
6625 // arguments.
6626 if (Entity && Entity->hasAttr<DLLImportAttr>())
6627 return NPV_NotNullPointer;
6628
6629 if (!S.isCompleteType(Loc: Arg->getExprLoc(), T: ParamType))
6630 llvm_unreachable(
6631 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6632
6633 if (!S.getLangOpts().CPlusPlus11)
6634 return NPV_NotNullPointer;
6635
6636 // Determine whether we have a constant expression.
6637 ExprResult ArgRV = S.DefaultFunctionArrayConversion(E: Arg);
6638 if (ArgRV.isInvalid())
6639 return NPV_Error;
6640 Arg = ArgRV.get();
6641
6642 Expr::EvalResult EvalResult;
6643 SmallVector<PartialDiagnosticAt, 8> Notes;
6644 EvalResult.Diag = &Notes;
6645 if (!Arg->EvaluateAsRValue(Result&: EvalResult, Ctx: S.Context) ||
6646 EvalResult.HasSideEffects) {
6647 SourceLocation DiagLoc = Arg->getExprLoc();
6648
6649 // If our only note is the usual "invalid subexpression" note, just point
6650 // the caret at its location rather than producing an essentially
6651 // redundant note.
6652 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6653 diag::note_invalid_subexpr_in_const_expr) {
6654 DiagLoc = Notes[0].first;
6655 Notes.clear();
6656 }
6657
6658 S.Diag(Loc: DiagLoc, DiagID: diag::err_template_arg_not_address_constant)
6659 << Arg->getType() << Arg->getSourceRange();
6660 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6661 S.Diag(Loc: Notes[I].first, PD: Notes[I].second);
6662
6663 S.NoteTemplateParameterLocation(Decl: *Param);
6664 return NPV_Error;
6665 }
6666
6667 // C++11 [temp.arg.nontype]p1:
6668 // - an address constant expression of type std::nullptr_t
6669 if (Arg->getType()->isNullPtrType())
6670 return NPV_NullPointer;
6671
6672 // - a constant expression that evaluates to a null pointer value (4.10); or
6673 // - a constant expression that evaluates to a null member pointer value
6674 // (4.11); or
6675 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6676 (EvalResult.Val.isMemberPointer() &&
6677 !EvalResult.Val.getMemberPointerDecl())) {
6678 // If our expression has an appropriate type, we've succeeded.
6679 bool ObjCLifetimeConversion;
6680 if (S.Context.hasSameUnqualifiedType(T1: Arg->getType(), T2: ParamType) ||
6681 S.IsQualificationConversion(FromType: Arg->getType(), ToType: ParamType, CStyle: false,
6682 ObjCLifetimeConversion))
6683 return NPV_NullPointer;
6684
6685 // The types didn't match, but we know we got a null pointer; complain,
6686 // then recover as if the types were correct.
6687 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_wrongtype_null_constant)
6688 << Arg->getType() << ParamType << Arg->getSourceRange();
6689 S.NoteTemplateParameterLocation(Decl: *Param);
6690 return NPV_NullPointer;
6691 }
6692
6693 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6694 // We found a pointer that isn't null, but doesn't refer to an object.
6695 // We could just return NPV_NotNullPointer, but we can print a better
6696 // message with the information we have here.
6697 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_invalid)
6698 << EvalResult.Val.getAsString(Ctx: S.Context, Ty: ParamType);
6699 S.NoteTemplateParameterLocation(Decl: *Param);
6700 return NPV_Error;
6701 }
6702
6703 // If we don't have a null pointer value, but we do have a NULL pointer
6704 // constant, suggest a cast to the appropriate type.
6705 if (Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_NeverValueDependent)) {
6706 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6707 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_untyped_null_constant)
6708 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code)
6709 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: Arg->getEndLoc()),
6710 Code: ")");
6711 S.NoteTemplateParameterLocation(Decl: *Param);
6712 return NPV_NullPointer;
6713 }
6714
6715 // FIXME: If we ever want to support general, address-constant expressions
6716 // as non-type template arguments, we should return the ExprResult here to
6717 // be interpreted by the caller.
6718 return NPV_NotNullPointer;
6719}
6720
6721/// Checks whether the given template argument is compatible with its
6722/// template parameter.
6723static bool
6724CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param,
6725 QualType ParamType, Expr *ArgIn,
6726 Expr *Arg, QualType ArgType) {
6727 bool ObjCLifetimeConversion;
6728 if (ParamType->isPointerType() &&
6729 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6730 S.IsQualificationConversion(FromType: ArgType, ToType: ParamType, CStyle: false,
6731 ObjCLifetimeConversion)) {
6732 // For pointer-to-object types, qualification conversions are
6733 // permitted.
6734 } else {
6735 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6736 if (!ParamRef->getPointeeType()->isFunctionType()) {
6737 // C++ [temp.arg.nontype]p5b3:
6738 // For a non-type template-parameter of type reference to
6739 // object, no conversions apply. The type referred to by the
6740 // reference may be more cv-qualified than the (otherwise
6741 // identical) type of the template- argument. The
6742 // template-parameter is bound directly to the
6743 // template-argument, which shall be an lvalue.
6744
6745 // FIXME: Other qualifiers?
6746 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6747 unsigned ArgQuals = ArgType.getCVRQualifiers();
6748
6749 if ((ParamQuals | ArgQuals) != ParamQuals) {
6750 S.Diag(Loc: Arg->getBeginLoc(),
6751 DiagID: diag::err_template_arg_ref_bind_ignores_quals)
6752 << ParamType << Arg->getType() << Arg->getSourceRange();
6753 S.NoteTemplateParameterLocation(Decl: *Param);
6754 return true;
6755 }
6756 }
6757 }
6758
6759 // At this point, the template argument refers to an object or
6760 // function with external linkage. We now need to check whether the
6761 // argument and parameter types are compatible.
6762 if (!S.Context.hasSameUnqualifiedType(T1: ArgType,
6763 T2: ParamType.getNonReferenceType())) {
6764 // We can't perform this conversion or binding.
6765 if (ParamType->isReferenceType())
6766 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_no_ref_bind)
6767 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6768 else
6769 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
6770 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6771 S.NoteTemplateParameterLocation(Decl: *Param);
6772 return true;
6773 }
6774 }
6775
6776 return false;
6777}
6778
6779/// Checks whether the given template argument is the address
6780/// of an object or function according to C++ [temp.arg.nontype]p1.
6781static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6782 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6783 bool IsSpecified, TemplateArgument &SugaredConverted,
6784 TemplateArgument &CanonicalConverted) {
6785 Expr *Arg = ArgIn;
6786 QualType ArgType = Arg->getType();
6787
6788 bool AddressTaken = false;
6789 SourceLocation AddrOpLoc;
6790 if (S.getLangOpts().MicrosoftExt) {
6791 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6792 // dereference and address-of operators.
6793 Arg = Arg->IgnoreParenCasts();
6794
6795 bool ExtWarnMSTemplateArg = false;
6796 UnaryOperatorKind FirstOpKind;
6797 SourceLocation FirstOpLoc;
6798 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6799 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6800 if (UnOpKind == UO_Deref)
6801 ExtWarnMSTemplateArg = true;
6802 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6803 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6804 if (!AddrOpLoc.isValid()) {
6805 FirstOpKind = UnOpKind;
6806 FirstOpLoc = UnOp->getOperatorLoc();
6807 }
6808 } else
6809 break;
6810 }
6811 if (FirstOpLoc.isValid()) {
6812 if (ExtWarnMSTemplateArg)
6813 S.Diag(Loc: ArgIn->getBeginLoc(), DiagID: diag::ext_ms_deref_template_argument)
6814 << ArgIn->getSourceRange();
6815
6816 if (FirstOpKind == UO_AddrOf)
6817 AddressTaken = true;
6818 else if (Arg->getType()->isPointerType()) {
6819 // We cannot let pointers get dereferenced here, that is obviously not a
6820 // constant expression.
6821 assert(FirstOpKind == UO_Deref);
6822 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6823 << Arg->getSourceRange();
6824 }
6825 }
6826 } else {
6827 // See through any implicit casts we added to fix the type.
6828 // Also ignore parentheses for deduced template arguments.
6829 Arg = IsSpecified ? Arg->IgnoreImpCasts() : Arg->IgnoreParenImpCasts();
6830
6831 // C++ [temp.arg.nontype]p1:
6832 //
6833 // A template-argument for a non-type, non-template
6834 // template-parameter shall be one of: [...]
6835 //
6836 // -- the address of an object or function with external
6837 // linkage, including function templates and function
6838 // template-ids but excluding non-static class members,
6839 // expressed as & id-expression where the & is optional if
6840 // the name refers to a function or array, or if the
6841 // corresponding template-parameter is a reference; or
6842
6843 // In C++98/03 mode, give an extension warning on any extra parentheses.
6844 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6845 if (IsSpecified) {
6846 bool ExtraParens = false;
6847 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
6848 if (!ExtraParens) {
6849 S.DiagCompat(Loc: Arg->getBeginLoc(),
6850 CompatDiagId: diag_compat::template_arg_extra_parens)
6851 << Arg->getSourceRange();
6852 ExtraParens = true;
6853 }
6854
6855 Arg = Parens->getSubExpr();
6856 }
6857 }
6858
6859 while (SubstNonTypeTemplateParmExpr *subst =
6860 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6861 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6862
6863 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6864 if (UnOp->getOpcode() == UO_AddrOf) {
6865 Arg = UnOp->getSubExpr();
6866 AddressTaken = true;
6867 AddrOpLoc = UnOp->getOperatorLoc();
6868 }
6869 }
6870
6871 while (SubstNonTypeTemplateParmExpr *subst =
6872 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6873 Arg = subst->getReplacement()->IgnoreParenImpCasts();
6874 }
6875
6876 ValueDecl *Entity = nullptr;
6877 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg))
6878 Entity = DRE->getDecl();
6879 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Val: Arg))
6880 Entity = CUE->getGuidDecl();
6881
6882 // If our parameter has pointer type, check for a null template value.
6883 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6884 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ArgIn,
6885 Entity)) {
6886 case NPV_NullPointer:
6887 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
6888 SugaredConverted = TemplateArgument(ParamType,
6889 /*isNullPtr=*/true);
6890 CanonicalConverted =
6891 TemplateArgument(S.Context.getCanonicalType(T: ParamType),
6892 /*isNullPtr=*/true);
6893 return false;
6894
6895 case NPV_Error:
6896 return true;
6897
6898 case NPV_NotNullPointer:
6899 break;
6900 }
6901 }
6902
6903 // Stop checking the precise nature of the argument if it is value dependent,
6904 // it should be checked when instantiated.
6905 if (Arg->isValueDependent()) {
6906 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6907 CanonicalConverted =
6908 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
6909 return false;
6910 }
6911
6912 if (!Entity) {
6913 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6914 << Arg->getSourceRange();
6915 S.NoteTemplateParameterLocation(Decl: *Param);
6916 return true;
6917 }
6918
6919 // Cannot refer to non-static data members
6920 if (isa<FieldDecl>(Val: Entity) || isa<IndirectFieldDecl>(Val: Entity)) {
6921 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_field)
6922 << Entity << Arg->getSourceRange();
6923 S.NoteTemplateParameterLocation(Decl: *Param);
6924 return true;
6925 }
6926
6927 // Cannot refer to non-static member functions
6928 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Entity)) {
6929 if (!Method->isStatic()) {
6930 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_method)
6931 << Method << Arg->getSourceRange();
6932 S.NoteTemplateParameterLocation(Decl: *Param);
6933 return true;
6934 }
6935 }
6936
6937 FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Entity);
6938 VarDecl *Var = dyn_cast<VarDecl>(Val: Entity);
6939 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Val: Entity);
6940
6941 // A non-type template argument must refer to an object or function.
6942 if (!Func && !Var && !Guid) {
6943 // We found something, but we don't know specifically what it is.
6944 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_object_or_func)
6945 << Arg->getSourceRange();
6946 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_refers_here);
6947 return true;
6948 }
6949
6950 // Address / reference template args must have external linkage in C++98.
6951 if (Entity->getFormalLinkage() == Linkage::Internal) {
6952 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_object_internal)
6953 << !Func << Entity << Arg->getSourceRange();
6954 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6955 << !Func;
6956 } else if (!Entity->hasLinkage()) {
6957 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_object_no_linkage)
6958 << !Func << Entity << Arg->getSourceRange();
6959 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6960 << !Func;
6961 return true;
6962 }
6963
6964 if (Var) {
6965 // A value of reference type is not an object.
6966 if (Var->getType()->isReferenceType()) {
6967 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_reference_var)
6968 << Var->getType() << Arg->getSourceRange();
6969 S.NoteTemplateParameterLocation(Decl: *Param);
6970 return true;
6971 }
6972
6973 // A template argument must have static storage duration.
6974 if (Var->getTLSKind()) {
6975 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_thread_local)
6976 << Arg->getSourceRange();
6977 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_template_arg_refers_here);
6978 return true;
6979 }
6980 }
6981
6982 if (AddressTaken && ParamType->isReferenceType()) {
6983 // If we originally had an address-of operator, but the
6984 // parameter has reference type, complain and (if things look
6985 // like they will work) drop the address-of operator.
6986 if (!S.Context.hasSameUnqualifiedType(T1: Entity->getType(),
6987 T2: ParamType.getNonReferenceType())) {
6988 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6989 << ParamType;
6990 S.NoteTemplateParameterLocation(Decl: *Param);
6991 return true;
6992 }
6993
6994 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6995 << ParamType
6996 << FixItHint::CreateRemoval(RemoveRange: AddrOpLoc);
6997 S.NoteTemplateParameterLocation(Decl: *Param);
6998
6999 ArgType = Entity->getType();
7000 }
7001
7002 // If the template parameter has pointer type, either we must have taken the
7003 // address or the argument must decay to a pointer.
7004 if (!AddressTaken && ParamType->isPointerType()) {
7005 if (Func) {
7006 // Function-to-pointer decay.
7007 ArgType = S.Context.getPointerType(T: Func->getType());
7008 } else if (Entity->getType()->isArrayType()) {
7009 // Array-to-pointer decay.
7010 ArgType = S.Context.getArrayDecayedType(T: Entity->getType());
7011 } else {
7012 // If the template parameter has pointer type but the address of
7013 // this object was not taken, complain and (possibly) recover by
7014 // taking the address of the entity.
7015 ArgType = S.Context.getPointerType(T: Entity->getType());
7016 if (!S.Context.hasSameUnqualifiedType(T1: ArgType, T2: ParamType)) {
7017 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
7018 << ParamType;
7019 S.NoteTemplateParameterLocation(Decl: *Param);
7020 return true;
7021 }
7022
7023 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
7024 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code: "&");
7025
7026 S.NoteTemplateParameterLocation(Decl: *Param);
7027 }
7028 }
7029
7030 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7031 Arg, ArgType))
7032 return true;
7033
7034 // Create the template argument.
7035 SugaredConverted = TemplateArgument(Entity, ParamType);
7036 CanonicalConverted =
7037 TemplateArgument(cast<ValueDecl>(Val: Entity->getCanonicalDecl()),
7038 S.Context.getCanonicalType(T: ParamType));
7039 S.MarkAnyDeclReferenced(Loc: Arg->getBeginLoc(), D: Entity, MightBeOdrUse: false);
7040 return false;
7041}
7042
7043/// Checks whether the given template argument is a pointer to
7044/// member constant according to C++ [temp.arg.nontype]p1.
7045static bool CheckTemplateArgumentPointerToMember(
7046 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
7047 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7048 bool Invalid = false;
7049
7050 Expr *Arg = ResultArg;
7051 bool ObjCLifetimeConversion;
7052
7053 // C++ [temp.arg.nontype]p1:
7054 //
7055 // A template-argument for a non-type, non-template
7056 // template-parameter shall be one of: [...]
7057 //
7058 // -- a pointer to member expressed as described in 5.3.1.
7059 DeclRefExpr *DRE = nullptr;
7060
7061 // In C++98/03 mode, give an extension warning on any extra parentheses.
7062 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7063 bool ExtraParens = false;
7064 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
7065 if (!Invalid && !ExtraParens) {
7066 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_extra_parens)
7067 << Arg->getSourceRange();
7068 ExtraParens = true;
7069 }
7070
7071 Arg = Parens->getSubExpr();
7072 }
7073
7074 while (SubstNonTypeTemplateParmExpr *subst =
7075 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
7076 Arg = subst->getReplacement()->IgnoreImpCasts();
7077
7078 // A pointer-to-member constant written &Class::member.
7079 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
7080 if (UnOp->getOpcode() == UO_AddrOf) {
7081 DRE = dyn_cast<DeclRefExpr>(Val: UnOp->getSubExpr());
7082 if (DRE && !DRE->getQualifier())
7083 DRE = nullptr;
7084 }
7085 }
7086 // A constant of pointer-to-member type.
7087 else if ((DRE = dyn_cast<DeclRefExpr>(Val: Arg))) {
7088 ValueDecl *VD = DRE->getDecl();
7089 if (VD->getType()->isMemberPointerType()) {
7090 if (isa<NonTypeTemplateParmDecl>(Val: VD)) {
7091 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7092 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7093 CanonicalConverted =
7094 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7095 } else {
7096 SugaredConverted = TemplateArgument(VD, ParamType);
7097 CanonicalConverted =
7098 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7099 S.Context.getCanonicalType(T: ParamType));
7100 }
7101 return Invalid;
7102 }
7103 }
7104
7105 DRE = nullptr;
7106 }
7107
7108 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7109
7110 // Check for a null pointer value.
7111 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ResultArg,
7112 Entity)) {
7113 case NPV_Error:
7114 return true;
7115 case NPV_NullPointer:
7116 S.Diag(Loc: ResultArg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7117 SugaredConverted = TemplateArgument(ParamType,
7118 /*isNullPtr*/ true);
7119 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(T: ParamType),
7120 /*isNullPtr*/ true);
7121 return false;
7122 case NPV_NotNullPointer:
7123 break;
7124 }
7125
7126 if (S.IsQualificationConversion(FromType: ResultArg->getType(),
7127 ToType: ParamType.getNonReferenceType(), CStyle: false,
7128 ObjCLifetimeConversion)) {
7129 ResultArg = S.ImpCastExprToType(E: ResultArg, Type: ParamType, CK: CK_NoOp,
7130 VK: ResultArg->getValueKind())
7131 .get();
7132 } else if (!S.Context.hasSameUnqualifiedType(
7133 T1: ResultArg->getType(), T2: ParamType.getNonReferenceType())) {
7134 // We can't perform this conversion.
7135 S.Diag(Loc: ResultArg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
7136 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7137 S.NoteTemplateParameterLocation(Decl: *Param);
7138 return true;
7139 }
7140
7141 if (!DRE)
7142 return S.Diag(Loc: Arg->getBeginLoc(),
7143 DiagID: diag::err_template_arg_not_pointer_to_member_form)
7144 << Arg->getSourceRange();
7145
7146 if (isa<FieldDecl>(Val: DRE->getDecl()) ||
7147 isa<IndirectFieldDecl>(Val: DRE->getDecl()) ||
7148 isa<CXXMethodDecl>(Val: DRE->getDecl())) {
7149 assert((isa<FieldDecl>(DRE->getDecl()) ||
7150 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7151 cast<CXXMethodDecl>(DRE->getDecl())
7152 ->isImplicitObjectMemberFunction()) &&
7153 "Only non-static member pointers can make it here");
7154
7155 // Okay: this is the address of a non-static member, and therefore
7156 // a member pointer constant.
7157 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7158 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7159 CanonicalConverted =
7160 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7161 } else {
7162 ValueDecl *D = DRE->getDecl();
7163 SugaredConverted = TemplateArgument(D, ParamType);
7164 CanonicalConverted =
7165 TemplateArgument(cast<ValueDecl>(Val: D->getCanonicalDecl()),
7166 S.Context.getCanonicalType(T: ParamType));
7167 }
7168 return Invalid;
7169 }
7170
7171 // We found something else, but we don't know specifically what it is.
7172 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_pointer_to_member_form)
7173 << Arg->getSourceRange();
7174 S.Diag(Loc: DRE->getDecl()->getLocation(), DiagID: diag::note_template_arg_refers_here);
7175 return true;
7176}
7177
7178/// Check a template argument against its corresponding
7179/// non-type template parameter.
7180///
7181/// This routine implements the semantics of C++ [temp.arg.nontype].
7182/// If an error occurred, it returns ExprError(); otherwise, it
7183/// returns the converted template argument. \p ParamType is the
7184/// type of the non-type template parameter after it has been instantiated.
7185ExprResult Sema::CheckTemplateArgument(NamedDecl *Param, QualType ParamType,
7186 Expr *Arg,
7187 TemplateArgument &SugaredConverted,
7188 TemplateArgument &CanonicalConverted,
7189 bool StrictCheck,
7190 CheckTemplateArgumentKind CTAK) {
7191 SourceLocation StartLoc = Arg->getBeginLoc();
7192 auto *ArgPE = dyn_cast<PackExpansionExpr>(Val: Arg);
7193 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7194 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7195 DeductionArg = NewDeductionArg;
7196 if (ArgPE) {
7197 // Recreate a pack expansion if we unwrapped one.
7198 Arg = new (Context) PackExpansionExpr(
7199 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7200 } else {
7201 Arg = DeductionArg;
7202 }
7203 };
7204
7205 // If the parameter type somehow involves auto, deduce the type now.
7206 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7207 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7208 if (IsDeduced) {
7209 // When checking a deduced template argument, deduce from its type even if
7210 // the type is dependent, in order to check the types of non-type template
7211 // arguments line up properly in partial ordering.
7212 TypeSourceInfo *TSI =
7213 Context.getTrivialTypeSourceInfo(T: ParamType, Loc: Param->getLocation());
7214 if (isa<DeducedTemplateSpecializationType>(Val: DeducedT)) {
7215 InitializedEntity Entity =
7216 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7217 InitializationKind Kind = InitializationKind::CreateForInit(
7218 Loc: DeductionArg->getBeginLoc(), /*DirectInit*/false, Init: DeductionArg);
7219 Expr *Inits[1] = {DeductionArg};
7220 ParamType =
7221 DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind, Init: Inits);
7222 if (ParamType.isNull())
7223 return ExprError();
7224 } else {
7225 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7226 Param->getTemplateDepth() + 1);
7227 ParamType = QualType();
7228 TemplateDeductionResult Result =
7229 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeductionArg, Result&: ParamType, Info,
7230 /*DependentDeduction=*/true,
7231 // We do not check constraints right now because the
7232 // immediately-declared constraint of the auto type is
7233 // also an associated constraint, and will be checked
7234 // along with the other associated constraints after
7235 // checking the template argument list.
7236 /*IgnoreConstraints=*/true);
7237 if (Result != TemplateDeductionResult::Success) {
7238 ParamType = TSI->getType();
7239 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7240 if (Result == TemplateDeductionResult::AlreadyDiagnosed)
7241 return ExprError();
7242 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param))
7243 Diag(Loc: Arg->getExprLoc(),
7244 DiagID: diag::err_non_type_template_parm_type_deduction_failure)
7245 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7246 << Arg->getSourceRange();
7247 NoteTemplateParameterLocation(Decl: *Param);
7248 return ExprError();
7249 }
7250 ParamType = SubstAutoTypeDependent(TypeWithAuto: ParamType);
7251 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7252 }
7253 }
7254 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7255 // an error. The error message normally references the parameter
7256 // declaration, but here we'll pass the argument location because that's
7257 // where the parameter type is deduced.
7258 ParamType = CheckNonTypeTemplateParameterType(T: ParamType, Loc: Arg->getExprLoc());
7259 if (ParamType.isNull()) {
7260 NoteTemplateParameterLocation(Decl: *Param);
7261 return ExprError();
7262 }
7263 }
7264
7265 // We should have already dropped all cv-qualifiers by now.
7266 assert(!ParamType.hasQualifiers() &&
7267 "non-type template parameter type cannot be qualified");
7268
7269 // If either the parameter has a dependent type or the argument is
7270 // type-dependent, there's nothing we can check now.
7271 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7272 // Force the argument to the type of the parameter to maintain invariants.
7273 if (!IsDeduced) {
7274 ExprResult E = ImpCastExprToType(
7275 E: DeductionArg, Type: ParamType.getNonLValueExprType(Context), CK: CK_Dependent,
7276 VK: ParamType->isLValueReferenceType() ? VK_LValue
7277 : ParamType->isRValueReferenceType() ? VK_XValue
7278 : VK_PRValue);
7279 if (E.isInvalid())
7280 return ExprError();
7281 setDeductionArg(E.get());
7282 }
7283 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7284 CanonicalConverted = TemplateArgument(
7285 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7286 return Arg;
7287 }
7288
7289 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7290 if (CTAK == CTAK_Deduced && !StrictCheck &&
7291 (ParamType->isReferenceType()
7292 ? !Context.hasSameType(T1: ParamType.getNonReferenceType(),
7293 T2: DeductionArg->getType())
7294 : !Context.hasSameUnqualifiedType(T1: ParamType,
7295 T2: DeductionArg->getType()))) {
7296 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7297 // we should actually be checking the type of the template argument in P,
7298 // not the type of the template argument deduced from A, against the
7299 // template parameter type.
7300 Diag(Loc: StartLoc, DiagID: diag::err_deduced_non_type_template_arg_type_mismatch)
7301 << Arg->getType() << ParamType.getUnqualifiedType();
7302 NoteTemplateParameterLocation(Decl: *Param);
7303 return ExprError();
7304 }
7305
7306 // If the argument is a pack expansion, we don't know how many times it would
7307 // expand. If we continue checking the argument, this will make the template
7308 // definition ill-formed if it would be ill-formed for any number of
7309 // expansions during instantiation time. When partial ordering or matching
7310 // template template parameters, this is exactly what we want. Otherwise, the
7311 // normal template rules apply: we accept the template if it would be valid
7312 // for any number of expansions (i.e. none).
7313 if (ArgPE && !StrictCheck) {
7314 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7315 CanonicalConverted = TemplateArgument(
7316 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7317 return Arg;
7318 }
7319
7320 // Avoid making a copy when initializing a template parameter of class type
7321 // from a template parameter object of the same type. This is going beyond
7322 // the standard, but is required for soundness: in
7323 // template<A a> struct X { X *p; X<a> *q; };
7324 // ... we need p and q to have the same type.
7325 //
7326 // Similarly, don't inject a call to a copy constructor when initializing
7327 // from a template parameter of the same type.
7328 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7329 if (ParamType->isRecordType() && isa<DeclRefExpr>(Val: InnerArg) &&
7330 Context.hasSameUnqualifiedType(T1: ParamType, T2: InnerArg->getType())) {
7331 NamedDecl *ND = cast<DeclRefExpr>(Val: InnerArg)->getDecl();
7332 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(Val: ND)) {
7333
7334 SugaredConverted = TemplateArgument(TPO, ParamType);
7335 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7336 ParamType.getCanonicalType());
7337 return Arg;
7338 }
7339 if (isa<NonTypeTemplateParmDecl>(Val: ND)) {
7340 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7341 CanonicalConverted =
7342 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7343 return Arg;
7344 }
7345 }
7346
7347 // The initialization of the parameter from the argument is
7348 // a constant-evaluated context.
7349 EnterExpressionEvaluationContext ConstantEvaluated(
7350 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7351
7352 bool IsConvertedConstantExpression = true;
7353 if (isa<InitListExpr>(Val: DeductionArg) || ParamType->isRecordType()) {
7354 InitializationKind Kind = InitializationKind::CreateForInit(
7355 Loc: StartLoc, /*DirectInit=*/false, Init: DeductionArg);
7356 Expr *Inits[1] = {DeductionArg};
7357 InitializedEntity Entity =
7358 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7359 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7360 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Inits);
7361 if (Result.isInvalid() || !Result.get())
7362 return ExprError();
7363 Result = ActOnConstantExpression(Res: Result.get());
7364 if (Result.isInvalid() || !Result.get())
7365 return ExprError();
7366 setDeductionArg(ActOnFinishFullExpr(Expr: Result.get(), CC: Arg->getBeginLoc(),
7367 /*DiscardedValue=*/false,
7368 /*IsConstexpr=*/true,
7369 /*IsTemplateArgument=*/true)
7370 .get());
7371 IsConvertedConstantExpression = false;
7372 }
7373
7374 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7375 // C++17 [temp.arg.nontype]p1:
7376 // A template-argument for a non-type template parameter shall be
7377 // a converted constant expression of the type of the template-parameter.
7378 APValue Value;
7379 ExprResult ArgResult;
7380 if (IsConvertedConstantExpression) {
7381 ArgResult = BuildConvertedConstantExpression(
7382 From: DeductionArg, T: ParamType,
7383 CCE: StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Dest: Param);
7384 assert(!ArgResult.isUnset());
7385 if (ArgResult.isInvalid()) {
7386 NoteTemplateParameterLocation(Decl: *Param);
7387 return ExprError();
7388 }
7389 } else {
7390 ArgResult = DeductionArg;
7391 }
7392
7393 // For a value-dependent argument, CheckConvertedConstantExpression is
7394 // permitted (and expected) to be unable to determine a value.
7395 if (ArgResult.get()->isValueDependent()) {
7396 setDeductionArg(ArgResult.get());
7397 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7398 CanonicalConverted =
7399 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7400 return Arg;
7401 }
7402
7403 APValue PreNarrowingValue;
7404 ArgResult = EvaluateConvertedConstantExpression(
7405 E: ArgResult.get(), T: ParamType, Value, CCE: CCEKind::TemplateArg, /*RequireInt=*/
7406 false, PreNarrowingValue);
7407 if (ArgResult.isInvalid())
7408 return ExprError();
7409 setDeductionArg(ArgResult.get());
7410
7411 if (Value.isLValue()) {
7412 APValue::LValueBase Base = Value.getLValueBase();
7413 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7414 // For a non-type template-parameter of pointer or reference type,
7415 // the value of the constant expression shall not refer to
7416 assert(ParamType->isPointerOrReferenceType() ||
7417 ParamType->isNullPtrType());
7418 // -- a temporary object
7419 // -- a string literal
7420 // -- the result of a typeid expression, or
7421 // -- a predefined __func__ variable
7422 if (Base &&
7423 (!VD ||
7424 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(Val: VD))) {
7425 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
7426 << Arg->getSourceRange();
7427 return ExprError();
7428 }
7429
7430 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7431 VD->getType()->isArrayType() &&
7432 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7433 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7434 if (ArgPE) {
7435 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7436 CanonicalConverted =
7437 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7438 } else {
7439 SugaredConverted = TemplateArgument(VD, ParamType);
7440 CanonicalConverted =
7441 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7442 ParamType.getCanonicalType());
7443 }
7444 return Arg;
7445 }
7446
7447 // -- a subobject [until C++20]
7448 if (!getLangOpts().CPlusPlus20) {
7449 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7450 Value.isLValueOnePastTheEnd()) {
7451 Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_subobject)
7452 << Value.getAsString(Ctx: Context, Ty: ParamType);
7453 return ExprError();
7454 }
7455 assert((VD || !ParamType->isReferenceType()) &&
7456 "null reference should not be a constant expression");
7457 assert((!VD || !ParamType->isNullPtrType()) &&
7458 "non-null value of type nullptr_t?");
7459 }
7460 }
7461
7462 if (Value.isAddrLabelDiff())
7463 return Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_addr_label_diff);
7464
7465 if (ArgPE) {
7466 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7467 CanonicalConverted =
7468 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7469 } else {
7470 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7471 CanonicalConverted =
7472 TemplateArgument(Context, ParamType.getCanonicalType(), Value);
7473 }
7474 return Arg;
7475 }
7476
7477 // These should have all been handled above using the C++17 rules.
7478 assert(!ArgPE && !StrictCheck);
7479
7480 // C++ [temp.arg.nontype]p5:
7481 // The following conversions are performed on each expression used
7482 // as a non-type template-argument. If a non-type
7483 // template-argument cannot be converted to the type of the
7484 // corresponding template-parameter then the program is
7485 // ill-formed.
7486 if (ParamType->isIntegralOrEnumerationType()) {
7487 // C++11:
7488 // -- for a non-type template-parameter of integral or
7489 // enumeration type, conversions permitted in a converted
7490 // constant expression are applied.
7491 //
7492 // C++98:
7493 // -- for a non-type template-parameter of integral or
7494 // enumeration type, integral promotions (4.5) and integral
7495 // conversions (4.7) are applied.
7496
7497 if (getLangOpts().CPlusPlus11) {
7498 // C++ [temp.arg.nontype]p1:
7499 // A template-argument for a non-type, non-template template-parameter
7500 // shall be one of:
7501 //
7502 // -- for a non-type template-parameter of integral or enumeration
7503 // type, a converted constant expression of the type of the
7504 // template-parameter; or
7505 llvm::APSInt Value;
7506 ExprResult ArgResult = CheckConvertedConstantExpression(
7507 From: Arg, T: ParamType, Value, CCE: CCEKind::TemplateArg);
7508 if (ArgResult.isInvalid())
7509 return ExprError();
7510 Arg = ArgResult.get();
7511
7512 // We can't check arbitrary value-dependent arguments.
7513 if (Arg->isValueDependent()) {
7514 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7515 CanonicalConverted =
7516 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7517 return Arg;
7518 }
7519
7520 // Widen the argument value to sizeof(parameter type). This is almost
7521 // always a no-op, except when the parameter type is bool. In
7522 // that case, this may extend the argument from 1 bit to 8 bits.
7523 QualType IntegerType = ParamType;
7524 if (const auto *ED = IntegerType->getAsEnumDecl())
7525 IntegerType = ED->getIntegerType();
7526 Value = Value.extOrTrunc(width: IntegerType->isBitIntType()
7527 ? Context.getIntWidth(T: IntegerType)
7528 : Context.getTypeSize(T: IntegerType));
7529
7530 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7531 CanonicalConverted =
7532 TemplateArgument(Context, Value, Context.getCanonicalType(T: ParamType));
7533 return Arg;
7534 }
7535
7536 ExprResult ArgResult = DefaultLvalueConversion(E: Arg);
7537 if (ArgResult.isInvalid())
7538 return ExprError();
7539 Arg = ArgResult.get();
7540
7541 QualType ArgType = Arg->getType();
7542
7543 // C++ [temp.arg.nontype]p1:
7544 // A template-argument for a non-type, non-template
7545 // template-parameter shall be one of:
7546 //
7547 // -- an integral constant-expression of integral or enumeration
7548 // type; or
7549 // -- the name of a non-type template-parameter; or
7550 llvm::APSInt Value;
7551 if (!ArgType->isIntegralOrEnumerationType()) {
7552 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_integral_or_enumeral)
7553 << ArgType << Arg->getSourceRange();
7554 NoteTemplateParameterLocation(Decl: *Param);
7555 return ExprError();
7556 }
7557 if (!Arg->isValueDependent()) {
7558 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7559 QualType T;
7560
7561 public:
7562 TmplArgICEDiagnoser(QualType T) : T(T) { }
7563
7564 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7565 SourceLocation Loc) override {
7566 return S.Diag(Loc, DiagID: diag::err_template_arg_not_ice) << T;
7567 }
7568 } Diagnoser(ArgType);
7569
7570 Arg = VerifyIntegerConstantExpression(E: Arg, Result: &Value, Diagnoser).get();
7571 if (!Arg)
7572 return ExprError();
7573 }
7574
7575 // From here on out, all we care about is the unqualified form
7576 // of the argument type.
7577 ArgType = ArgType.getUnqualifiedType();
7578
7579 // Try to convert the argument to the parameter's type.
7580 if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
7581 // Okay: no conversion necessary
7582 } else if (ParamType->isBooleanType()) {
7583 // This is an integral-to-boolean conversion.
7584 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralToBoolean).get();
7585 } else if (IsIntegralPromotion(From: Arg, FromType: ArgType, ToType: ParamType) ||
7586 !ParamType->isEnumeralType()) {
7587 // This is an integral promotion or conversion.
7588 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralCast).get();
7589 } else {
7590 // We can't perform this conversion.
7591 Diag(Loc: StartLoc, DiagID: diag::err_template_arg_not_convertible)
7592 << Arg->getType() << ParamType << Arg->getSourceRange();
7593 NoteTemplateParameterLocation(Decl: *Param);
7594 return ExprError();
7595 }
7596
7597 // Add the value of this argument to the list of converted
7598 // arguments. We use the bitwidth and signedness of the template
7599 // parameter.
7600 if (Arg->isValueDependent()) {
7601 // The argument is value-dependent. Create a new
7602 // TemplateArgument with the converted expression.
7603 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7604 CanonicalConverted =
7605 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7606 return Arg;
7607 }
7608
7609 QualType IntegerType = ParamType;
7610 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7611 IntegerType = ED->getIntegerType();
7612 }
7613
7614 if (ParamType->isBooleanType()) {
7615 // Value must be zero or one.
7616 Value = Value != 0;
7617 unsigned AllowedBits = Context.getTypeSize(T: IntegerType);
7618 if (Value.getBitWidth() != AllowedBits)
7619 Value = Value.extOrTrunc(width: AllowedBits);
7620 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7621 } else {
7622 llvm::APSInt OldValue = Value;
7623
7624 // Coerce the template argument's value to the value it will have
7625 // based on the template parameter's type.
7626 unsigned AllowedBits = IntegerType->isBitIntType()
7627 ? Context.getIntWidth(T: IntegerType)
7628 : Context.getTypeSize(T: IntegerType);
7629 if (Value.getBitWidth() != AllowedBits)
7630 Value = Value.extOrTrunc(width: AllowedBits);
7631 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7632
7633 // Complain if an unsigned parameter received a negative value.
7634 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7635 (OldValue.isSigned() && OldValue.isNegative())) {
7636 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_negative)
7637 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7638 << Arg->getSourceRange();
7639 NoteTemplateParameterLocation(Decl: *Param);
7640 }
7641
7642 // Complain if we overflowed the template parameter's type.
7643 unsigned RequiredBits;
7644 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7645 RequiredBits = OldValue.getActiveBits();
7646 else if (OldValue.isUnsigned())
7647 RequiredBits = OldValue.getActiveBits() + 1;
7648 else
7649 RequiredBits = OldValue.getSignificantBits();
7650 if (RequiredBits > AllowedBits) {
7651 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_too_large)
7652 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7653 << Arg->getSourceRange();
7654 NoteTemplateParameterLocation(Decl: *Param);
7655 }
7656 }
7657
7658 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7659 SugaredConverted = TemplateArgument(Context, Value, T);
7660 CanonicalConverted =
7661 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7662 return Arg;
7663 }
7664
7665 QualType ArgType = Arg->getType();
7666 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7667 bool IsSpecified = CTAK == CTAK_Specified;
7668
7669 // Handle pointer-to-function, reference-to-function, and
7670 // pointer-to-member-function all in (roughly) the same way.
7671 if (// -- For a non-type template-parameter of type pointer to
7672 // function, only the function-to-pointer conversion (4.3) is
7673 // applied. If the template-argument represents a set of
7674 // overloaded functions (or a pointer to such), the matching
7675 // function is selected from the set (13.4).
7676 (ParamType->isPointerType() &&
7677 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7678 // -- For a non-type template-parameter of type reference to
7679 // function, no conversions apply. If the template-argument
7680 // represents a set of overloaded functions, the matching
7681 // function is selected from the set (13.4).
7682 (ParamType->isReferenceType() &&
7683 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7684 // -- For a non-type template-parameter of type pointer to
7685 // member function, no conversions apply. If the
7686 // template-argument represents a set of overloaded member
7687 // functions, the matching member function is selected from
7688 // the set (13.4).
7689 (ParamType->isMemberPointerType() &&
7690 ParamType->castAs<MemberPointerType>()->getPointeeType()
7691 ->isFunctionType())) {
7692
7693 if (Arg->getType() == Context.OverloadTy) {
7694 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg, TargetType: ParamType,
7695 Complain: true,
7696 Found&: FoundResult)) {
7697 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7698 return ExprError();
7699
7700 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7701 if (Res.isInvalid())
7702 return ExprError();
7703 Arg = Res.get();
7704 ArgType = Arg->getType();
7705 } else
7706 return ExprError();
7707 }
7708
7709 if (!ParamType->isMemberPointerType()) {
7710 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7711 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7712 CanonicalConverted))
7713 return ExprError();
7714 return Arg;
7715 }
7716
7717 if (CheckTemplateArgumentPointerToMember(
7718 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7719 return ExprError();
7720 return Arg;
7721 }
7722
7723 if (ParamType->isPointerType()) {
7724 // -- for a non-type template-parameter of type pointer to
7725 // object, qualification conversions (4.4) and the
7726 // array-to-pointer conversion (4.2) are applied.
7727 // C++0x also allows a value of std::nullptr_t.
7728 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7729 "Only object pointers allowed here");
7730
7731 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7732 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7733 CanonicalConverted))
7734 return ExprError();
7735 return Arg;
7736 }
7737
7738 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7739 // -- For a non-type template-parameter of type reference to
7740 // object, no conversions apply. The type referred to by the
7741 // reference may be more cv-qualified than the (otherwise
7742 // identical) type of the template-argument. The
7743 // template-parameter is bound directly to the
7744 // template-argument, which must be an lvalue.
7745 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7746 "Only object references allowed here");
7747
7748 if (Arg->getType() == Context.OverloadTy) {
7749 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg,
7750 TargetType: ParamRefType->getPointeeType(),
7751 Complain: true,
7752 Found&: FoundResult)) {
7753 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7754 return ExprError();
7755 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7756 if (Res.isInvalid())
7757 return ExprError();
7758 Arg = Res.get();
7759 ArgType = Arg->getType();
7760 } else
7761 return ExprError();
7762 }
7763
7764 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7765 S&: *this, Param, ParamType, ArgIn: Arg, IsSpecified, SugaredConverted,
7766 CanonicalConverted))
7767 return ExprError();
7768 return Arg;
7769 }
7770
7771 // Deal with parameters of type std::nullptr_t.
7772 if (ParamType->isNullPtrType()) {
7773 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7774 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7775 CanonicalConverted =
7776 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7777 return Arg;
7778 }
7779
7780 switch (isNullPointerValueTemplateArgument(S&: *this, Param, ParamType, Arg)) {
7781 case NPV_NotNullPointer:
7782 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_not_convertible)
7783 << Arg->getType() << ParamType;
7784 NoteTemplateParameterLocation(Decl: *Param);
7785 return ExprError();
7786
7787 case NPV_Error:
7788 return ExprError();
7789
7790 case NPV_NullPointer:
7791 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7792 SugaredConverted = TemplateArgument(ParamType,
7793 /*isNullPtr=*/true);
7794 CanonicalConverted = TemplateArgument(Context.getCanonicalType(T: ParamType),
7795 /*isNullPtr=*/true);
7796 return Arg;
7797 }
7798 }
7799
7800 // -- For a non-type template-parameter of type pointer to data
7801 // member, qualification conversions (4.4) are applied.
7802 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7803
7804 if (CheckTemplateArgumentPointerToMember(
7805 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7806 return ExprError();
7807 return Arg;
7808}
7809
7810static void DiagnoseTemplateParameterListArityMismatch(
7811 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7812 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7813
7814bool Sema::CheckDeclCompatibleWithTemplateTemplate(
7815 TemplateDecl *Template, TemplateTemplateParmDecl *Param,
7816 const TemplateArgumentLoc &Arg) {
7817 // C++0x [temp.arg.template]p1:
7818 // A template-argument for a template template-parameter shall be
7819 // the name of a class template or an alias template, expressed as an
7820 // id-expression. When the template-argument names a class template, only
7821 // primary class templates are considered when matching the
7822 // template template argument with the corresponding parameter;
7823 // partial specializations are not considered even if their
7824 // parameter lists match that of the template template parameter.
7825 //
7826
7827 TemplateNameKind Kind = TNK_Non_template;
7828 unsigned DiagFoundKind = 0;
7829
7830 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Val: Template)) {
7831 switch (TTP->templateParameterKind()) {
7832 case TemplateNameKind::TNK_Concept_template:
7833 DiagFoundKind = 3;
7834 break;
7835 case TemplateNameKind::TNK_Var_template:
7836 DiagFoundKind = 2;
7837 break;
7838 default:
7839 DiagFoundKind = 1;
7840 break;
7841 }
7842 Kind = TTP->templateParameterKind();
7843 } else if (isa<ConceptDecl>(Val: Template)) {
7844 Kind = TemplateNameKind::TNK_Concept_template;
7845 DiagFoundKind = 3;
7846 } else if (isa<FunctionTemplateDecl>(Val: Template)) {
7847 Kind = TemplateNameKind::TNK_Function_template;
7848 DiagFoundKind = 0;
7849 } else if (isa<VarTemplateDecl>(Val: Template)) {
7850 Kind = TemplateNameKind::TNK_Var_template;
7851 DiagFoundKind = 2;
7852 } else if (isa<ClassTemplateDecl>(Val: Template) ||
7853 isa<TypeAliasTemplateDecl>(Val: Template) ||
7854 isa<BuiltinTemplateDecl>(Val: Template)) {
7855 Kind = TemplateNameKind::TNK_Type_template;
7856 DiagFoundKind = 1;
7857 } else {
7858 assert(false && "Unexpected Decl");
7859 }
7860
7861 if (Kind == Param->templateParameterKind()) {
7862 return true;
7863 }
7864
7865 unsigned DiagKind = 0;
7866 switch (Param->templateParameterKind()) {
7867 case TemplateNameKind::TNK_Concept_template:
7868 DiagKind = 2;
7869 break;
7870 case TemplateNameKind::TNK_Var_template:
7871 DiagKind = 1;
7872 break;
7873 default:
7874 DiagKind = 0;
7875 break;
7876 }
7877 Diag(Loc: Arg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
7878 << DiagKind;
7879 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_arg_refers_to_template_here)
7880 << DiagFoundKind << Template;
7881 return false;
7882}
7883
7884/// Check a template argument against its corresponding
7885/// template template parameter.
7886///
7887/// This routine implements the semantics of C++ [temp.arg.template].
7888/// It returns true if an error occurred, and false otherwise.
7889bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7890 TemplateParameterList *Params,
7891 TemplateArgumentLoc &Arg,
7892 bool PartialOrdering,
7893 bool *StrictPackMatch) {
7894 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7895 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7896 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7897 if (!Template) {
7898 // FIXME: Handle AssumedTemplateNames
7899 // Any dependent template name is fine.
7900 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7901 return false;
7902 }
7903
7904 if (Template->isInvalidDecl())
7905 return true;
7906
7907 if (!CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg)) {
7908 return true;
7909 }
7910
7911 // C++1z [temp.arg.template]p3: (DR 150)
7912 // A template-argument matches a template template-parameter P when P
7913 // is at least as specialized as the template-argument A.
7914 if (!isTemplateTemplateParameterAtLeastAsSpecializedAs(
7915 PParam: Params, PArg: Param, AArg: Template, DefaultArgs, ArgLoc: Arg.getLocation(),
7916 PartialOrdering, StrictPackMatch))
7917 return true;
7918 // P2113
7919 // C++20[temp.func.order]p2
7920 // [...] If both deductions succeed, the partial ordering selects the
7921 // more constrained template (if one exists) as determined below.
7922 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7923 Params->getAssociatedConstraints(AC&: ParamsAC);
7924 // C++20[temp.arg.template]p3
7925 // [...] In this comparison, if P is unconstrained, the constraints on A
7926 // are not considered.
7927 if (ParamsAC.empty())
7928 return false;
7929
7930 Template->getAssociatedConstraints(AC&: TemplateAC);
7931
7932 bool IsParamAtLeastAsConstrained;
7933 if (IsAtLeastAsConstrained(D1: Param, AC1: ParamsAC, D2: Template, AC2: TemplateAC,
7934 Result&: IsParamAtLeastAsConstrained))
7935 return true;
7936 if (!IsParamAtLeastAsConstrained) {
7937 Diag(Loc: Arg.getLocation(),
7938 DiagID: diag::err_template_template_parameter_not_at_least_as_constrained)
7939 << Template << Param << Arg.getSourceRange();
7940 Diag(Loc: Param->getLocation(), DiagID: diag::note_entity_declared_at) << Param;
7941 Diag(Loc: Template->getLocation(), DiagID: diag::note_entity_declared_at) << Template;
7942 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Param, AC1: ParamsAC, D2: Template,
7943 AC2: TemplateAC);
7944 return true;
7945 }
7946 return false;
7947}
7948
7949static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7950 unsigned HereDiagID,
7951 unsigned ExternalDiagID) {
7952 if (Decl.getLocation().isValid())
7953 return S.Diag(Loc: Decl.getLocation(), DiagID: HereDiagID);
7954
7955 SmallString<128> Str;
7956 llvm::raw_svector_ostream Out(Str);
7957 PrintingPolicy PP = S.getPrintingPolicy();
7958 PP.TerseOutput = 1;
7959 Decl.print(Out, Policy: PP);
7960 return S.Diag(Loc: Decl.getLocation(), DiagID: ExternalDiagID) << Out.str();
7961}
7962
7963void Sema::NoteTemplateLocation(const NamedDecl &Decl,
7964 std::optional<SourceRange> ParamRange) {
7965 SemaDiagnosticBuilder DB =
7966 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_decl_here,
7967 ExternalDiagID: diag::note_template_decl_external);
7968 if (ParamRange && ParamRange->isValid()) {
7969 assert(Decl.getLocation().isValid() &&
7970 "Parameter range has location when Decl does not");
7971 DB << *ParamRange;
7972 }
7973}
7974
7975void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
7976 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_param_here,
7977 ExternalDiagID: diag::note_template_param_external);
7978}
7979
7980/// Given a non-type template argument that refers to a
7981/// declaration and the type of its corresponding non-type template
7982/// parameter, produce an expression that properly refers to that
7983/// declaration.
7984ExprResult Sema::BuildExpressionFromDeclTemplateArgument(
7985 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc) {
7986 // C++ [temp.param]p8:
7987 //
7988 // A non-type template-parameter of type "array of T" or
7989 // "function returning T" is adjusted to be of type "pointer to
7990 // T" or "pointer to function returning T", respectively.
7991 if (ParamType->isArrayType())
7992 ParamType = Context.getArrayDecayedType(T: ParamType);
7993 else if (ParamType->isFunctionType())
7994 ParamType = Context.getPointerType(T: ParamType);
7995
7996 // For a NULL non-type template argument, return nullptr casted to the
7997 // parameter's type.
7998 if (Arg.getKind() == TemplateArgument::NullPtr) {
7999 return ImpCastExprToType(
8000 E: new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
8001 Type: ParamType,
8002 CK: ParamType->getAs<MemberPointerType>()
8003 ? CK_NullToMemberPointer
8004 : CK_NullToPointer);
8005 }
8006 assert(Arg.getKind() == TemplateArgument::Declaration &&
8007 "Only declaration template arguments permitted here");
8008
8009 ValueDecl *VD = Arg.getAsDecl();
8010
8011 CXXScopeSpec SS;
8012 if (ParamType->isMemberPointerType()) {
8013 // If this is a pointer to member, we need to use a qualified name to
8014 // form a suitable pointer-to-member constant.
8015 assert(VD->getDeclContext()->isRecord() &&
8016 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
8017 isa<IndirectFieldDecl>(VD)));
8018 CanQualType ClassType =
8019 Context.getCanonicalTagType(TD: cast<RecordDecl>(Val: VD->getDeclContext()));
8020 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
8021 SS.MakeTrivial(Context, Qualifier, R: Loc);
8022 }
8023
8024 ExprResult RefExpr = BuildDeclarationNameExpr(
8025 SS, NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
8026 if (RefExpr.isInvalid())
8027 return ExprError();
8028
8029 // For a pointer, the argument declaration is the pointee. Take its address.
8030 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8031 if (ParamType->isPointerType() && !ElemT.isNull() &&
8032 Context.hasSimilarType(T1: ElemT, T2: ParamType->getPointeeType())) {
8033 // Decay an array argument if we want a pointer to its first element.
8034 RefExpr = DefaultFunctionArrayConversion(E: RefExpr.get());
8035 if (RefExpr.isInvalid())
8036 return ExprError();
8037 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8038 // For any other pointer, take the address (or form a pointer-to-member).
8039 RefExpr = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_AddrOf, InputExpr: RefExpr.get());
8040 if (RefExpr.isInvalid())
8041 return ExprError();
8042 } else if (ParamType->isRecordType()) {
8043 assert(isa<TemplateParamObjectDecl>(VD) &&
8044 "arg for class template param not a template parameter object");
8045 // No conversions apply in this case.
8046 return RefExpr;
8047 } else {
8048 assert(ParamType->isReferenceType() &&
8049 "unexpected type for decl template argument");
8050 // If the parameter has reference type, wrap it in paretheses so that this
8051 // expression will have the correct type under `decltype`.
8052 RefExpr = new (Context) ParenExpr(Loc, Loc, RefExpr.get());
8053 }
8054
8055 // At this point we should have the right value category.
8056 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8057 "value kind mismatch for non-type template argument");
8058
8059 // The type of the template parameter can differ from the type of the
8060 // argument in various ways; convert it now if necessary.
8061 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8062 QualType SrcExprType = RefExpr.get()->getType();
8063 if (!Context.hasSameType(T1: SrcExprType, T2: DestExprType)) {
8064 CastKind CK;
8065 if (Context.hasSimilarType(T1: SrcExprType, T2: DestExprType) ||
8066 IsFunctionConversion(FromType: SrcExprType, ToType: DestExprType)) {
8067 CK = CK_NoOp;
8068 } else if (ParamType->isVoidPointerType() && SrcExprType->isPointerType()) {
8069 CK = CK_BitCast;
8070 } else {
8071 // FIXME: Pointers to members can need conversion derived-to-base or
8072 // base-to-derived conversions. We currently don't retain enough
8073 // information to convert properly (we need to track a cast path or
8074 // subobject number in the template argument).
8075 llvm_unreachable(
8076 "unexpected conversion required for non-type template argument");
8077 }
8078 RefExpr = ImpCastExprToType(E: RefExpr.get(), Type: DestExprType, CK,
8079 VK: RefExpr.get()->getValueKind());
8080 }
8081
8082 return RefExpr;
8083}
8084
8085/// Construct a new expression that refers to the given
8086/// integral template argument with the given source-location
8087/// information.
8088///
8089/// This routine takes care of the mapping from an integral template
8090/// argument (which may have any integral type) to the appropriate
8091/// literal value.
8092static Expr *BuildExpressionFromIntegralTemplateArgumentValue(
8093 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8094 assert(OrigT->isIntegralOrEnumerationType());
8095
8096 // If this is an enum type that we're instantiating, we need to use an integer
8097 // type the same size as the enumerator. We don't want to build an
8098 // IntegerLiteral with enum type. The integer type of an enum type can be of
8099 // any integral type with C++11 enum classes, make sure we create the right
8100 // type of literal for it.
8101 QualType T = OrigT;
8102 if (const auto *ED = OrigT->getAsEnumDecl())
8103 T = ED->getIntegerType();
8104
8105 Expr *E;
8106 if (T->isAnyCharacterType()) {
8107 CharacterLiteralKind Kind;
8108 if (T->isWideCharType())
8109 Kind = CharacterLiteralKind::Wide;
8110 else if (T->isChar8Type() && S.getLangOpts().Char8)
8111 Kind = CharacterLiteralKind::UTF8;
8112 else if (T->isChar16Type())
8113 Kind = CharacterLiteralKind::UTF16;
8114 else if (T->isChar32Type())
8115 Kind = CharacterLiteralKind::UTF32;
8116 else
8117 Kind = CharacterLiteralKind::Ascii;
8118
8119 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8120 } else if (T->isBooleanType()) {
8121 E = CXXBoolLiteralExpr::Create(C: S.Context, Val: Int.getBoolValue(), Ty: T, Loc);
8122 } else {
8123 E = IntegerLiteral::Create(C: S.Context, V: Int, type: T, l: Loc);
8124 }
8125
8126 if (OrigT->isEnumeralType()) {
8127 // FIXME: This is a hack. We need a better way to handle substituted
8128 // non-type template parameters.
8129 E = CStyleCastExpr::Create(Context: S.Context, T: OrigT, VK: VK_PRValue, K: CK_IntegralCast, Op: E,
8130 BasePath: nullptr, FPO: S.CurFPFeatureOverrides(),
8131 WrittenTy: S.Context.getTrivialTypeSourceInfo(T: OrigT, Loc),
8132 L: Loc, R: Loc);
8133 }
8134
8135 return E;
8136}
8137
8138/// Construct a new reflect expression that refers to the given
8139/// entity with the given source-location of the reflection operator.
8140static ExprResult BuildExpressionFromReflection(Sema &S, const APValue &RV,
8141 SourceLocation CaretCaretLoc) {
8142 // TODO(Reflection): Add support for NamespaceReference, TemplateReference,
8143 // and DeclRefExpr.
8144 return CXXReflectExpr::Create(
8145 C&: S.Context, OperatorLoc: CaretCaretLoc,
8146 TSI: static_cast<TypeSourceInfo *>(
8147 const_cast<void *>(RV.getReflectionOpaqueOperand())));
8148}
8149
8150static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(
8151 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8152 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8153 auto *ILE = new (S.Context)
8154 InitListExpr(S.Context, Loc, Elts, Loc, /*isExplicit=*/false);
8155 ILE->setType(T);
8156 return ILE;
8157 };
8158
8159 switch (Val.getKind()) {
8160 case APValue::AddrLabelDiff:
8161 // This cannot occur in a template argument at all.
8162 case APValue::Array:
8163 case APValue::Struct:
8164 case APValue::Union:
8165 // These can only occur within a template parameter object, which is
8166 // represented as a TemplateArgument::Declaration.
8167 llvm_unreachable("unexpected template argument value");
8168
8169 case APValue::Int:
8170 return BuildExpressionFromIntegralTemplateArgumentValue(S, OrigT: T, Int: Val.getInt(),
8171 Loc);
8172
8173 case APValue::Float:
8174 return FloatingLiteral::Create(C: S.Context, V: Val.getFloat(), /*IsExact=*/isexact: true,
8175 Type: T, L: Loc);
8176
8177 case APValue::FixedPoint:
8178 return FixedPointLiteral::CreateFromRawInt(
8179 C: S.Context, V: Val.getFixedPoint().getValue(), type: T, l: Loc,
8180 Scale: Val.getFixedPoint().getScale());
8181
8182 case APValue::ComplexInt: {
8183 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8184 return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(
8185 S, OrigT: ElemT, Int: Val.getComplexIntReal(), Loc),
8186 BuildExpressionFromIntegralTemplateArgumentValue(
8187 S, OrigT: ElemT, Int: Val.getComplexIntImag(), Loc)});
8188 }
8189
8190 case APValue::ComplexFloat: {
8191 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8192 return MakeInitList(
8193 {FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatReal(), isexact: true,
8194 Type: ElemT, L: Loc),
8195 FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatImag(), isexact: true,
8196 Type: ElemT, L: Loc)});
8197 }
8198
8199 case APValue::Vector: {
8200 QualType ElemT = T->castAs<VectorType>()->getElementType();
8201 llvm::SmallVector<Expr *, 8> Elts;
8202 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8203 Elts.push_back(Elt: BuildExpressionFromNonTypeTemplateArgumentValue(
8204 S, T: ElemT, Val: Val.getVectorElt(I), Loc));
8205 return MakeInitList(Elts);
8206 }
8207
8208 case APValue::Matrix:
8209 llvm_unreachable("Matrix template argument expression not yet supported");
8210
8211 case APValue::None:
8212 case APValue::Indeterminate:
8213 llvm_unreachable("Unexpected APValue kind.");
8214 case APValue::LValue:
8215 case APValue::MemberPointer: {
8216 // There isn't necessarily a valid equivalent source-level syntax for
8217 // these; in particular, a naive lowering might violate access control.
8218 // So for now we lower to a ConstantExpr holding the value, wrapped around
8219 // an OpaqueValueExpr.
8220 // FIXME: We should have a better representation for this.
8221 ExprValueKind VK = VK_PRValue;
8222 if (T->isReferenceType()) {
8223 T = T->getPointeeType();
8224 VK = VK_LValue;
8225 }
8226 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8227 return ConstantExpr::Create(Context: S.Context, E: OVE, Result: Val);
8228 }
8229 case APValue::Reflection:
8230 return BuildExpressionFromReflection(S, RV: Val, CaretCaretLoc: Loc).get();
8231 }
8232 llvm_unreachable("Unhandled APValue::ValueKind enum");
8233}
8234
8235ExprResult
8236Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
8237 SourceLocation Loc) {
8238 switch (Arg.getKind()) {
8239 case TemplateArgument::Null:
8240 case TemplateArgument::Type:
8241 case TemplateArgument::Template:
8242 case TemplateArgument::TemplateExpansion:
8243 case TemplateArgument::Pack:
8244 llvm_unreachable("not a non-type template argument");
8245
8246 case TemplateArgument::Expression:
8247 return Arg.getAsExpr();
8248
8249 case TemplateArgument::NullPtr:
8250 case TemplateArgument::Declaration:
8251 return BuildExpressionFromDeclTemplateArgument(
8252 Arg, ParamType: Arg.getNonTypeTemplateArgumentType(), Loc);
8253
8254 case TemplateArgument::Integral:
8255 return BuildExpressionFromIntegralTemplateArgumentValue(
8256 S&: *this, OrigT: Arg.getIntegralType(), Int: Arg.getAsIntegral(), Loc);
8257
8258 case TemplateArgument::StructuralValue:
8259 return BuildExpressionFromNonTypeTemplateArgumentValue(
8260 S&: *this, T: Arg.getStructuralValueType(), Val: Arg.getAsStructuralValue(), Loc);
8261 }
8262 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8263}
8264
8265/// Match two template parameters within template parameter lists.
8266static bool MatchTemplateParameterKind(
8267 Sema &S, NamedDecl *New,
8268 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8269 const NamedDecl *OldInstFrom, bool Complain,
8270 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8271 // Check the actual kind (type, non-type, template).
8272 if (Old->getKind() != New->getKind()) {
8273 if (Complain) {
8274 unsigned NextDiag = diag::err_template_param_different_kind;
8275 if (TemplateArgLoc.isValid()) {
8276 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8277 NextDiag = diag::note_template_param_different_kind;
8278 }
8279 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8280 << (Kind != Sema::TPL_TemplateMatch);
8281 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_prev_declaration)
8282 << (Kind != Sema::TPL_TemplateMatch);
8283 }
8284
8285 return false;
8286 }
8287
8288 // Check that both are parameter packs or neither are parameter packs.
8289 // However, if we are matching a template template argument to a
8290 // template template parameter, the template template parameter can have
8291 // a parameter pack where the template template argument does not.
8292 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8293 if (Complain) {
8294 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8295 if (TemplateArgLoc.isValid()) {
8296 S.Diag(Loc: TemplateArgLoc,
8297 DiagID: diag::err_template_arg_template_params_mismatch);
8298 NextDiag = diag::note_template_parameter_pack_non_pack;
8299 }
8300
8301 unsigned ParamKind = isa<TemplateTypeParmDecl>(Val: New)? 0
8302 : isa<NonTypeTemplateParmDecl>(Val: New)? 1
8303 : 2;
8304 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8305 << ParamKind << New->isParameterPack();
8306 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_parameter_pack_here)
8307 << ParamKind << Old->isParameterPack();
8308 }
8309
8310 return false;
8311 }
8312 // For non-type template parameters, check the type of the parameter.
8313 if (NonTypeTemplateParmDecl *OldNTTP =
8314 dyn_cast<NonTypeTemplateParmDecl>(Val: Old)) {
8315 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(Val: New);
8316
8317 // If we are matching a template template argument to a template
8318 // template parameter and one of the non-type template parameter types
8319 // is dependent, then we must wait until template instantiation time
8320 // to actually compare the arguments.
8321 if (Kind != Sema::TPL_TemplateTemplateParmMatch ||
8322 (!OldNTTP->getType()->isDependentType() &&
8323 !NewNTTP->getType()->isDependentType())) {
8324 // C++20 [temp.over.link]p6:
8325 // Two [non-type] template-parameters are equivalent [if] they have
8326 // equivalent types ignoring the use of type-constraints for
8327 // placeholder types
8328 QualType OldType = S.Context.getUnconstrainedType(T: OldNTTP->getType());
8329 QualType NewType = S.Context.getUnconstrainedType(T: NewNTTP->getType());
8330 if (!S.Context.hasSameType(T1: OldType, T2: NewType)) {
8331 if (Complain) {
8332 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8333 if (TemplateArgLoc.isValid()) {
8334 S.Diag(Loc: TemplateArgLoc,
8335 DiagID: diag::err_template_arg_template_params_mismatch);
8336 NextDiag = diag::note_template_nontype_parm_different_type;
8337 }
8338 S.Diag(Loc: NewNTTP->getLocation(), DiagID: NextDiag)
8339 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8340 S.Diag(Loc: OldNTTP->getLocation(),
8341 DiagID: diag::note_template_nontype_parm_prev_declaration)
8342 << OldNTTP->getType();
8343 }
8344 return false;
8345 }
8346 }
8347 }
8348 // For template template parameters, check the template parameter types.
8349 // The template parameter lists of template template
8350 // parameters must agree.
8351 else if (TemplateTemplateParmDecl *OldTTP =
8352 dyn_cast<TemplateTemplateParmDecl>(Val: Old)) {
8353 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(Val: New);
8354 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8355 return false;
8356 if (!S.TemplateParameterListsAreEqual(
8357 NewInstFrom, New: NewTTP->getTemplateParameters(), OldInstFrom,
8358 Old: OldTTP->getTemplateParameters(), Complain,
8359 Kind: (Kind == Sema::TPL_TemplateMatch
8360 ? Sema::TPL_TemplateTemplateParmMatch
8361 : Kind),
8362 TemplateArgLoc))
8363 return false;
8364 }
8365
8366 if (Kind != Sema::TPL_TemplateParamsEquivalent &&
8367 Kind != Sema::TPL_TemplateTemplateParmMatch &&
8368 !isa<TemplateTemplateParmDecl>(Val: Old)) {
8369 const Expr *NewC = nullptr, *OldC = nullptr;
8370
8371 if (isa<TemplateTypeParmDecl>(Val: New)) {
8372 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: New)->getTypeConstraint())
8373 NewC = TC->getImmediatelyDeclaredConstraint();
8374 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: Old)->getTypeConstraint())
8375 OldC = TC->getImmediatelyDeclaredConstraint();
8376 } else if (isa<NonTypeTemplateParmDecl>(Val: New)) {
8377 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: New)
8378 ->getPlaceholderTypeConstraint())
8379 NewC = E;
8380 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: Old)
8381 ->getPlaceholderTypeConstraint())
8382 OldC = E;
8383 } else
8384 llvm_unreachable("unexpected template parameter type");
8385
8386 auto Diagnose = [&] {
8387 S.Diag(Loc: NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8388 DiagID: diag::err_template_different_type_constraint);
8389 S.Diag(Loc: OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8390 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8391 };
8392
8393 if (!NewC != !OldC) {
8394 if (Complain)
8395 Diagnose();
8396 return false;
8397 }
8398
8399 if (NewC) {
8400 if (!S.AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldC, New: NewInstFrom,
8401 NewConstr: NewC)) {
8402 if (Complain)
8403 Diagnose();
8404 return false;
8405 }
8406 }
8407 }
8408
8409 return true;
8410}
8411
8412/// Diagnose a known arity mismatch when comparing template argument
8413/// lists.
8414static
8415void DiagnoseTemplateParameterListArityMismatch(Sema &S,
8416 TemplateParameterList *New,
8417 TemplateParameterList *Old,
8418 Sema::TemplateParameterListEqualKind Kind,
8419 SourceLocation TemplateArgLoc) {
8420 unsigned NextDiag = diag::err_template_param_list_different_arity;
8421 if (TemplateArgLoc.isValid()) {
8422 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8423 NextDiag = diag::note_template_param_list_different_arity;
8424 }
8425 S.Diag(Loc: New->getTemplateLoc(), DiagID: NextDiag)
8426 << (New->size() > Old->size())
8427 << (Kind != Sema::TPL_TemplateMatch)
8428 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8429 S.Diag(Loc: Old->getTemplateLoc(), DiagID: diag::note_template_prev_declaration)
8430 << (Kind != Sema::TPL_TemplateMatch)
8431 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8432}
8433
8434bool Sema::TemplateParameterListsAreEqual(
8435 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8436 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8437 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8438 if (Old->size() != New->size()) {
8439 if (Complain)
8440 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8441 TemplateArgLoc);
8442
8443 return false;
8444 }
8445
8446 // C++0x [temp.arg.template]p3:
8447 // A template-argument matches a template template-parameter (call it P)
8448 // when each of the template parameters in the template-parameter-list of
8449 // the template-argument's corresponding class template or alias template
8450 // (call it A) matches the corresponding template parameter in the
8451 // template-parameter-list of P. [...]
8452 TemplateParameterList::iterator NewParm = New->begin();
8453 TemplateParameterList::iterator NewParmEnd = New->end();
8454 for (TemplateParameterList::iterator OldParm = Old->begin(),
8455 OldParmEnd = Old->end();
8456 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8457 if (NewParm == NewParmEnd) {
8458 if (Complain)
8459 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8460 TemplateArgLoc);
8461 return false;
8462 }
8463 if (!MatchTemplateParameterKind(S&: *this, New: *NewParm, NewInstFrom, Old: *OldParm,
8464 OldInstFrom, Complain, Kind,
8465 TemplateArgLoc))
8466 return false;
8467 }
8468
8469 // Make sure we exhausted all of the arguments.
8470 if (NewParm != NewParmEnd) {
8471 if (Complain)
8472 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8473 TemplateArgLoc);
8474
8475 return false;
8476 }
8477
8478 if (Kind != TPL_TemplateParamsEquivalent) {
8479 const Expr *NewRC = New->getRequiresClause();
8480 const Expr *OldRC = Old->getRequiresClause();
8481
8482 auto Diagnose = [&] {
8483 Diag(Loc: NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8484 DiagID: diag::err_template_different_requires_clause);
8485 Diag(Loc: OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8486 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8487 };
8488
8489 if (!NewRC != !OldRC) {
8490 if (Complain)
8491 Diagnose();
8492 return false;
8493 }
8494
8495 if (NewRC) {
8496 if (!AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldRC, New: NewInstFrom,
8497 NewConstr: NewRC)) {
8498 if (Complain)
8499 Diagnose();
8500 return false;
8501 }
8502 }
8503 }
8504
8505 return true;
8506}
8507
8508bool
8509Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
8510 if (!S)
8511 return false;
8512
8513 // Find the nearest enclosing declaration scope.
8514 S = S->getDeclParent();
8515
8516 // C++ [temp.pre]p6: [P2096]
8517 // A template, explicit specialization, or partial specialization shall not
8518 // have C linkage.
8519 DeclContext *Ctx = S->getEntity();
8520 if (Ctx && Ctx->isExternCContext()) {
8521 SourceRange Range =
8522 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8523 ? TemplateParams->getParam(Idx: 0)->getSourceRange()
8524 : TemplateParams->getSourceRange();
8525 Diag(Loc: Range.getBegin(), DiagID: diag::err_template_linkage) << Range;
8526 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8527 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
8528 return true;
8529 }
8530 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8531
8532 // C++ [temp]p2:
8533 // A template-declaration can appear only as a namespace scope or
8534 // class scope declaration.
8535 // C++ [temp.expl.spec]p3:
8536 // An explicit specialization may be declared in any scope in which the
8537 // corresponding primary template may be defined.
8538 // C++ [temp.class.spec]p6: [P2096]
8539 // A partial specialization may be declared in any scope in which the
8540 // corresponding primary template may be defined.
8541 if (Ctx) {
8542 if (Ctx->isFileContext())
8543 return false;
8544 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Ctx)) {
8545 // C++ [temp.mem]p2:
8546 // A local class shall not have member templates.
8547
8548 // Trace the outer context chain, bypassing nested records and OpenMP
8549 // captured regions, to determine if the class in defined inside a
8550 // function or method.
8551 const DeclContext *OutCtx = RD->getDeclContext();
8552 while (isa_and_nonnull<CapturedDecl, CXXRecordDecl>(Val: OutCtx))
8553 OutCtx = OutCtx->getParent();
8554
8555 if (OutCtx && OutCtx->isFunctionOrMethod())
8556 return Diag(Loc: TemplateParams->getTemplateLoc(),
8557 DiagID: diag::err_template_inside_local_class)
8558 << TemplateParams->getSourceRange();
8559
8560 return false;
8561 }
8562 }
8563
8564 return Diag(Loc: TemplateParams->getTemplateLoc(),
8565 DiagID: diag::err_template_outside_namespace_or_class_scope)
8566 << TemplateParams->getSourceRange();
8567}
8568
8569/// Determine what kind of template specialization the given declaration
8570/// is.
8571static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8572 if (!D)
8573 return TSK_Undeclared;
8574
8575 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D))
8576 return Record->getTemplateSpecializationKind();
8577 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D))
8578 return Function->getTemplateSpecializationKind();
8579 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D))
8580 return Var->getTemplateSpecializationKind();
8581
8582 return TSK_Undeclared;
8583}
8584
8585/// Check whether a specialization is well-formed in the current
8586/// context.
8587///
8588/// This routine determines whether a template specialization can be declared
8589/// in the current context (C++ [temp.expl.spec]p2).
8590///
8591/// \param S the semantic analysis object for which this check is being
8592/// performed.
8593///
8594/// \param Specialized the entity being specialized or instantiated, which
8595/// may be a kind of template (class template, function template, etc.) or
8596/// a member of a class template (member function, static data member,
8597/// member class).
8598///
8599/// \param PrevDecl the previous declaration of this entity, if any.
8600///
8601/// \param Loc the location of the explicit specialization or instantiation of
8602/// this entity.
8603///
8604/// \param IsPartialSpecialization whether this is a partial specialization of
8605/// a class template.
8606///
8607/// \returns true if there was an error that we cannot recover from, false
8608/// otherwise.
8609static bool CheckTemplateSpecializationScope(Sema &S,
8610 NamedDecl *Specialized,
8611 NamedDecl *PrevDecl,
8612 SourceLocation Loc,
8613 bool IsPartialSpecialization) {
8614 // Keep these "kind" numbers in sync with the %select statements in the
8615 // various diagnostics emitted by this routine.
8616 int EntityKind = 0;
8617 if (isa<ClassTemplateDecl>(Val: Specialized))
8618 EntityKind = IsPartialSpecialization? 1 : 0;
8619 else if (isa<VarTemplateDecl>(Val: Specialized))
8620 EntityKind = IsPartialSpecialization ? 3 : 2;
8621 else if (isa<FunctionTemplateDecl>(Val: Specialized))
8622 EntityKind = 4;
8623 else if (isa<CXXMethodDecl>(Val: Specialized))
8624 EntityKind = 5;
8625 else if (isa<VarDecl>(Val: Specialized))
8626 EntityKind = 6;
8627 else if (isa<RecordDecl>(Val: Specialized))
8628 EntityKind = 7;
8629 else if (isa<EnumDecl>(Val: Specialized) && S.getLangOpts().CPlusPlus11)
8630 EntityKind = 8;
8631 else {
8632 S.Diag(Loc, DiagID: diag::err_template_spec_unknown_kind)
8633 << S.getLangOpts().CPlusPlus11;
8634 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8635 return true;
8636 }
8637
8638 // C++ [temp.expl.spec]p2:
8639 // An explicit specialization may be declared in any scope in which
8640 // the corresponding primary template may be defined.
8641 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8642 S.Diag(Loc, DiagID: diag::err_template_spec_decl_function_scope)
8643 << Specialized;
8644 return true;
8645 }
8646
8647 // C++ [temp.class.spec]p6:
8648 // A class template partial specialization may be declared in any
8649 // scope in which the primary template may be defined.
8650 DeclContext *SpecializedContext =
8651 Specialized->getDeclContext()->getRedeclContext();
8652 DeclContext *DC = S.CurContext->getRedeclContext();
8653
8654 // Make sure that this redeclaration (or definition) occurs in the same
8655 // scope or an enclosing namespace.
8656 if (!(DC->isFileContext() ? DC->Encloses(DC: SpecializedContext)
8657 : DC->Equals(DC: SpecializedContext))) {
8658 if (isa<TranslationUnitDecl>(Val: SpecializedContext))
8659 S.Diag(Loc, DiagID: diag::err_template_spec_redecl_global_scope)
8660 << EntityKind << Specialized;
8661 else {
8662 auto *ND = cast<NamedDecl>(Val: SpecializedContext);
8663 int Diag = diag::err_template_spec_redecl_out_of_scope;
8664 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8665 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8666 S.Diag(Loc, DiagID: Diag) << EntityKind << Specialized
8667 << ND << isa<CXXRecordDecl>(Val: ND);
8668 }
8669
8670 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8671
8672 // Don't allow specializing in the wrong class during error recovery.
8673 // Otherwise, things can go horribly wrong.
8674 if (DC->isRecord())
8675 return true;
8676 }
8677
8678 return false;
8679}
8680
8681static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8682 if (!E->isTypeDependent())
8683 return SourceLocation();
8684 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8685 Checker.TraverseStmt(S: E);
8686 if (Checker.MatchLoc.isInvalid())
8687 return E->getSourceRange();
8688 return Checker.MatchLoc;
8689}
8690
8691static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8692 if (!TL.getType()->isDependentType())
8693 return SourceLocation();
8694 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8695 Checker.TraverseTypeLoc(TL);
8696 if (Checker.MatchLoc.isInvalid())
8697 return TL.getSourceRange();
8698 return Checker.MatchLoc;
8699}
8700
8701/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8702/// that checks non-type template partial specialization arguments.
8703static bool CheckNonTypeTemplatePartialSpecializationArgs(
8704 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8705 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8706 bool HasError = false;
8707 for (unsigned I = 0; I != NumArgs; ++I) {
8708 if (Args[I].getKind() == TemplateArgument::Pack) {
8709 if (CheckNonTypeTemplatePartialSpecializationArgs(
8710 S, TemplateNameLoc, Param, Args: Args[I].pack_begin(),
8711 NumArgs: Args[I].pack_size(), IsDefaultArgument))
8712 return true;
8713
8714 continue;
8715 }
8716
8717 if (Args[I].getKind() != TemplateArgument::Expression)
8718 continue;
8719
8720 Expr *ArgExpr = Args[I].getAsExpr();
8721 if (ArgExpr->containsErrors()) {
8722 HasError = true;
8723 continue;
8724 }
8725
8726 // We can have a pack expansion of any of the bullets below.
8727 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Val: ArgExpr))
8728 ArgExpr = Expansion->getPattern();
8729
8730 // Strip off any implicit casts we added as part of type checking.
8731 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
8732 ArgExpr = ICE->getSubExpr();
8733
8734 // C++ [temp.class.spec]p8:
8735 // A non-type argument is non-specialized if it is the name of a
8736 // non-type parameter. All other non-type arguments are
8737 // specialized.
8738 //
8739 // Below, we check the two conditions that only apply to
8740 // specialized non-type arguments, so skip any non-specialized
8741 // arguments.
8742 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ArgExpr))
8743 if (isa<NonTypeTemplateParmDecl>(Val: DRE->getDecl()))
8744 continue;
8745
8746 if (isa<DependentTemplateIdExpr>(Val: ArgExpr))
8747 continue;
8748
8749 // C++ [temp.class.spec]p9:
8750 // Within the argument list of a class template partial
8751 // specialization, the following restrictions apply:
8752 // -- A partially specialized non-type argument expression
8753 // shall not involve a template parameter of the partial
8754 // specialization except when the argument expression is a
8755 // simple identifier.
8756 // -- The type of a template parameter corresponding to a
8757 // specialized non-type argument shall not be dependent on a
8758 // parameter of the specialization.
8759 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8760 // We implement a compromise between the original rules and DR1315:
8761 // -- A specialized non-type template argument shall not be
8762 // type-dependent and the corresponding template parameter
8763 // shall have a non-dependent type.
8764 SourceRange ParamUseRange =
8765 findTemplateParameterInType(Depth: Param->getDepth(), E: ArgExpr);
8766 if (ParamUseRange.isValid()) {
8767 if (IsDefaultArgument) {
8768 S.Diag(Loc: TemplateNameLoc,
8769 DiagID: diag::err_dependent_non_type_arg_in_partial_spec);
8770 S.Diag(Loc: ParamUseRange.getBegin(),
8771 DiagID: diag::note_dependent_non_type_default_arg_in_partial_spec)
8772 << ParamUseRange;
8773 } else {
8774 S.Diag(Loc: ParamUseRange.getBegin(),
8775 DiagID: diag::err_dependent_non_type_arg_in_partial_spec)
8776 << ParamUseRange;
8777 }
8778 return true;
8779 }
8780
8781 ParamUseRange = findTemplateParameter(
8782 Depth: Param->getDepth(), TL: Param->getTypeSourceInfo()->getTypeLoc());
8783 if (ParamUseRange.isValid()) {
8784 S.Diag(Loc: IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8785 DiagID: diag::err_dependent_typed_non_type_arg_in_partial_spec)
8786 << Param->getType();
8787 S.NoteTemplateParameterLocation(Decl: *Param);
8788 return true;
8789 }
8790 }
8791
8792 return HasError;
8793}
8794
8795bool Sema::CheckTemplatePartialSpecializationArgs(
8796 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8797 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8798 // We have to be conservative when checking a template in a dependent
8799 // context.
8800 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8801 return false;
8802
8803 TemplateParameterList *TemplateParams =
8804 PrimaryTemplate->getTemplateParameters();
8805 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8806 NonTypeTemplateParmDecl *Param
8807 = dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: I));
8808 if (!Param)
8809 continue;
8810
8811 if (CheckNonTypeTemplatePartialSpecializationArgs(S&: *this, TemplateNameLoc,
8812 Param, Args: &TemplateArgs[I],
8813 NumArgs: 1, IsDefaultArgument: I >= NumExplicit))
8814 return true;
8815 }
8816
8817 return false;
8818}
8819
8820DeclResult Sema::ActOnClassTemplateSpecialization(
8821 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8822 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8823 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8824 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8825 assert(TUK != TagUseKind::Reference && "References are not specializations");
8826
8827 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8828 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8829 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8830
8831 // Find the class template we're specializing
8832 TemplateName Name = TemplateId.Template.get();
8833 ClassTemplateDecl *ClassTemplate
8834 = dyn_cast_or_null<ClassTemplateDecl>(Val: Name.getAsTemplateDecl());
8835
8836 if (!ClassTemplate) {
8837 Diag(Loc: TemplateNameLoc, DiagID: diag::err_not_class_template_specialization)
8838 << (Name.getAsTemplateDecl() &&
8839 isa<TemplateTemplateParmDecl>(Val: Name.getAsTemplateDecl()));
8840 return true;
8841 }
8842
8843 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8844 auto Message = DSA->getMessage();
8845 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
8846 << ClassTemplate << !Message.empty() << Message;
8847 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
8848 }
8849
8850 if (S->isTemplateParamScope())
8851 EnterTemplatedContext(S, DC: ClassTemplate->getTemplatedDecl());
8852
8853 DeclContext *DC = ClassTemplate->getDeclContext();
8854
8855 bool isMemberSpecialization = false;
8856 bool isPartialSpecialization = false;
8857
8858 if (SS.isSet()) {
8859 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8860 diagnoseQualifiedDeclaration(SS, DC, Name: ClassTemplate->getDeclName(),
8861 Loc: TemplateNameLoc, TemplateId: &TemplateId,
8862 /*IsMemberSpecialization=*/false))
8863 return true;
8864 }
8865
8866 // Check the validity of the template headers that introduce this
8867 // template.
8868 // FIXME: We probably shouldn't complain about these headers for
8869 // friend declarations.
8870 bool Invalid = false;
8871 TemplateParameterList *TemplateParams =
8872 MatchTemplateParametersToScopeSpecifier(
8873 DeclStartLoc: KWLoc, DeclLoc: TemplateNameLoc, SS, TemplateId: &TemplateId, ParamLists: TemplateParameterLists,
8874 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
8875 if (Invalid)
8876 return true;
8877
8878 // Check that we can declare a template specialization here.
8879 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8880 return true;
8881
8882 if (TemplateParams && DC->isDependentContext()) {
8883 ContextRAII SavedContext(*this, DC);
8884 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
8885 return true;
8886 }
8887
8888 if (TemplateParams && TemplateParams->size() > 0) {
8889 isPartialSpecialization = true;
8890
8891 if (TUK == TagUseKind::Friend) {
8892 Diag(Loc: KWLoc, DiagID: diag::err_partial_specialization_friend)
8893 << SourceRange(LAngleLoc, RAngleLoc);
8894 return true;
8895 }
8896
8897 // C++ [temp.class.spec]p10:
8898 // The template parameter list of a specialization shall not
8899 // contain default template argument values.
8900 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8901 Decl *Param = TemplateParams->getParam(Idx: I);
8902 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
8903 if (TTP->hasDefaultArgument()) {
8904 Diag(Loc: TTP->getDefaultArgumentLoc(),
8905 DiagID: diag::err_default_arg_in_partial_spec);
8906 TTP->removeDefaultArgument();
8907 }
8908 } else if (NonTypeTemplateParmDecl *NTTP
8909 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
8910 if (NTTP->hasDefaultArgument()) {
8911 Diag(Loc: NTTP->getDefaultArgumentLoc(),
8912 DiagID: diag::err_default_arg_in_partial_spec)
8913 << NTTP->getDefaultArgument().getSourceRange();
8914 NTTP->removeDefaultArgument();
8915 }
8916 } else {
8917 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
8918 if (TTP->hasDefaultArgument()) {
8919 Diag(Loc: TTP->getDefaultArgument().getLocation(),
8920 DiagID: diag::err_default_arg_in_partial_spec)
8921 << TTP->getDefaultArgument().getSourceRange();
8922 TTP->removeDefaultArgument();
8923 }
8924 }
8925 }
8926 } else if (TemplateParams) {
8927 if (TUK == TagUseKind::Friend)
8928 Diag(Loc: KWLoc, DiagID: diag::err_template_spec_friend)
8929 << FixItHint::CreateRemoval(
8930 RemoveRange: SourceRange(TemplateParams->getTemplateLoc(),
8931 TemplateParams->getRAngleLoc()))
8932 << SourceRange(LAngleLoc, RAngleLoc);
8933 } else {
8934 assert(TUK == TagUseKind::Friend &&
8935 "should have a 'template<>' for this decl");
8936 }
8937
8938 // Check that the specialization uses the same tag kind as the
8939 // original template.
8940 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
8941 assert(Kind != TagTypeKind::Enum &&
8942 "Invalid enum tag in class template spec!");
8943 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(), NewTag: Kind,
8944 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
8945 Name: ClassTemplate->getIdentifier())) {
8946 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
8947 << ClassTemplate
8948 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
8949 Code: ClassTemplate->getTemplatedDecl()->getKindName());
8950 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
8951 DiagID: diag::note_previous_use);
8952 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8953 }
8954
8955 // Translate the parser's template argument list in our AST format.
8956 TemplateArgumentListInfo TemplateArgs =
8957 makeTemplateArgumentListInfo(S&: *this, TemplateId);
8958
8959 // Check for unexpanded parameter packs in any of the template arguments.
8960 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8961 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
8962 UPPC: isPartialSpecialization
8963 ? UPPC_PartialSpecialization
8964 : UPPC_ExplicitSpecialization))
8965 return true;
8966
8967 // Check that the template argument list is well-formed for this
8968 // template.
8969 CheckTemplateArgumentInfo CTAI;
8970 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
8971 /*DefaultArgs=*/{},
8972 /*PartialTemplateArgs=*/false, CTAI,
8973 /*UpdateArgsWithConversions=*/true))
8974 return true;
8975
8976 // Find the class template (partial) specialization declaration that
8977 // corresponds to these arguments.
8978 if (isPartialSpecialization) {
8979 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, PrimaryTemplate: ClassTemplate,
8980 NumExplicit: TemplateArgs.size(),
8981 TemplateArgs: CTAI.CanonicalConverted))
8982 return true;
8983
8984 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8985 // also do it during instantiation.
8986 if (!Name.isDependent() &&
8987 !TemplateSpecializationType::anyDependentTemplateArguments(
8988 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
8989 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
8990 << ClassTemplate->getDeclName();
8991 isPartialSpecialization = false;
8992 Invalid = true;
8993 }
8994 }
8995
8996 llvm::FoldingSetInsertToken InsertToken;
8997 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8998
8999 if (isPartialSpecialization)
9000 PrevDecl = ClassTemplate->findPartialSpecialization(
9001 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertToken);
9002 else
9003 PrevDecl =
9004 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertToken);
9005
9006 ClassTemplateSpecializationDecl *Specialization = nullptr;
9007
9008 // Check whether we can declare a class template specialization in
9009 // the current scope.
9010 if (TUK != TagUseKind::Friend &&
9011 CheckTemplateSpecializationScope(S&: *this, Specialized: ClassTemplate, PrevDecl,
9012 Loc: TemplateNameLoc,
9013 IsPartialSpecialization: isPartialSpecialization))
9014 return true;
9015
9016 if (!isPartialSpecialization) {
9017 // Create a new class template specialization declaration node for
9018 // this explicit specialization or friend declaration.
9019 Specialization = ClassTemplateSpecializationDecl::Create(
9020 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
9021 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
9022 Specialization->setTemplateArgsAsWritten(TemplateArgs);
9023 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
9024 if (TemplateParameterLists.size() > 0) {
9025 Specialization->setTemplateParameterListsInfo(Context,
9026 TPLists: TemplateParameterLists);
9027 }
9028
9029 if (!PrevDecl)
9030 ClassTemplate->AddSpecialization(D: Specialization, InsertToken);
9031 } else {
9032 CanQualType CanonType = CanQualType::CreateUnsafe(
9033 Other: Context.getCanonicalTemplateSpecializationType(
9034 Keyword: ElaboratedTypeKeyword::None,
9035 T: TemplateName(ClassTemplate->getCanonicalDecl()),
9036 CanonicalArgs: CTAI.CanonicalConverted));
9037 if (Context.hasSameType(
9038 T1: CanonType,
9039 T2: ClassTemplate->getCanonicalInjectedSpecializationType(Ctx: Context)) &&
9040 (!Context.getLangOpts().CPlusPlus20 ||
9041 !TemplateParams->hasAssociatedConstraints())) {
9042 // C++ [temp.class.spec]p9b3:
9043 //
9044 // -- The argument list of the specialization shall not be identical
9045 // to the implicit argument list of the primary template.
9046 //
9047 // This rule has since been removed, because it's redundant given DR1495,
9048 // but we keep it because it produces better diagnostics and recovery.
9049 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
9050 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
9051 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
9052 return CheckClassTemplate(
9053 S, TagSpec, TUK, KWLoc, SS, Name: ClassTemplate->getIdentifier(),
9054 NameLoc: TemplateNameLoc, Attr, TemplateParams, AS: AS_none,
9055 /*ModulePrivateLoc=*/SourceLocation(),
9056 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
9057 OuterTemplateParamLists: TemplateParameterLists.data(), IsMemberSpecialization: isMemberSpecialization);
9058 }
9059
9060 // Create a new class template partial specialization declaration node.
9061 ClassTemplatePartialSpecializationDecl *PrevPartial =
9062 cast_or_null<ClassTemplatePartialSpecializationDecl>(Val: PrevDecl);
9063 ClassTemplatePartialSpecializationDecl *Partial =
9064 ClassTemplatePartialSpecializationDecl::Create(
9065 Context, TK: Kind, DC, StartLoc: KWLoc, IdLoc: TemplateNameLoc, Params: TemplateParams,
9066 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, CanonInjectedTST: CanonType, PrevDecl: PrevPartial);
9067 Partial->setTemplateArgsAsWritten(TemplateArgs);
9068 SetNestedNameSpecifier(S&: *this, T: Partial, SS);
9069 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9070 Partial->setTemplateParameterListsInfo(
9071 Context, TPLists: TemplateParameterLists.drop_back(N: 1));
9072 }
9073
9074 if (!PrevPartial)
9075 ClassTemplate->AddPartialSpecialization(D: Partial, InsertToken);
9076 Specialization = Partial;
9077
9078 // If we are providing an explicit specialization of a member class
9079 // template specialization, make a note of that.
9080 if (isMemberSpecialization)
9081 Partial->setMemberSpecialization();
9082
9083 CheckTemplatePartialSpecialization(Partial);
9084 }
9085
9086 // C++ [temp.expl.spec]p6:
9087 // If a template, a member template or the member of a class template is
9088 // explicitly specialized then that specialization shall be declared
9089 // before the first use of that specialization that would cause an implicit
9090 // instantiation to take place, in every translation unit in which such a
9091 // use occurs; no diagnostic is required.
9092 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9093 bool Okay = false;
9094 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9095 // Is there any previous explicit specialization declaration?
9096 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9097 Okay = true;
9098 break;
9099 }
9100 }
9101
9102 if (!Okay) {
9103 SourceRange Range(TemplateNameLoc, RAngleLoc);
9104 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
9105 << Context.getCanonicalTagType(TD: Specialization) << Range;
9106
9107 Diag(Loc: PrevDecl->getPointOfInstantiation(),
9108 DiagID: diag::note_instantiation_required_here)
9109 << (PrevDecl->getTemplateSpecializationKind()
9110 != TSK_ImplicitInstantiation);
9111 return true;
9112 }
9113 }
9114
9115 // If this is not a friend, note that this is an explicit specialization.
9116 if (TUK != TagUseKind::Friend)
9117 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9118
9119 // Check that this isn't a redefinition of this specialization.
9120 if (TUK == TagUseKind::Definition) {
9121 RecordDecl *Def = Specialization->getDefinition();
9122 NamedDecl *Hidden = nullptr;
9123 bool HiddenDefVisible = false;
9124 if (Def && SkipBody &&
9125 isRedefinitionAllowedFor(D: Def, NewDefinitionLoc: TemplateNameLoc, Suggested: &Hidden,
9126 Visible&: HiddenDefVisible)) {
9127 SkipBody->ShouldSkip = true;
9128 SkipBody->Previous = Def;
9129 if (!HiddenDefVisible && Hidden)
9130 makeMergedDefinitionVisible(ND: Hidden);
9131 } else if (Def) {
9132 SourceRange Range(TemplateNameLoc, RAngleLoc);
9133 Diag(Loc: TemplateNameLoc, DiagID: diag::err_redefinition) << Specialization << Range;
9134 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
9135 Specialization->setInvalidDecl();
9136 return true;
9137 }
9138 }
9139
9140 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
9141 ProcessAPINotes(D: Specialization);
9142
9143 // Add alignment attributes if necessary; these attributes are checked when
9144 // the ASTContext lays out the structure.
9145 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9146 if (LangOpts.HLSL)
9147 Specialization->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
9148 AddAlignmentAttributesForRecord(RD: Specialization);
9149 AddMsStructLayoutForRecord(RD: Specialization);
9150 }
9151
9152 if (ModulePrivateLoc.isValid())
9153 Diag(Loc: Specialization->getLocation(), DiagID: diag::err_module_private_specialization)
9154 << (isPartialSpecialization? 1 : 0)
9155 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
9156
9157 // C++ [temp.expl.spec]p9:
9158 // A template explicit specialization is in the scope of the
9159 // namespace in which the template was defined.
9160 //
9161 // We actually implement this paragraph where we set the semantic
9162 // context (in the creation of the ClassTemplateSpecializationDecl),
9163 // but we also maintain the lexical context where the actual
9164 // definition occurs.
9165 Specialization->setLexicalDeclContext(CurContext);
9166
9167 // We may be starting the definition of this specialization.
9168 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9169 Specialization->startDefinition();
9170
9171 if (TUK == TagUseKind::Friend) {
9172 CanQualType CanonType = Context.getCanonicalTagType(TD: Specialization);
9173 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9174 Keyword: ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9175 QualifierLoc: SS.getWithLocInContext(Context),
9176 /*TemplateKeywordLoc=*/SourceLocation(), T: Name, TLoc: TemplateNameLoc,
9177 SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted, Canon: CanonType);
9178
9179 // Build the fully-sugared type for this class template
9180 // specialization as the user wrote in the specialization
9181 // itself. This means that we'll pretty-print the type retrieved
9182 // from the specialization's declaration the way that the user
9183 // actually wrote the specialization, rather than formatting the
9184 // name based on the "canonical" representation used to store the
9185 // template arguments in the specialization.
9186 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext,
9187 L: TemplateNameLoc,
9188 Friend: WrittenTy,
9189 /*FIXME:*/FriendL: KWLoc);
9190 Friend->setAccess(AS_public);
9191 CurContext->addDecl(D: Friend);
9192 } else {
9193 // Add the specialization into its lexical context, so that it can
9194 // be seen when iterating through the list of declarations in that
9195 // context. However, specializations are not found by name lookup.
9196 CurContext->addDecl(D: Specialization);
9197 }
9198
9199 if (SkipBody && SkipBody->ShouldSkip)
9200 return SkipBody->Previous;
9201
9202 Specialization->setInvalidDecl(Invalid);
9203 inferGslOwnerPointerAttribute(Record: Specialization);
9204 return Specialization;
9205}
9206
9207Decl *Sema::ActOnTemplateDeclarator(Scope *S,
9208 MultiTemplateParamsArg TemplateParameterLists,
9209 Declarator &D) {
9210 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9211 ActOnDocumentableDecl(D: NewDecl);
9212 return NewDecl;
9213}
9214
9215ConceptDecl *Sema::ActOnStartConceptDefinition(
9216 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9217 const IdentifierInfo *Name, SourceLocation NameLoc) {
9218 DeclContext *DC = CurContext;
9219
9220 if (!DC->getRedeclContext()->isFileContext()) {
9221 Diag(Loc: NameLoc,
9222 DiagID: diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9223 return nullptr;
9224 }
9225
9226 if (TemplateParameterLists.size() > 1) {
9227 Diag(Loc: NameLoc, DiagID: diag::err_concept_extra_headers);
9228 return nullptr;
9229 }
9230
9231 TemplateParameterList *Params = TemplateParameterLists.front();
9232
9233 if (Params->size() == 0) {
9234 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_parameters);
9235 return nullptr;
9236 }
9237
9238 // Ensure that the parameter pack, if present, is the last parameter in the
9239 // template.
9240 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9241 ParamEnd = Params->end();
9242 ParamIt != ParamEnd; ++ParamIt) {
9243 Decl const *Param = *ParamIt;
9244 if (Param->isParameterPack()) {
9245 if (++ParamIt == ParamEnd)
9246 break;
9247 Diag(Loc: Param->getLocation(),
9248 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
9249 return nullptr;
9250 }
9251 }
9252
9253 ConceptDecl *NewDecl =
9254 ConceptDecl::Create(C&: Context, DC, L: NameLoc, Name, Params);
9255
9256 if (NewDecl->hasAssociatedConstraints()) {
9257 // C++2a [temp.concept]p4:
9258 // A concept shall not have associated constraints.
9259 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_associated_constraints);
9260 NewDecl->setInvalidDecl();
9261 }
9262
9263 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9264 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9265 forRedeclarationInCurContext());
9266 LookupName(R&: Previous, S);
9267 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9268 /*AllowInlineNamespace*/ false);
9269
9270 // We cannot properly handle redeclarations until we parse the constraint
9271 // expression, so only inject the name if we are sure we are not redeclaring a
9272 // symbol
9273 if (Previous.empty())
9274 PushOnScopeChains(D: NewDecl, S, AddToContext: true);
9275
9276 return NewDecl;
9277}
9278
9279static bool RemoveLookupResult(LookupResult &R, NamedDecl *C) {
9280 bool Found = false;
9281 LookupResult::Filter F = R.makeFilter();
9282 while (F.hasNext()) {
9283 NamedDecl *D = F.next();
9284 if (D == C) {
9285 F.erase();
9286 Found = true;
9287 break;
9288 }
9289 }
9290 F.done();
9291 return Found;
9292}
9293
9294ConceptDecl *
9295Sema::ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
9296 Expr *ConstraintExpr,
9297 const ParsedAttributesView &Attrs) {
9298 assert(!C->hasDefinition() && "Concept already defined");
9299 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr)) {
9300 C->setInvalidDecl();
9301 return nullptr;
9302 }
9303 C->setDefinition(ConstraintExpr);
9304 ProcessDeclAttributeList(S, D: C, AttrList: Attrs);
9305
9306 // Check for conflicting previous declaration.
9307 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9308 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9309 forRedeclarationInCurContext());
9310 LookupName(R&: Previous, S);
9311 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9312 /*AllowInlineNamespace*/ false);
9313 bool WasAlreadyAdded = RemoveLookupResult(R&: Previous, C);
9314 bool AddToScope = true;
9315 CheckConceptRedefinition(NewDecl: C, Previous, AddToScope);
9316
9317 ActOnDocumentableDecl(D: C);
9318 if (!WasAlreadyAdded && AddToScope)
9319 PushOnScopeChains(D: C, S);
9320
9321 return C;
9322}
9323
9324void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
9325 LookupResult &Previous, bool &AddToScope) {
9326 AddToScope = true;
9327
9328 if (Previous.empty())
9329 return;
9330
9331 auto *OldConcept = dyn_cast<ConceptDecl>(Val: Previous.getRepresentativeDecl()->getUnderlyingDecl());
9332 if (!OldConcept) {
9333 auto *Old = Previous.getRepresentativeDecl();
9334 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_kind)
9335 << NewDecl->getDeclName();
9336 notePreviousDefinition(Old, New: NewDecl->getLocation());
9337 AddToScope = false;
9338 return;
9339 }
9340 // Check if we can merge with a concept declaration.
9341 bool IsSame = Context.isSameEntity(X: NewDecl, Y: OldConcept);
9342 if (!IsSame) {
9343 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_concept)
9344 << NewDecl->getDeclName();
9345 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9346 AddToScope = false;
9347 return;
9348 }
9349 if (hasReachableDefinition(D: OldConcept) &&
9350 IsRedefinitionInModule(New: NewDecl, Old: OldConcept)) {
9351 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition)
9352 << NewDecl->getDeclName();
9353 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9354 AddToScope = false;
9355 return;
9356 }
9357 if (!Previous.isSingleResult()) {
9358 // FIXME: we should produce an error in case of ambig and failed lookups.
9359 // Other decls (e.g. namespaces) also have this shortcoming.
9360 return;
9361 }
9362 // We unwrap canonical decl late to check for module visibility.
9363 Context.setPrimaryMergedDecl(D: NewDecl, Primary: OldConcept->getCanonicalDecl());
9364}
9365
9366bool Sema::CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc) {
9367 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Val: Concept);
9368 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9369 Diag(Loc, DiagID: diag::err_recursive_concept) << CE;
9370 Diag(Loc: CE->getLocation(), DiagID: diag::note_declared_at);
9371 CE->setInvalidDecl();
9372 return true;
9373 }
9374 // Concept template parameters don't have a definition and can't
9375 // be defined recursively.
9376 return false;
9377}
9378
9379/// \brief Strips various properties off an implicit instantiation
9380/// that has just been explicitly specialized.
9381static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9382 if (MinGW || (isa<FunctionDecl>(Val: D) &&
9383 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization()))
9384 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9385
9386 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D))
9387 FD->setInlineSpecified(false);
9388}
9389
9390/// Create an ExplicitInstantiationDecl to record source-location info for an
9391/// explicit template instantiation statement, and add it to \p CurContext.
9392///
9393/// For class templates / nested classes, the caller should build a
9394/// TypeSourceInfo that encodes the tag keyword, qualifier, name, and template
9395/// arguments, and pass empty QualifierLoc / null ArgsAsWritten.
9396///
9397/// For function / variable templates, the caller should pass TypeAsWritten for
9398/// the declared type, and separate QualifierLoc / ArgsAsWritten.
9399static void addExplicitInstantiationDecl(
9400 ASTContext &Context, DeclContext *CurContext, NamedDecl *Spec,
9401 SourceLocation ExternLoc, SourceLocation TemplateLoc,
9402 NestedNameSpecifierLoc QualifierLoc,
9403 const ASTTemplateArgumentListInfo *ArgsAsWritten, SourceLocation NameLoc,
9404 TypeSourceInfo *TypeAsWritten, TemplateSpecializationKind TSK) {
9405 auto *EID = ExplicitInstantiationDecl::Create(
9406 C&: Context, DC: CurContext, Specialization: Spec, ExternLoc, TemplateLoc, QualifierLoc,
9407 ArgsAsWritten, NameLoc, TypeAsWritten, TSK);
9408 Context.addExplicitInstantiationDecl(Spec, EID);
9409 CurContext->addDecl(D: EID);
9410}
9411
9412/// Compute the diagnostic location for an explicit instantiation
9413// declaration or definition.
9414static SourceLocation
9415DiagLocForExplicitInstantiation(NamedDecl *D,
9416 SourceLocation PointOfInstantiation) {
9417 for (auto *EID : D->getASTContext().getExplicitInstantiationDecls(Spec: D))
9418 if (EID->getTemplateSpecializationKind() ==
9419 TSK_ExplicitInstantiationDefinition)
9420 return EID->getTemplateLoc();
9421
9422 // Explicit instantiations following a specialization have no effect and
9423 // hence no PointOfInstantiation. In that case, walk decl backwards
9424 // until a valid name loc is found.
9425 SourceLocation PrevDiagLoc = PointOfInstantiation;
9426 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9427 Prev = Prev->getPreviousDecl()) {
9428 PrevDiagLoc = Prev->getLocation();
9429 }
9430 assert(PrevDiagLoc.isValid() &&
9431 "Explicit instantiation without point of instantiation?");
9432 return PrevDiagLoc;
9433}
9434
9435bool
9436Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
9437 TemplateSpecializationKind NewTSK,
9438 NamedDecl *PrevDecl,
9439 TemplateSpecializationKind PrevTSK,
9440 SourceLocation PrevPointOfInstantiation,
9441 bool &HasNoEffect) {
9442 HasNoEffect = false;
9443
9444 switch (NewTSK) {
9445 case TSK_Undeclared:
9446 case TSK_ImplicitInstantiation:
9447 assert(
9448 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9449 "previous declaration must be implicit!");
9450 return false;
9451
9452 case TSK_ExplicitSpecialization:
9453 switch (PrevTSK) {
9454 case TSK_Undeclared:
9455 case TSK_ExplicitSpecialization:
9456 // Okay, we're just specializing something that is either already
9457 // explicitly specialized or has merely been mentioned without any
9458 // instantiation.
9459 return false;
9460
9461 case TSK_ImplicitInstantiation:
9462 if (PrevPointOfInstantiation.isInvalid()) {
9463 // The declaration itself has not actually been instantiated, so it is
9464 // still okay to specialize it.
9465 StripImplicitInstantiation(
9466 D: PrevDecl, MinGW: Context.getTargetInfo().getTriple().isOSCygMing());
9467 return false;
9468 }
9469 // Fall through
9470 [[fallthrough]];
9471
9472 case TSK_ExplicitInstantiationDeclaration:
9473 case TSK_ExplicitInstantiationDefinition:
9474 assert((PrevTSK == TSK_ImplicitInstantiation ||
9475 PrevPointOfInstantiation.isValid()) &&
9476 "Explicit instantiation without point of instantiation?");
9477
9478 // C++ [temp.expl.spec]p6:
9479 // If a template, a member template or the member of a class template
9480 // is explicitly specialized then that specialization shall be declared
9481 // before the first use of that specialization that would cause an
9482 // implicit instantiation to take place, in every translation unit in
9483 // which such a use occurs; no diagnostic is required.
9484 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9485 // Is there any previous explicit specialization declaration?
9486 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization)
9487 return false;
9488 }
9489
9490 Diag(Loc: NewLoc, DiagID: diag::err_specialization_after_instantiation)
9491 << PrevDecl;
9492 Diag(Loc: PrevPointOfInstantiation, DiagID: diag::note_instantiation_required_here)
9493 << (PrevTSK != TSK_ImplicitInstantiation);
9494
9495 return true;
9496 }
9497 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9498
9499 case TSK_ExplicitInstantiationDeclaration:
9500 switch (PrevTSK) {
9501 case TSK_ExplicitInstantiationDeclaration:
9502 // This explicit instantiation declaration is redundant (that's okay).
9503 HasNoEffect = true;
9504 return false;
9505
9506 case TSK_Undeclared:
9507 case TSK_ImplicitInstantiation:
9508 // We're explicitly instantiating something that may have already been
9509 // implicitly instantiated; that's fine.
9510 return false;
9511
9512 case TSK_ExplicitSpecialization:
9513 // C++0x [temp.explicit]p4:
9514 // For a given set of template parameters, if an explicit instantiation
9515 // of a template appears after a declaration of an explicit
9516 // specialization for that template, the explicit instantiation has no
9517 // effect.
9518 HasNoEffect = true;
9519 return false;
9520
9521 case TSK_ExplicitInstantiationDefinition:
9522 // C++0x [temp.explicit]p10:
9523 // If an entity is the subject of both an explicit instantiation
9524 // declaration and an explicit instantiation definition in the same
9525 // translation unit, the definition shall follow the declaration.
9526 Diag(Loc: NewLoc,
9527 DiagID: diag::err_explicit_instantiation_declaration_after_definition);
9528
9529 // Explicit instantiations following a specialization have no effect and
9530 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9531 // until a valid name loc is found.
9532 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9533 DiagID: diag::note_explicit_instantiation_definition_here);
9534 HasNoEffect = true;
9535 return false;
9536 }
9537 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9538
9539 case TSK_ExplicitInstantiationDefinition:
9540 switch (PrevTSK) {
9541 case TSK_Undeclared:
9542 case TSK_ImplicitInstantiation:
9543 // We're explicitly instantiating something that may have already been
9544 // implicitly instantiated; that's fine.
9545 return false;
9546
9547 case TSK_ExplicitSpecialization:
9548 // C++ DR 259, C++0x [temp.explicit]p4:
9549 // For a given set of template parameters, if an explicit
9550 // instantiation of a template appears after a declaration of
9551 // an explicit specialization for that template, the explicit
9552 // instantiation has no effect.
9553 Diag(Loc: NewLoc, DiagID: diag::warn_explicit_instantiation_after_specialization)
9554 << PrevDecl;
9555 Diag(Loc: PrevDecl->getLocation(),
9556 DiagID: diag::note_previous_template_specialization);
9557 HasNoEffect = true;
9558 return false;
9559
9560 case TSK_ExplicitInstantiationDeclaration:
9561 // We're explicitly instantiating a definition for something for which we
9562 // were previously asked to suppress instantiations. That's fine.
9563
9564 // C++0x [temp.explicit]p4:
9565 // For a given set of template parameters, if an explicit instantiation
9566 // of a template appears after a declaration of an explicit
9567 // specialization for that template, the explicit instantiation has no
9568 // effect.
9569 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9570 // Is there any previous explicit specialization declaration?
9571 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9572 HasNoEffect = true;
9573 break;
9574 }
9575 }
9576
9577 return false;
9578
9579 case TSK_ExplicitInstantiationDefinition:
9580 // C++0x [temp.spec]p5:
9581 // For a given template and a given set of template-arguments,
9582 // - an explicit instantiation definition shall appear at most once
9583 // in a program,
9584
9585 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9586 Diag(Loc: NewLoc, DiagID: (getLangOpts().MSVCCompat)
9587 ? diag::ext_explicit_instantiation_duplicate
9588 : diag::err_explicit_instantiation_duplicate)
9589 << PrevDecl;
9590 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9591 DiagID: diag::note_previous_explicit_instantiation);
9592 HasNoEffect = true;
9593 return false;
9594 }
9595 }
9596
9597 llvm_unreachable("Missing specialization/instantiation case?");
9598}
9599
9600bool Sema::CheckDependentFunctionTemplateSpecialization(
9601 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9602 LookupResult &Previous) {
9603 // Remove anything from Previous that isn't a function template in
9604 // the correct context.
9605 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9606 LookupResult::Filter F = Previous.makeFilter();
9607 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9608 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9609 while (F.hasNext()) {
9610 NamedDecl *D = F.next()->getUnderlyingDecl();
9611 if (!isa<FunctionTemplateDecl>(Val: D)) {
9612 F.erase();
9613 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAFunctionTemplate, y&: D));
9614 continue;
9615 }
9616
9617 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9618 NS: D->getDeclContext()->getRedeclContext())) {
9619 F.erase();
9620 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAMemberOfEnclosing, y&: D));
9621 continue;
9622 }
9623 }
9624 F.done();
9625
9626 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9627 if (Previous.empty()) {
9628 NestedNameSpecifier FriendQualifier = FD->getQualifier();
9629 if (IsFriend && FriendQualifier.isDependent() &&
9630 FriendQualifier.getKind() == NestedNameSpecifier::Kind::Type &&
9631 FriendQualifier.getAsType()->getAs<TemplateSpecializationType>()) {
9632 FD->setDependentTemplateSpecialization(
9633 Context, Templates: Previous.asUnresolvedSet(), TemplateArgs: ExplicitTemplateArgs);
9634 return false;
9635 }
9636
9637 Diag(Loc: FD->getLocation(), DiagID: diag::err_dependent_function_template_spec_no_match)
9638 << IsFriend;
9639 for (auto &P : DiscardedCandidates)
9640 Diag(Loc: P.second->getLocation(),
9641 DiagID: diag::note_dependent_function_template_spec_discard_reason)
9642 << P.first << IsFriend;
9643 return true;
9644 }
9645
9646 FD->setDependentTemplateSpecialization(Context, Templates: Previous.asUnresolvedSet(),
9647 TemplateArgs: ExplicitTemplateArgs);
9648 return false;
9649}
9650
9651bool Sema::CheckFunctionTemplateSpecialization(
9652 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9653 LookupResult &Previous, bool QualifiedFriend) {
9654 // The set of function template specializations that could match this
9655 // explicit function template specialization.
9656 UnresolvedSet<8> Candidates;
9657 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9658 /*ForTakingAddress=*/false);
9659
9660 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9661 ConvertedTemplateArgs;
9662
9663 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9664 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9665 I != E; ++I) {
9666 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9667 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Ovl)) {
9668 // Only consider templates found within the same semantic lookup scope as
9669 // FD.
9670 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9671 NS: Ovl->getDeclContext()->getRedeclContext()))
9672 continue;
9673
9674 QualType FT = FD->getType();
9675 // C++11 [dcl.constexpr]p8:
9676 // A constexpr specifier for a non-static member function that is not
9677 // a constructor declares that member function to be const.
9678 //
9679 // When matching a constexpr member function template specialization
9680 // against the primary template, we don't yet know whether the
9681 // specialization has an implicit 'const' (because we don't know whether
9682 // it will be a static member function until we know which template it
9683 // specializes). This rule was removed in C++14.
9684 if (auto *NewMD = dyn_cast<CXXMethodDecl>(Val: FD);
9685 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9686 !isa<CXXConstructorDecl, CXXDestructorDecl>(Val: NewMD)) {
9687 auto *OldMD = dyn_cast<CXXMethodDecl>(Val: FunTmpl->getTemplatedDecl());
9688 if (OldMD && OldMD->isConst()) {
9689 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9690 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9691 EPI.TypeQuals.addConst();
9692 FT = Context.getFunctionType(ResultTy: FPT->getReturnType(),
9693 Args: FPT->getParamTypes(), EPI);
9694 }
9695 }
9696
9697 TemplateArgumentListInfo Args;
9698 if (ExplicitTemplateArgs)
9699 Args = *ExplicitTemplateArgs;
9700
9701 // C++ [temp.expl.spec]p11:
9702 // A trailing template-argument can be left unspecified in the
9703 // template-id naming an explicit function template specialization
9704 // provided it can be deduced from the function argument type.
9705 // Perform template argument deduction to determine whether we may be
9706 // specializing this template.
9707 // FIXME: It is somewhat wasteful to build
9708 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9709 FunctionDecl *Specialization = nullptr;
9710 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9711 FunctionTemplate: cast<FunctionTemplateDecl>(Val: FunTmpl->getFirstDecl()),
9712 ExplicitTemplateArgs: ExplicitTemplateArgs ? &Args : nullptr, ArgFunctionType: FT, Specialization, Info);
9713 TDK != TemplateDeductionResult::Success) {
9714 // Template argument deduction failed; record why it failed, so
9715 // that we can provide nifty diagnostics.
9716 FailedCandidates.addCandidate().set(
9717 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9718 Info: MakeDeductionFailureInfo(Context, TDK, Info));
9719 (void)TDK;
9720 continue;
9721 }
9722
9723 // Target attributes are part of the cuda function signature, so
9724 // the deduced template's cuda target must match that of the
9725 // specialization. Given that C++ template deduction does not
9726 // take target attributes into account, we reject candidates
9727 // here that have a different target.
9728 if (LangOpts.CUDA &&
9729 CUDA().IdentifyTarget(D: Specialization,
9730 /* IgnoreImplicitHDAttr = */ true) !=
9731 CUDA().IdentifyTarget(D: FD, /* IgnoreImplicitHDAttr = */ true)) {
9732 FailedCandidates.addCandidate().set(
9733 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9734 Info: MakeDeductionFailureInfo(
9735 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
9736 continue;
9737 }
9738
9739 // Record this candidate.
9740 if (ExplicitTemplateArgs)
9741 ConvertedTemplateArgs[Specialization] = std::move(Args);
9742 Candidates.addDecl(D: Specialization, AS: I.getAccess());
9743 }
9744 }
9745
9746 // For a qualified friend declaration (with no explicit marker to indicate
9747 // that a template specialization was intended), note all (template and
9748 // non-template) candidates.
9749 if (QualifiedFriend && Candidates.empty()) {
9750 Diag(Loc: FD->getLocation(), DiagID: diag::err_qualified_friend_no_match)
9751 << FD->getDeclName() << FDLookupContext;
9752 // FIXME: We should form a single candidate list and diagnose all
9753 // candidates at once, to get proper sorting and limiting.
9754 for (auto *OldND : Previous) {
9755 if (auto *OldFD = dyn_cast<FunctionDecl>(Val: OldND->getUnderlyingDecl()))
9756 NoteOverloadCandidate(Found: OldND, Fn: OldFD, RewriteKind: CRK_None, DestType: FD->getType(), TakingAddress: false);
9757 }
9758 FailedCandidates.NoteCandidates(S&: *this, Loc: FD->getLocation());
9759 return true;
9760 }
9761
9762 // Find the most specialized function template.
9763 UnresolvedSetIterator Result = getMostSpecialized(
9764 SBegin: Candidates.begin(), SEnd: Candidates.end(), FailedCandidates, Loc: FD->getLocation(),
9765 NoneDiag: PDiag(DiagID: diag::err_function_template_spec_no_match) << FD->getDeclName(),
9766 AmbigDiag: PDiag(DiagID: diag::err_function_template_spec_ambiguous)
9767 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9768 CandidateDiag: PDiag(DiagID: diag::note_function_template_spec_matched));
9769
9770 if (Result == Candidates.end())
9771 return true;
9772
9773 // Ignore access information; it doesn't figure into redeclaration checking.
9774 FunctionDecl *Specialization = cast<FunctionDecl>(Val: *Result);
9775
9776 if (const auto *PT = Specialization->getPrimaryTemplate();
9777 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9778 auto Message = DSA->getMessage();
9779 Diag(Loc: FD->getLocation(), DiagID: diag::warn_invalid_specialization)
9780 << PT << !Message.empty() << Message;
9781 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
9782 }
9783
9784 // C++23 [except.spec]p13:
9785 // An exception specification is considered to be needed when:
9786 // - [...]
9787 // - the exception specification is compared to that of another declaration
9788 // (e.g., an explicit specialization or an overriding virtual function);
9789 // - [...]
9790 //
9791 // The exception specification of a defaulted function is evaluated as
9792 // described above only when needed; similarly, the noexcept-specifier of a
9793 // specialization of a function template or member function of a class
9794 // template is instantiated only when needed.
9795 //
9796 // The standard doesn't specify what the "comparison with another declaration"
9797 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9798 // not state which properties of an explicit specialization must match the
9799 // primary template.
9800 //
9801 // We assume that an explicit specialization must correspond with (per
9802 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9803 // the declaration produced by substitution into the function template.
9804 //
9805 // Since the determination whether two function declarations correspond does
9806 // not consider exception specification, we only need to instantiate it once
9807 // we determine the primary template when comparing types per
9808 // [basic.link]p11.1.
9809 auto *SpecializationFPT =
9810 Specialization->getType()->castAs<FunctionProtoType>();
9811 // If the function has a dependent exception specification, resolve it after
9812 // we have selected the primary template so we can check whether it matches.
9813 if (getLangOpts().CPlusPlus17 &&
9814 isUnresolvedExceptionSpec(ESpecType: SpecializationFPT->getExceptionSpecType()) &&
9815 !ResolveExceptionSpec(Loc: FD->getLocation(), FPT: SpecializationFPT))
9816 return true;
9817
9818 FunctionTemplateSpecializationInfo *SpecInfo
9819 = Specialization->getTemplateSpecializationInfo();
9820 assert(SpecInfo && "Function template specialization info missing?");
9821
9822 // Note: do not overwrite location info if previous template
9823 // specialization kind was explicit.
9824 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9825 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9826 Specialization->setLocation(FD->getLocation());
9827 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9828 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9829 // function can differ from the template declaration with respect to
9830 // the constexpr specifier.
9831 // FIXME: We need an update record for this AST mutation.
9832 // FIXME: What if there are multiple such prior declarations (for instance,
9833 // from different modules)?
9834 Specialization->setConstexprKind(FD->getConstexprKind());
9835 }
9836
9837 // FIXME: Check if the prior specialization has a point of instantiation.
9838 // If so, we have run afoul of .
9839
9840 // If this is a friend declaration, then we're not really declaring
9841 // an explicit specialization.
9842 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9843
9844 // Check the scope of this explicit specialization.
9845 if (!isFriend &&
9846 CheckTemplateSpecializationScope(S&: *this,
9847 Specialized: Specialization->getPrimaryTemplate(),
9848 PrevDecl: Specialization, Loc: FD->getLocation(),
9849 IsPartialSpecialization: false))
9850 return true;
9851
9852 // C++ [temp.expl.spec]p6:
9853 // If a template, a member template or the member of a class template is
9854 // explicitly specialized then that specialization shall be declared
9855 // before the first use of that specialization that would cause an implicit
9856 // instantiation to take place, in every translation unit in which such a
9857 // use occurs; no diagnostic is required.
9858 bool HasNoEffect = false;
9859 if (!isFriend &&
9860 CheckSpecializationInstantiationRedecl(NewLoc: FD->getLocation(),
9861 NewTSK: TSK_ExplicitSpecialization,
9862 PrevDecl: Specialization,
9863 PrevTSK: SpecInfo->getTemplateSpecializationKind(),
9864 PrevPointOfInstantiation: SpecInfo->getPointOfInstantiation(),
9865 HasNoEffect))
9866 return true;
9867
9868 // Mark the prior declaration as an explicit specialization, so that later
9869 // clients know that this is an explicit specialization.
9870 // A dependent friend specialization which has a definition should be treated
9871 // as explicit specialization, despite being invalid.
9872 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9873 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9874 // Since explicit specializations do not inherit '=delete' from their
9875 // primary function template - check if the 'specialization' that was
9876 // implicitly generated (during template argument deduction for partial
9877 // ordering) from the most specialized of all the function templates that
9878 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9879 // first check that it was implicitly generated during template argument
9880 // deduction by making sure it wasn't referenced, and then reset the deleted
9881 // flag to not-deleted, so that we can inherit that information from 'FD'.
9882 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9883 !Specialization->getCanonicalDecl()->isReferenced()) {
9884 // FIXME: This assert will not hold in the presence of modules.
9885 assert(
9886 Specialization->getCanonicalDecl() == Specialization &&
9887 "This must be the only existing declaration of this specialization");
9888 // FIXME: We need an update record for this AST mutation.
9889 Specialization->setDeletedAsWritten(D: false);
9890 }
9891 // FIXME: We need an update record for this AST mutation.
9892 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9893 MarkUnusedFileScopedDecl(D: Specialization);
9894 }
9895
9896 // Turn the given function declaration into a function template
9897 // specialization, with the template arguments from the previous
9898 // specialization.
9899 // Take copies of (semantic and syntactic) template argument lists.
9900 TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy(
9901 Context, Args: Specialization->getTemplateSpecializationArgs()->asArray());
9902 FD->setFunctionTemplateSpecialization(
9903 Template: Specialization->getPrimaryTemplate(), TemplateArgs: TemplArgs, /*InsertToken=*/{},
9904 TSK: SpecInfo->getTemplateSpecializationKind(),
9905 TemplateArgsAsWritten: ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9906
9907 // A function template specialization inherits the target attributes
9908 // of its template. (We require the attributes explicitly in the
9909 // code to match, but a template may have implicit attributes by
9910 // virtue e.g. of being constexpr, and it passes these implicit
9911 // attributes on to its specializations.)
9912 if (LangOpts.CUDA)
9913 CUDA().inheritTargetAttrs(FD, TD: *Specialization->getPrimaryTemplate());
9914
9915 // The "previous declaration" for this function template specialization is
9916 // the prior function template specialization.
9917 Previous.clear();
9918 Previous.addDecl(D: Specialization);
9919 return false;
9920}
9921
9922bool
9923Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9924 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9925 "Only for non-template members");
9926
9927 // Try to find the member we are instantiating.
9928 NamedDecl *FoundInstantiation = nullptr;
9929 NamedDecl *Instantiation = nullptr;
9930 NamedDecl *InstantiatedFrom = nullptr;
9931 MemberSpecializationInfo *MSInfo = nullptr;
9932
9933 if (Previous.empty()) {
9934 // Nowhere to look anyway.
9935 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Member)) {
9936 UnresolvedSet<8> Candidates;
9937 for (NamedDecl *Candidate : Previous) {
9938 auto *Method = dyn_cast<CXXMethodDecl>(Val: Candidate->getUnderlyingDecl());
9939 // Ignore any candidates that aren't member functions.
9940 if (!Method)
9941 continue;
9942
9943 QualType Adjusted = Function->getType();
9944 if (!hasExplicitCallingConv(T: Adjusted))
9945 Adjusted = adjustCCAndNoReturn(ArgFunctionType: Adjusted, FunctionType: Method->getType());
9946 // Ignore any candidates with the wrong type.
9947 // This doesn't handle deduced return types, but both function
9948 // declarations should be undeduced at this point.
9949 // FIXME: The exception specification should probably be ignored when
9950 // comparing the types.
9951 if (!Context.hasSameType(T1: Adjusted, T2: Method->getType()))
9952 continue;
9953
9954 // Ignore any candidates with unsatisfied constraints.
9955 if (ConstraintSatisfaction Satisfaction;
9956 Method->getTrailingRequiresClause() &&
9957 (CheckFunctionConstraints(FD: Method, Satisfaction,
9958 /*UsageLoc=*/Member->getLocation(),
9959 /*ForOverloadResolution=*/true) ||
9960 !Satisfaction.IsSatisfied))
9961 continue;
9962
9963 Candidates.addDecl(D: Candidate);
9964 }
9965
9966 // If we have no viable candidates left after filtering, we are done.
9967 if (Candidates.empty())
9968 return false;
9969
9970 // Find the function that is more constrained than every other function it
9971 // has been compared to.
9972 UnresolvedSetIterator Best = Candidates.begin();
9973 CXXMethodDecl *BestMethod = nullptr;
9974 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9975 I != E; ++I) {
9976 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9977 if (I == Best ||
9978 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) == Method) {
9979 Best = I;
9980 BestMethod = Method;
9981 }
9982 }
9983
9984 FoundInstantiation = *Best;
9985 Instantiation = BestMethod;
9986 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9987 MSInfo = BestMethod->getMemberSpecializationInfo();
9988
9989 // Make sure the best candidate is more constrained than all of the others.
9990 bool Ambiguous = false;
9991 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9992 I != E; ++I) {
9993 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9994 if (I != Best &&
9995 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) != BestMethod) {
9996 Ambiguous = true;
9997 break;
9998 }
9999 }
10000
10001 if (Ambiguous) {
10002 Diag(Loc: Member->getLocation(), DiagID: diag::err_function_member_spec_ambiguous)
10003 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
10004 for (NamedDecl *Candidate : Candidates) {
10005 Candidate = Candidate->getUnderlyingDecl();
10006 Diag(Loc: Candidate->getLocation(), DiagID: diag::note_function_member_spec_matched)
10007 << Candidate;
10008 }
10009 return true;
10010 }
10011 } else if (isa<VarDecl>(Val: Member)) {
10012 VarDecl *PrevVar;
10013 if (Previous.isSingleResult() &&
10014 (PrevVar = dyn_cast<VarDecl>(Val: Previous.getFoundDecl())))
10015 if (PrevVar->isStaticDataMember()) {
10016 FoundInstantiation = Previous.getRepresentativeDecl();
10017 Instantiation = PrevVar;
10018 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
10019 MSInfo = PrevVar->getMemberSpecializationInfo();
10020 }
10021 } else if (isa<RecordDecl>(Val: Member)) {
10022 CXXRecordDecl *PrevRecord;
10023 if (Previous.isSingleResult() &&
10024 (PrevRecord = dyn_cast<CXXRecordDecl>(Val: Previous.getFoundDecl()))) {
10025 FoundInstantiation = Previous.getRepresentativeDecl();
10026 Instantiation = PrevRecord;
10027 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
10028 MSInfo = PrevRecord->getMemberSpecializationInfo();
10029 }
10030 } else if (isa<EnumDecl>(Val: Member)) {
10031 EnumDecl *PrevEnum;
10032 if (Previous.isSingleResult() &&
10033 (PrevEnum = dyn_cast<EnumDecl>(Val: Previous.getFoundDecl()))) {
10034 FoundInstantiation = Previous.getRepresentativeDecl();
10035 Instantiation = PrevEnum;
10036 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
10037 MSInfo = PrevEnum->getMemberSpecializationInfo();
10038 }
10039 }
10040
10041 if (!Instantiation) {
10042 // There is no previous declaration that matches. Since member
10043 // specializations are always out-of-line, the caller will complain about
10044 // this mismatch later.
10045 return false;
10046 }
10047
10048 // A member specialization in a friend declaration isn't really declaring
10049 // an explicit specialization, just identifying a specific (possibly implicit)
10050 // specialization. Don't change the template specialization kind.
10051 //
10052 // FIXME: Is this really valid? Other compilers reject.
10053 if (Member->getFriendObjectKind() != Decl::FOK_None) {
10054 // Preserve instantiation information.
10055 if (InstantiatedFrom && isa<CXXMethodDecl>(Val: Member)) {
10056 cast<CXXMethodDecl>(Val: Member)->setInstantiationOfMemberFunction(
10057 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom),
10058 TSK: cast<CXXMethodDecl>(Val: Instantiation)->getTemplateSpecializationKind());
10059 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Val: Member)) {
10060 cast<CXXRecordDecl>(Val: Member)->setInstantiationOfMemberClass(
10061 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom),
10062 TSK: cast<CXXRecordDecl>(Val: Instantiation)->getTemplateSpecializationKind());
10063 }
10064
10065 Previous.clear();
10066 Previous.addDecl(D: FoundInstantiation);
10067 return false;
10068 }
10069
10070 // Make sure that this is a specialization of a member.
10071 if (!InstantiatedFrom) {
10072 Diag(Loc: Member->getLocation(), DiagID: diag::err_spec_member_not_instantiated)
10073 << Member;
10074 Diag(Loc: Instantiation->getLocation(), DiagID: diag::note_specialized_decl);
10075 return true;
10076 }
10077
10078 // C++ [temp.expl.spec]p6:
10079 // If a template, a member template or the member of a class template is
10080 // explicitly specialized then that specialization shall be declared
10081 // before the first use of that specialization that would cause an implicit
10082 // instantiation to take place, in every translation unit in which such a
10083 // use occurs; no diagnostic is required.
10084 assert(MSInfo && "Member specialization info missing?");
10085
10086 bool HasNoEffect = false;
10087 if (CheckSpecializationInstantiationRedecl(NewLoc: Member->getLocation(),
10088 NewTSK: TSK_ExplicitSpecialization,
10089 PrevDecl: Instantiation,
10090 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10091 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10092 HasNoEffect))
10093 return true;
10094
10095 // Check the scope of this explicit specialization.
10096 if (CheckTemplateSpecializationScope(S&: *this,
10097 Specialized: InstantiatedFrom,
10098 PrevDecl: Instantiation, Loc: Member->getLocation(),
10099 IsPartialSpecialization: false))
10100 return true;
10101
10102 // Note that this member specialization is an "instantiation of" the
10103 // corresponding member of the original template.
10104 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Val: Member)) {
10105 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Val: Instantiation);
10106 if (InstantiationFunction->getTemplateSpecializationKind() ==
10107 TSK_ImplicitInstantiation) {
10108 // Explicit specializations of member functions of class templates do not
10109 // inherit '=delete' from the member function they are specializing.
10110 if (InstantiationFunction->isDeleted()) {
10111 // FIXME: This assert will not hold in the presence of modules.
10112 assert(InstantiationFunction->getCanonicalDecl() ==
10113 InstantiationFunction);
10114 // FIXME: We need an update record for this AST mutation.
10115 InstantiationFunction->setDeletedAsWritten(D: false);
10116 }
10117 }
10118
10119 MemberFunction->setInstantiationOfMemberFunction(
10120 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10121 } else if (auto *MemberVar = dyn_cast<VarDecl>(Val: Member)) {
10122 MemberVar->setInstantiationOfStaticDataMember(
10123 VD: cast<VarDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10124 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Val: Member)) {
10125 MemberClass->setInstantiationOfMemberClass(
10126 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10127 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Val: Member)) {
10128 MemberEnum->setInstantiationOfMemberEnum(
10129 ED: cast<EnumDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10130 } else {
10131 llvm_unreachable("unknown member specialization kind");
10132 }
10133
10134 // Save the caller the trouble of having to figure out which declaration
10135 // this specialization matches.
10136 Previous.clear();
10137 Previous.addDecl(D: FoundInstantiation);
10138 return false;
10139}
10140
10141/// Complete the explicit specialization of a member of a class template by
10142/// updating the instantiated member to be marked as an explicit specialization.
10143///
10144/// \param OrigD The member declaration instantiated from the template.
10145/// \param Loc The location of the explicit specialization of the member.
10146template<typename DeclT>
10147static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10148 SourceLocation Loc) {
10149 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10150 return;
10151
10152 // FIXME: Inform AST mutation listeners of this AST mutation.
10153 // FIXME: If there are multiple in-class declarations of the member (from
10154 // multiple modules, or a declaration and later definition of a member type),
10155 // should we update all of them?
10156 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10157 OrigD->setLocation(Loc);
10158}
10159
10160void Sema::CompleteMemberSpecialization(NamedDecl *Member,
10161 LookupResult &Previous) {
10162 NamedDecl *Instantiation = cast<NamedDecl>(Val: Member->getCanonicalDecl());
10163 if (Instantiation == Member)
10164 return;
10165
10166 if (auto *Function = dyn_cast<CXXMethodDecl>(Val: Instantiation))
10167 completeMemberSpecializationImpl(S&: *this, OrigD: Function, Loc: Member->getLocation());
10168 else if (auto *Var = dyn_cast<VarDecl>(Val: Instantiation))
10169 completeMemberSpecializationImpl(S&: *this, OrigD: Var, Loc: Member->getLocation());
10170 else if (auto *Record = dyn_cast<CXXRecordDecl>(Val: Instantiation))
10171 completeMemberSpecializationImpl(S&: *this, OrigD: Record, Loc: Member->getLocation());
10172 else if (auto *Enum = dyn_cast<EnumDecl>(Val: Instantiation))
10173 completeMemberSpecializationImpl(S&: *this, OrigD: Enum, Loc: Member->getLocation());
10174 else
10175 llvm_unreachable("unknown member specialization kind");
10176}
10177
10178/// Check the scope of an explicit instantiation.
10179///
10180/// \returns true if a serious error occurs, false otherwise.
10181static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
10182 SourceLocation InstLoc,
10183 bool WasQualifiedName) {
10184 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
10185 DeclContext *CurContext = S.CurContext->getRedeclContext();
10186
10187 if (CurContext->isRecord()) {
10188 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_in_class)
10189 << D;
10190 return true;
10191 }
10192
10193 // C++11 [temp.explicit]p3:
10194 // An explicit instantiation shall appear in an enclosing namespace of its
10195 // template. If the name declared in the explicit instantiation is an
10196 // unqualified name, the explicit instantiation shall appear in the
10197 // namespace where its template is declared or, if that namespace is inline
10198 // (7.3.1), any namespace from its enclosing namespace set.
10199 //
10200 // This is DR275, which we do not retroactively apply to C++98/03.
10201 if (WasQualifiedName) {
10202 if (CurContext->Encloses(DC: OrigContext))
10203 return false;
10204 } else {
10205 if (CurContext->InEnclosingNamespaceSetOf(NS: OrigContext))
10206 return false;
10207 }
10208
10209 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: OrigContext)) {
10210 if (WasQualifiedName)
10211 S.Diag(Loc: InstLoc,
10212 DiagID: S.getLangOpts().CPlusPlus11?
10213 diag::err_explicit_instantiation_out_of_scope :
10214 diag::warn_explicit_instantiation_out_of_scope_0x)
10215 << D << NS;
10216 else
10217 S.Diag(Loc: InstLoc,
10218 DiagID: S.getLangOpts().CPlusPlus11?
10219 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10220 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10221 << D << NS;
10222 } else
10223 S.Diag(Loc: InstLoc,
10224 DiagID: S.getLangOpts().CPlusPlus11?
10225 diag::err_explicit_instantiation_must_be_global :
10226 diag::warn_explicit_instantiation_must_be_global_0x)
10227 << D;
10228 S.Diag(Loc: D->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10229 return false;
10230}
10231
10232/// Common checks for whether an explicit instantiation of \p D is valid.
10233static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
10234 SourceLocation InstLoc,
10235 bool WasQualifiedName,
10236 TemplateSpecializationKind TSK) {
10237 // C++ [temp.explicit]p13:
10238 // An explicit instantiation declaration shall not name a specialization of
10239 // a template with internal linkage.
10240 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10241 D->getFormalLinkage() == Linkage::Internal) {
10242 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_internal_linkage) << D;
10243 return true;
10244 }
10245
10246 // C++11 [temp.explicit]p3: [DR 275]
10247 // An explicit instantiation shall appear in an enclosing namespace of its
10248 // template.
10249 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10250 return true;
10251
10252 return false;
10253}
10254
10255/// Determine whether the given scope specifier has a template-id in it.
10256static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
10257 // C++11 [temp.explicit]p3:
10258 // If the explicit instantiation is for a member function, a member class
10259 // or a static data member of a class template specialization, the name of
10260 // the class template specialization in the qualified-id for the member
10261 // name shall be a simple-template-id.
10262 //
10263 // C++98 has the same restriction, just worded differently.
10264 for (NestedNameSpecifier NNS = SS.getScopeRep();
10265 NNS.getKind() == NestedNameSpecifier::Kind::Type;
10266 /**/) {
10267 const Type *T = NNS.getAsType();
10268 if (isa<TemplateSpecializationType>(Val: T))
10269 return true;
10270 NNS = T->getPrefix();
10271 }
10272 return false;
10273}
10274
10275/// Make a dllexport or dllimport attr on a class template specialization take
10276/// effect.
10277static void dllExportImportClassTemplateSpecialization(
10278 Sema &S, ClassTemplateSpecializationDecl *Def) {
10279 auto *A = cast_or_null<InheritableAttr>(Val: getDLLAttr(D: Def));
10280 assert(A && "dllExportImportClassTemplateSpecialization called "
10281 "on Def without dllexport or dllimport");
10282
10283 // We reject explicit instantiations in class scope, so there should
10284 // never be any delayed exported classes to worry about.
10285 assert(S.DelayedDllExportClasses.empty() &&
10286 "delayed exports present at explicit instantiation");
10287 S.checkClassLevelDLLAttribute(Class: Def);
10288
10289 // Propagate attribute to base class templates.
10290 for (auto &B : Def->bases()) {
10291 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10292 Val: B.getType()->getAsCXXRecordDecl()))
10293 S.propagateDLLAttrToBaseClassTemplate(Class: Def, ClassAttr: A, BaseTemplateSpec: BT, BaseLoc: B.getBeginLoc());
10294 }
10295
10296 S.referenceDLLExportedClassMethods();
10297}
10298
10299DeclResult Sema::ActOnExplicitInstantiation(
10300 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10301 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10302 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10303 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10304 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10305 // Find the class template we're specializing
10306 TemplateName Name = TemplateD.get();
10307 TemplateDecl *TD = Name.getAsTemplateDecl();
10308 // Check that the specialization uses the same tag kind as the
10309 // original template.
10310 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10311 assert(Kind != TagTypeKind::Enum &&
10312 "Invalid enum tag in class template explicit instantiation!");
10313
10314 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: TD);
10315
10316 if (!ClassTemplate) {
10317 NonTagKind NTK = getNonTagTypeDeclKind(D: TD, TTK: Kind);
10318 Diag(Loc: TemplateNameLoc, DiagID: diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10319 Diag(Loc: TD->getLocation(), DiagID: diag::note_previous_use);
10320 return true;
10321 }
10322
10323 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(),
10324 NewTag: Kind, /*isDefinition*/false, NewTagLoc: KWLoc,
10325 Name: ClassTemplate->getIdentifier())) {
10326 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
10327 << ClassTemplate
10328 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
10329 Code: ClassTemplate->getTemplatedDecl()->getKindName());
10330 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
10331 DiagID: diag::note_previous_use);
10332 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10333 }
10334
10335 // C++0x [temp.explicit]p2:
10336 // There are two forms of explicit instantiation: an explicit instantiation
10337 // definition and an explicit instantiation declaration. An explicit
10338 // instantiation declaration begins with the extern keyword. [...]
10339 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10340 ? TSK_ExplicitInstantiationDefinition
10341 : TSK_ExplicitInstantiationDeclaration;
10342
10343 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10344 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10345 // Check for dllexport class template instantiation declarations,
10346 // except for MinGW mode.
10347 for (const ParsedAttr &AL : Attr) {
10348 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10349 Diag(Loc: ExternLoc,
10350 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10351 Diag(Loc: AL.getLoc(), DiagID: diag::note_attribute);
10352 break;
10353 }
10354 }
10355
10356 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10357 Diag(Loc: ExternLoc,
10358 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10359 Diag(Loc: A->getLocation(), DiagID: diag::note_attribute);
10360 }
10361 }
10362
10363 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10364 // instantiation declarations for most purposes.
10365 bool DLLImportExplicitInstantiationDef = false;
10366 if (TSK == TSK_ExplicitInstantiationDefinition &&
10367 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10368 // Check for dllimport class template instantiation definitions.
10369 bool DLLImport =
10370 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10371 for (const ParsedAttr &AL : Attr) {
10372 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10373 DLLImport = true;
10374 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10375 // dllexport trumps dllimport here.
10376 DLLImport = false;
10377 break;
10378 }
10379 }
10380 if (DLLImport) {
10381 TSK = TSK_ExplicitInstantiationDeclaration;
10382 DLLImportExplicitInstantiationDef = true;
10383 }
10384 }
10385
10386 // Translate the parser's template argument list in our AST format.
10387 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10388 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10389
10390 // Check that the template argument list is well-formed for this
10391 // template.
10392 CheckTemplateArgumentInfo CTAI;
10393 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
10394 /*DefaultArgs=*/{}, PartialTemplateArgs: false, CTAI,
10395 /*UpdateArgsWithConversions=*/true,
10396 /*ConstraintsNotSatisfied=*/nullptr))
10397 return true;
10398
10399 // Find the class template specialization declaration that
10400 // corresponds to these arguments.
10401 llvm::FoldingSetInsertToken InsertToken;
10402 ClassTemplateSpecializationDecl *PrevDecl =
10403 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertToken);
10404
10405 TemplateSpecializationKind PrevDecl_TSK
10406 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10407
10408 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10409 Context.getTargetInfo().getTriple().isOSCygMing()) {
10410 // Check for dllexport class template instantiation definitions in MinGW
10411 // mode, if a previous declaration of the instantiation was seen.
10412 for (const ParsedAttr &AL : Attr) {
10413 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10414 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10415 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attr_dllexport_explicit_inst_def);
10416 } else {
10417 Diag(Loc: AL.getLoc(),
10418 DiagID: diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10419 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_prev_decl_missing_dllexport);
10420 }
10421 break;
10422 }
10423 }
10424 }
10425
10426 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10427 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10428 llvm::none_of(Range: Attr, P: [](const ParsedAttr &AL) {
10429 return AL.getKind() == ParsedAttr::AT_DLLExport;
10430 })) {
10431 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10432 Diag(Loc: TemplateLoc, DiagID: diag::warn_dllexport_on_decl_ignored);
10433 Diag(Loc: DEA->getLoc(), DiagID: diag::note_dllexport_on_decl);
10434 }
10435 }
10436
10437 if (CheckExplicitInstantiation(S&: *this, D: ClassTemplate, InstLoc: TemplateNameLoc,
10438 WasQualifiedName: SS.isSet(), TSK))
10439 return true;
10440
10441 ClassTemplateSpecializationDecl *Specialization = nullptr;
10442
10443 bool HasNoEffect = false;
10444 if (PrevDecl) {
10445 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateNameLoc, NewTSK: TSK,
10446 PrevDecl, PrevTSK: PrevDecl_TSK,
10447 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
10448 HasNoEffect))
10449 return PrevDecl;
10450
10451 // Even though HasNoEffect == true means that this explicit instantiation
10452 // has no effect on semantics, we go on to put its syntax in the AST.
10453
10454 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10455 PrevDecl_TSK == TSK_Undeclared) {
10456 // Since the only prior class template specialization with these
10457 // arguments was referenced but not declared, reuse that
10458 // declaration node as our own, updating the source location
10459 // for the template name to reflect our new declaration.
10460 // (Other source locations will be updated later.)
10461 Specialization = PrevDecl;
10462 Specialization->setLocation(TemplateNameLoc);
10463 PrevDecl = nullptr;
10464 }
10465
10466 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10467 DLLImportExplicitInstantiationDef) {
10468 // The new specialization might add a dllimport attribute.
10469 HasNoEffect = false;
10470 }
10471 }
10472
10473 if (!Specialization) {
10474 // Create a new class template specialization declaration node for
10475 // this explicit specialization.
10476 Specialization = ClassTemplateSpecializationDecl::Create(
10477 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
10478 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
10479 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
10480
10481 // A MSInheritanceAttr attached to the previous declaration must be
10482 // propagated to the new node prior to instantiation.
10483 if (PrevDecl) {
10484 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10485 auto *Clone = A->clone(C&: getASTContext());
10486 Clone->setInherited(true);
10487 Specialization->addAttr(A: Clone);
10488 Consumer.AssignInheritanceModel(RD: Specialization);
10489 }
10490 }
10491
10492 if (!HasNoEffect && !PrevDecl) {
10493 // Insert the new specialization.
10494 ClassTemplate->AddSpecialization(D: Specialization, InsertToken);
10495 }
10496 }
10497
10498 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10499
10500 // Set source locations for keywords.
10501 Specialization->setExternKeywordLoc(ExternLoc);
10502 Specialization->setTemplateKeywordLoc(TemplateLoc);
10503 Specialization->setBraceRange(SourceRange());
10504
10505 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10506 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
10507 ProcessAPINotes(D: Specialization);
10508
10509 // Add the explicit instantiation into its lexical context. However,
10510 // since explicit instantiations are never found by name lookup, we
10511 // just put it into the declaration context directly.
10512 Specialization->setLexicalDeclContext(CurContext);
10513 CurContext->addDecl(D: Specialization);
10514
10515 // Syntax is now OK, so return if it has no other effect on semantics.
10516 if (HasNoEffect) {
10517 // Set the template specialization kind.
10518 Specialization->setTemplateSpecializationKind(TSK);
10519
10520 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
10521 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10522 Keyword: KW, ElaboratedKeywordLoc: KWLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: SourceLocation(), T: Name,
10523 TLoc: TemplateNameLoc, SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted,
10524 Canon: Context.getCanonicalTagType(TD: Specialization));
10525 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
10526 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10527 NameLoc: TemplateNameLoc, TypeAsWritten: TSI, TSK);
10528 return Specialization;
10529 }
10530
10531 // C++ [temp.explicit]p3:
10532 // A definition of a class template or class member template
10533 // shall be in scope at the point of the explicit instantiation of
10534 // the class template or class member template.
10535 //
10536 // This check comes when we actually try to perform the
10537 // instantiation.
10538 ClassTemplateSpecializationDecl *Def
10539 = cast_or_null<ClassTemplateSpecializationDecl>(
10540 Val: Specialization->getDefinition());
10541 if (!Def)
10542 InstantiateClassTemplateSpecialization(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Specialization, TSK,
10543 /*Complain=*/true,
10544 PrimaryStrictPackMatch: CTAI.StrictPackMatch);
10545 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10546 MarkVTableUsed(Loc: TemplateNameLoc, Class: Specialization, DefinitionRequired: true);
10547 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10548 }
10549
10550 // Instantiate the members of this class template specialization.
10551 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10552 Val: Specialization->getDefinition());
10553 if (Def) {
10554 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
10555 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10556 // TSK_ExplicitInstantiationDefinition
10557 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10558 (TSK == TSK_ExplicitInstantiationDefinition ||
10559 DLLImportExplicitInstantiationDef)) {
10560 // FIXME: Need to notify the ASTMutationListener that we did this.
10561 Def->setTemplateSpecializationKind(TSK);
10562
10563 if (!getDLLAttr(D: Def) && getDLLAttr(D: Specialization) &&
10564 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10565 // An explicit instantiation definition can add a dll attribute to a
10566 // template with a previous instantiation declaration. MinGW doesn't
10567 // allow this.
10568 auto *A = cast<InheritableAttr>(
10569 Val: getDLLAttr(D: Specialization)->clone(C&: getASTContext()));
10570 A->setInherited(true);
10571 Def->addAttr(A);
10572 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10573 }
10574 }
10575
10576 // Fix a TSK_ImplicitInstantiation followed by a
10577 // TSK_ExplicitInstantiationDefinition
10578 bool NewlyDLLExported =
10579 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10580 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10581 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10582 // An explicit instantiation definition can add a dll attribute to a
10583 // template with a previous implicit instantiation. MinGW doesn't allow
10584 // this. We limit clang to only adding dllexport, to avoid potentially
10585 // strange codegen behavior. For example, if we extend this conditional
10586 // to dllimport, and we have a source file calling a method on an
10587 // implicitly instantiated template class instance and then declaring a
10588 // dllimport explicit instantiation definition for the same template
10589 // class, the codegen for the method call will not respect the dllimport,
10590 // while it will with cl. The Def will already have the DLL attribute,
10591 // since the Def and Specialization will be the same in the case of
10592 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10593 // attribute to the Specialization; we just need to make it take effect.
10594 assert(Def == Specialization &&
10595 "Def and Specialization should match for implicit instantiation");
10596 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10597 }
10598
10599 // In MinGW mode, export the template instantiation if the declaration
10600 // was marked dllexport.
10601 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10602 Context.getTargetInfo().getTriple().isOSCygMing() &&
10603 PrevDecl->hasAttr<DLLExportAttr>()) {
10604 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10605 }
10606
10607 // Set the template specialization kind. Make sure it is set before
10608 // instantiating the members which will trigger ASTConsumer callbacks.
10609 Specialization->setTemplateSpecializationKind(TSK);
10610 InstantiateClassTemplateSpecializationMembers(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Def, TSK);
10611 } else {
10612
10613 // Set the template specialization kind.
10614 Specialization->setTemplateSpecializationKind(TSK);
10615 }
10616
10617 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
10618 TypeSourceInfo *TSI = Context.getTemplateSpecializationTypeInfo(
10619 Keyword: KW, ElaboratedKeywordLoc: KWLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: SourceLocation(), T: Name,
10620 TLoc: TemplateNameLoc, SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted,
10621 Canon: Context.getCanonicalTagType(TD: Specialization));
10622 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
10623 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10624 NameLoc: TemplateNameLoc, TypeAsWritten: TSI, TSK);
10625 return Specialization;
10626}
10627
10628DeclResult
10629Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10630 SourceLocation TemplateLoc, unsigned TagSpec,
10631 SourceLocation KWLoc, CXXScopeSpec &SS,
10632 IdentifierInfo *Name, SourceLocation NameLoc,
10633 const ParsedAttributesView &Attr) {
10634
10635 bool Owned = false;
10636 bool IsDependent = false;
10637 Decl *TagD =
10638 ActOnTag(S, TagSpec, TUK: TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10639 Attr, AS: AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10640 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent, ScopedEnumKWLoc: SourceLocation(),
10641 ScopedEnumUsesClassTag: false, UnderlyingType: TypeResult(), /*IsTypeSpecifier*/ false,
10642 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10643 .get();
10644
10645 if (!TagD)
10646 return true;
10647
10648 assert(!IsDependent &&
10649 "explicit instantiation of dependent name not yet handled");
10650
10651 TagDecl *Tag = cast<TagDecl>(Val: TagD);
10652 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10653
10654 if (Tag->isInvalidDecl())
10655 return true;
10656
10657 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: Tag);
10658 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10659 if (!Pattern) {
10660 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_nontemplate_type)
10661 << Context.getCanonicalTagType(TD: Record);
10662 Diag(Loc: Record->getLocation(), DiagID: diag::note_nontemplate_decl_here);
10663 return true;
10664 }
10665
10666 // C++0x [temp.explicit]p2:
10667 // If the explicit instantiation is for a class or member class, the
10668 // elaborated-type-specifier in the declaration shall include a
10669 // simple-template-id.
10670 //
10671 // C++98 has the same restriction, just worded differently.
10672 if (!ScopeSpecifierHasTemplateId(SS))
10673 Diag(Loc: TemplateLoc, DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10674 << Record << SS.getRange();
10675
10676 // C++0x [temp.explicit]p2:
10677 // There are two forms of explicit instantiation: an explicit instantiation
10678 // definition and an explicit instantiation declaration. An explicit
10679 // instantiation declaration begins with the extern keyword. [...]
10680 TemplateSpecializationKind TSK
10681 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10682 : TSK_ExplicitInstantiationDeclaration;
10683
10684 CheckExplicitInstantiation(S&: *this, D: Record, InstLoc: NameLoc, WasQualifiedName: true, TSK);
10685
10686 // Verify that it is okay to explicitly instantiate here.
10687 CXXRecordDecl *PrevDecl
10688 = cast_or_null<CXXRecordDecl>(Val: Record->getPreviousDecl());
10689 if (!PrevDecl && Record->getDefinition())
10690 PrevDecl = Record;
10691 if (PrevDecl) {
10692 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10693 bool HasNoEffect = false;
10694 assert(MSInfo && "No member specialization information?");
10695 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateLoc, NewTSK: TSK,
10696 PrevDecl,
10697 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10698 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10699 HasNoEffect))
10700 return true;
10701 if (HasNoEffect) {
10702 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10703 ElaboratedTypeKeyword KW =
10704 TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
10705 QualType TagTy = Context.getTagType(Keyword: KW, Qualifier: SS.getScopeRep(), TD: Record, OwnsTag: false);
10706 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T: TagTy);
10707 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10708 TL.setElaboratedKeywordLoc(KWLoc);
10709 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10710 TL.setNameLoc(NameLoc);
10711 addExplicitInstantiationDecl(Context, CurContext, Spec: Record, ExternLoc,
10712 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(),
10713 ArgsAsWritten: nullptr, NameLoc, TypeAsWritten: TSI, TSK);
10714 return TagD;
10715 }
10716 }
10717
10718 CXXRecordDecl *RecordDef
10719 = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10720 if (!RecordDef) {
10721 // C++ [temp.explicit]p3:
10722 // A definition of a member class of a class template shall be in scope
10723 // at the point of an explicit instantiation of the member class.
10724 CXXRecordDecl *Def
10725 = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition());
10726 if (!Def) {
10727 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_undefined_member)
10728 << 0 << Record->getDeclName() << Record->getDeclContext();
10729 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_forward_declaration)
10730 << Pattern;
10731 return true;
10732 } else {
10733 if (InstantiateClass(PointOfInstantiation: NameLoc, Instantiation: Record, Pattern: Def,
10734 TemplateArgs: getTemplateInstantiationArgs(D: Record),
10735 TSK))
10736 return true;
10737
10738 RecordDef = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10739 if (!RecordDef)
10740 return true;
10741 }
10742 }
10743
10744 // Instantiate all of the members of the class.
10745 InstantiateClassMembers(PointOfInstantiation: NameLoc, Instantiation: RecordDef,
10746 TemplateArgs: getTemplateInstantiationArgs(D: Record), TSK);
10747
10748 if (TSK == TSK_ExplicitInstantiationDefinition)
10749 MarkVTableUsed(Loc: NameLoc, Class: RecordDef, DefinitionRequired: true);
10750
10751 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10752 ElaboratedTypeKeyword KW = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
10753 QualType TagTy = Context.getTagType(Keyword: KW, Qualifier: SS.getScopeRep(), TD: Record, OwnsTag: false);
10754 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T: TagTy);
10755 auto TL = TSI->getTypeLoc().castAs<TagTypeLoc>();
10756 TL.setElaboratedKeywordLoc(KWLoc);
10757 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10758 TL.setNameLoc(NameLoc);
10759 addExplicitInstantiationDecl(Context, CurContext, Spec: Record, ExternLoc,
10760 TemplateLoc, QualifierLoc: NestedNameSpecifierLoc(), ArgsAsWritten: nullptr,
10761 NameLoc, TypeAsWritten: TSI, TSK);
10762 return TagD;
10763}
10764
10765DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10766 SourceLocation ExternLoc,
10767 SourceLocation TemplateLoc,
10768 Declarator &D) {
10769 // Explicit instantiations always require a name.
10770 // TODO: check if/when DNInfo should replace Name.
10771 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10772 DeclarationName Name = NameInfo.getName();
10773 if (!Name) {
10774 if (!D.isInvalidType())
10775 Diag(Loc: D.getDeclSpec().getBeginLoc(),
10776 DiagID: diag::err_explicit_instantiation_requires_name)
10777 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10778
10779 return true;
10780 }
10781
10782 // Get the innermost enclosing declaration scope.
10783 S = S->getDeclParent();
10784
10785 // Determine the type of the declaration.
10786 TypeSourceInfo *T = GetTypeForDeclarator(D);
10787 QualType R = T->getType();
10788 if (R.isNull())
10789 return true;
10790
10791 // C++ [dcl.stc]p1:
10792 // A storage-class-specifier shall not be specified in [...] an explicit
10793 // instantiation (14.7.2) directive.
10794 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10795 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_of_typedef)
10796 << Name;
10797 return true;
10798 } else if (D.getDeclSpec().getStorageClassSpec()
10799 != DeclSpec::SCS_unspecified) {
10800 // Complain about then remove the storage class specifier.
10801 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_storage_class)
10802 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10803
10804 D.getMutableDeclSpec().ClearStorageClassSpecs();
10805 }
10806
10807 // C++0x [temp.explicit]p1:
10808 // [...] An explicit instantiation of a function template shall not use the
10809 // inline or constexpr specifiers.
10810 // Presumably, this also applies to member functions of class templates as
10811 // well.
10812 if (D.getDeclSpec().isInlineSpecified())
10813 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10814 DiagID: getLangOpts().CPlusPlus11 ?
10815 diag::err_explicit_instantiation_inline :
10816 diag::warn_explicit_instantiation_inline_0x)
10817 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10818 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10819 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10820 // not already specified.
10821 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10822 DiagID: diag::err_explicit_instantiation_constexpr);
10823
10824 // A deduction guide is not on the list of entities that can be explicitly
10825 // instantiated.
10826 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10827 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
10828 << /*explicit instantiation*/ 0;
10829 return true;
10830 }
10831
10832 // C++0x [temp.explicit]p2:
10833 // There are two forms of explicit instantiation: an explicit instantiation
10834 // definition and an explicit instantiation declaration. An explicit
10835 // instantiation declaration begins with the extern keyword. [...]
10836 TemplateSpecializationKind TSK
10837 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10838 : TSK_ExplicitInstantiationDeclaration;
10839
10840 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10841 LookupParsedName(R&: Previous, S, SS: &D.getCXXScopeSpec(),
10842 /*ObjectType=*/QualType());
10843
10844 if (!R->isFunctionType()) {
10845 // C++ [temp.explicit]p1:
10846 // A [...] static data member of a class template can be explicitly
10847 // instantiated from the member definition associated with its class
10848 // template.
10849 // C++1y [temp.explicit]p1:
10850 // A [...] variable [...] template specialization can be explicitly
10851 // instantiated from its template.
10852 if (Previous.isAmbiguous())
10853 return true;
10854
10855 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10856 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10857 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
10858
10859 if (!PrevTemplate) {
10860 if (!Prev || !Prev->isStaticDataMember()) {
10861 // We expect to see a static data member here.
10862 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_not_known)
10863 << Name;
10864 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10865 P != PEnd; ++P)
10866 Diag(Loc: (*P)->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10867 return true;
10868 }
10869
10870 if (!Prev->getInstantiatedFromStaticDataMember()) {
10871 // FIXME: Check for explicit specialization?
10872 Diag(Loc: D.getIdentifierLoc(),
10873 DiagID: diag::err_explicit_instantiation_data_member_not_instantiated)
10874 << Prev;
10875 Diag(Loc: Prev->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10876 // FIXME: Can we provide a note showing where this was declared?
10877 return true;
10878 }
10879 } else {
10880 // Explicitly instantiate a variable template.
10881
10882 // C++1y [dcl.spec.auto]p6:
10883 // ... A program that uses auto or decltype(auto) in a context not
10884 // explicitly allowed in this section is ill-formed.
10885 //
10886 // This includes auto-typed variable template instantiations.
10887 if (R->isUndeducedType()) {
10888 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10889 DiagID: diag::err_auto_not_allowed_var_inst);
10890 return true;
10891 }
10892
10893 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10894 // C++1y [temp.explicit]p3:
10895 // If the explicit instantiation is for a variable, the unqualified-id
10896 // in the declaration shall be a template-id.
10897 Diag(Loc: D.getIdentifierLoc(),
10898 DiagID: diag::err_explicit_instantiation_without_template_id)
10899 << PrevTemplate;
10900 Diag(Loc: PrevTemplate->getLocation(),
10901 DiagID: diag::note_explicit_instantiation_here);
10902 return true;
10903 }
10904
10905 // Translate the parser's template argument list into our AST format.
10906 TemplateArgumentListInfo TemplateArgs =
10907 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10908
10909 DeclResult Res =
10910 CheckVarTemplateId(Template: PrevTemplate, TemplateLoc, TemplateNameLoc: D.getIdentifierLoc(),
10911 TemplateArgs, /*SetWrittenArgs=*/true);
10912 if (Res.isInvalid())
10913 return true;
10914
10915 if (!Res.isUsable()) {
10916 // We somehow specified dependent template arguments in an explicit
10917 // instantiation. This should probably only happen during error
10918 // recovery.
10919 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_dependent);
10920 return true;
10921 }
10922
10923 // Ignore access control bits, we don't need them for redeclaration
10924 // checking.
10925 Prev = cast<VarDecl>(Val: Res.get());
10926 ArgsAsWritten =
10927 ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
10928 }
10929
10930 // C++0x [temp.explicit]p2:
10931 // If the explicit instantiation is for a member function, a member class
10932 // or a static data member of a class template specialization, the name of
10933 // the class template specialization in the qualified-id for the member
10934 // name shall be a simple-template-id.
10935 //
10936 // C++98 has the same restriction, just worded differently.
10937 //
10938 // This does not apply to variable template specializations, where the
10939 // template-id is in the unqualified-id instead.
10940 if (!ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()) && !PrevTemplate)
10941 Diag(Loc: D.getIdentifierLoc(),
10942 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10943 << Prev << D.getCXXScopeSpec().getRange();
10944
10945 CheckExplicitInstantiation(S&: *this, D: Prev, InstLoc: D.getIdentifierLoc(), WasQualifiedName: true, TSK);
10946
10947 // Verify that it is okay to explicitly instantiate here.
10948 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10949 SourceLocation POI = Prev->getPointOfInstantiation();
10950 bool HasNoEffect = false;
10951 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK, PrevDecl: Prev,
10952 PrevTSK, PrevPointOfInstantiation: POI, HasNoEffect))
10953 return true;
10954
10955 if (!HasNoEffect) {
10956 // Instantiate static data member or variable template.
10957 Prev->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
10958 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Val: Prev)) {
10959 VTSD->setExternKeywordLoc(ExternLoc);
10960 VTSD->setTemplateKeywordLoc(TemplateLoc);
10961 }
10962
10963 // Merge attributes.
10964 ProcessDeclAttributeList(S, D: Prev, AttrList: D.getDeclSpec().getAttributes());
10965 if (PrevTemplate)
10966 ProcessAPINotes(D: Prev);
10967
10968 if (TSK == TSK_ExplicitInstantiationDefinition)
10969 InstantiateVariableDefinition(PointOfInstantiation: D.getIdentifierLoc(), Var: Prev);
10970 }
10971
10972 // Check the new variable specialization against the parsed input.
10973 if (PrevTemplate && !Context.hasSameType(T1: Prev->getType(), T2: R)) {
10974 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10975 DiagID: diag::err_invalid_var_template_spec_type)
10976 << 0 << PrevTemplate << R << Prev->getType();
10977 Diag(Loc: PrevTemplate->getLocation(), DiagID: diag::note_template_declared_here)
10978 << 2 << PrevTemplate->getDeclName();
10979 return true;
10980 }
10981
10982 addExplicitInstantiationDecl(
10983 Context, CurContext, Spec: Prev, ExternLoc, TemplateLoc,
10984 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
10985 NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
10986 return (Decl *)nullptr;
10987 }
10988
10989 // If the declarator is a template-id, translate the parser's template
10990 // argument list into our AST format.
10991 bool HasExplicitTemplateArgs = false;
10992 TemplateArgumentListInfo TemplateArgs;
10993 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10994 TemplateArgs = makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10995 HasExplicitTemplateArgs = true;
10996 }
10997
10998 // C++ [temp.explicit]p1:
10999 // A [...] function [...] can be explicitly instantiated from its template.
11000 // A member function [...] of a class template can be explicitly
11001 // instantiated from the member definition associated with its class
11002 // template.
11003 UnresolvedSet<8> TemplateMatches;
11004 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
11005 OverloadCandidateSet::CSK_Normal);
11006 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
11007 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
11008 P != PEnd; ++P) {
11009 NamedDecl *Prev = *P;
11010 if (!HasExplicitTemplateArgs) {
11011 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Prev)) {
11012 QualType Adjusted = adjustCCAndNoReturn(ArgFunctionType: R, FunctionType: Method->getType(),
11013 /*AdjustExceptionSpec*/true);
11014 if (Context.hasSameUnqualifiedType(T1: Method->getType(), T2: Adjusted)) {
11015 if (Method->getPrimaryTemplate()) {
11016 TemplateMatches.addDecl(D: Method, AS: P.getAccess());
11017 } else {
11018 OverloadCandidate &C = NonTemplateMatches.addCandidate();
11019 C.FoundDecl = P.getPair();
11020 C.Function = Method;
11021 C.Viable = true;
11022 ConstraintSatisfaction S;
11023 if (Method->getTrailingRequiresClause() &&
11024 (CheckFunctionConstraints(FD: Method, Satisfaction&: S, UsageLoc: D.getIdentifierLoc(),
11025 /*ForOverloadResolution=*/true) ||
11026 !S.IsSatisfied)) {
11027 C.Viable = false;
11028 C.FailureKind = ovl_fail_constraints_not_satisfied;
11029 }
11030 }
11031 }
11032 }
11033 }
11034
11035 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Prev);
11036 if (!FunTmpl)
11037 continue;
11038
11039 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
11040 FunctionDecl *Specialization = nullptr;
11041 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
11042 FunctionTemplate: FunTmpl, ExplicitTemplateArgs: (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), ArgFunctionType: R,
11043 Specialization, Info);
11044 TDK != TemplateDeductionResult::Success) {
11045 // Keep track of almost-matches.
11046 FailedTemplateCandidates.addCandidate().set(
11047 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
11048 Info: MakeDeductionFailureInfo(Context, TDK, Info));
11049 (void)TDK;
11050 continue;
11051 }
11052
11053 // Target attributes are part of the cuda function signature, so
11054 // the cuda target of the instantiated function must match that of its
11055 // template. Given that C++ template deduction does not take
11056 // target attributes into account, we reject candidates here that
11057 // have a different target.
11058 if (LangOpts.CUDA &&
11059 CUDA().IdentifyTarget(D: Specialization,
11060 /* IgnoreImplicitHDAttr = */ true) !=
11061 CUDA().IdentifyTarget(Attrs: D.getDeclSpec().getAttributes())) {
11062 FailedTemplateCandidates.addCandidate().set(
11063 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
11064 Info: MakeDeductionFailureInfo(
11065 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
11066 continue;
11067 }
11068
11069 TemplateMatches.addDecl(D: Specialization, AS: P.getAccess());
11070 }
11071
11072 FunctionDecl *Specialization = nullptr;
11073 if (!NonTemplateMatches.empty()) {
11074 unsigned Msg = 0;
11075 OverloadCandidateDisplayKind DisplayKind;
11076 OverloadCandidateSet::iterator Best;
11077 switch (NonTemplateMatches.BestViableFunction(S&: *this, Loc: D.getIdentifierLoc(),
11078 Best)) {
11079 case OR_Success:
11080 case OR_Deleted:
11081 Specialization = cast<FunctionDecl>(Val: Best->Function);
11082 break;
11083 case OR_Ambiguous:
11084 Msg = diag::err_explicit_instantiation_ambiguous;
11085 DisplayKind = OCD_AmbiguousCandidates;
11086 break;
11087 case OR_No_Viable_Function:
11088 Msg = diag::err_explicit_instantiation_no_candidate;
11089 DisplayKind = OCD_AllCandidates;
11090 break;
11091 }
11092 if (Msg) {
11093 PartialDiagnostic Diag = PDiag(DiagID: Msg) << Name;
11094 NonTemplateMatches.NoteCandidates(
11095 PA: PartialDiagnosticAt(D.getIdentifierLoc(), Diag), S&: *this, OCD: DisplayKind,
11096 Args: {});
11097 return true;
11098 }
11099 }
11100
11101 if (!Specialization) {
11102 // Find the most specialized function template specialization.
11103 UnresolvedSetIterator Result = getMostSpecialized(
11104 SBegin: TemplateMatches.begin(), SEnd: TemplateMatches.end(),
11105 FailedCandidates&: FailedTemplateCandidates, Loc: D.getIdentifierLoc(),
11106 NoneDiag: PDiag(DiagID: diag::err_explicit_instantiation_not_known) << Name,
11107 AmbigDiag: PDiag(DiagID: diag::err_explicit_instantiation_ambiguous) << Name,
11108 CandidateDiag: PDiag(DiagID: diag::note_explicit_instantiation_candidate));
11109
11110 if (Result == TemplateMatches.end())
11111 return true;
11112
11113 // Ignore access control bits, we don't need them for redeclaration checking.
11114 Specialization = cast<FunctionDecl>(Val: *Result);
11115 }
11116
11117 // C++11 [except.spec]p4
11118 // In an explicit instantiation an exception-specification may be specified,
11119 // but is not required.
11120 // If an exception-specification is specified in an explicit instantiation
11121 // directive, it shall be compatible with the exception-specifications of
11122 // other declarations of that function.
11123 if (auto *FPT = R->getAs<FunctionProtoType>())
11124 if (FPT->hasExceptionSpec()) {
11125 unsigned DiagID =
11126 diag::err_mismatched_exception_spec_explicit_instantiation;
11127 if (getLangOpts().MicrosoftExt)
11128 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11129 bool Result = CheckEquivalentExceptionSpec(
11130 DiagID: PDiag(DiagID) << Specialization->getType(),
11131 NoteID: PDiag(DiagID: diag::note_explicit_instantiation_here),
11132 Old: Specialization->getType()->getAs<FunctionProtoType>(),
11133 OldLoc: Specialization->getLocation(), New: FPT, NewLoc: D.getBeginLoc());
11134 // In Microsoft mode, mismatching exception specifications just cause a
11135 // warning.
11136 if (!getLangOpts().MicrosoftExt && Result)
11137 return true;
11138 }
11139
11140 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11141 Diag(Loc: D.getIdentifierLoc(),
11142 DiagID: diag::err_explicit_instantiation_member_function_not_instantiated)
11143 << Specialization
11144 << (Specialization->getTemplateSpecializationKind() ==
11145 TSK_ExplicitSpecialization);
11146 Diag(Loc: Specialization->getLocation(), DiagID: diag::note_explicit_instantiation_here);
11147 return true;
11148 }
11149
11150 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11151 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11152 PrevDecl = Specialization;
11153
11154 if (PrevDecl) {
11155 bool HasNoEffect = false;
11156 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK,
11157 PrevDecl,
11158 PrevTSK: PrevDecl->getTemplateSpecializationKind(),
11159 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
11160 HasNoEffect))
11161 return true;
11162
11163 if (HasNoEffect) {
11164 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11165 if (HasExplicitTemplateArgs)
11166 ArgsAsWritten =
11167 ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
11168 addExplicitInstantiationDecl(
11169 Context, CurContext, Spec: Specialization, ExternLoc, TemplateLoc,
11170 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context), ArgsAsWritten,
11171 NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
11172 return (Decl *)nullptr;
11173 }
11174 }
11175
11176 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11177 // functions
11178 // valarray<size_t>::valarray(size_t) and
11179 // valarray<size_t>::~valarray()
11180 // that it declared to have internal linkage with the internal_linkage
11181 // attribute. Ignore the explicit instantiation declaration in this case.
11182 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11183 TSK == TSK_ExplicitInstantiationDeclaration) {
11184 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Specialization->getDeclContext()))
11185 if (RD->getIdentifier() && RD->getIdentifier()->isStr(Str: "valarray") &&
11186 RD->isInStdNamespace())
11187 return (Decl*) nullptr;
11188 }
11189
11190 ProcessDeclAttributeList(S, D: Specialization, AttrList: D.getDeclSpec().getAttributes());
11191 ProcessAPINotes(D: Specialization);
11192
11193 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11194 // instantiation declarations.
11195 if (TSK == TSK_ExplicitInstantiationDefinition &&
11196 Specialization->hasAttr<DLLImportAttr>() &&
11197 Context.getTargetInfo().getCXXABI().isMicrosoft())
11198 TSK = TSK_ExplicitInstantiationDeclaration;
11199
11200 Specialization->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
11201 if (Specialization->isDefined()) {
11202 // Let the ASTConsumer know that this function has been explicitly
11203 // instantiated now, and its linkage might have changed.
11204 Consumer.HandleTopLevelDecl(D: DeclGroupRef(Specialization));
11205 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
11206 // C++2c [expr.prim.lambda.closure]/19 A member of a closure type shall not
11207 // be explicitly instantiated.
11208 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: Specialization->getParent());
11209 RD && RD->isLambda()) {
11210 Diag(Loc: D.getBeginLoc(), DiagID: diag::err_lambda_explicit_temp_spec)
11211 << /*instantiation*/ 1;
11212 Diag(Loc: RD->getLocation(), DiagID: diag::note_defined_here) << RD;
11213 return (Decl *)nullptr;
11214 }
11215 InstantiateFunctionDefinition(PointOfInstantiation: D.getIdentifierLoc(), Function: Specialization);
11216 }
11217
11218 // C++0x [temp.explicit]p2:
11219 // If the explicit instantiation is for a member function, a member class
11220 // or a static data member of a class template specialization, the name of
11221 // the class template specialization in the qualified-id for the member
11222 // name shall be a simple-template-id.
11223 //
11224 // C++98 has the same restriction, just worded differently.
11225 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11226 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11227 D.getCXXScopeSpec().isSet() &&
11228 !ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()))
11229 Diag(Loc: D.getIdentifierLoc(),
11230 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
11231 << Specialization << D.getCXXScopeSpec().getRange();
11232
11233 CheckExplicitInstantiation(
11234 S&: *this,
11235 D: FunTmpl ? (NamedDecl *)FunTmpl
11236 : Specialization->getInstantiatedFromMemberFunction(),
11237 InstLoc: D.getIdentifierLoc(), WasQualifiedName: D.getCXXScopeSpec().isSet(), TSK);
11238
11239 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
11240 if (HasExplicitTemplateArgs)
11241 ArgsAsWritten = ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgs);
11242 addExplicitInstantiationDecl(Context, CurContext, Spec: Specialization, ExternLoc,
11243 TemplateLoc,
11244 QualifierLoc: D.getCXXScopeSpec().getWithLocInContext(Context),
11245 ArgsAsWritten, NameLoc: D.getIdentifierLoc(), TypeAsWritten: T, TSK);
11246 return (Decl *)nullptr;
11247}
11248
11249TypeResult Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11250 const CXXScopeSpec &SS,
11251 const IdentifierInfo *Name,
11252 SourceLocation TagLoc,
11253 SourceLocation NameLoc) {
11254 // This has to hold, because SS is expected to be defined.
11255 assert(Name && "Expected a name in a dependent tag");
11256
11257 NestedNameSpecifier NNS = SS.getScopeRep();
11258 if (!NNS)
11259 return true;
11260
11261 if (TUK == TagUseKind::Friend &&
11262 DiagnosePackIndexingInFriendNNS(Loc: NameLoc, NNSLoc: SS.getWithLocInContext(Context)))
11263 return true;
11264
11265 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
11266
11267 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11268 Diag(Loc: NameLoc, DiagID: diag::err_dependent_tag_decl)
11269 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11270 return true;
11271 }
11272
11273 // Create the resulting type.
11274 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
11275 QualType Result = Context.getDependentNameType(Keyword: Kwd, NNS, Name);
11276
11277 // Create type-source location information for this type.
11278 TypeLocBuilder TLB;
11279 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: Result);
11280 TL.setElaboratedKeywordLoc(TagLoc);
11281 TL.setQualifierLoc(SS.getWithLocInContext(Context));
11282 TL.setNameLoc(NameLoc);
11283 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
11284}
11285
11286TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11287 const CXXScopeSpec &SS,
11288 const IdentifierInfo &II,
11289 SourceLocation IdLoc,
11290 ImplicitTypenameContext IsImplicitTypename) {
11291 if (SS.isInvalid())
11292 return true;
11293
11294 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11295 DiagCompat(Loc: TypenameLoc, CompatDiagId: diag_compat::typename_outside_of_template)
11296 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11297
11298 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11299 TypeSourceInfo *TSI = nullptr;
11300 QualType T =
11301 CheckTypenameType(Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11302 : ElaboratedTypeKeyword::None,
11303 KeywordLoc: TypenameLoc, QualifierLoc, II, IILoc: IdLoc, TSI: &TSI,
11304 /*DeducedTSTContext=*/true);
11305 if (T.isNull())
11306 return true;
11307 return CreateParsedType(T, TInfo: TSI);
11308}
11309
11310TypeResult
11311Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11312 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11313 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11314 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11315 ASTTemplateArgsPtr TemplateArgsIn,
11316 SourceLocation RAngleLoc) {
11317 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11318 Diag(Loc: TypenameLoc, DiagID: getLangOpts().CPlusPlus11
11319 ? diag::compat_cxx11_typename_outside_of_template
11320 : diag::compat_pre_cxx11_typename_outside_of_template)
11321 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11322
11323 // Strangely, non-type results are not ignored by this lookup, so the
11324 // program is ill-formed if it finds an injected-class-name.
11325 if (TypenameLoc.isValid()) {
11326 auto *LookupRD =
11327 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: false));
11328 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11329 Diag(Loc: TemplateIILoc,
11330 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
11331 << TemplateII << 0 /*injected-class-name used as template name*/
11332 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11333 }
11334 }
11335
11336 // Translate the parser's template argument list in our AST format.
11337 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11338 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11339
11340 QualType T = CheckTemplateIdType(
11341 Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11342 : ElaboratedTypeKeyword::None,
11343 Name: TemplateIn.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
11344 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11345 if (T.isNull())
11346 return true;
11347
11348 // Provide source-location information for the template specialization type.
11349 TypeLocBuilder Builder;
11350 TemplateSpecializationTypeLoc SpecTL
11351 = Builder.push<TemplateSpecializationTypeLoc>(T);
11352 SpecTL.set(ElaboratedKeywordLoc: TypenameLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
11353 NameLoc: TemplateIILoc, TAL: TemplateArgs);
11354 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11355 return CreateParsedType(T, TInfo: TSI);
11356}
11357
11358/// Determine whether this failed name lookup should be treated as being
11359/// disabled by a usage of std::enable_if.
11360static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
11361 SourceRange &CondRange, Expr *&Cond) {
11362 // We must be looking for a ::type...
11363 if (!II.isStr(Str: "type"))
11364 return false;
11365
11366 // ... within an explicitly-written template specialization...
11367 if (NNS.getNestedNameSpecifier().getKind() != NestedNameSpecifier::Kind::Type)
11368 return false;
11369
11370 // FIXME: Look through sugar.
11371 auto EnableIfTSTLoc =
11372 NNS.castAsTypeLoc().getAs<TemplateSpecializationTypeLoc>();
11373 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11374 return false;
11375 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11376
11377 // ... which names a complete class template declaration...
11378 const TemplateDecl *EnableIfDecl =
11379 EnableIfTST->getTemplateName().getAsTemplateDecl();
11380 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11381 return false;
11382
11383 // ... called "enable_if".
11384 const IdentifierInfo *EnableIfII =
11385 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11386 if (!EnableIfII || !EnableIfII->isStr(Str: "enable_if"))
11387 return false;
11388
11389 // Assume the first template argument is the condition.
11390 CondRange = EnableIfTSTLoc.getArgLoc(i: 0).getSourceRange();
11391
11392 // Dig out the condition.
11393 Cond = nullptr;
11394 if (EnableIfTSTLoc.getArgLoc(i: 0).getArgument().getKind()
11395 != TemplateArgument::Expression)
11396 return true;
11397
11398 Cond = EnableIfTSTLoc.getArgLoc(i: 0).getSourceExpression();
11399
11400 // Ignore Boolean literals; they add no value.
11401 if (isa<CXXBoolLiteralExpr>(Val: Cond->IgnoreParenCasts()))
11402 Cond = nullptr;
11403
11404 return true;
11405}
11406
11407QualType
11408Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11409 SourceLocation KeywordLoc,
11410 NestedNameSpecifierLoc QualifierLoc,
11411 const IdentifierInfo &II,
11412 SourceLocation IILoc,
11413 TypeSourceInfo **TSI,
11414 bool DeducedTSTContext) {
11415 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11416 DeducedTSTContext);
11417 if (T.isNull())
11418 return QualType();
11419
11420 TypeLocBuilder TLB;
11421 if (isa<DependentNameType>(Val: T)) {
11422 auto TL = TLB.push<DependentNameTypeLoc>(T);
11423 TL.setElaboratedKeywordLoc(KeywordLoc);
11424 TL.setQualifierLoc(QualifierLoc);
11425 TL.setNameLoc(IILoc);
11426 } else if (isa<DeducedTemplateSpecializationType>(Val: T)) {
11427 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
11428 TL.setElaboratedKeywordLoc(KeywordLoc);
11429 TL.setQualifierLoc(QualifierLoc);
11430 TL.setNameLoc(IILoc);
11431 } else if (isa<TemplateTypeParmType>(Val: T)) {
11432 // FIXME: There might be a 'typename' keyword here, but we just drop it
11433 // as it can't be represented.
11434 assert(!QualifierLoc);
11435 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11436 } else if (isa<TagType>(Val: T)) {
11437 auto TL = TLB.push<TagTypeLoc>(T);
11438 TL.setElaboratedKeywordLoc(KeywordLoc);
11439 TL.setQualifierLoc(QualifierLoc);
11440 TL.setNameLoc(IILoc);
11441 } else if (isa<TypedefType>(Val: T)) {
11442 TLB.push<TypedefTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11443 } else {
11444 TLB.push<UnresolvedUsingTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11445 }
11446 *TSI = TLB.getTypeSourceInfo(Context, T);
11447 return T;
11448}
11449
11450/// Build the type that describes a C++ typename specifier,
11451/// e.g., "typename T::type".
11452QualType
11453Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11454 SourceLocation KeywordLoc,
11455 NestedNameSpecifierLoc QualifierLoc,
11456 const IdentifierInfo &II,
11457 SourceLocation IILoc, bool DeducedTSTContext) {
11458 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11459
11460 CXXScopeSpec SS;
11461 SS.Adopt(Other: QualifierLoc);
11462
11463 DeclContext *Ctx = nullptr;
11464 if (QualifierLoc) {
11465 Ctx = computeDeclContext(SS);
11466 if (!Ctx) {
11467 // If the nested-name-specifier is dependent and couldn't be
11468 // resolved to a type, build a typename type.
11469 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11470 return Context.getDependentNameType(Keyword,
11471 NNS: QualifierLoc.getNestedNameSpecifier(),
11472 Name: &II);
11473 }
11474
11475 // If the nested-name-specifier refers to the current instantiation,
11476 // the "typename" keyword itself is superfluous. In C++03, the
11477 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11478 // allows such extraneous "typename" keywords, and we retroactively
11479 // apply this DR to C++03 code with only a warning. In any case we continue.
11480
11481 if (RequireCompleteDeclContext(SS, DC: Ctx))
11482 return QualType();
11483 }
11484
11485 DeclarationName Name(&II);
11486 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11487 if (Ctx)
11488 LookupQualifiedName(R&: Result, LookupCtx: Ctx, SS);
11489 else
11490 LookupName(R&: Result, S: CurScope);
11491 unsigned DiagID = 0;
11492 Decl *Referenced = nullptr;
11493 switch (Result.getResultKind()) {
11494 case LookupResultKind::NotFound: {
11495 // If we're looking up 'type' within a template named 'enable_if', produce
11496 // a more specific diagnostic.
11497 SourceRange CondRange;
11498 Expr *Cond = nullptr;
11499 if (Ctx && isEnableIf(NNS: QualifierLoc, II, CondRange, Cond)) {
11500 // If we have a condition, narrow it down to the specific failed
11501 // condition.
11502 if (Cond) {
11503 Expr *FailedCond;
11504 std::string FailedDescription;
11505 std::tie(args&: FailedCond, args&: FailedDescription) =
11506 findFailedBooleanCondition(Cond);
11507
11508 Diag(Loc: FailedCond->getExprLoc(),
11509 DiagID: diag::err_typename_nested_not_found_requirement)
11510 << FailedDescription
11511 << FailedCond->getSourceRange();
11512 return QualType();
11513 }
11514
11515 Diag(Loc: CondRange.getBegin(),
11516 DiagID: diag::err_typename_nested_not_found_enable_if)
11517 << Ctx << CondRange;
11518 return QualType();
11519 }
11520
11521 DiagID = Ctx ? diag::err_typename_nested_not_found
11522 : diag::err_unknown_typename;
11523 break;
11524 }
11525
11526 case LookupResultKind::FoundUnresolvedValue: {
11527 // We found a using declaration that is a value. Most likely, the using
11528 // declaration itself is meant to have the 'typename' keyword.
11529 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11530 IILoc);
11531 Diag(Loc: IILoc, DiagID: diag::err_typename_refers_to_using_value_decl)
11532 << Name << Ctx << FullRange;
11533 if (UnresolvedUsingValueDecl *Using
11534 = dyn_cast<UnresolvedUsingValueDecl>(Val: Result.getRepresentativeDecl())){
11535 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11536 Diag(Loc, DiagID: diag::note_using_value_decl_missing_typename)
11537 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
11538 }
11539 }
11540 // Fall through to create a dependent typename type, from which we can
11541 // recover better.
11542 [[fallthrough]];
11543
11544 case LookupResultKind::NotFoundInCurrentInstantiation:
11545 // Okay, it's a member of an unknown instantiation.
11546 return Context.getDependentNameType(Keyword,
11547 NNS: QualifierLoc.getNestedNameSpecifier(),
11548 Name: &II);
11549
11550 case LookupResultKind::Found:
11551 // FXIME: Missing support for UsingShadowDecl on this path?
11552 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: Result.getFoundDecl())) {
11553 // C++ [class.qual]p2:
11554 // In a lookup in which function names are not ignored and the
11555 // nested-name-specifier nominates a class C, if the name specified
11556 // after the nested-name-specifier, when looked up in C, is the
11557 // injected-class-name of C [...] then the name is instead considered
11558 // to name the constructor of class C.
11559 //
11560 // Unlike in an elaborated-type-specifier, function names are not ignored
11561 // in typename-specifier lookup. However, they are ignored in all the
11562 // contexts where we form a typename type with no keyword (that is, in
11563 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11564 //
11565 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11566 // ignore functions, but that appears to be an oversight.
11567 checkTypeDeclType(LookupCtx: Ctx,
11568 DCK: Keyword == ElaboratedTypeKeyword::Typename
11569 ? DiagCtorKind::Typename
11570 : DiagCtorKind::None,
11571 TD: Type, NameLoc: IILoc);
11572 // FIXME: This appears to be the only case where a template type parameter
11573 // can have an elaborated keyword. We should preserve it somehow.
11574 if (isa<TemplateTypeParmDecl>(Val: Type)) {
11575 assert(Keyword == ElaboratedTypeKeyword::Typename);
11576 assert(!QualifierLoc);
11577 Keyword = ElaboratedTypeKeyword::None;
11578 }
11579 return Context.getTypeDeclType(
11580 Keyword, Qualifier: QualifierLoc.getNestedNameSpecifier(), Decl: Type);
11581 }
11582
11583 // C++ [dcl.type.simple]p2:
11584 // A type-specifier of the form
11585 // typename[opt] nested-name-specifier[opt] template-name
11586 // is a placeholder for a deduced class type [...].
11587 if (getLangOpts().CPlusPlus17) {
11588 if (auto *TD = getAsTypeTemplateDecl(D: Result.getFoundDecl())) {
11589 if (!DeducedTSTContext) {
11590 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11591 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11592 Diag(Loc: IILoc, DiagID: diag::err_dependent_deduced_tst)
11593 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
11594 << QualType(Qualifier.getAsType(), 0);
11595 else
11596 Diag(Loc: IILoc, DiagID: diag::err_deduced_tst)
11597 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD));
11598 NoteTemplateLocation(Decl: *TD);
11599 return QualType();
11600 }
11601 TemplateName Name = Context.getQualifiedTemplateName(
11602 Qualifier: QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11603 Template: TemplateName(TD));
11604 return Context.getDeducedTemplateSpecializationType(
11605 DK: DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11606 Template: Name);
11607 }
11608 }
11609
11610 DiagID = Ctx ? diag::err_typename_nested_not_type
11611 : diag::err_typename_not_type;
11612 Referenced = Result.getFoundDecl();
11613 break;
11614
11615 case LookupResultKind::FoundOverloaded:
11616 DiagID = Ctx ? diag::err_typename_nested_not_type
11617 : diag::err_typename_not_type;
11618 Referenced = *Result.begin();
11619 break;
11620
11621 case LookupResultKind::Ambiguous:
11622 return QualType();
11623 }
11624
11625 // If we get here, it's because name lookup did not find a
11626 // type. Emit an appropriate diagnostic and return an error.
11627 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11628 IILoc);
11629 if (Ctx)
11630 Diag(Loc: IILoc, DiagID) << FullRange << Name << Ctx;
11631 else
11632 Diag(Loc: IILoc, DiagID) << FullRange << Name;
11633 if (Referenced)
11634 Diag(Loc: Referenced->getLocation(),
11635 DiagID: Ctx ? diag::note_typename_member_refers_here
11636 : diag::note_typename_refers_here)
11637 << Name;
11638 return QualType();
11639}
11640
11641namespace {
11642 // See Sema::RebuildTypeInCurrentInstantiation
11643 class CurrentInstantiationRebuilder
11644 : public TreeTransform<CurrentInstantiationRebuilder> {
11645 SourceLocation Loc;
11646 DeclarationName Entity;
11647
11648 public:
11649 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11650
11651 CurrentInstantiationRebuilder(Sema &SemaRef,
11652 SourceLocation Loc,
11653 DeclarationName Entity)
11654 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11655 Loc(Loc), Entity(Entity) { }
11656
11657 /// Determine whether the given type \p T has already been
11658 /// transformed.
11659 ///
11660 /// For the purposes of type reconstruction, a type has already been
11661 /// transformed if it is NULL or if it is not dependent.
11662 bool AlreadyTransformed(QualType T) {
11663 return T.isNull() || !T->isInstantiationDependentType();
11664 }
11665
11666 /// Returns the location of the entity whose type is being
11667 /// rebuilt.
11668 SourceLocation getBaseLocation() { return Loc; }
11669
11670 /// Returns the name of the entity whose type is being rebuilt.
11671 DeclarationName getBaseEntity() { return Entity; }
11672
11673 /// Sets the "base" location and entity when that
11674 /// information is known based on another transformation.
11675 void setBase(SourceLocation Loc, DeclarationName Entity) {
11676 this->Loc = Loc;
11677 this->Entity = Entity;
11678 }
11679
11680 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11681 // Lambdas never need to be transformed.
11682 return E;
11683 }
11684 };
11685} // end anonymous namespace
11686
11687TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11688 SourceLocation Loc,
11689 DeclarationName Name) {
11690 if (!T || !T->getType()->isInstantiationDependentType())
11691 return T;
11692
11693 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11694 return Rebuilder.TransformType(TSI: T);
11695}
11696
11697ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11698 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11699 DeclarationName());
11700 return Rebuilder.TransformExpr(E);
11701}
11702
11703bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11704 if (SS.isInvalid())
11705 return true;
11706
11707 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11708 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11709 DeclarationName());
11710 NestedNameSpecifierLoc Rebuilt
11711 = Rebuilder.TransformNestedNameSpecifierLoc(NNS: QualifierLoc);
11712 if (!Rebuilt)
11713 return true;
11714
11715 SS.Adopt(Other: Rebuilt);
11716 return false;
11717}
11718
11719bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11720 TemplateParameterList *Params) {
11721 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11722 Decl *Param = Params->getParam(Idx: I);
11723
11724 // There is nothing to rebuild in a type parameter.
11725 if (isa<TemplateTypeParmDecl>(Val: Param))
11726 continue;
11727
11728 // Rebuild the template parameter list of a template template parameter.
11729 if (TemplateTemplateParmDecl *TTP
11730 = dyn_cast<TemplateTemplateParmDecl>(Val: Param)) {
11731 if (RebuildTemplateParamsInCurrentInstantiation(
11732 Params: TTP->getTemplateParameters()))
11733 return true;
11734
11735 continue;
11736 }
11737
11738 // Rebuild the type of a non-type template parameter.
11739 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Val: Param);
11740 TypeSourceInfo *NewTSI
11741 = RebuildTypeInCurrentInstantiation(T: NTTP->getTypeSourceInfo(),
11742 Loc: NTTP->getLocation(),
11743 Name: NTTP->getDeclName());
11744 if (!NewTSI)
11745 return true;
11746
11747 if (NewTSI->getType()->isUndeducedType()) {
11748 // C++17 [temp.dep.expr]p3:
11749 // An id-expression is type-dependent if it contains
11750 // - an identifier associated by name lookup with a non-type
11751 // template-parameter declared with a type that contains a
11752 // placeholder type (7.1.7.4),
11753 NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: NewTSI);
11754 }
11755
11756 if (NewTSI != NTTP->getTypeSourceInfo()) {
11757 NTTP->setTypeSourceInfo(NewTSI);
11758 NTTP->setType(NewTSI->getType());
11759 }
11760 }
11761
11762 return false;
11763}
11764
11765std::string
11766Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11767 const TemplateArgumentList &Args) {
11768 return getTemplateArgumentBindingsText(Params, Args: Args.data(), NumArgs: Args.size());
11769}
11770
11771std::string
11772Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11773 const TemplateArgument *Args,
11774 unsigned NumArgs) {
11775 SmallString<128> Str;
11776 llvm::raw_svector_ostream Out(Str);
11777
11778 if (!Params || Params->size() == 0 || NumArgs == 0)
11779 return std::string();
11780
11781 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11782 if (I >= NumArgs)
11783 break;
11784
11785 if (I == 0)
11786 Out << "[with ";
11787 else
11788 Out << ", ";
11789
11790 if (const IdentifierInfo *Id = Params->getParam(Idx: I)->getIdentifier()) {
11791 Out << Id->getName();
11792 } else {
11793 Out << '$' << I;
11794 }
11795
11796 Out << " = ";
11797 Args[I].print(Policy: getPrintingPolicy(), Out,
11798 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
11799 Policy: getPrintingPolicy(), TPL: Params, Idx: I));
11800 }
11801
11802 Out << ']';
11803 return std::string(Out.str());
11804}
11805
11806void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11807 CachedTokens &Toks) {
11808 if (!FD)
11809 return;
11810
11811 auto LPT = std::make_unique<LateParsedTemplate>();
11812
11813 // Take tokens to avoid allocations
11814 LPT->Toks.swap(RHS&: Toks);
11815 LPT->D = FnD;
11816 LPT->FPO = getCurFPFeatures();
11817 LateParsedTemplateMap.insert(KV: std::make_pair(x&: FD, y: std::move(LPT)));
11818
11819 FD->setLateTemplateParsed(true);
11820}
11821
11822void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11823 if (!FD)
11824 return;
11825 FD->setLateTemplateParsed(false);
11826}
11827
11828bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11829 DeclContext *DC = CurContext;
11830
11831 while (DC) {
11832 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
11833 const FunctionDecl *FD = RD->isLocalClass();
11834 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11835 } else if (DC->isTranslationUnit() || DC->isNamespace())
11836 return false;
11837
11838 DC = DC->getParent();
11839 }
11840 return false;
11841}
11842
11843namespace {
11844/// Walk the path from which a declaration was instantiated, and check
11845/// that every explicit specialization along that path is visible. This enforces
11846/// C++ [temp.expl.spec]/6:
11847///
11848/// If a template, a member template or a member of a class template is
11849/// explicitly specialized then that specialization shall be declared before
11850/// the first use of that specialization that would cause an implicit
11851/// instantiation to take place, in every translation unit in which such a
11852/// use occurs; no diagnostic is required.
11853///
11854/// and also C++ [temp.class.spec]/1:
11855///
11856/// A partial specialization shall be declared before the first use of a
11857/// class template specialization that would make use of the partial
11858/// specialization as the result of an implicit or explicit instantiation
11859/// in every translation unit in which such a use occurs; no diagnostic is
11860/// required.
11861class ExplicitSpecializationVisibilityChecker {
11862 Sema &S;
11863 SourceLocation Loc;
11864 llvm::SmallVector<Module *, 8> Modules;
11865 Sema::AcceptableKind Kind;
11866
11867public:
11868 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11869 Sema::AcceptableKind Kind)
11870 : S(S), Loc(Loc), Kind(Kind) {}
11871
11872 void check(NamedDecl *ND) {
11873 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
11874 return checkImpl(Spec: FD);
11875 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
11876 return checkImpl(Spec: RD);
11877 if (auto *VD = dyn_cast<VarDecl>(Val: ND))
11878 return checkImpl(Spec: VD);
11879 if (auto *ED = dyn_cast<EnumDecl>(Val: ND))
11880 return checkImpl(Spec: ED);
11881 }
11882
11883private:
11884 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11885 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11886 : Sema::MissingImportKind::ExplicitSpecialization;
11887 const bool Recover = true;
11888
11889 // If we got a custom set of modules (because only a subset of the
11890 // declarations are interesting), use them, otherwise let
11891 // diagnoseMissingImport intelligently pick some.
11892 if (Modules.empty())
11893 S.diagnoseMissingImport(Loc, Decl: D, MIK: Kind, Recover);
11894 else
11895 S.diagnoseMissingImport(Loc, Decl: D, DeclLoc: D->getLocation(), Modules, MIK: Kind, Recover);
11896 }
11897
11898 bool CheckMemberSpecialization(const NamedDecl *D) {
11899 return Kind == Sema::AcceptableKind::Visible
11900 ? S.hasVisibleMemberSpecialization(D)
11901 : S.hasReachableMemberSpecialization(D);
11902 }
11903
11904 bool CheckExplicitSpecialization(const NamedDecl *D) {
11905 return Kind == Sema::AcceptableKind::Visible
11906 ? S.hasVisibleExplicitSpecialization(D)
11907 : S.hasReachableExplicitSpecialization(D);
11908 }
11909
11910 bool CheckDeclaration(const NamedDecl *D) {
11911 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11912 : S.hasReachableDeclaration(D);
11913 }
11914
11915 // Check a specific declaration. There are three problematic cases:
11916 //
11917 // 1) The declaration is an explicit specialization of a template
11918 // specialization.
11919 // 2) The declaration is an explicit specialization of a member of an
11920 // templated class.
11921 // 3) The declaration is an instantiation of a template, and that template
11922 // is an explicit specialization of a member of a templated class.
11923 //
11924 // We don't need to go any deeper than that, as the instantiation of the
11925 // surrounding class / etc is not triggered by whatever triggered this
11926 // instantiation, and thus should be checked elsewhere.
11927 template<typename SpecDecl>
11928 void checkImpl(SpecDecl *Spec) {
11929 bool IsHiddenExplicitSpecialization = false;
11930 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11931 // Some invalid friend declarations are written as specializations but are
11932 // instantiated implicitly.
11933 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11934 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11935 if (SpecKind == TSK_ExplicitSpecialization) {
11936 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11937 ? !CheckMemberSpecialization(D: Spec)
11938 : !CheckExplicitSpecialization(D: Spec);
11939 } else {
11940 checkInstantiated(Spec);
11941 }
11942
11943 if (IsHiddenExplicitSpecialization)
11944 diagnose(D: Spec->getMostRecentDecl(), IsPartialSpec: false);
11945 }
11946
11947 void checkInstantiated(FunctionDecl *FD) {
11948 if (auto *TD = FD->getPrimaryTemplate())
11949 checkTemplate(TD);
11950 }
11951
11952 void checkInstantiated(CXXRecordDecl *RD) {
11953 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD);
11954 if (!SD)
11955 return;
11956
11957 auto From = SD->getSpecializedTemplateOrPartial();
11958 if (auto *TD = dyn_cast<ClassTemplateDecl *>(Val&: From))
11959 checkTemplate(TD);
11960 else if (auto *TD =
11961 dyn_cast<ClassTemplatePartialSpecializationDecl *>(Val&: From)) {
11962 if (!CheckDeclaration(D: TD))
11963 diagnose(D: TD, IsPartialSpec: true);
11964 checkTemplate(TD);
11965 }
11966 }
11967
11968 void checkInstantiated(VarDecl *RD) {
11969 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(Val: RD);
11970 if (!SD)
11971 return;
11972
11973 auto From = SD->getSpecializedTemplateOrPartial();
11974 if (auto *TD = dyn_cast<VarTemplateDecl *>(Val&: From))
11975 checkTemplate(TD);
11976 else if (auto *TD =
11977 dyn_cast<VarTemplatePartialSpecializationDecl *>(Val&: From)) {
11978 if (!CheckDeclaration(D: TD))
11979 diagnose(D: TD, IsPartialSpec: true);
11980 checkTemplate(TD);
11981 }
11982 }
11983
11984 void checkInstantiated(EnumDecl *FD) {}
11985
11986 template<typename TemplDecl>
11987 void checkTemplate(TemplDecl *TD) {
11988 if (TD->isMemberSpecialization()) {
11989 if (!CheckMemberSpecialization(D: TD))
11990 diagnose(D: TD->getMostRecentDecl(), IsPartialSpec: false);
11991 }
11992 }
11993};
11994} // end anonymous namespace
11995
11996void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
11997 if (!getLangOpts().Modules)
11998 return;
11999
12000 ExplicitSpecializationVisibilityChecker(*this, Loc,
12001 Sema::AcceptableKind::Visible)
12002 .check(ND: Spec);
12003}
12004
12005void Sema::checkSpecializationReachability(SourceLocation Loc,
12006 NamedDecl *Spec) {
12007 if (!getLangOpts().CPlusPlusModules)
12008 return checkSpecializationVisibility(Loc, Spec);
12009
12010 ExplicitSpecializationVisibilityChecker(*this, Loc,
12011 Sema::AcceptableKind::Reachable)
12012 .check(ND: Spec);
12013}
12014
12015SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
12016 if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
12017 return N->getLocation();
12018 if (const auto *FD = dyn_cast<FunctionDecl>(Val: N)) {
12019 if (!FD->isFunctionTemplateSpecialization())
12020 return FD->getLocation();
12021 } else if (!isa<ClassTemplateSpecializationDecl,
12022 VarTemplateSpecializationDecl>(Val: N)) {
12023 return N->getLocation();
12024 }
12025 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
12026 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
12027 continue;
12028 return CSC.PointOfInstantiation;
12029 }
12030 return N->getLocation();
12031}
12032