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/DeclFriend.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/DynamicRecursiveASTVisitor.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/TemplateName.h"
22#include "clang/AST/Type.h"
23#include "clang/AST/TypeOrdering.h"
24#include "clang/AST/TypeVisitor.h"
25#include "clang/Basic/Builtins.h"
26#include "clang/Basic/DiagnosticSema.h"
27#include "clang/Basic/LangOptions.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceLocation.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/EnterExpressionEvaluationContext.h"
33#include "clang/Sema/Initialization.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/Overload.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/SemaCUDA.h"
39#include "clang/Sema/SemaInternal.h"
40#include "clang/Sema/Template.h"
41#include "clang/Sema/TemplateDeduction.h"
42#include "llvm/ADT/SmallBitVector.h"
43#include "llvm/ADT/StringExtras.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/SaveAndRestore.h"
46
47#include <optional>
48using namespace clang;
49using namespace sema;
50
51// Exported for use by Parser.
52SourceRange
53clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
54 unsigned N) {
55 if (!N) return SourceRange();
56 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
57}
58
59unsigned Sema::getTemplateDepth(Scope *S) const {
60 unsigned Depth = 0;
61
62 // Each template parameter scope represents one level of template parameter
63 // depth.
64 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
65 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
66 ++Depth;
67 }
68
69 // Note that there are template parameters with the given depth.
70 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(a: Depth, b: D + 1); };
71
72 // Look for parameters of an enclosing generic lambda. We don't create a
73 // template parameter scope for these.
74 for (FunctionScopeInfo *FSI : getFunctionScopes()) {
75 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FSI)) {
76 if (!LSI->TemplateParams.empty()) {
77 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
78 break;
79 }
80 if (LSI->GLTemplateParameterList) {
81 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
82 break;
83 }
84 }
85 }
86
87 // Look for parameters of an enclosing terse function template. We don't
88 // create a template parameter scope for these either.
89 for (const InventedTemplateParameterInfo &Info :
90 getInventedParameterInfos()) {
91 if (!Info.TemplateParams.empty()) {
92 ParamsAtDepth(Info.AutoTemplateParameterDepth);
93 break;
94 }
95 }
96
97 return Depth;
98}
99
100/// \brief Determine whether the declaration found is acceptable as the name
101/// of a template and, if so, return that template declaration. Otherwise,
102/// returns null.
103///
104/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
105/// is true. In all other cases it will return a TemplateDecl (or null).
106NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
107 bool AllowFunctionTemplates,
108 bool AllowDependent) {
109 D = D->getUnderlyingDecl();
110
111 if (isa<TemplateDecl>(Val: D)) {
112 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(Val: D))
113 return nullptr;
114
115 return D;
116 }
117
118 if (const auto *Record = dyn_cast<CXXRecordDecl>(Val: D)) {
119 // C++ [temp.local]p1:
120 // Like normal (non-template) classes, class templates have an
121 // injected-class-name (Clause 9). The injected-class-name
122 // can be used with or without a template-argument-list. When
123 // it is used without a template-argument-list, it is
124 // equivalent to the injected-class-name followed by the
125 // template-parameters of the class template enclosed in
126 // <>. When it is used with a template-argument-list, it
127 // refers to the specified class template specialization,
128 // which could be the current specialization or another
129 // specialization.
130 if (Record->isInjectedClassName()) {
131 Record = cast<CXXRecordDecl>(Val: Record->getDeclContext());
132 if (Record->getDescribedClassTemplate())
133 return Record->getDescribedClassTemplate();
134
135 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record))
136 return Spec->getSpecializedTemplate();
137 }
138
139 return nullptr;
140 }
141
142 // 'using Dependent::foo;' can resolve to a template name.
143 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
144 // injected-class-name).
145 if (AllowDependent && isa<UnresolvedUsingValueDecl>(Val: D))
146 return D;
147
148 return nullptr;
149}
150
151void Sema::FilterAcceptableTemplateNames(LookupResult &R,
152 bool AllowFunctionTemplates,
153 bool AllowDependent) {
154 LookupResult::Filter filter = R.makeFilter();
155 while (filter.hasNext()) {
156 NamedDecl *Orig = filter.next();
157 if (!getAsTemplateNameDecl(D: Orig, AllowFunctionTemplates, AllowDependent))
158 filter.erase();
159 }
160 filter.done();
161}
162
163bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
164 bool AllowFunctionTemplates,
165 bool AllowDependent,
166 bool AllowNonTemplateFunctions) {
167 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
168 if (getAsTemplateNameDecl(D: *I, AllowFunctionTemplates, AllowDependent))
169 return true;
170 if (AllowNonTemplateFunctions &&
171 isa<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
172 return true;
173 }
174
175 return false;
176}
177
178TemplateNameKind Sema::isTemplateName(Scope *S,
179 CXXScopeSpec &SS,
180 bool hasTemplateKeyword,
181 const UnqualifiedId &Name,
182 ParsedType ObjectTypePtr,
183 bool EnteringContext,
184 TemplateTy &TemplateResult,
185 bool &MemberOfUnknownSpecialization,
186 bool Disambiguation) {
187 assert(getLangOpts().CPlusPlus && "No template names in C!");
188
189 DeclarationName TName;
190 MemberOfUnknownSpecialization = false;
191
192 switch (Name.getKind()) {
193 case UnqualifiedIdKind::IK_Identifier:
194 TName = DeclarationName(Name.Identifier);
195 break;
196
197 case UnqualifiedIdKind::IK_OperatorFunctionId:
198 TName = Context.DeclarationNames.getCXXOperatorName(
199 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,
217 /*AllowTypoCorrection=*/!Disambiguation))
218 return TNK_Non_template;
219 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
220
221 if (AssumedTemplate != AssumedTemplateKind::None) {
222 TemplateResult = TemplateTy::make(P: Context.getAssumedTemplateName(Name: TName));
223 // Let the parser know whether we found nothing or found functions; if we
224 // found nothing, we want to more carefully check whether this is actually
225 // a function template name versus some other kind of undeclared identifier.
226 return AssumedTemplate == AssumedTemplateKind::FoundNothing
227 ? TNK_Undeclared_template
228 : TNK_Function_template;
229 }
230
231 if (R.empty())
232 return TNK_Non_template;
233
234 NamedDecl *D = nullptr;
235 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *R.begin());
236 if (R.isAmbiguous()) {
237 // If we got an ambiguity involving a non-function template, treat this
238 // as a template name, and pick an arbitrary template for error recovery.
239 bool AnyFunctionTemplates = false;
240 for (NamedDecl *FoundD : R) {
241 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(D: FoundD)) {
242 if (isa<FunctionTemplateDecl>(Val: FoundTemplate))
243 AnyFunctionTemplates = true;
244 else {
245 D = FoundTemplate;
246 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: FoundD);
247 break;
248 }
249 }
250 }
251
252 // If we didn't find any templates at all, this isn't a template name.
253 // Leave the ambiguity for a later lookup to diagnose.
254 if (!D && !AnyFunctionTemplates) {
255 R.suppressDiagnostics();
256 return TNK_Non_template;
257 }
258
259 // If the only templates were function templates, filter out the rest.
260 // We'll diagnose the ambiguity later.
261 if (!D)
262 FilterAcceptableTemplateNames(R);
263 }
264
265 // At this point, we have either picked a single template name declaration D
266 // or we have a non-empty set of results R containing either one template name
267 // declaration or a set of function templates.
268
269 TemplateName Template;
270 TemplateNameKind TemplateKind;
271
272 unsigned ResultCount = R.end() - R.begin();
273 if (!D && ResultCount > 1) {
274 // We assume that we'll preserve the qualifier from a function
275 // template name in other ways.
276 Template = Context.getOverloadedTemplateName(Begin: R.begin(), End: R.end());
277 TemplateKind = TNK_Function_template;
278
279 // We'll do this lookup again later.
280 R.suppressDiagnostics();
281 } else {
282 if (!D) {
283 D = getAsTemplateNameDecl(D: *R.begin());
284 assert(D && "unambiguous result is not a template name");
285 }
286
287 if (isa<UnresolvedUsingValueDecl>(Val: D)) {
288 // We don't yet know whether this is a template-name or not.
289 MemberOfUnknownSpecialization = true;
290 return TNK_Non_template;
291 }
292
293 TemplateDecl *TD = cast<TemplateDecl>(Val: D);
294 Template =
295 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
296 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
297 if (!SS.isInvalid()) {
298 NestedNameSpecifier Qualifier = SS.getScopeRep();
299 Template = Context.getQualifiedTemplateName(Qualifier, TemplateKeyword: hasTemplateKeyword,
300 Template);
301 }
302
303 if (isa<FunctionTemplateDecl>(Val: TD)) {
304 TemplateKind = TNK_Function_template;
305
306 // We'll do this lookup again later.
307 R.suppressDiagnostics();
308 } else {
309 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
310 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
311 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
312 TemplateKind =
313 isa<TemplateTemplateParmDecl>(Val: TD)
314 ? dyn_cast<TemplateTemplateParmDecl>(Val: TD)->templateParameterKind()
315 : isa<VarTemplateDecl>(Val: TD) ? TNK_Var_template
316 : isa<ConceptDecl>(Val: TD) ? TNK_Concept_template
317 : TNK_Type_template;
318 }
319 }
320
321 if (isPackProducingBuiltinTemplateName(N: Template) && S &&
322 S->getTemplateParamParent() == nullptr)
323 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_builtin_pack_outside_template) << TName;
324 // Recover by returning the template, even though we would never be able to
325 // substitute it.
326
327 TemplateResult = TemplateTy::make(P: Template);
328 return TemplateKind;
329}
330
331bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
332 SourceLocation NameLoc, CXXScopeSpec &SS,
333 ParsedTemplateTy *Template /*=nullptr*/) {
334 // We could use redeclaration lookup here, but we don't need to: the
335 // syntactic form of a deduction guide is enough to identify it even
336 // if we can't look up the template name at all.
337 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
338 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
339 /*EnteringContext*/ false))
340 return false;
341
342 if (R.empty()) return false;
343 if (R.isAmbiguous()) {
344 // FIXME: Diagnose an ambiguity if we find at least one template.
345 R.suppressDiagnostics();
346 return false;
347 }
348
349 // We only treat template-names that name type templates as valid deduction
350 // guide names.
351 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
352 if (!TD || !getAsTypeTemplateDecl(D: TD))
353 return false;
354
355 if (Template) {
356 TemplateName Name = Context.getQualifiedTemplateName(
357 Qualifier: SS.getScopeRep(), /*TemplateKeyword=*/false, Template: TemplateName(TD));
358 *Template = TemplateTy::make(P: Name);
359 }
360 return true;
361}
362
363bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
364 SourceLocation IILoc,
365 Scope *S,
366 const CXXScopeSpec *SS,
367 TemplateTy &SuggestedTemplate,
368 TemplateNameKind &SuggestedKind) {
369 // We can't recover unless there's a dependent scope specifier preceding the
370 // template name.
371 // FIXME: Typo correction?
372 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(SS: *SS) ||
373 computeDeclContext(SS: *SS))
374 return false;
375
376 // The code is missing a 'template' keyword prior to the dependent template
377 // name.
378 SuggestedTemplate = TemplateTy::make(P: Context.getDependentTemplateName(
379 Name: {SS->getScopeRep(), &II, /*HasTemplateKeyword=*/false}));
380 Diag(Loc: IILoc, DiagID: diag::err_template_kw_missing)
381 << SuggestedTemplate.get()
382 << FixItHint::CreateInsertion(InsertionLoc: IILoc, Code: "template ");
383 SuggestedKind = TNK_Dependent_template_name;
384 return true;
385}
386
387bool Sema::LookupTemplateName(LookupResult &Found, Scope *S, CXXScopeSpec &SS,
388 QualType ObjectType, bool EnteringContext,
389 RequiredTemplateKind RequiredTemplate,
390 AssumedTemplateKind *ATK,
391 bool AllowTypoCorrection) {
392 if (ATK)
393 *ATK = AssumedTemplateKind::None;
394
395 if (SS.isInvalid())
396 return true;
397
398 Found.setTemplateNameLookup(true);
399
400 // Determine where to perform name lookup
401 DeclContext *LookupCtx = nullptr;
402 bool IsDependent = false;
403 if (!ObjectType.isNull()) {
404 // This nested-name-specifier occurs in a member access expression, e.g.,
405 // x->B::f, and we are looking into the type of the object.
406 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
407 LookupCtx = computeDeclContext(T: ObjectType);
408 IsDependent = !LookupCtx && ObjectType->isDependentType();
409 assert((IsDependent || !ObjectType->isIncompleteType() ||
410 !ObjectType->getAs<TagType>() ||
411 ObjectType->castAs<TagType>()->getDecl()->isEntityBeingDefined()) &&
412 "Caller should have completed object type");
413
414 // Template names cannot appear inside an Objective-C class or object type
415 // or a vector type.
416 //
417 // FIXME: This is wrong. For example:
418 //
419 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
420 // Vec<int> vi;
421 // vi.Vec<int>::~Vec<int>();
422 //
423 // ... should be accepted but we will not treat 'Vec' as a template name
424 // here. The right thing to do would be to check if the name is a valid
425 // vector component name, and look up a template name if not. And similarly
426 // for lookups into Objective-C class and object types, where the same
427 // problem can arise.
428 if (ObjectType->isObjCObjectOrInterfaceType() ||
429 ObjectType->isVectorType()) {
430 Found.clear();
431 return false;
432 }
433 } else if (SS.isNotEmpty()) {
434 // This nested-name-specifier occurs after another nested-name-specifier,
435 // so long into the context associated with the prior nested-name-specifier.
436 LookupCtx = computeDeclContext(SS, EnteringContext);
437 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
438
439 // The declaration context must be complete.
440 if (LookupCtx && RequireCompleteDeclContext(SS, DC: LookupCtx))
441 return true;
442 }
443
444 bool ObjectTypeSearchedInScope = false;
445 bool AllowFunctionTemplatesInLookup = true;
446 if (LookupCtx) {
447 // Perform "qualified" name lookup into the declaration context we
448 // computed, which is either the type of the base of a member access
449 // expression or the declaration context associated with a prior
450 // nested-name-specifier.
451 LookupQualifiedName(R&: Found, LookupCtx);
452
453 // FIXME: The C++ standard does not clearly specify what happens in the
454 // case where the object type is dependent, and implementations vary. In
455 // Clang, we treat a name after a . or -> as a template-name if lookup
456 // finds a non-dependent member or member of the current instantiation that
457 // is a type template, or finds no such members and lookup in the context
458 // of the postfix-expression finds a type template. In the latter case, the
459 // name is nonetheless dependent, and we may resolve it to a member of an
460 // unknown specialization when we come to instantiate the template.
461 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
462 }
463
464 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
465 // C++ [basic.lookup.classref]p1:
466 // In a class member access expression (5.2.5), if the . or -> token is
467 // immediately followed by an identifier followed by a <, the
468 // identifier must be looked up to determine whether the < is the
469 // beginning of a template argument list (14.2) or a less-than operator.
470 // The identifier is first looked up in the class of the object
471 // expression. If the identifier is not found, it is then looked up in
472 // the context of the entire postfix-expression and shall name a class
473 // template.
474 if (S)
475 LookupName(R&: Found, S);
476
477 if (!ObjectType.isNull()) {
478 // FIXME: We should filter out all non-type templates here, particularly
479 // variable templates and concepts. But the exclusion of alias templates
480 // and template template parameters is a wording defect.
481 AllowFunctionTemplatesInLookup = false;
482 ObjectTypeSearchedInScope = true;
483 }
484
485 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
486 }
487
488 if (Found.isAmbiguous())
489 return false;
490
491 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
492 !RequiredTemplate.hasTemplateKeyword()) {
493 // C++2a [temp.names]p2:
494 // A name is also considered to refer to a template if it is an
495 // unqualified-id followed by a < and name lookup finds either one or more
496 // functions or finds nothing.
497 //
498 // To keep our behavior consistent, we apply the "finds nothing" part in
499 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
500 // successfully form a call to an undeclared template-id.
501 bool AllFunctions =
502 getLangOpts().CPlusPlus20 && llvm::all_of(Range&: Found, P: [](NamedDecl *ND) {
503 return isa<FunctionDecl>(Val: ND->getUnderlyingDecl());
504 });
505 if (AllFunctions || (Found.empty() && !IsDependent)) {
506 // If lookup found any functions, or if this is a name that can only be
507 // used for a function, then strongly assume this is a function
508 // template-id.
509 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
510 ? AssumedTemplateKind::FoundNothing
511 : AssumedTemplateKind::FoundFunctions;
512 Found.clear();
513 return false;
514 }
515 }
516
517 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
518 // If we did not find any names, and this is not a disambiguation, attempt
519 // to correct any typos.
520 DeclarationName Name = Found.getLookupName();
521 Found.clear();
522 // Simple filter callback that, for keywords, only accepts the C++ *_cast
523 DefaultFilterCCC FilterCCC{};
524 FilterCCC.WantTypeSpecifiers = false;
525 FilterCCC.WantExpressionKeywords = false;
526 FilterCCC.WantRemainingKeywords = false;
527 FilterCCC.WantCXXNamedCasts = true;
528 if (TypoCorrection Corrected = CorrectTypo(
529 Typo: Found.getLookupNameInfo(), LookupKind: Found.getLookupKind(), S, SS: &SS, CCC&: FilterCCC,
530 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
531 if (auto *ND = Corrected.getFoundDecl())
532 Found.addDecl(D: ND);
533 FilterAcceptableTemplateNames(R&: Found);
534 if (Found.isAmbiguous()) {
535 Found.clear();
536 } else if (!Found.empty()) {
537 // Do not erase the typo-corrected result to avoid duplicated
538 // diagnostics.
539 AllowFunctionTemplatesInLookup = true;
540 Found.setLookupName(Corrected.getCorrection());
541 if (LookupCtx) {
542 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
543 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
544 Name.getAsString() == CorrectedStr;
545 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_template_suggest)
546 << Name << LookupCtx << DroppedSpecifier
547 << SS.getRange());
548 } else {
549 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_template_suggest) << Name);
550 }
551 }
552 }
553 }
554
555 NamedDecl *ExampleLookupResult =
556 Found.empty() ? nullptr : Found.getRepresentativeDecl();
557 FilterAcceptableTemplateNames(R&: Found, AllowFunctionTemplates: AllowFunctionTemplatesInLookup);
558 if (Found.empty()) {
559 if (IsDependent) {
560 Found.setNotFoundInCurrentInstantiation();
561 return false;
562 }
563
564 // If a 'template' keyword was used, a lookup that finds only non-template
565 // names is an error.
566 if (ExampleLookupResult && RequiredTemplate) {
567 Diag(Loc: Found.getNameLoc(), DiagID: diag::err_template_kw_refers_to_non_template)
568 << Found.getLookupName() << SS.getRange()
569 << RequiredTemplate.hasTemplateKeyword()
570 << RequiredTemplate.getTemplateKeywordLoc();
571 Diag(Loc: ExampleLookupResult->getUnderlyingDecl()->getLocation(),
572 DiagID: diag::note_template_kw_refers_to_non_template)
573 << Found.getLookupName();
574 return true;
575 }
576
577 return false;
578 }
579
580 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
581 !getLangOpts().CPlusPlus11) {
582 // C++03 [basic.lookup.classref]p1:
583 // [...] If the lookup in the class of the object expression finds a
584 // template, the name is also looked up in the context of the entire
585 // postfix-expression and [...]
586 //
587 // Note: C++11 does not perform this second lookup.
588 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
589 LookupOrdinaryName);
590 FoundOuter.setTemplateNameLookup(true);
591 LookupName(R&: FoundOuter, S);
592 // FIXME: We silently accept an ambiguous lookup here, in violation of
593 // [basic.lookup]/1.
594 FilterAcceptableTemplateNames(R&: FoundOuter, /*AllowFunctionTemplates=*/false);
595
596 NamedDecl *OuterTemplate;
597 if (FoundOuter.empty()) {
598 // - if the name is not found, the name found in the class of the
599 // object expression is used, otherwise
600 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
601 !(OuterTemplate =
602 getAsTemplateNameDecl(D: FoundOuter.getFoundDecl()))) {
603 // - if the name is found in the context of the entire
604 // postfix-expression and does not name a class template, the name
605 // found in the class of the object expression is used, otherwise
606 FoundOuter.clear();
607 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
608 // - if the name found is a class template, it must refer to the same
609 // entity as the one found in the class of the object expression,
610 // otherwise the program is ill-formed.
611 if (!Found.isSingleResult() ||
612 getAsTemplateNameDecl(D: Found.getFoundDecl())->getCanonicalDecl() !=
613 OuterTemplate->getCanonicalDecl()) {
614 Diag(Loc: Found.getNameLoc(),
615 DiagID: diag::ext_nested_name_member_ref_lookup_ambiguous)
616 << Found.getLookupName()
617 << ObjectType;
618 Diag(Loc: Found.getRepresentativeDecl()->getLocation(),
619 DiagID: diag::note_ambig_member_ref_object_type)
620 << ObjectType;
621 Diag(Loc: FoundOuter.getFoundDecl()->getLocation(),
622 DiagID: diag::note_ambig_member_ref_scope);
623
624 // Recover by taking the template that we found in the object
625 // expression's type.
626 }
627 }
628 }
629
630 return false;
631}
632
633void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
634 SourceLocation Less,
635 SourceLocation Greater) {
636 if (TemplateName.isInvalid())
637 return;
638
639 DeclarationNameInfo NameInfo;
640 CXXScopeSpec SS;
641 LookupNameKind LookupKind;
642
643 DeclContext *LookupCtx = nullptr;
644 NamedDecl *Found = nullptr;
645 bool MissingTemplateKeyword = false;
646
647 // Figure out what name we looked up.
648 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: TemplateName.get())) {
649 NameInfo = DRE->getNameInfo();
650 SS.Adopt(Other: DRE->getQualifierLoc());
651 LookupKind = LookupOrdinaryName;
652 Found = DRE->getFoundDecl();
653 } else if (auto *ME = dyn_cast<MemberExpr>(Val: TemplateName.get())) {
654 NameInfo = ME->getMemberNameInfo();
655 SS.Adopt(Other: ME->getQualifierLoc());
656 LookupKind = LookupMemberName;
657 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
658 Found = ME->getMemberDecl();
659 } else if (auto *DSDRE =
660 dyn_cast<DependentScopeDeclRefExpr>(Val: TemplateName.get())) {
661 NameInfo = DSDRE->getNameInfo();
662 SS.Adopt(Other: DSDRE->getQualifierLoc());
663 MissingTemplateKeyword = true;
664 } else if (auto *DSME =
665 dyn_cast<CXXDependentScopeMemberExpr>(Val: TemplateName.get())) {
666 NameInfo = DSME->getMemberNameInfo();
667 SS.Adopt(Other: DSME->getQualifierLoc());
668 MissingTemplateKeyword = true;
669 } else {
670 llvm_unreachable("unexpected kind of potential template name");
671 }
672
673 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
674 // was missing.
675 if (MissingTemplateKeyword) {
676 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_template_kw_missing)
677 << NameInfo.getName() << SourceRange(Less, Greater);
678 return;
679 }
680
681 // Try to correct the name by looking for templates and C++ named casts.
682 struct TemplateCandidateFilter : CorrectionCandidateCallback {
683 Sema &S;
684 TemplateCandidateFilter(Sema &S) : S(S) {
685 WantTypeSpecifiers = false;
686 WantExpressionKeywords = false;
687 WantRemainingKeywords = false;
688 WantCXXNamedCasts = true;
689 };
690 bool ValidateCandidate(const TypoCorrection &Candidate) override {
691 if (auto *ND = Candidate.getCorrectionDecl())
692 return S.getAsTemplateNameDecl(D: ND);
693 return Candidate.isKeyword();
694 }
695
696 std::unique_ptr<CorrectionCandidateCallback> clone() override {
697 return std::make_unique<TemplateCandidateFilter>(args&: *this);
698 }
699 };
700
701 DeclarationName Name = NameInfo.getName();
702 TemplateCandidateFilter CCC(*this);
703 if (TypoCorrection Corrected =
704 CorrectTypo(Typo: NameInfo, LookupKind, S, SS: &SS, CCC,
705 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
706 auto *ND = Corrected.getFoundDecl();
707 if (ND)
708 ND = getAsTemplateNameDecl(D: ND);
709 if (ND || Corrected.isKeyword()) {
710 if (LookupCtx) {
711 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
712 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
713 Name.getAsString() == CorrectedStr;
714 diagnoseTypo(Correction: Corrected,
715 TypoDiag: PDiag(DiagID: diag::err_non_template_in_member_template_id_suggest)
716 << Name << LookupCtx << DroppedSpecifier
717 << SS.getRange(), ErrorRecovery: false);
718 } else {
719 diagnoseTypo(Correction: Corrected,
720 TypoDiag: PDiag(DiagID: diag::err_non_template_in_template_id_suggest)
721 << Name, ErrorRecovery: false);
722 }
723 if (Found)
724 Diag(Loc: Found->getLocation(),
725 DiagID: diag::note_non_template_in_template_id_found);
726 return;
727 }
728 }
729
730 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_non_template_in_template_id)
731 << Name << SourceRange(Less, Greater);
732 if (Found)
733 Diag(Loc: Found->getLocation(), DiagID: diag::note_non_template_in_template_id_found);
734}
735
736ExprResult
737Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
738 SourceLocation TemplateKWLoc,
739 const DeclarationNameInfo &NameInfo,
740 bool isAddressOfOperand,
741 const TemplateArgumentListInfo *TemplateArgs) {
742 if (SS.isEmpty()) {
743 // FIXME: This codepath is only used by dependent unqualified names
744 // (e.g. a dependent conversion-function-id, or operator= once we support
745 // it). It doesn't quite do the right thing, and it will silently fail if
746 // getCurrentThisType() returns null.
747 QualType ThisType = getCurrentThisType();
748 if (ThisType.isNull())
749 return ExprError();
750
751 return CXXDependentScopeMemberExpr::Create(
752 Ctx: Context, /*Base=*/nullptr, BaseType: ThisType,
753 /*IsArrow=*/!Context.getLangOpts().HLSL,
754 /*OperatorLoc=*/SourceLocation(),
755 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
756 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
757 }
758 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
759}
760
761ExprResult
762Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
763 SourceLocation TemplateKWLoc,
764 const DeclarationNameInfo &NameInfo,
765 const TemplateArgumentListInfo *TemplateArgs) {
766 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
767 if (!SS.isValid())
768 return CreateRecoveryExpr(
769 Begin: SS.getBeginLoc(),
770 End: TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), SubExprs: {});
771
772 return DependentScopeDeclRefExpr::Create(
773 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
774 TemplateArgs);
775}
776
777ExprResult Sema::BuildSubstNonTypeTemplateParmExpr(
778 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP,
779 SourceLocation Loc, TemplateArgument Arg, UnsignedOrNone PackIndex,
780 bool Final) {
781 // The template argument itself might be an expression, in which case we just
782 // return that expression. This happens when substituting into an alias
783 // template.
784 Expr *Replacement;
785 bool refParam = true;
786 if (Arg.getKind() == TemplateArgument::Expression) {
787 Replacement = Arg.getAsExpr();
788 refParam = Replacement->isLValue();
789 if (refParam && Replacement->getType()->isRecordType()) {
790 QualType ParamType =
791 NTTP->isExpandedParameterPack()
792 ? NTTP->getExpansionType(I: *SemaRef.ArgPackSubstIndex)
793 : NTTP->getType();
794 if (const auto *PET = dyn_cast<PackExpansionType>(Val&: ParamType))
795 ParamType = PET->getPattern();
796 refParam = ParamType->isReferenceType();
797 }
798 } else {
799 ExprResult result =
800 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
801 if (result.isInvalid())
802 return ExprError();
803 Replacement = result.get();
804 refParam = Arg.getNonTypeTemplateArgumentType()->isReferenceType();
805 }
806 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
807 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
808 AssociatedDecl, NTTP->getIndex(), PackIndex, refParam, Final);
809}
810
811bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
812 NamedDecl *Instantiation,
813 bool InstantiatedFromMember,
814 const NamedDecl *Pattern,
815 const NamedDecl *PatternDef,
816 TemplateSpecializationKind TSK,
817 bool Complain, bool *Unreachable) {
818 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
819 isa<VarDecl>(Instantiation));
820
821 bool IsEntityBeingDefined = false;
822 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(Val: PatternDef))
823 IsEntityBeingDefined = TD->isBeingDefined();
824
825 if (PatternDef && !IsEntityBeingDefined) {
826 NamedDecl *SuggestedDef = nullptr;
827 if (!hasReachableDefinition(D: const_cast<NamedDecl *>(PatternDef),
828 Suggested: &SuggestedDef,
829 /*OnlyNeedComplete*/ false)) {
830 if (Unreachable)
831 *Unreachable = true;
832 // If we're allowed to diagnose this and recover, do so.
833 bool Recover = Complain && !isSFINAEContext();
834 if (Complain)
835 diagnoseMissingImport(Loc: PointOfInstantiation, Decl: SuggestedDef,
836 MIK: Sema::MissingImportKind::Definition, Recover);
837 return !Recover;
838 }
839 return false;
840 }
841
842 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
843 return true;
844
845 CanQualType InstantiationTy;
846 if (TagDecl *TD = dyn_cast<TagDecl>(Val: Instantiation))
847 InstantiationTy = Context.getCanonicalTagType(TD);
848 if (PatternDef) {
849 Diag(Loc: PointOfInstantiation,
850 DiagID: diag::err_template_instantiate_within_definition)
851 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
852 << InstantiationTy;
853 // Not much point in noting the template declaration here, since
854 // we're lexically inside it.
855 Instantiation->setInvalidDecl();
856 } else if (InstantiatedFromMember) {
857 if (isa<FunctionDecl>(Val: Instantiation)) {
858 Diag(Loc: PointOfInstantiation,
859 DiagID: diag::err_explicit_instantiation_undefined_member)
860 << /*member function*/ 1 << Instantiation->getDeclName()
861 << Instantiation->getDeclContext();
862 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
863 } else {
864 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
865 Diag(Loc: PointOfInstantiation,
866 DiagID: diag::err_implicit_instantiate_member_undefined)
867 << InstantiationTy;
868 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_member_declared_at);
869 }
870 } else {
871 if (isa<FunctionDecl>(Val: Instantiation)) {
872 Diag(Loc: PointOfInstantiation,
873 DiagID: diag::err_explicit_instantiation_undefined_func_template)
874 << Pattern;
875 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
876 } else if (isa<TagDecl>(Val: Instantiation)) {
877 Diag(Loc: PointOfInstantiation, DiagID: diag::err_template_instantiate_undefined)
878 << (TSK != TSK_ImplicitInstantiation)
879 << InstantiationTy;
880 NoteTemplateLocation(Decl: *Pattern);
881 } else {
882 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
883 if (isa<VarTemplateSpecializationDecl>(Val: Instantiation)) {
884 Diag(Loc: PointOfInstantiation,
885 DiagID: diag::err_explicit_instantiation_undefined_var_template)
886 << Instantiation;
887 Instantiation->setInvalidDecl();
888 } else
889 Diag(Loc: PointOfInstantiation,
890 DiagID: diag::err_explicit_instantiation_undefined_member)
891 << /*static data member*/ 2 << Instantiation->getDeclName()
892 << Instantiation->getDeclContext();
893 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
894 }
895 }
896
897 // In general, Instantiation isn't marked invalid to get more than one
898 // error for multiple undefined instantiations. But the code that does
899 // explicit declaration -> explicit definition conversion can't handle
900 // invalid declarations, so mark as invalid in that case.
901 if (TSK == TSK_ExplicitInstantiationDeclaration)
902 Instantiation->setInvalidDecl();
903 return true;
904}
905
906void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
907 bool SupportedForCompatibility) {
908 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
909
910 // C++23 [temp.local]p6:
911 // The name of a template-parameter shall not be bound to any following.
912 // declaration whose locus is contained by the scope to which the
913 // template-parameter belongs.
914 //
915 // When MSVC compatibility is enabled, the diagnostic is always a warning
916 // by default. Otherwise, it an error unless SupportedForCompatibility is
917 // true, in which case it is a default-to-error warning.
918 unsigned DiagId =
919 getLangOpts().MSVCCompat
920 ? diag::ext_template_param_shadow
921 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
922 : diag::err_template_param_shadow);
923 const auto *ND = cast<NamedDecl>(Val: PrevDecl);
924 Diag(Loc, DiagID: DiagId) << ND->getDeclName();
925 NoteTemplateParameterLocation(Decl: *ND);
926}
927
928TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
929 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(Val: D)) {
930 D = Temp->getTemplatedDecl();
931 return Temp;
932 }
933 return nullptr;
934}
935
936ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
937 SourceLocation EllipsisLoc) const {
938 assert(Kind == Template &&
939 "Only template template arguments can be pack expansions here");
940 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
941 "Template template argument pack expansion without packs");
942 ParsedTemplateArgument Result(*this);
943 Result.EllipsisLoc = EllipsisLoc;
944 return Result;
945}
946
947static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
948 const ParsedTemplateArgument &Arg) {
949
950 switch (Arg.getKind()) {
951 case ParsedTemplateArgument::Type: {
952 TypeSourceInfo *TSI;
953 QualType T = SemaRef.GetTypeFromParser(Ty: Arg.getAsType(), TInfo: &TSI);
954 if (!TSI)
955 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc: Arg.getNameLoc());
956 return TemplateArgumentLoc(TemplateArgument(T), TSI);
957 }
958
959 case ParsedTemplateArgument::NonType: {
960 Expr *E = Arg.getAsExpr();
961 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
962 }
963
964 case ParsedTemplateArgument::Template: {
965 TemplateName Template = Arg.getAsTemplate().get();
966 TemplateArgument TArg;
967 if (Arg.getEllipsisLoc().isValid())
968 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
969 else
970 TArg = Template;
971 return TemplateArgumentLoc(
972 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
973 Arg.getScopeSpec().getWithLocInContext(Context&: SemaRef.Context),
974 Arg.getNameLoc(), Arg.getEllipsisLoc());
975 }
976 }
977
978 llvm_unreachable("Unhandled parsed template argument");
979}
980
981void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
982 TemplateArgumentListInfo &TemplateArgs) {
983 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
984 TemplateArgs.addArgument(Loc: translateTemplateArgument(SemaRef&: *this,
985 Arg: TemplateArgsIn[I]));
986}
987
988static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
989 SourceLocation Loc,
990 const IdentifierInfo *Name) {
991 NamedDecl *PrevDecl =
992 SemaRef.LookupSingleName(S, Name, Loc, NameKind: Sema::LookupOrdinaryName,
993 Redecl: RedeclarationKind::ForVisibleRedeclaration);
994 if (PrevDecl && PrevDecl->isTemplateParameter())
995 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
996}
997
998ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
999 TypeSourceInfo *TInfo;
1000 QualType T = GetTypeFromParser(Ty: ParsedType.get(), TInfo: &TInfo);
1001 if (T.isNull())
1002 return ParsedTemplateArgument();
1003 assert(TInfo && "template argument with no location");
1004
1005 // If we might have formed a deduced template specialization type, convert
1006 // it to a template template argument.
1007 if (getLangOpts().CPlusPlus17) {
1008 TypeLoc TL = TInfo->getTypeLoc();
1009 SourceLocation EllipsisLoc;
1010 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1011 EllipsisLoc = PET.getEllipsisLoc();
1012 TL = PET.getPatternLoc();
1013 }
1014
1015 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1016 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1017 CXXScopeSpec SS;
1018 SS.Adopt(Other: DTST.getQualifierLoc());
1019 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1020 TemplateTy::make(P: Name),
1021 DTST.getTemplateNameLoc());
1022 if (EllipsisLoc.isValid())
1023 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1024 return Result;
1025 }
1026 }
1027
1028 // This is a normal type template argument. Note, if the type template
1029 // argument is an injected-class-name for a template, it has a dual nature
1030 // and can be used as either a type or a template. We handle that in
1031 // convertTypeTemplateArgumentToTemplate.
1032 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1033 ParsedType.get().getAsOpaquePtr(),
1034 TInfo->getTypeLoc().getBeginLoc());
1035}
1036
1037NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
1038 SourceLocation EllipsisLoc,
1039 SourceLocation KeyLoc,
1040 IdentifierInfo *ParamName,
1041 SourceLocation ParamNameLoc,
1042 unsigned Depth, unsigned Position,
1043 SourceLocation EqualLoc,
1044 ParsedType DefaultArg,
1045 bool HasTypeConstraint) {
1046 assert(S->isTemplateParamScope() &&
1047 "Template type parameter not in template parameter scope!");
1048
1049 bool IsParameterPack = EllipsisLoc.isValid();
1050 TemplateTypeParmDecl *Param
1051 = TemplateTypeParmDecl::Create(C: Context, DC: Context.getTranslationUnitDecl(),
1052 KeyLoc, NameLoc: ParamNameLoc, D: Depth, P: Position,
1053 Id: ParamName, Typename, ParameterPack: IsParameterPack,
1054 HasTypeConstraint);
1055 Param->setAccess(AS_public);
1056
1057 if (Param->isParameterPack())
1058 if (auto *CSI = getEnclosingLambdaOrBlock())
1059 CSI->LocalPacks.push_back(Elt: Param);
1060
1061 if (ParamName) {
1062 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: ParamNameLoc, Name: ParamName);
1063
1064 // Add the template parameter into the current scope.
1065 S->AddDecl(D: Param);
1066 IdResolver.AddDecl(D: Param);
1067 }
1068
1069 // C++0x [temp.param]p9:
1070 // A default template-argument may be specified for any kind of
1071 // template-parameter that is not a template parameter pack.
1072 if (DefaultArg && IsParameterPack) {
1073 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1074 DefaultArg = nullptr;
1075 }
1076
1077 // Handle the default argument, if provided.
1078 if (DefaultArg) {
1079 TypeSourceInfo *DefaultTInfo;
1080 GetTypeFromParser(Ty: DefaultArg, TInfo: &DefaultTInfo);
1081
1082 assert(DefaultTInfo && "expected source information for type");
1083
1084 // Check for unexpanded parameter packs.
1085 if (DiagnoseUnexpandedParameterPack(Loc: ParamNameLoc, T: DefaultTInfo,
1086 UPPC: UPPC_DefaultArgument))
1087 return Param;
1088
1089 // Check the template argument itself.
1090 if (CheckTemplateArgument(Arg: DefaultTInfo)) {
1091 Param->setInvalidDecl();
1092 return Param;
1093 }
1094
1095 Param->setDefaultArgument(
1096 C: Context, DefArg: TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1097 }
1098
1099 return Param;
1100}
1101
1102/// Convert the parser's template argument list representation into our form.
1103static TemplateArgumentListInfo
1104makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1105 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1106 TemplateId.RAngleLoc);
1107 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1108 TemplateId.NumArgs);
1109 S.translateTemplateArguments(TemplateArgsIn: TemplateArgsPtr, TemplateArgs);
1110 return TemplateArgs;
1111}
1112
1113bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {
1114
1115 TemplateName TN = TypeConstr->Template.get();
1116 NamedDecl *CD = nullptr;
1117 bool IsTypeConcept = false;
1118 bool RequiresArguments = false;
1119 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: TN.getAsTemplateDecl())) {
1120 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1121 RequiresArguments =
1122 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1123 CD = TTP;
1124 } else {
1125 CD = TN.getAsTemplateDecl();
1126 IsTypeConcept = cast<ConceptDecl>(Val: CD)->isTypeConcept();
1127 RequiresArguments = cast<ConceptDecl>(Val: CD)
1128 ->getTemplateParameters()
1129 ->getMinRequiredArguments() > 1;
1130 }
1131
1132 // C++2a [temp.param]p4:
1133 // [...] The concept designated by a type-constraint shall be a type
1134 // concept ([temp.concept]).
1135 if (!IsTypeConcept) {
1136 Diag(Loc: TypeConstr->TemplateNameLoc,
1137 DiagID: diag::err_type_constraint_non_type_concept);
1138 return true;
1139 }
1140
1141 if (CheckConceptUseInDefinition(Concept: CD, Loc: TypeConstr->TemplateNameLoc))
1142 return true;
1143
1144 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1145
1146 if (!WereArgsSpecified && RequiresArguments) {
1147 Diag(Loc: TypeConstr->TemplateNameLoc,
1148 DiagID: diag::err_type_constraint_missing_arguments)
1149 << CD;
1150 return true;
1151 }
1152 return false;
1153}
1154
1155bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1156 TemplateIdAnnotation *TypeConstr,
1157 TemplateTypeParmDecl *ConstrainedParameter,
1158 SourceLocation EllipsisLoc) {
1159 return BuildTypeConstraint(SS, TypeConstraint: TypeConstr, ConstrainedParameter, EllipsisLoc,
1160 AllowUnexpandedPack: false);
1161}
1162
1163bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1164 TemplateIdAnnotation *TypeConstr,
1165 TemplateTypeParmDecl *ConstrainedParameter,
1166 SourceLocation EllipsisLoc,
1167 bool AllowUnexpandedPack) {
1168
1169 if (CheckTypeConstraint(TypeConstr))
1170 return true;
1171
1172 TemplateName TN = TypeConstr->Template.get();
1173 TemplateDecl *CD = cast<TemplateDecl>(Val: TN.getAsTemplateDecl());
1174 UsingShadowDecl *USD = TN.getAsUsingShadowDecl();
1175
1176 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1177 TypeConstr->TemplateNameLoc);
1178
1179 TemplateArgumentListInfo TemplateArgs;
1180 if (TypeConstr->LAngleLoc.isValid()) {
1181 TemplateArgs =
1182 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TypeConstr);
1183
1184 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1185 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1186 if (DiagnoseUnexpandedParameterPack(Arg, UPPC: UPPC_TypeConstraint))
1187 return true;
1188 }
1189 }
1190 }
1191 return AttachTypeConstraint(
1192 NS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1193 NameInfo: ConceptName, NamedConcept: CD, /*FoundDecl=*/USD ? cast<NamedDecl>(Val: USD) : CD,
1194 TemplateArgs: TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1195 ConstrainedParameter, EllipsisLoc);
1196}
1197
1198template <typename ArgumentLocAppender>
1199static ExprResult formImmediatelyDeclaredConstraint(
1200 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1201 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1202 SourceLocation RAngleLoc, QualType ConstrainedType,
1203 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1204 SourceLocation EllipsisLoc) {
1205
1206 TemplateArgumentListInfo ConstraintArgs;
1207 ConstraintArgs.addArgument(
1208 Loc: S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(ConstrainedType),
1209 /*NTTPType=*/QualType(), Loc: ParamNameLoc));
1210
1211 ConstraintArgs.setRAngleLoc(RAngleLoc);
1212 ConstraintArgs.setLAngleLoc(LAngleLoc);
1213 Appender(ConstraintArgs);
1214
1215 // C++2a [temp.param]p4:
1216 // [...] This constraint-expression E is called the immediately-declared
1217 // constraint of T. [...]
1218 CXXScopeSpec SS;
1219 SS.Adopt(Other: NS);
1220 ExprResult ImmediatelyDeclaredConstraint;
1221 if (auto *CD = dyn_cast<ConceptDecl>(Val: NamedConcept)) {
1222 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1223 SS, /*TemplateKWLoc=*/SourceLocation(), ConceptNameInfo: NameInfo,
1224 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, NamedConcept: CD, TemplateArgs: &ConstraintArgs,
1225 /*DoCheckConstraintSatisfaction=*/
1226 !S.inParameterMappingSubstitution());
1227 }
1228 // We have a template template parameter
1229 else {
1230 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(Val: NamedConcept);
1231 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1232 SS, NameInfo, Template: CDT, TemplateLoc: SourceLocation(), TemplateArgs: &ConstraintArgs);
1233 }
1234 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1235 return ImmediatelyDeclaredConstraint;
1236
1237 // C++2a [temp.param]p4:
1238 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1239 //
1240 // We have the following case:
1241 //
1242 // template<typename T> concept C1 = true;
1243 // template<C1... T> struct s1;
1244 //
1245 // The constraint: (C1<T> && ...)
1246 //
1247 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1248 // any unqualified lookups for 'operator&&' here.
1249 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/Callee: nullptr,
1250 /*LParenLoc=*/SourceLocation(),
1251 LHS: ImmediatelyDeclaredConstraint.get(), Operator: BO_LAnd,
1252 EllipsisLoc, /*RHS=*/nullptr,
1253 /*RParenLoc=*/SourceLocation(),
1254 /*NumExpansions=*/std::nullopt);
1255}
1256
1257bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1258 DeclarationNameInfo NameInfo,
1259 TemplateDecl *NamedConcept,
1260 NamedDecl *FoundDecl,
1261 const TemplateArgumentListInfo *TemplateArgs,
1262 TemplateTypeParmDecl *ConstrainedParameter,
1263 SourceLocation EllipsisLoc) {
1264 // C++2a [temp.param]p4:
1265 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1266 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1267 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1268 TemplateArgs ? ASTTemplateArgumentListInfo::Create(C: Context,
1269 List: *TemplateArgs) : nullptr;
1270
1271 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1272
1273 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1274 S&: *this, NS, NameInfo, NamedConcept, FoundDecl,
1275 LAngleLoc: TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1276 RAngleLoc: TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1277 ConstrainedType: ParamAsArgument, ParamNameLoc: ConstrainedParameter->getLocation(),
1278 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1279 if (TemplateArgs)
1280 for (const auto &ArgLoc : TemplateArgs->arguments())
1281 ConstraintArgs.addArgument(Loc: ArgLoc);
1282 },
1283 EllipsisLoc);
1284 if (ImmediatelyDeclaredConstraint.isInvalid())
1285 return true;
1286
1287 auto *CL = ConceptReference::Create(C: Context, /*NNS=*/NS,
1288 /*TemplateKWLoc=*/SourceLocation{},
1289 /*ConceptNameInfo=*/NameInfo,
1290 /*FoundDecl=*/FoundDecl,
1291 /*NamedConcept=*/NamedConcept,
1292 /*ArgsWritten=*/ArgsAsWritten);
1293 ConstrainedParameter->setTypeConstraint(
1294 CR: CL, ImmediatelyDeclaredConstraint: ImmediatelyDeclaredConstraint.get(), ArgPackSubstIndex: std::nullopt);
1295 return false;
1296}
1297
1298bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
1299 NonTypeTemplateParmDecl *NewConstrainedParm,
1300 NonTypeTemplateParmDecl *OrigConstrainedParm,
1301 SourceLocation EllipsisLoc) {
1302 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1303 TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1304 Diag(Loc: NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1305 DiagID: diag::err_unsupported_placeholder_constraint)
1306 << NewConstrainedParm->getTypeSourceInfo()
1307 ->getTypeLoc()
1308 .getSourceRange();
1309 return true;
1310 }
1311 // FIXME: Concepts: This should be the type of the placeholder, but this is
1312 // unclear in the wording right now.
1313 DeclRefExpr *Ref =
1314 BuildDeclRefExpr(D: OrigConstrainedParm, Ty: OrigConstrainedParm->getType(),
1315 VK: VK_PRValue, Loc: OrigConstrainedParm->getLocation());
1316 if (!Ref)
1317 return true;
1318 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1319 S&: *this, NS: TL.getNestedNameSpecifierLoc(), NameInfo: TL.getConceptNameInfo(),
1320 NamedConcept: TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), LAngleLoc: TL.getLAngleLoc(),
1321 RAngleLoc: TL.getRAngleLoc(), ConstrainedType: BuildDecltypeType(E: Ref),
1322 ParamNameLoc: OrigConstrainedParm->getLocation(),
1323 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1324 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1325 ConstraintArgs.addArgument(Loc: TL.getArgLoc(i: I));
1326 },
1327 EllipsisLoc);
1328 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1329 !ImmediatelyDeclaredConstraint.isUsable())
1330 return true;
1331
1332 NewConstrainedParm->setPlaceholderTypeConstraint(
1333 ImmediatelyDeclaredConstraint.get());
1334 return false;
1335}
1336
1337QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1338 SourceLocation Loc) {
1339 if (TSI->getType()->isUndeducedType()) {
1340 // C++17 [temp.dep.expr]p3:
1341 // An id-expression is type-dependent if it contains
1342 // - an identifier associated by name lookup with a non-type
1343 // template-parameter declared with a type that contains a
1344 // placeholder type (7.1.7.4),
1345 TypeSourceInfo *NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSI);
1346 if (!NewTSI)
1347 return QualType();
1348 TSI = NewTSI;
1349 }
1350
1351 return CheckNonTypeTemplateParameterType(T: TSI->getType(), Loc);
1352}
1353
1354bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1355 if (T->isDependentType())
1356 return false;
1357
1358 if (RequireCompleteType(Loc, T, DiagID: diag::err_template_nontype_parm_incomplete))
1359 return true;
1360
1361 if (T->isStructuralType())
1362 return false;
1363
1364 // Structural types are required to be object types or lvalue references.
1365 if (T->isRValueReferenceType()) {
1366 Diag(Loc, DiagID: diag::err_template_nontype_parm_rvalue_ref) << T;
1367 return true;
1368 }
1369
1370 // Don't mention structural types in our diagnostic prior to C++20. Also,
1371 // there's not much more we can say about non-scalar non-class types --
1372 // because we can't see functions or arrays here, those can only be language
1373 // extensions.
1374 if (!getLangOpts().CPlusPlus20 ||
1375 (!T->isScalarType() && !T->isRecordType())) {
1376 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_type) << T;
1377 return true;
1378 }
1379
1380 // Structural types are required to be literal types.
1381 if (RequireLiteralType(Loc, T, DiagID: diag::err_template_nontype_parm_not_literal))
1382 return true;
1383
1384 Diag(Loc, DiagID: diag::err_template_nontype_parm_not_structural) << T;
1385
1386 // Drill down into the reason why the class is non-structural.
1387 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1388 // All members are required to be public and non-mutable, and can't be of
1389 // rvalue reference type. Check these conditions first to prefer a "local"
1390 // reason over a more distant one.
1391 for (const FieldDecl *FD : RD->fields()) {
1392 if (FD->getAccess() != AS_public) {
1393 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_non_public) << T << 0;
1394 return true;
1395 }
1396 if (FD->isMutable()) {
1397 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_mutable_field) << T;
1398 return true;
1399 }
1400 if (FD->getType()->isRValueReferenceType()) {
1401 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_rvalue_ref_field)
1402 << T;
1403 return true;
1404 }
1405 }
1406
1407 // All bases are required to be public.
1408 for (const auto &BaseSpec : RD->bases()) {
1409 if (BaseSpec.getAccessSpecifier() != AS_public) {
1410 Diag(Loc: BaseSpec.getBaseTypeLoc(), DiagID: diag::note_not_structural_non_public)
1411 << T << 1;
1412 return true;
1413 }
1414 }
1415
1416 // All subobjects are required to be of structural types.
1417 SourceLocation SubLoc;
1418 QualType SubType;
1419 int Kind = -1;
1420
1421 for (const FieldDecl *FD : RD->fields()) {
1422 QualType T = Context.getBaseElementType(QT: FD->getType());
1423 if (!T->isStructuralType()) {
1424 SubLoc = FD->getLocation();
1425 SubType = T;
1426 Kind = 0;
1427 break;
1428 }
1429 }
1430
1431 if (Kind == -1) {
1432 for (const auto &BaseSpec : RD->bases()) {
1433 QualType T = BaseSpec.getType();
1434 if (!T->isStructuralType()) {
1435 SubLoc = BaseSpec.getBaseTypeLoc();
1436 SubType = T;
1437 Kind = 1;
1438 break;
1439 }
1440 }
1441 }
1442
1443 assert(Kind != -1 && "couldn't find reason why type is not structural");
1444 Diag(Loc: SubLoc, DiagID: diag::note_not_structural_subobject)
1445 << T << Kind << SubType;
1446 T = SubType;
1447 RD = T->getAsCXXRecordDecl();
1448 }
1449
1450 return true;
1451}
1452
1453QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1454 SourceLocation Loc) {
1455 // We don't allow variably-modified types as the type of non-type template
1456 // parameters.
1457 if (T->isVariablyModifiedType()) {
1458 Diag(Loc, DiagID: diag::err_variably_modified_nontype_template_param)
1459 << T;
1460 return QualType();
1461 }
1462
1463 // C++ [temp.param]p4:
1464 //
1465 // A non-type template-parameter shall have one of the following
1466 // (optionally cv-qualified) types:
1467 //
1468 // -- integral or enumeration type,
1469 if (T->isIntegralOrEnumerationType() ||
1470 // -- pointer to object or pointer to function,
1471 T->isPointerType() ||
1472 // -- lvalue reference to object or lvalue reference to function,
1473 T->isLValueReferenceType() ||
1474 // -- pointer to member,
1475 T->isMemberPointerType() ||
1476 // -- std::nullptr_t, or
1477 T->isNullPtrType() ||
1478 // -- a type that contains a placeholder type.
1479 T->isUndeducedType()) {
1480 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1481 // are ignored when determining its type.
1482 return T.getUnqualifiedType();
1483 }
1484
1485 // C++ [temp.param]p8:
1486 //
1487 // A non-type template-parameter of type "array of T" or
1488 // "function returning T" is adjusted to be of type "pointer to
1489 // T" or "pointer to function returning T", respectively.
1490 if (T->isArrayType() || T->isFunctionType())
1491 return Context.getDecayedType(T);
1492
1493 // If T is a dependent type, we can't do the check now, so we
1494 // assume that it is well-formed. Note that stripping off the
1495 // qualifiers here is not really correct if T turns out to be
1496 // an array type, but we'll recompute the type everywhere it's
1497 // used during instantiation, so that should be OK. (Using the
1498 // qualified type is equally wrong.)
1499 if (T->isDependentType())
1500 return T.getUnqualifiedType();
1501
1502 // C++20 [temp.param]p6:
1503 // -- a structural type
1504 if (RequireStructuralType(T, Loc))
1505 return QualType();
1506
1507 if (!getLangOpts().CPlusPlus20) {
1508 // FIXME: Consider allowing structural types as an extension in C++17. (In
1509 // earlier language modes, the template argument evaluation rules are too
1510 // inflexible.)
1511 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_structural_type) << T;
1512 return QualType();
1513 }
1514
1515 Diag(Loc, DiagID: diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1516 return T.getUnqualifiedType();
1517}
1518
1519NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1520 unsigned Depth,
1521 unsigned Position,
1522 SourceLocation EqualLoc,
1523 Expr *Default) {
1524 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
1525
1526 // Check that we have valid decl-specifiers specified.
1527 auto CheckValidDeclSpecifiers = [this, &D] {
1528 // C++ [temp.param]
1529 // p1
1530 // template-parameter:
1531 // ...
1532 // parameter-declaration
1533 // p2
1534 // ... A storage class shall not be specified in a template-parameter
1535 // declaration.
1536 // [dcl.typedef]p1:
1537 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1538 // of a parameter-declaration
1539 const DeclSpec &DS = D.getDeclSpec();
1540 auto EmitDiag = [this](SourceLocation Loc) {
1541 Diag(Loc, DiagID: diag::err_invalid_decl_specifier_in_nontype_parm)
1542 << FixItHint::CreateRemoval(RemoveRange: Loc);
1543 };
1544 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1545 EmitDiag(DS.getStorageClassSpecLoc());
1546
1547 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1548 EmitDiag(DS.getThreadStorageClassSpecLoc());
1549
1550 // [dcl.inline]p1:
1551 // The inline specifier can be applied only to the declaration or
1552 // definition of a variable or function.
1553
1554 if (DS.isInlineSpecified())
1555 EmitDiag(DS.getInlineSpecLoc());
1556
1557 // [dcl.constexpr]p1:
1558 // The constexpr specifier shall be applied only to the definition of a
1559 // variable or variable template or the declaration of a function or
1560 // function template.
1561
1562 if (DS.hasConstexprSpecifier())
1563 EmitDiag(DS.getConstexprSpecLoc());
1564
1565 // [dcl.fct.spec]p1:
1566 // Function-specifiers can be used only in function declarations.
1567
1568 if (DS.isVirtualSpecified())
1569 EmitDiag(DS.getVirtualSpecLoc());
1570
1571 if (DS.hasExplicitSpecifier())
1572 EmitDiag(DS.getExplicitSpecLoc());
1573
1574 if (DS.isNoreturnSpecified())
1575 EmitDiag(DS.getNoreturnSpecLoc());
1576 };
1577
1578 CheckValidDeclSpecifiers();
1579
1580 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1581 if (isa<AutoType>(Val: T))
1582 Diag(Loc: D.getIdentifierLoc(),
1583 DiagID: diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1584 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1585
1586 assert(S->isTemplateParamScope() &&
1587 "Non-type template parameter not in template parameter scope!");
1588 bool Invalid = false;
1589
1590 QualType T = CheckNonTypeTemplateParameterType(TSI&: TInfo, Loc: D.getIdentifierLoc());
1591 if (T.isNull()) {
1592 T = Context.IntTy; // Recover with an 'int' type.
1593 Invalid = true;
1594 }
1595
1596 CheckFunctionOrTemplateParamDeclarator(S, D);
1597
1598 const IdentifierInfo *ParamName = D.getIdentifier();
1599 bool IsParameterPack = D.hasEllipsis();
1600 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1601 C: Context, DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
1602 IdLoc: D.getIdentifierLoc(), D: Depth, P: Position, Id: ParamName, T, ParameterPack: IsParameterPack,
1603 TInfo);
1604 Param->setAccess(AS_public);
1605
1606 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1607 if (TL.isConstrained()) {
1608 if (D.getEllipsisLoc().isInvalid() &&
1609 T->containsUnexpandedParameterPack()) {
1610 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1611 for (auto &Loc :
1612 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1613 Invalid |= DiagnoseUnexpandedParameterPack(
1614 Arg: Loc, UPPC: UnexpandedParameterPackContext::UPPC_TypeConstraint);
1615 }
1616 if (!Invalid &&
1617 AttachTypeConstraint(TL, NewConstrainedParm: Param, OrigConstrainedParm: Param, EllipsisLoc: D.getEllipsisLoc()))
1618 Invalid = true;
1619 }
1620
1621 if (Invalid)
1622 Param->setInvalidDecl();
1623
1624 if (Param->isParameterPack())
1625 if (auto *CSI = getEnclosingLambdaOrBlock())
1626 CSI->LocalPacks.push_back(Elt: Param);
1627
1628 if (ParamName) {
1629 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: D.getIdentifierLoc(),
1630 Name: ParamName);
1631
1632 // Add the template parameter into the current scope.
1633 S->AddDecl(D: Param);
1634 IdResolver.AddDecl(D: Param);
1635 }
1636
1637 // C++0x [temp.param]p9:
1638 // A default template-argument may be specified for any kind of
1639 // template-parameter that is not a template parameter pack.
1640 if (Default && IsParameterPack) {
1641 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1642 Default = nullptr;
1643 }
1644
1645 // Check the well-formedness of the default template argument, if provided.
1646 if (Default) {
1647 // Check for unexpanded parameter packs.
1648 if (DiagnoseUnexpandedParameterPack(E: Default, UPPC: UPPC_DefaultArgument))
1649 return Param;
1650
1651 Param->setDefaultArgument(
1652 C: Context, DefArg: getTrivialTemplateArgumentLoc(
1653 Arg: TemplateArgument(Default, /*IsCanonical=*/false),
1654 NTTPType: QualType(), Loc: SourceLocation()));
1655 }
1656
1657 return Param;
1658}
1659
1660/// ActOnTemplateTemplateParameter - Called when a C++ template template
1661/// parameter (e.g. T in template <template \<typename> class T> class array)
1662/// has been parsed. S is the current scope.
1663NamedDecl *Sema::ActOnTemplateTemplateParameter(
1664 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1665 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1666 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1667 unsigned Position, SourceLocation EqualLoc,
1668 ParsedTemplateArgument Default) {
1669 assert(S->isTemplateParamScope() &&
1670 "Template template parameter not in template parameter scope!");
1671
1672 bool IsParameterPack = EllipsisLoc.isValid();
1673
1674 bool Invalid = false;
1675 if (CheckTemplateParameterList(
1676 NewParams: Params,
1677 /*OldParams=*/nullptr,
1678 TPC: IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1679 Invalid = true;
1680
1681 // Construct the parameter object.
1682 TemplateTemplateParmDecl *Param = TemplateTemplateParmDecl::Create(
1683 C: Context, DC: Context.getTranslationUnitDecl(),
1684 L: NameLoc.isInvalid() ? TmpLoc : NameLoc, D: Depth, P: Position, ParameterPack: IsParameterPack,
1685 Id: Name, ParameterKind: Kind, Typename, Params);
1686 Param->setAccess(AS_public);
1687
1688 if (Param->isParameterPack())
1689 if (auto *LSI = getEnclosingLambdaOrBlock())
1690 LSI->LocalPacks.push_back(Elt: Param);
1691
1692 // If the template template parameter has a name, then link the identifier
1693 // into the scope and lookup mechanisms.
1694 if (Name) {
1695 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: NameLoc, Name);
1696
1697 S->AddDecl(D: Param);
1698 IdResolver.AddDecl(D: Param);
1699 }
1700
1701 if (Params->size() == 0) {
1702 Diag(Loc: Param->getLocation(), DiagID: diag::err_template_template_parm_no_parms)
1703 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1704 Invalid = true;
1705 }
1706
1707 if (Invalid)
1708 Param->setInvalidDecl();
1709
1710 // C++0x [temp.param]p9:
1711 // A default template-argument may be specified for any kind of
1712 // template-parameter that is not a template parameter pack.
1713 if (IsParameterPack && !Default.isInvalid()) {
1714 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1715 Default = ParsedTemplateArgument();
1716 }
1717
1718 if (!Default.isInvalid()) {
1719 // Check only that we have a template template argument. We don't want to
1720 // try to check well-formedness now, because our template template parameter
1721 // might have dependent types in its template parameters, which we wouldn't
1722 // be able to match now.
1723 //
1724 // If none of the template template parameter's template arguments mention
1725 // other template parameters, we could actually perform more checking here.
1726 // However, it isn't worth doing.
1727 TemplateArgumentLoc DefaultArg = translateTemplateArgument(SemaRef&: *this, Arg: Default);
1728 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1729 Diag(Loc: DefaultArg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
1730 << DefaultArg.getSourceRange();
1731 return Param;
1732 }
1733
1734 TemplateName Name =
1735 DefaultArg.getArgument().getAsTemplateOrTemplatePattern();
1736 TemplateDecl *Template = Name.getAsTemplateDecl();
1737 if (Template &&
1738 !CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg: DefaultArg)) {
1739 return Param;
1740 }
1741
1742 // Check for unexpanded parameter packs.
1743 if (DiagnoseUnexpandedParameterPack(Loc: DefaultArg.getLocation(),
1744 Template: DefaultArg.getArgument().getAsTemplate(),
1745 UPPC: UPPC_DefaultArgument))
1746 return Param;
1747
1748 Param->setDefaultArgument(C: Context, DefArg: DefaultArg);
1749 }
1750
1751 return Param;
1752}
1753
1754namespace {
1755class ConstraintRefersToContainingTemplateChecker
1756 : public ConstDynamicRecursiveASTVisitor {
1757 using inherited = ConstDynamicRecursiveASTVisitor;
1758 bool Result = false;
1759 const FunctionDecl *Friend = nullptr;
1760 unsigned TemplateDepth = 0;
1761
1762 // Check a record-decl that we've seen to see if it is a lexical parent of the
1763 // Friend, likely because it was referred to without its template arguments.
1764 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1765 CheckingRD = CheckingRD->getMostRecentDecl();
1766 if (!CheckingRD->isTemplated())
1767 return true;
1768
1769 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1770 DC && !DC->isFileContext(); DC = DC->getParent())
1771 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
1772 if (CheckingRD == RD->getMostRecentDecl()) {
1773 Result = true;
1774 return false;
1775 }
1776
1777 return true;
1778 }
1779
1780 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1781 if (D->getDepth() < TemplateDepth)
1782 Result = true;
1783
1784 // Necessary because the type of the NTTP might be what refers to the parent
1785 // constriant.
1786 return TraverseType(T: D->getType());
1787 }
1788
1789public:
1790 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1791 unsigned TemplateDepth)
1792 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1793
1794 bool getResult() const { return Result; }
1795
1796 // This should be the only template parm type that we have to deal with.
1797 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1798 // FunctionParmPackExpr are all partially substituted, which cannot happen
1799 // with concepts at this point in translation.
1800 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1801 if (Type->getDecl()->getDepth() < TemplateDepth) {
1802 Result = true;
1803 return false;
1804 }
1805 return true;
1806 }
1807
1808 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1809 return TraverseDecl(D: E->getDecl());
1810 }
1811
1812 bool TraverseTypedefType(const TypedefType *TT,
1813 bool /*TraverseQualifier*/) override {
1814 return TraverseType(T: TT->desugar());
1815 }
1816
1817 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1818 // We don't care about TypeLocs. So traverse Types instead.
1819 return TraverseType(T: TL.getType(), TraverseQualifier);
1820 }
1821
1822 bool VisitTagType(const TagType *T) override {
1823 return TraverseDecl(D: T->getDecl());
1824 }
1825
1826 bool TraverseDecl(const Decl *D) override {
1827 assert(D);
1828 // FIXME : This is possibly an incomplete list, but it is unclear what other
1829 // Decl kinds could be used to refer to the template parameters. This is a
1830 // best guess so far based on examples currently available, but the
1831 // unreachable should catch future instances/cases.
1832 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
1833 return TraverseType(T: TD->getUnderlyingType());
1834 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Val: D))
1835 return CheckNonTypeTemplateParmDecl(D: NTTPD);
1836 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
1837 return TraverseType(T: VD->getType());
1838 if (isa<TemplateDecl>(Val: D))
1839 return true;
1840 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1841 return CheckIfContainingRecord(CheckingRD: RD);
1842
1843 if (isa<NamedDecl, RequiresExprBodyDecl>(Val: D)) {
1844 // No direct types to visit here I believe.
1845 } else
1846 llvm_unreachable("Don't know how to handle this declaration type yet");
1847 return true;
1848 }
1849};
1850} // namespace
1851
1852bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1853 const FunctionDecl *Friend, unsigned TemplateDepth,
1854 const Expr *Constraint) {
1855 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1856 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1857 Checker.TraverseStmt(S: Constraint);
1858 return Checker.getResult();
1859}
1860
1861TemplateParameterList *
1862Sema::ActOnTemplateParameterList(unsigned Depth,
1863 SourceLocation ExportLoc,
1864 SourceLocation TemplateLoc,
1865 SourceLocation LAngleLoc,
1866 ArrayRef<NamedDecl *> Params,
1867 SourceLocation RAngleLoc,
1868 Expr *RequiresClause) {
1869 if (ExportLoc.isValid())
1870 Diag(Loc: ExportLoc, DiagID: diag::warn_template_export_unsupported);
1871
1872 for (NamedDecl *P : Params)
1873 warnOnReservedIdentifier(D: P);
1874
1875 return TemplateParameterList::Create(C: Context, TemplateLoc, LAngleLoc,
1876 Params: llvm::ArrayRef(Params), RAngleLoc,
1877 RequiresClause);
1878}
1879
1880static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1881 const CXXScopeSpec &SS) {
1882 if (SS.isSet())
1883 T->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
1884}
1885
1886// Returns the template parameter list with all default template argument
1887// information.
1888TemplateParameterList *Sema::GetTemplateParameterList(TemplateDecl *TD) {
1889 // Make sure we get the template parameter list from the most
1890 // recent declaration, since that is the only one that is guaranteed to
1891 // have all the default template argument information.
1892 Decl *D = TD->getMostRecentDecl();
1893 // C++11 N3337 [temp.param]p12:
1894 // A default template argument shall not be specified in a friend class
1895 // template declaration.
1896 //
1897 // Skip past friend *declarations* because they are not supposed to contain
1898 // default template arguments. Moreover, these declarations may introduce
1899 // template parameters living in different template depths than the
1900 // corresponding template parameters in TD, causing unmatched constraint
1901 // substitution.
1902 //
1903 // FIXME: Diagnose such cases within a class template:
1904 // template <class T>
1905 // struct S {
1906 // template <class = void> friend struct C;
1907 // };
1908 // template struct S<int>;
1909 while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
1910 D->getPreviousDecl())
1911 D = D->getPreviousDecl();
1912 return cast<TemplateDecl>(Val: D)->getTemplateParameters();
1913}
1914
1915DeclResult Sema::CheckClassTemplate(
1916 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1917 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1918 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1919 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1920 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1921 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1922 assert(TemplateParams && TemplateParams->size() > 0 &&
1923 "No template parameters");
1924 assert(TUK != TagUseKind::Reference &&
1925 "Can only declare or define class templates");
1926 bool Invalid = false;
1927
1928 // Check that we can declare a template here.
1929 if (CheckTemplateDeclScope(S, TemplateParams))
1930 return true;
1931
1932 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
1933 assert(Kind != TagTypeKind::Enum &&
1934 "can't build template of enumerated type");
1935
1936 // There is no such thing as an unnamed class template.
1937 if (!Name) {
1938 Diag(Loc: KWLoc, DiagID: diag::err_template_unnamed_class);
1939 return true;
1940 }
1941
1942 // Find any previous declaration with this name. For a friend with no
1943 // scope explicitly specified, we only look for tag declarations (per
1944 // C++11 [basic.lookup.elab]p2).
1945 DeclContext *SemanticContext;
1946 LookupResult Previous(*this, Name, NameLoc,
1947 (SS.isEmpty() && TUK == TagUseKind::Friend)
1948 ? LookupTagName
1949 : LookupOrdinaryName,
1950 forRedeclarationInCurContext());
1951 if (SS.isNotEmpty() && !SS.isInvalid()) {
1952 SemanticContext = computeDeclContext(SS, EnteringContext: true);
1953 if (!SemanticContext) {
1954 // FIXME: Horrible, horrible hack! We can't currently represent this
1955 // in the AST, and historically we have just ignored such friend
1956 // class templates, so don't complain here.
1957 Diag(Loc: NameLoc, DiagID: TUK == TagUseKind::Friend
1958 ? diag::warn_template_qualified_friend_ignored
1959 : diag::err_template_qualified_declarator_no_match)
1960 << SS.getScopeRep() << SS.getRange();
1961 return TUK != TagUseKind::Friend;
1962 }
1963
1964 if (RequireCompleteDeclContext(SS, DC: SemanticContext))
1965 return true;
1966
1967 // If we're adding a template to a dependent context, we may need to
1968 // rebuilding some of the types used within the template parameter list,
1969 // now that we know what the current instantiation is.
1970 if (SemanticContext->isDependentContext()) {
1971 ContextRAII SavedContext(*this, SemanticContext);
1972 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
1973 Invalid = true;
1974 }
1975
1976 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1977 diagnoseQualifiedDeclaration(SS, DC: SemanticContext, Name, Loc: NameLoc,
1978 /*TemplateId-*/ TemplateId: nullptr,
1979 /*IsMemberSpecialization*/ false);
1980
1981 LookupQualifiedName(R&: Previous, LookupCtx: SemanticContext);
1982 } else {
1983 SemanticContext = CurContext;
1984
1985 // C++14 [class.mem]p14:
1986 // If T is the name of a class, then each of the following shall have a
1987 // name different from T:
1988 // -- every member template of class T
1989 if (TUK != TagUseKind::Friend &&
1990 DiagnoseClassNameShadow(DC: SemanticContext,
1991 Info: DeclarationNameInfo(Name, NameLoc)))
1992 return true;
1993
1994 LookupName(R&: Previous, S);
1995 }
1996
1997 if (Previous.isAmbiguous())
1998 return true;
1999
2000 // Let the template parameter scope enter the lookup chain of the current
2001 // class template. For example, given
2002 //
2003 // namespace ns {
2004 // template <class> bool Param = false;
2005 // template <class T> struct N;
2006 // }
2007 //
2008 // template <class Param> struct ns::N { void foo(Param); };
2009 //
2010 // When we reference Param inside the function parameter list, our name lookup
2011 // chain for it should be like:
2012 // FunctionScope foo
2013 // -> RecordScope N
2014 // -> TemplateParamScope (where we will find Param)
2015 // -> NamespaceScope ns
2016 //
2017 // See also CppLookupName().
2018 if (S->isTemplateParamScope())
2019 EnterTemplatedContext(S, DC: SemanticContext);
2020
2021 NamedDecl *PrevDecl = nullptr;
2022 if (Previous.begin() != Previous.end())
2023 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2024
2025 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2026 // Maybe we will complain about the shadowed template parameter.
2027 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl);
2028 // Just pretend that we didn't see the previous declaration.
2029 PrevDecl = nullptr;
2030 }
2031
2032 // If there is a previous declaration with the same name, check
2033 // whether this is a valid redeclaration.
2034 ClassTemplateDecl *PrevClassTemplate =
2035 dyn_cast_or_null<ClassTemplateDecl>(Val: PrevDecl);
2036
2037 // We may have found the injected-class-name of a class template,
2038 // class template partial specialization, or class template specialization.
2039 // In these cases, grab the template that is being defined or specialized.
2040 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(Val: PrevDecl) &&
2041 cast<CXXRecordDecl>(Val: PrevDecl)->isInjectedClassName()) {
2042 PrevDecl = cast<CXXRecordDecl>(Val: PrevDecl->getDeclContext());
2043 PrevClassTemplate
2044 = cast<CXXRecordDecl>(Val: PrevDecl)->getDescribedClassTemplate();
2045 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(Val: PrevDecl)) {
2046 PrevClassTemplate
2047 = cast<ClassTemplateSpecializationDecl>(Val: PrevDecl)
2048 ->getSpecializedTemplate();
2049 }
2050 }
2051
2052 if (TUK == TagUseKind::Friend) {
2053 // C++ [namespace.memdef]p3:
2054 // [...] When looking for a prior declaration of a class or a function
2055 // declared as a friend, and when the name of the friend class or
2056 // function is neither a qualified name nor a template-id, scopes outside
2057 // the innermost enclosing namespace scope are not considered.
2058 if (!SS.isSet()) {
2059 DeclContext *OutermostContext = CurContext;
2060 while (!OutermostContext->isFileContext())
2061 OutermostContext = OutermostContext->getLookupParent();
2062
2063 if (PrevDecl &&
2064 (OutermostContext->Equals(DC: PrevDecl->getDeclContext()) ||
2065 OutermostContext->Encloses(DC: PrevDecl->getDeclContext()))) {
2066 SemanticContext = PrevDecl->getDeclContext();
2067 } else {
2068 // Declarations in outer scopes don't matter. However, the outermost
2069 // context we computed is the semantic context for our new
2070 // declaration.
2071 PrevDecl = PrevClassTemplate = nullptr;
2072 SemanticContext = OutermostContext;
2073
2074 // Check that the chosen semantic context doesn't already contain a
2075 // declaration of this name as a non-tag type.
2076 Previous.clear(Kind: LookupOrdinaryName);
2077 DeclContext *LookupContext = SemanticContext;
2078 while (LookupContext->isTransparentContext())
2079 LookupContext = LookupContext->getLookupParent();
2080 LookupQualifiedName(R&: Previous, LookupCtx: LookupContext);
2081
2082 if (Previous.isAmbiguous())
2083 return true;
2084
2085 if (Previous.begin() != Previous.end())
2086 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2087 }
2088 }
2089 } else if (PrevDecl && !isDeclInScope(D: Previous.getRepresentativeDecl(),
2090 Ctx: SemanticContext, S, AllowInlineNamespace: SS.isValid()))
2091 PrevDecl = PrevClassTemplate = nullptr;
2092
2093 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2094 Val: PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2095 if (SS.isEmpty() &&
2096 !(PrevClassTemplate &&
2097 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2098 DC: SemanticContext->getRedeclContext()))) {
2099 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
2100 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
2101 DiagID: diag::note_using_decl_target);
2102 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
2103 // Recover by ignoring the old declaration.
2104 PrevDecl = PrevClassTemplate = nullptr;
2105 }
2106 }
2107
2108 if (PrevClassTemplate) {
2109 // Ensure that the template parameter lists are compatible. Skip this check
2110 // for a friend in a dependent context: the template parameter list itself
2111 // could be dependent.
2112 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2113 !TemplateParameterListsAreEqual(
2114 NewInstFrom: TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2115 : CurContext,
2116 CurContext, KWLoc),
2117 New: TemplateParams, OldInstFrom: PrevClassTemplate,
2118 Old: PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2119 Kind: TPL_TemplateMatch))
2120 return true;
2121
2122 // C++ [temp.class]p4:
2123 // In a redeclaration, partial specialization, explicit
2124 // specialization or explicit instantiation of a class template,
2125 // the class-key shall agree in kind with the original class
2126 // template declaration (7.1.5.3).
2127 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2128 if (!isAcceptableTagRedeclaration(
2129 Previous: PrevRecordDecl, NewTag: Kind, isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc, Name)) {
2130 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
2131 << Name
2132 << FixItHint::CreateReplacement(RemoveRange: KWLoc, Code: PrevRecordDecl->getKindName());
2133 Diag(Loc: PrevRecordDecl->getLocation(), DiagID: diag::note_previous_use);
2134 Kind = PrevRecordDecl->getTagKind();
2135 }
2136
2137 // Check for redefinition of this class template.
2138 if (TUK == TagUseKind::Definition) {
2139 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2140 // If we have a prior definition that is not visible, treat this as
2141 // simply making that previous definition visible.
2142 NamedDecl *Hidden = nullptr;
2143 bool HiddenDefVisible = false;
2144 if (SkipBody &&
2145 isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible)) {
2146 SkipBody->ShouldSkip = true;
2147 SkipBody->Previous = Def;
2148 if (!HiddenDefVisible && Hidden) {
2149 auto *Tmpl =
2150 cast<CXXRecordDecl>(Val: Hidden)->getDescribedClassTemplate();
2151 assert(Tmpl && "original definition of a class template is not a "
2152 "class template?");
2153 makeMergedDefinitionVisible(ND: Hidden);
2154 makeMergedDefinitionVisible(ND: Tmpl);
2155 }
2156 } else {
2157 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
2158 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
2159 // FIXME: Would it make sense to try to "forget" the previous
2160 // definition, as part of error recovery?
2161 return true;
2162 }
2163 }
2164 }
2165 } else if (PrevDecl) {
2166 // C++ [temp]p5:
2167 // A class template shall not have the same name as any other
2168 // template, class, function, object, enumeration, enumerator,
2169 // namespace, or type in the same scope (3.3), except as specified
2170 // in (14.5.4).
2171 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
2172 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
2173 return true;
2174 }
2175
2176 // Check the template parameter list of this declaration, possibly
2177 // merging in the template parameter list from the previous class
2178 // template declaration. Skip this check for a friend in a dependent
2179 // context, because the template parameter list might be dependent.
2180 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2181 CheckTemplateParameterList(
2182 NewParams: TemplateParams,
2183 OldParams: PrevClassTemplate ? GetTemplateParameterList(TD: PrevClassTemplate)
2184 : nullptr,
2185 TPC: (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2186 SemanticContext->isDependentContext())
2187 ? TPC_ClassTemplateMember
2188 : TUK == TagUseKind::Friend ? TPC_FriendClassTemplate
2189 : TPC_Other,
2190 SkipBody))
2191 Invalid = true;
2192
2193 if (SS.isSet()) {
2194 // If the name of the template was qualified, we must be defining the
2195 // template out-of-line.
2196 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2197 Diag(Loc: NameLoc, DiagID: TUK == TagUseKind::Friend
2198 ? diag::err_friend_decl_does_not_match
2199 : diag::err_member_decl_does_not_match)
2200 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2201 Invalid = true;
2202 }
2203 }
2204
2205 // If this is a templated friend in a dependent context we should not put it
2206 // on the redecl chain. In some cases, the templated friend can be the most
2207 // recent declaration tricking the template instantiator to make substitutions
2208 // there.
2209 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2210 bool ShouldAddRedecl =
2211 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2212
2213 CXXRecordDecl *NewClass = CXXRecordDecl::Create(
2214 C: Context, TK: Kind, DC: SemanticContext, StartLoc: KWLoc, IdLoc: NameLoc, Id: Name,
2215 PrevDecl: PrevClassTemplate && ShouldAddRedecl
2216 ? PrevClassTemplate->getTemplatedDecl()
2217 : nullptr);
2218 SetNestedNameSpecifier(S&: *this, T: NewClass, SS);
2219 if (NumOuterTemplateParamLists > 0)
2220 NewClass->setTemplateParameterListsInfo(
2221 Context,
2222 TPLists: llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2223
2224 // Add alignment attributes if necessary; these attributes are checked when
2225 // the ASTContext lays out the structure.
2226 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2227 if (LangOpts.HLSL)
2228 NewClass->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
2229 AddAlignmentAttributesForRecord(RD: NewClass);
2230 AddMsStructLayoutForRecord(RD: NewClass);
2231 }
2232
2233 ClassTemplateDecl *NewTemplate
2234 = ClassTemplateDecl::Create(C&: Context, DC: SemanticContext, L: NameLoc,
2235 Name: DeclarationName(Name), Params: TemplateParams,
2236 Decl: NewClass);
2237
2238 if (ShouldAddRedecl)
2239 NewTemplate->setPreviousDecl(PrevClassTemplate);
2240
2241 NewClass->setDescribedClassTemplate(NewTemplate);
2242
2243 if (ModulePrivateLoc.isValid())
2244 NewTemplate->setModulePrivate();
2245
2246 // If we are providing an explicit specialization of a member that is a
2247 // class template, make a note of that.
2248 if (PrevClassTemplate &&
2249 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2250 PrevClassTemplate->setMemberSpecialization();
2251
2252 // Set the access specifier.
2253 if (!Invalid && TUK != TagUseKind::Friend &&
2254 NewTemplate->getDeclContext()->isRecord())
2255 SetMemberAccessSpecifier(MemberDecl: NewTemplate, PrevMemberDecl: PrevClassTemplate, LexicalAS: AS);
2256
2257 // Set the lexical context of these templates
2258 NewClass->setLexicalDeclContext(CurContext);
2259 NewTemplate->setLexicalDeclContext(CurContext);
2260
2261 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2262 NewClass->startDefinition();
2263
2264 ProcessDeclAttributeList(S, D: NewClass, AttrList: Attr);
2265
2266 if (PrevClassTemplate)
2267 mergeDeclAttributes(New: NewClass, Old: PrevClassTemplate->getTemplatedDecl());
2268
2269 AddPushedVisibilityAttribute(RD: NewClass);
2270 inferGslOwnerPointerAttribute(Record: NewClass);
2271 inferNullableClassAttribute(CRD: NewClass);
2272
2273 if (TUK != TagUseKind::Friend) {
2274 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2275 Scope *Outer = S;
2276 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2277 Outer = Outer->getParent();
2278 PushOnScopeChains(D: NewTemplate, S: Outer);
2279 } else {
2280 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2281 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2282 NewClass->setAccess(PrevClassTemplate->getAccess());
2283 }
2284
2285 NewTemplate->setObjectOfFriendDecl();
2286
2287 // Friend templates are visible in fairly strange ways.
2288 if (!CurContext->isDependentContext()) {
2289 DeclContext *DC = SemanticContext->getRedeclContext();
2290 DC->makeDeclVisibleInContext(D: NewTemplate);
2291 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2292 PushOnScopeChains(D: NewTemplate, S: EnclosingScope,
2293 /* AddToContext = */ false);
2294 }
2295
2296 FriendDecl *Friend = FriendDecl::Create(
2297 C&: Context, DC: CurContext, L: NewClass->getLocation(), Friend_: NewTemplate, FriendL: FriendLoc);
2298 Friend->setAccess(AS_public);
2299 CurContext->addDecl(D: Friend);
2300 }
2301
2302 if (PrevClassTemplate)
2303 CheckRedeclarationInModule(New: NewTemplate, Old: PrevClassTemplate);
2304
2305 if (Invalid) {
2306 NewTemplate->setInvalidDecl();
2307 NewClass->setInvalidDecl();
2308 }
2309
2310 ActOnDocumentableDecl(D: NewTemplate);
2311
2312 if (SkipBody && SkipBody->ShouldSkip)
2313 return SkipBody->Previous;
2314
2315 return NewTemplate;
2316}
2317
2318/// Diagnose the presence of a default template argument on a
2319/// template parameter, which is ill-formed in certain contexts.
2320///
2321/// \returns true if the default template argument should be dropped.
2322static bool DiagnoseDefaultTemplateArgument(Sema &S,
2323 Sema::TemplateParamListContext TPC,
2324 SourceLocation ParamLoc,
2325 SourceRange DefArgRange) {
2326 switch (TPC) {
2327 case Sema::TPC_Other:
2328 case Sema::TPC_TemplateTemplateParameterPack:
2329 return false;
2330
2331 case Sema::TPC_FunctionTemplate:
2332 case Sema::TPC_FriendFunctionTemplateDefinition:
2333 // C++ [temp.param]p9:
2334 // A default template-argument shall not be specified in a
2335 // function template declaration or a function template
2336 // definition [...]
2337 // If a friend function template declaration specifies a default
2338 // template-argument, that declaration shall be a definition and shall be
2339 // the only declaration of the function template in the translation unit.
2340 // (C++98/03 doesn't have this wording; see DR226).
2341 S.DiagCompat(Loc: ParamLoc, CompatDiagId: diag_compat::templ_default_in_function_templ)
2342 << DefArgRange;
2343 return false;
2344
2345 case Sema::TPC_ClassTemplateMember:
2346 // C++0x [temp.param]p9:
2347 // A default template-argument shall not be specified in the
2348 // template-parameter-lists of the definition of a member of a
2349 // class template that appears outside of the member's class.
2350 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_template_member)
2351 << DefArgRange;
2352 return true;
2353
2354 case Sema::TPC_FriendClassTemplate:
2355 case Sema::TPC_FriendFunctionTemplate:
2356 // C++ [temp.param]p9:
2357 // A default template-argument shall not be specified in a
2358 // friend template declaration.
2359 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_friend_template)
2360 << DefArgRange;
2361 return true;
2362
2363 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2364 // for friend function templates if there is only a single
2365 // declaration (and it is a definition). Strange!
2366 }
2367
2368 llvm_unreachable("Invalid TemplateParamListContext!");
2369}
2370
2371/// Check for unexpanded parameter packs within the template parameters
2372/// of a template template parameter, recursively.
2373static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2374 TemplateTemplateParmDecl *TTP) {
2375 // A template template parameter which is a parameter pack is also a pack
2376 // expansion.
2377 if (TTP->isParameterPack())
2378 return false;
2379
2380 TemplateParameterList *Params = TTP->getTemplateParameters();
2381 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2382 NamedDecl *P = Params->getParam(Idx: I);
2383 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: P)) {
2384 if (!TTP->isParameterPack())
2385 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2386 if (TC->hasExplicitTemplateArgs())
2387 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2388 if (S.DiagnoseUnexpandedParameterPack(Arg: ArgLoc,
2389 UPPC: Sema::UPPC_TypeConstraint))
2390 return true;
2391 continue;
2392 }
2393
2394 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: P)) {
2395 if (!NTTP->isParameterPack() &&
2396 S.DiagnoseUnexpandedParameterPack(Loc: NTTP->getLocation(),
2397 T: NTTP->getTypeSourceInfo(),
2398 UPPC: Sema::UPPC_NonTypeTemplateParameterType))
2399 return true;
2400
2401 continue;
2402 }
2403
2404 if (TemplateTemplateParmDecl *InnerTTP
2405 = dyn_cast<TemplateTemplateParmDecl>(Val: P))
2406 if (DiagnoseUnexpandedParameterPacks(S, TTP: InnerTTP))
2407 return true;
2408 }
2409
2410 return false;
2411}
2412
2413bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2414 TemplateParameterList *OldParams,
2415 TemplateParamListContext TPC,
2416 SkipBodyInfo *SkipBody) {
2417 bool Invalid = false;
2418
2419 // C++ [temp.param]p10:
2420 // The set of default template-arguments available for use with a
2421 // template declaration or definition is obtained by merging the
2422 // default arguments from the definition (if in scope) and all
2423 // declarations in scope in the same way default function
2424 // arguments are (8.3.6).
2425 bool SawDefaultArgument = false;
2426 SourceLocation PreviousDefaultArgLoc;
2427
2428 // Dummy initialization to avoid warnings.
2429 TemplateParameterList::iterator OldParam = NewParams->end();
2430 if (OldParams)
2431 OldParam = OldParams->begin();
2432
2433 bool RemoveDefaultArguments = false;
2434 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2435 NewParamEnd = NewParams->end();
2436 NewParam != NewParamEnd; ++NewParam) {
2437 // Whether we've seen a duplicate default argument in the same translation
2438 // unit.
2439 bool RedundantDefaultArg = false;
2440 // Whether we've found inconsis inconsitent default arguments in different
2441 // translation unit.
2442 bool InconsistentDefaultArg = false;
2443 // The name of the module which contains the inconsistent default argument.
2444 std::string PrevModuleName;
2445
2446 SourceLocation OldDefaultLoc;
2447 SourceLocation NewDefaultLoc;
2448
2449 // Variable used to diagnose missing default arguments
2450 bool MissingDefaultArg = false;
2451
2452 // Variable used to diagnose non-final parameter packs
2453 bool SawParameterPack = false;
2454
2455 if (TemplateTypeParmDecl *NewTypeParm
2456 = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam)) {
2457 // Check the presence of a default argument here.
2458 if (NewTypeParm->hasDefaultArgument() &&
2459 DiagnoseDefaultTemplateArgument(
2460 S&: *this, TPC, ParamLoc: NewTypeParm->getLocation(),
2461 DefArgRange: NewTypeParm->getDefaultArgument().getSourceRange()))
2462 NewTypeParm->removeDefaultArgument();
2463
2464 // Merge default arguments for template type parameters.
2465 TemplateTypeParmDecl *OldTypeParm
2466 = OldParams? cast<TemplateTypeParmDecl>(Val: *OldParam) : nullptr;
2467 if (NewTypeParm->isParameterPack()) {
2468 assert(!NewTypeParm->hasDefaultArgument() &&
2469 "Parameter packs can't have a default argument!");
2470 SawParameterPack = true;
2471 } else if (OldTypeParm && hasVisibleDefaultArgument(D: OldTypeParm) &&
2472 NewTypeParm->hasDefaultArgument() &&
2473 (!SkipBody || !SkipBody->ShouldSkip)) {
2474 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2475 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2476 SawDefaultArgument = true;
2477
2478 if (!OldTypeParm->getOwningModule())
2479 RedundantDefaultArg = true;
2480 else if (!getASTContext().isSameDefaultTemplateArgument(X: OldTypeParm,
2481 Y: NewTypeParm)) {
2482 InconsistentDefaultArg = true;
2483 PrevModuleName =
2484 OldTypeParm->getImportedOwningModule()->getFullModuleName();
2485 }
2486 PreviousDefaultArgLoc = NewDefaultLoc;
2487 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2488 // Merge the default argument from the old declaration to the
2489 // new declaration.
2490 NewTypeParm->setInheritedDefaultArgument(C: Context, Prev: OldTypeParm);
2491 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2492 } else if (NewTypeParm->hasDefaultArgument()) {
2493 SawDefaultArgument = true;
2494 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2495 } else if (SawDefaultArgument)
2496 MissingDefaultArg = true;
2497 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2498 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam)) {
2499 // Check for unexpanded parameter packs, except in a template template
2500 // parameter pack, as in those any unexpanded packs should be expanded
2501 // along with the parameter itself.
2502 if (TPC != TPC_TemplateTemplateParameterPack &&
2503 !NewNonTypeParm->isParameterPack() &&
2504 DiagnoseUnexpandedParameterPack(Loc: NewNonTypeParm->getLocation(),
2505 T: NewNonTypeParm->getTypeSourceInfo(),
2506 UPPC: UPPC_NonTypeTemplateParameterType)) {
2507 Invalid = true;
2508 continue;
2509 }
2510
2511 // Check the presence of a default argument here.
2512 if (NewNonTypeParm->hasDefaultArgument() &&
2513 DiagnoseDefaultTemplateArgument(
2514 S&: *this, TPC, ParamLoc: NewNonTypeParm->getLocation(),
2515 DefArgRange: NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2516 NewNonTypeParm->removeDefaultArgument();
2517 }
2518
2519 // Merge default arguments for non-type template parameters
2520 NonTypeTemplateParmDecl *OldNonTypeParm
2521 = OldParams? cast<NonTypeTemplateParmDecl>(Val: *OldParam) : nullptr;
2522 if (NewNonTypeParm->isParameterPack()) {
2523 assert(!NewNonTypeParm->hasDefaultArgument() &&
2524 "Parameter packs can't have a default argument!");
2525 if (!NewNonTypeParm->isPackExpansion())
2526 SawParameterPack = true;
2527 } else if (OldNonTypeParm && hasVisibleDefaultArgument(D: OldNonTypeParm) &&
2528 NewNonTypeParm->hasDefaultArgument() &&
2529 (!SkipBody || !SkipBody->ShouldSkip)) {
2530 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2531 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2532 SawDefaultArgument = true;
2533 if (!OldNonTypeParm->getOwningModule())
2534 RedundantDefaultArg = true;
2535 else if (!getASTContext().isSameDefaultTemplateArgument(
2536 X: OldNonTypeParm, Y: NewNonTypeParm)) {
2537 InconsistentDefaultArg = true;
2538 PrevModuleName =
2539 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2540 }
2541 PreviousDefaultArgLoc = NewDefaultLoc;
2542 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2543 // Merge the default argument from the old declaration to the
2544 // new declaration.
2545 NewNonTypeParm->setInheritedDefaultArgument(C: Context, Parm: OldNonTypeParm);
2546 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2547 } else if (NewNonTypeParm->hasDefaultArgument()) {
2548 SawDefaultArgument = true;
2549 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2550 } else if (SawDefaultArgument)
2551 MissingDefaultArg = true;
2552 } else {
2553 TemplateTemplateParmDecl *NewTemplateParm
2554 = cast<TemplateTemplateParmDecl>(Val: *NewParam);
2555
2556 // Check for unexpanded parameter packs, recursively.
2557 if (::DiagnoseUnexpandedParameterPacks(S&: *this, TTP: NewTemplateParm)) {
2558 Invalid = true;
2559 continue;
2560 }
2561
2562 // Check the presence of a default argument here.
2563 if (NewTemplateParm->hasDefaultArgument() &&
2564 DiagnoseDefaultTemplateArgument(S&: *this, TPC,
2565 ParamLoc: NewTemplateParm->getLocation(),
2566 DefArgRange: NewTemplateParm->getDefaultArgument().getSourceRange()))
2567 NewTemplateParm->removeDefaultArgument();
2568
2569 // Merge default arguments for template template parameters
2570 TemplateTemplateParmDecl *OldTemplateParm
2571 = OldParams? cast<TemplateTemplateParmDecl>(Val: *OldParam) : nullptr;
2572 if (NewTemplateParm->isParameterPack()) {
2573 assert(!NewTemplateParm->hasDefaultArgument() &&
2574 "Parameter packs can't have a default argument!");
2575 if (!NewTemplateParm->isPackExpansion())
2576 SawParameterPack = true;
2577 } else if (OldTemplateParm &&
2578 hasVisibleDefaultArgument(D: OldTemplateParm) &&
2579 NewTemplateParm->hasDefaultArgument() &&
2580 (!SkipBody || !SkipBody->ShouldSkip)) {
2581 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2582 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2583 SawDefaultArgument = true;
2584 if (!OldTemplateParm->getOwningModule())
2585 RedundantDefaultArg = true;
2586 else if (!getASTContext().isSameDefaultTemplateArgument(
2587 X: OldTemplateParm, Y: NewTemplateParm)) {
2588 InconsistentDefaultArg = true;
2589 PrevModuleName =
2590 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2591 }
2592 PreviousDefaultArgLoc = NewDefaultLoc;
2593 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2594 // Merge the default argument from the old declaration to the
2595 // new declaration.
2596 NewTemplateParm->setInheritedDefaultArgument(C: Context, Prev: OldTemplateParm);
2597 PreviousDefaultArgLoc
2598 = OldTemplateParm->getDefaultArgument().getLocation();
2599 } else if (NewTemplateParm->hasDefaultArgument()) {
2600 SawDefaultArgument = true;
2601 PreviousDefaultArgLoc
2602 = NewTemplateParm->getDefaultArgument().getLocation();
2603 } else if (SawDefaultArgument)
2604 MissingDefaultArg = true;
2605 }
2606
2607 // C++11 [temp.param]p11:
2608 // If a template parameter of a primary class template or alias template
2609 // is a template parameter pack, it shall be the last template parameter.
2610 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2611 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2612 Diag(Loc: (*NewParam)->getLocation(),
2613 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
2614 Invalid = true;
2615 }
2616
2617 // [basic.def.odr]/13:
2618 // There can be more than one definition of a
2619 // ...
2620 // default template argument
2621 // ...
2622 // in a program provided that each definition appears in a different
2623 // translation unit and the definitions satisfy the [same-meaning
2624 // criteria of the ODR].
2625 //
2626 // Simply, the design of modules allows the definition of template default
2627 // argument to be repeated across translation unit. Note that the ODR is
2628 // checked elsewhere. But it is still not allowed to repeat template default
2629 // argument in the same translation unit.
2630 if (RedundantDefaultArg) {
2631 Diag(Loc: NewDefaultLoc, DiagID: diag::err_template_param_default_arg_redefinition);
2632 Diag(Loc: OldDefaultLoc, DiagID: diag::note_template_param_prev_default_arg);
2633 Invalid = true;
2634 } else if (InconsistentDefaultArg) {
2635 // We could only diagnose about the case that the OldParam is imported.
2636 // The case NewParam is imported should be handled in ASTReader.
2637 Diag(Loc: NewDefaultLoc,
2638 DiagID: diag::err_template_param_default_arg_inconsistent_redefinition);
2639 Diag(Loc: OldDefaultLoc,
2640 DiagID: diag::note_template_param_prev_default_arg_in_other_module)
2641 << PrevModuleName;
2642 Invalid = true;
2643 } else if (MissingDefaultArg &&
2644 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2645 TPC == TPC_FriendClassTemplate)) {
2646 // C++ 23[temp.param]p14:
2647 // If a template-parameter of a class template, variable template, or
2648 // alias template has a default template argument, each subsequent
2649 // template-parameter shall either have a default template argument
2650 // supplied or be a template parameter pack.
2651 Diag(Loc: (*NewParam)->getLocation(),
2652 DiagID: diag::err_template_param_default_arg_missing);
2653 Diag(Loc: PreviousDefaultArgLoc, DiagID: diag::note_template_param_prev_default_arg);
2654 Invalid = true;
2655 RemoveDefaultArguments = true;
2656 }
2657
2658 // If we have an old template parameter list that we're merging
2659 // in, move on to the next parameter.
2660 if (OldParams)
2661 ++OldParam;
2662 }
2663
2664 // We were missing some default arguments at the end of the list, so remove
2665 // all of the default arguments.
2666 if (RemoveDefaultArguments) {
2667 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2668 NewParamEnd = NewParams->end();
2669 NewParam != NewParamEnd; ++NewParam) {
2670 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam))
2671 TTP->removeDefaultArgument();
2672 else if (NonTypeTemplateParmDecl *NTTP
2673 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam))
2674 NTTP->removeDefaultArgument();
2675 else
2676 cast<TemplateTemplateParmDecl>(Val: *NewParam)->removeDefaultArgument();
2677 }
2678 }
2679
2680 return Invalid;
2681}
2682
2683namespace {
2684
2685/// A class which looks for a use of a certain level of template
2686/// parameter.
2687struct DependencyChecker : DynamicRecursiveASTVisitor {
2688 unsigned Depth;
2689
2690 // Whether we're looking for a use of a template parameter that makes the
2691 // overall construct type-dependent / a dependent type. This is strictly
2692 // best-effort for now; we may fail to match at all for a dependent type
2693 // in some cases if this is set.
2694 bool IgnoreNonTypeDependent;
2695
2696 bool Match;
2697 SourceLocation MatchLoc;
2698
2699 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2700 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2701 Match(false) {}
2702
2703 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2704 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2705 NamedDecl *ND = Params->getParam(Idx: 0);
2706 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(Val: ND)) {
2707 Depth = PD->getDepth();
2708 } else if (NonTypeTemplateParmDecl *PD =
2709 dyn_cast<NonTypeTemplateParmDecl>(Val: ND)) {
2710 Depth = PD->getDepth();
2711 } else {
2712 Depth = cast<TemplateTemplateParmDecl>(Val: ND)->getDepth();
2713 }
2714 }
2715
2716 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2717 if (ParmDepth >= Depth) {
2718 Match = true;
2719 MatchLoc = Loc;
2720 return true;
2721 }
2722 return false;
2723 }
2724
2725 bool TraverseStmt(Stmt *S) override {
2726 // Prune out non-type-dependent expressions if requested. This can
2727 // sometimes result in us failing to find a template parameter reference
2728 // (if a value-dependent expression creates a dependent type), but this
2729 // mode is best-effort only.
2730 if (auto *E = dyn_cast_or_null<Expr>(Val: S))
2731 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2732 return true;
2733 return DynamicRecursiveASTVisitor::TraverseStmt(S);
2734 }
2735
2736 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2737 if (IgnoreNonTypeDependent && !TL.isNull() &&
2738 !TL.getType()->isDependentType())
2739 return true;
2740 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2741 }
2742
2743 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2744 return !Matches(ParmDepth: TL.getTypePtr()->getDepth(), Loc: TL.getNameLoc());
2745 }
2746
2747 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2748 // For a best-effort search, keep looking until we find a location.
2749 return IgnoreNonTypeDependent || !Matches(ParmDepth: T->getDepth());
2750 }
2751
2752 bool TraverseTemplateName(TemplateName N) override {
2753 if (TemplateTemplateParmDecl *PD =
2754 dyn_cast_or_null<TemplateTemplateParmDecl>(Val: N.getAsTemplateDecl()))
2755 if (Matches(ParmDepth: PD->getDepth()))
2756 return false;
2757 return DynamicRecursiveASTVisitor::TraverseTemplateName(Template: N);
2758 }
2759
2760 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2761 if (NonTypeTemplateParmDecl *PD =
2762 dyn_cast<NonTypeTemplateParmDecl>(Val: E->getDecl()))
2763 if (Matches(ParmDepth: PD->getDepth(), Loc: E->getExprLoc()))
2764 return false;
2765 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(S: E);
2766 }
2767
2768 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
2769 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
2770 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
2771 if (Matches(ParmDepth: TTP->getDepth(), Loc: ULE->getExprLoc()))
2772 return false;
2773 }
2774 for (auto &TLoc : ULE->template_arguments())
2775 DynamicRecursiveASTVisitor::TraverseTemplateArgumentLoc(ArgLoc: TLoc);
2776 }
2777 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(S: ULE);
2778 }
2779
2780 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2781 return TraverseType(T: T->getReplacementType());
2782 }
2783
2784 bool VisitSubstTemplateTypeParmPackType(
2785 SubstTemplateTypeParmPackType *T) override {
2786 return TraverseTemplateArgument(Arg: T->getArgumentPack());
2787 }
2788
2789 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2790 bool TraverseQualifier) override {
2791 // An InjectedClassNameType will never have a dependent template name,
2792 // so no need to traverse it.
2793 return TraverseTemplateArguments(
2794 Args: T->getTemplateArgs(Ctx: T->getDecl()->getASTContext()));
2795 }
2796};
2797} // end anonymous namespace
2798
2799/// Determines whether a given type depends on the given parameter
2800/// list.
2801static bool
2802DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2803 if (!Params->size())
2804 return false;
2805
2806 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2807 Checker.TraverseType(T);
2808 return Checker.Match;
2809}
2810
2811// Find the source range corresponding to the named type in the given
2812// nested-name-specifier, if any.
2813static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2814 QualType T,
2815 const CXXScopeSpec &SS) {
2816 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2817 for (;;) {
2818 NestedNameSpecifier NNS = NNSLoc.getNestedNameSpecifier();
2819 if (NNS.getKind() != NestedNameSpecifier::Kind::Type)
2820 break;
2821 if (Context.hasSameUnqualifiedType(T1: T, T2: QualType(NNS.getAsType(), 0)))
2822 return NNSLoc.castAsTypeLoc().getSourceRange();
2823 // FIXME: This will always be empty.
2824 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2825 }
2826
2827 return SourceRange();
2828}
2829
2830TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2831 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2832 TemplateIdAnnotation *TemplateId,
2833 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2834 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2835 IsMemberSpecialization = false;
2836 Invalid = false;
2837
2838 // The sequence of nested types to which we will match up the template
2839 // parameter lists. We first build this list by starting with the type named
2840 // by the nested-name-specifier and walking out until we run out of types.
2841 SmallVector<QualType, 4> NestedTypes;
2842 QualType T;
2843 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2844 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2845 if (CXXRecordDecl *Record =
2846 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: true)))
2847 T = Context.getCanonicalTagType(TD: Record);
2848 else
2849 T = QualType(Qualifier.getAsType(), 0);
2850 }
2851
2852 // If we found an explicit specialization that prevents us from needing
2853 // 'template<>' headers, this will be set to the location of that
2854 // explicit specialization.
2855 SourceLocation ExplicitSpecLoc;
2856
2857 while (!T.isNull()) {
2858 NestedTypes.push_back(Elt: T);
2859
2860 // Retrieve the parent of a record type.
2861 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2862 // If this type is an explicit specialization, we're done.
2863 if (ClassTemplateSpecializationDecl *Spec
2864 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
2865 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Spec) &&
2866 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2867 ExplicitSpecLoc = Spec->getLocation();
2868 break;
2869 }
2870 } else if (Record->getTemplateSpecializationKind()
2871 == TSK_ExplicitSpecialization) {
2872 ExplicitSpecLoc = Record->getLocation();
2873 break;
2874 }
2875
2876 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Record->getParent()))
2877 T = Context.getTypeDeclType(Decl: Parent);
2878 else
2879 T = QualType();
2880 continue;
2881 }
2882
2883 if (const TemplateSpecializationType *TST
2884 = T->getAs<TemplateSpecializationType>()) {
2885 TemplateName Name = TST->getTemplateName();
2886 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2887 // Look one step prior in a dependent template specialization type.
2888 if (NestedNameSpecifier NNS = DTS->getQualifier();
2889 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2890 T = QualType(NNS.getAsType(), 0);
2891 else
2892 T = QualType();
2893 continue;
2894 }
2895 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2896 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Template->getDeclContext()))
2897 T = Context.getTypeDeclType(Decl: Parent);
2898 else
2899 T = QualType();
2900 continue;
2901 }
2902 }
2903
2904 // Look one step prior in a dependent name type.
2905 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2906 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2907 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2908 T = QualType(NNS.getAsType(), 0);
2909 else
2910 T = QualType();
2911 continue;
2912 }
2913
2914 // Retrieve the parent of an enumeration type.
2915 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2916 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2917 // check here.
2918 EnumDecl *Enum = EnumT->getDecl();
2919
2920 // Get to the parent type.
2921 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Enum->getParent()))
2922 T = Context.getCanonicalTypeDeclType(TD: Parent);
2923 else
2924 T = QualType();
2925 continue;
2926 }
2927
2928 T = QualType();
2929 }
2930 // Reverse the nested types list, since we want to traverse from the outermost
2931 // to the innermost while checking template-parameter-lists.
2932 std::reverse(first: NestedTypes.begin(), last: NestedTypes.end());
2933
2934 // C++0x [temp.expl.spec]p17:
2935 // A member or a member template may be nested within many
2936 // enclosing class templates. In an explicit specialization for
2937 // such a member, the member declaration shall be preceded by a
2938 // template<> for each enclosing class template that is
2939 // explicitly specialized.
2940 bool SawNonEmptyTemplateParameterList = false;
2941
2942 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2943 if (SawNonEmptyTemplateParameterList) {
2944 if (!SuppressDiagnostic)
2945 Diag(Loc: DeclLoc, DiagID: diag::err_specialize_member_of_template)
2946 << !Recovery << Range;
2947 Invalid = true;
2948 IsMemberSpecialization = false;
2949 return true;
2950 }
2951
2952 return false;
2953 };
2954
2955 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2956 // Check that we can have an explicit specialization here.
2957 if (CheckExplicitSpecialization(Range, true))
2958 return true;
2959
2960 // We don't have a template header, but we should.
2961 SourceLocation ExpectedTemplateLoc;
2962 if (!ParamLists.empty())
2963 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2964 else
2965 ExpectedTemplateLoc = DeclStartLoc;
2966
2967 if (!SuppressDiagnostic)
2968 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_header)
2969 << Range
2970 << FixItHint::CreateInsertion(InsertionLoc: ExpectedTemplateLoc, Code: "template<> ");
2971 return false;
2972 };
2973
2974 unsigned ParamIdx = 0;
2975 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2976 ++TypeIdx) {
2977 T = NestedTypes[TypeIdx];
2978
2979 // Whether we expect a 'template<>' header.
2980 bool NeedEmptyTemplateHeader = false;
2981
2982 // Whether we expect a template header with parameters.
2983 bool NeedNonemptyTemplateHeader = false;
2984
2985 // For a dependent type, the set of template parameters that we
2986 // expect to see.
2987 TemplateParameterList *ExpectedTemplateParams = nullptr;
2988
2989 // C++0x [temp.expl.spec]p15:
2990 // A member or a member template may be nested within many enclosing
2991 // class templates. In an explicit specialization for such a member, the
2992 // member declaration shall be preceded by a template<> for each
2993 // enclosing class template that is explicitly specialized.
2994 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2995 if (ClassTemplatePartialSpecializationDecl *Partial
2996 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Record)) {
2997 ExpectedTemplateParams = Partial->getTemplateParameters();
2998 NeedNonemptyTemplateHeader = true;
2999 } else if (Record->isDependentType()) {
3000 if (Record->getDescribedClassTemplate()) {
3001 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3002 ->getTemplateParameters();
3003 NeedNonemptyTemplateHeader = true;
3004 }
3005 } else if (ClassTemplateSpecializationDecl *Spec
3006 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
3007 // C++0x [temp.expl.spec]p4:
3008 // Members of an explicitly specialized class template are defined
3009 // in the same manner as members of normal classes, and not using
3010 // the template<> syntax.
3011 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3012 NeedEmptyTemplateHeader = true;
3013 else
3014 continue;
3015 } else if (Record->getTemplateSpecializationKind()) {
3016 if (Record->getTemplateSpecializationKind()
3017 != TSK_ExplicitSpecialization &&
3018 TypeIdx == NumTypes - 1)
3019 IsMemberSpecialization = true;
3020
3021 continue;
3022 }
3023 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3024 TemplateName Name = TST->getTemplateName();
3025 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3026 ExpectedTemplateParams = Template->getTemplateParameters();
3027 NeedNonemptyTemplateHeader = true;
3028 } else if (Name.getAsDeducedTemplateName()) {
3029 // FIXME: We actually could/should check the template arguments here
3030 // against the corresponding template parameter list.
3031 NeedNonemptyTemplateHeader = false;
3032 }
3033 }
3034
3035 // C++ [temp.expl.spec]p16:
3036 // In an explicit specialization declaration for a member of a class
3037 // template or a member template that appears in namespace scope, the
3038 // member template and some of its enclosing class templates may remain
3039 // unspecialized, except that the declaration shall not explicitly
3040 // specialize a class member template if its enclosing class templates
3041 // are not explicitly specialized as well.
3042 if (ParamIdx < ParamLists.size()) {
3043 if (ParamLists[ParamIdx]->size() == 0) {
3044 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3045 false))
3046 return nullptr;
3047 } else
3048 SawNonEmptyTemplateParameterList = true;
3049 }
3050
3051 if (NeedEmptyTemplateHeader) {
3052 // If we're on the last of the types, and we need a 'template<>' header
3053 // here, then it's a member specialization.
3054 if (TypeIdx == NumTypes - 1)
3055 IsMemberSpecialization = true;
3056
3057 if (ParamIdx < ParamLists.size()) {
3058 if (ParamLists[ParamIdx]->size() > 0) {
3059 // The header has template parameters when it shouldn't. Complain.
3060 if (!SuppressDiagnostic)
3061 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3062 DiagID: diag::err_template_param_list_matches_nontemplate)
3063 << T
3064 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3065 ParamLists[ParamIdx]->getRAngleLoc())
3066 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3067 Invalid = true;
3068 return nullptr;
3069 }
3070
3071 // Consume this template header.
3072 ++ParamIdx;
3073 continue;
3074 }
3075
3076 if (!IsFriend)
3077 if (DiagnoseMissingExplicitSpecialization(
3078 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3079 return nullptr;
3080
3081 continue;
3082 }
3083
3084 if (NeedNonemptyTemplateHeader) {
3085 // In friend declarations we can have template-ids which don't
3086 // depend on the corresponding template parameter lists. But
3087 // assume that empty parameter lists are supposed to match this
3088 // template-id.
3089 if (IsFriend && T->isDependentType()) {
3090 if (ParamIdx < ParamLists.size() &&
3091 DependsOnTemplateParameters(T, Params: ParamLists[ParamIdx]))
3092 ExpectedTemplateParams = nullptr;
3093 else
3094 continue;
3095 }
3096
3097 if (ParamIdx < ParamLists.size()) {
3098 // Check the template parameter list, if we can.
3099 if (ExpectedTemplateParams &&
3100 !TemplateParameterListsAreEqual(New: ParamLists[ParamIdx],
3101 Old: ExpectedTemplateParams,
3102 Complain: !SuppressDiagnostic, Kind: TPL_TemplateMatch))
3103 Invalid = true;
3104
3105 if (!Invalid &&
3106 CheckTemplateParameterList(NewParams: ParamLists[ParamIdx], OldParams: nullptr,
3107 TPC: TPC_ClassTemplateMember))
3108 Invalid = true;
3109
3110 ++ParamIdx;
3111 continue;
3112 }
3113
3114 if (!SuppressDiagnostic)
3115 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_template_parameters)
3116 << T
3117 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3118 Invalid = true;
3119 continue;
3120 }
3121 }
3122
3123 // If there were at least as many template-ids as there were template
3124 // parameter lists, then there are no template parameter lists remaining for
3125 // the declaration itself.
3126 if (ParamIdx >= ParamLists.size()) {
3127 if (TemplateId && !IsFriend) {
3128 // We don't have a template header for the declaration itself, but we
3129 // should.
3130 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3131 TemplateId->RAngleLoc));
3132
3133 // Fabricate an empty template parameter list for the invented header.
3134 return TemplateParameterList::Create(C: Context, TemplateLoc: SourceLocation(),
3135 LAngleLoc: SourceLocation(), Params: {},
3136 RAngleLoc: SourceLocation(), RequiresClause: nullptr);
3137 }
3138
3139 return nullptr;
3140 }
3141
3142 // If there were too many template parameter lists, complain about that now.
3143 if (ParamIdx < ParamLists.size() - 1) {
3144 bool HasAnyExplicitSpecHeader = false;
3145 bool AllExplicitSpecHeaders = true;
3146 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3147 if (ParamLists[I]->size() == 0)
3148 HasAnyExplicitSpecHeader = true;
3149 else
3150 AllExplicitSpecHeaders = false;
3151 }
3152
3153 if (!SuppressDiagnostic)
3154 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3155 DiagID: AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3156 : diag::err_template_spec_extra_headers)
3157 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3158 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3159
3160 // If there was a specialization somewhere, such that 'template<>' is
3161 // not required, and there were any 'template<>' headers, note where the
3162 // specialization occurred.
3163 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3164 !SuppressDiagnostic)
3165 Diag(Loc: ExplicitSpecLoc,
3166 DiagID: diag::note_explicit_template_spec_does_not_need_header)
3167 << NestedTypes.back();
3168
3169 // We have a template parameter list with no corresponding scope, which
3170 // means that the resulting template declaration can't be instantiated
3171 // properly (we'll end up with dependent nodes when we shouldn't).
3172 if (!AllExplicitSpecHeaders)
3173 Invalid = true;
3174 }
3175
3176 // C++ [temp.expl.spec]p16:
3177 // In an explicit specialization declaration for a member of a class
3178 // template or a member template that ap- pears in namespace scope, the
3179 // member template and some of its enclosing class templates may remain
3180 // unspecialized, except that the declaration shall not explicitly
3181 // specialize a class member template if its en- closing class templates
3182 // are not explicitly specialized as well.
3183 if (ParamLists.back()->size() == 0 &&
3184 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3185 false))
3186 return nullptr;
3187
3188 // Return the last template parameter list, which corresponds to the
3189 // entity being declared.
3190 return ParamLists.back();
3191}
3192
3193void Sema::NoteAllFoundTemplates(TemplateName Name) {
3194 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3195 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_declared_here)
3196 << (isa<FunctionTemplateDecl>(Val: Template)
3197 ? 0
3198 : isa<ClassTemplateDecl>(Val: Template)
3199 ? 1
3200 : isa<VarTemplateDecl>(Val: Template)
3201 ? 2
3202 : isa<TypeAliasTemplateDecl>(Val: Template) ? 3 : 4)
3203 << Template->getDeclName();
3204 return;
3205 }
3206
3207 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3208 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3209 IEnd = OST->end();
3210 I != IEnd; ++I)
3211 Diag(Loc: (*I)->getLocation(), DiagID: diag::note_template_declared_here)
3212 << 0 << (*I)->getDeclName();
3213
3214 return;
3215 }
3216}
3217
3218static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword,
3219 TemplateName BaseTemplate,
3220 SourceLocation TemplateLoc,
3221 ArrayRef<TemplateArgument> Ts) {
3222 auto lookUpCommonType = [&](TemplateArgument T1,
3223 TemplateArgument T2) -> QualType {
3224 // Don't bother looking for other specializations if both types are
3225 // builtins - users aren't allowed to specialize for them
3226 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3227 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3228 Ts: {T1, T2});
3229
3230 TemplateArgumentListInfo Args;
3231 Args.addArgument(Loc: TemplateArgumentLoc(
3232 T1, S.Context.getTrivialTypeSourceInfo(T: T1.getAsType())));
3233 Args.addArgument(Loc: TemplateArgumentLoc(
3234 T2, S.Context.getTrivialTypeSourceInfo(T: T2.getAsType())));
3235
3236 EnterExpressionEvaluationContext UnevaluatedContext(
3237 S, Sema::ExpressionEvaluationContext::Unevaluated);
3238 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3239 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3240
3241 QualType BaseTemplateInst = S.CheckTemplateIdType(
3242 Keyword, Template: BaseTemplate, TemplateLoc, TemplateArgs&: Args,
3243 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3244
3245 if (SFINAE.hasErrorOccurred())
3246 return QualType();
3247
3248 return BaseTemplateInst;
3249 };
3250
3251 // Note A: For the common_type trait applied to a template parameter pack T of
3252 // types, the member type shall be either defined or not present as follows:
3253 switch (Ts.size()) {
3254
3255 // If sizeof...(T) is zero, there shall be no member type.
3256 case 0:
3257 return QualType();
3258
3259 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3260 // pack T. The member typedef-name type shall denote the same type, if any, as
3261 // common_type_t<T0, T0>; otherwise there shall be no member type.
3262 case 1:
3263 return lookUpCommonType(Ts[0], Ts[0]);
3264
3265 // If sizeof...(T) is two, let the first and second types constituting T be
3266 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3267 // as decay_t<T1> and decay_t<T2>, respectively.
3268 case 2: {
3269 QualType T1 = Ts[0].getAsType();
3270 QualType T2 = Ts[1].getAsType();
3271 QualType D1 = S.BuiltinDecay(BaseType: T1, Loc: {});
3272 QualType D2 = S.BuiltinDecay(BaseType: T2, Loc: {});
3273
3274 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3275 // the same type, if any, as common_type_t<D1, D2>.
3276 if (!S.Context.hasSameType(T1, T2: D1) || !S.Context.hasSameType(T1: T2, T2: D2))
3277 return lookUpCommonType(D1, D2);
3278
3279 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3280 // denotes a valid type, let C denote that type.
3281 {
3282 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3283 EnterExpressionEvaluationContext UnevaluatedContext(
3284 S, Sema::ExpressionEvaluationContext::Unevaluated);
3285 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3286 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3287
3288 // false
3289 OpaqueValueExpr CondExpr(SourceLocation(), S.Context.BoolTy,
3290 VK_PRValue);
3291 ExprResult Cond = &CondExpr;
3292
3293 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3294 if (ConstRefQual) {
3295 D1.addConst();
3296 D2.addConst();
3297 }
3298
3299 // declval<D1>()
3300 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3301 ExprResult LHS = &LHSExpr;
3302
3303 // declval<D2>()
3304 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3305 ExprResult RHS = &RHSExpr;
3306
3307 ExprValueKind VK = VK_PRValue;
3308 ExprObjectKind OK = OK_Ordinary;
3309
3310 // decltype(false ? declval<D1>() : declval<D2>())
3311 QualType Result =
3312 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc: TemplateLoc);
3313
3314 if (Result.isNull() || SFINAE.hasErrorOccurred())
3315 return QualType();
3316
3317 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3318 return S.BuiltinDecay(BaseType: Result, Loc: TemplateLoc);
3319 };
3320
3321 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3322 return Res;
3323
3324 // Let:
3325 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3326 // COND-RES(X, Y) be
3327 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3328
3329 // C++20 only
3330 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3331 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3332 if (!S.Context.getLangOpts().CPlusPlus20)
3333 return QualType();
3334 return CheckConditionalOperands(true);
3335 }
3336 }
3337
3338 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3339 // denote the first, second, and (pack of) remaining types constituting T. Let
3340 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3341 // a type C, the member typedef-name type shall denote the same type, if any,
3342 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3343 default: {
3344 QualType Result = Ts.front().getAsType();
3345 for (auto T : llvm::drop_begin(RangeOrContainer&: Ts)) {
3346 Result = lookUpCommonType(Result, T.getAsType());
3347 if (Result.isNull())
3348 return QualType();
3349 }
3350 return Result;
3351 }
3352 }
3353}
3354
3355static bool isInVkNamespace(const RecordType *RT) {
3356 DeclContext *DC = RT->getDecl()->getDeclContext();
3357 if (!DC)
3358 return false;
3359
3360 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Val: DC);
3361 if (!ND)
3362 return false;
3363
3364 return ND->getQualifiedNameAsString() == "hlsl::vk";
3365}
3366
3367static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3368 QualType OperandArg,
3369 SourceLocation Loc) {
3370 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3371 bool Literal = false;
3372 SourceLocation LiteralLoc;
3373 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3374 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3375 assert(SpecDecl);
3376
3377 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3378 QualType ConstantType = LiteralArgs[0].getAsType();
3379 RT = ConstantType->getAsCanonical<RecordType>();
3380 Literal = true;
3381 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3382 }
3383
3384 if (RT && isInVkNamespace(RT) &&
3385 RT->getDecl()->getName() == "integral_constant") {
3386 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3387 assert(SpecDecl);
3388
3389 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3390
3391 QualType ConstantType = ConstantArgs[0].getAsType();
3392 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3393
3394 if (Literal)
3395 return SpirvOperand::createLiteral(Val: Value);
3396 return SpirvOperand::createConstant(ResultType: ConstantType, Val: Value);
3397 } else if (Literal) {
3398 SemaRef.Diag(Loc: LiteralLoc, DiagID: diag::err_hlsl_vk_literal_must_contain_constant);
3399 return SpirvOperand();
3400 }
3401 }
3402 if (SemaRef.RequireCompleteType(Loc, T: OperandArg,
3403 DiagID: diag::err_call_incomplete_argument))
3404 return SpirvOperand();
3405 return SpirvOperand::createType(T: OperandArg);
3406}
3407
3408static QualType checkBuiltinTemplateIdType(
3409 Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD,
3410 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3411 TemplateArgumentListInfo &TemplateArgs) {
3412 ASTContext &Context = SemaRef.getASTContext();
3413
3414 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3415 "Builtin template arguments do not match its parameters");
3416
3417 switch (BTD->getBuiltinTemplateKind()) {
3418 case BTK__make_integer_seq: {
3419 // Specializations of __make_integer_seq<S, T, N> are treated like
3420 // S<T, 0, ..., N-1>.
3421
3422 QualType OrigType = Converted[1].getAsType();
3423 // C++14 [inteseq.intseq]p1:
3424 // T shall be an integer type.
3425 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Ctx: Context)) {
3426 SemaRef.Diag(Loc: TemplateArgs[1].getLocation(),
3427 DiagID: diag::err_integer_sequence_integral_element_type);
3428 return QualType();
3429 }
3430
3431 TemplateArgument NumArgsArg = Converted[2];
3432 if (NumArgsArg.isDependent())
3433 return QualType();
3434
3435 TemplateArgumentListInfo SyntheticTemplateArgs;
3436 // The type argument, wrapped in substitution sugar, gets reused as the
3437 // first template argument in the synthetic template argument list.
3438 SyntheticTemplateArgs.addArgument(
3439 Loc: TemplateArgumentLoc(TemplateArgument(OrigType),
3440 SemaRef.Context.getTrivialTypeSourceInfo(
3441 T: OrigType, Loc: TemplateArgs[1].getLocation())));
3442
3443 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3444 // Expand N into 0 ... N-1.
3445 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3446 I < NumArgs; ++I) {
3447 TemplateArgument TA(Context, I, OrigType);
3448 SyntheticTemplateArgs.addArgument(Loc: SemaRef.getTrivialTemplateArgumentLoc(
3449 Arg: TA, NTTPType: OrigType, Loc: TemplateArgs[2].getLocation()));
3450 }
3451 } else {
3452 // C++14 [inteseq.make]p1:
3453 // If N is negative the program is ill-formed.
3454 SemaRef.Diag(Loc: TemplateArgs[2].getLocation(),
3455 DiagID: diag::err_integer_sequence_negative_length);
3456 return QualType();
3457 }
3458
3459 // The first template argument will be reused as the template decl that
3460 // our synthetic template arguments will be applied to.
3461 return SemaRef.CheckTemplateIdType(Keyword, Template: Converted[0].getAsTemplate(),
3462 TemplateLoc, TemplateArgs&: SyntheticTemplateArgs,
3463 /*Scope=*/nullptr,
3464 /*ForNestedNameSpecifier=*/false);
3465 }
3466
3467 case BTK__type_pack_element: {
3468 // Specializations of
3469 // __type_pack_element<Index, T_1, ..., T_N>
3470 // are treated like T_Index.
3471 assert(Converted.size() == 2 &&
3472 "__type_pack_element should be given an index and a parameter pack");
3473
3474 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3475 if (IndexArg.isDependent() || Ts.isDependent())
3476 return QualType();
3477
3478 llvm::APSInt Index = IndexArg.getAsIntegral();
3479 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3480 "type std::size_t, and hence be non-negative");
3481 // If the Index is out of bounds, the program is ill-formed.
3482 if (Index >= Ts.pack_size()) {
3483 SemaRef.Diag(Loc: TemplateArgs[0].getLocation(),
3484 DiagID: diag::err_type_pack_element_out_of_bounds);
3485 return QualType();
3486 }
3487
3488 // We simply return the type at index `Index`.
3489 int64_t N = Index.getExtValue();
3490 return Ts.getPackAsArray()[N].getAsType();
3491 }
3492
3493 case BTK__builtin_common_type: {
3494 assert(Converted.size() == 4);
3495 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3496 return QualType();
3497
3498 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3499 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3500 if (auto CT = builtinCommonTypeImpl(S&: SemaRef, Keyword, BaseTemplate,
3501 TemplateLoc, Ts);
3502 !CT.isNull()) {
3503 TemplateArgumentListInfo TAs;
3504 TAs.addArgument(Loc: TemplateArgumentLoc(
3505 TemplateArgument(CT), SemaRef.Context.getTrivialTypeSourceInfo(
3506 T: CT, Loc: TemplateArgs[1].getLocation())));
3507 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3508 return SemaRef.CheckTemplateIdType(Keyword, Template: HasTypeMember, TemplateLoc,
3509 TemplateArgs&: TAs, /*Scope=*/nullptr,
3510 /*ForNestedNameSpecifier=*/false);
3511 }
3512 QualType HasNoTypeMember = Converted[2].getAsType();
3513 return HasNoTypeMember;
3514 }
3515
3516 case BTK__hlsl_spirv_type: {
3517 assert(Converted.size() == 4);
3518
3519 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3520 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_hlsl_spirv_only) << BTD;
3521 }
3522
3523 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3524 return QualType();
3525
3526 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3527 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3528 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3529
3530 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3531
3532 llvm::SmallVector<SpirvOperand> Operands;
3533
3534 for (auto &OperandTA : OperandArgs) {
3535 QualType OperandArg = OperandTA.getAsType();
3536 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3537 Loc: TemplateArgs[3].getLocation());
3538 if (!Operand.isValid())
3539 return QualType();
3540 Operands.push_back(Elt: Operand);
3541 }
3542
3543 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3544 }
3545 case BTK__builtin_dedup_pack: {
3546 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3547 "a parameter pack");
3548 TemplateArgument Ts = Converted[0];
3549 // Delay the computation until we can compute the final result. We choose
3550 // not to remove the duplicates upfront before substitution to keep the code
3551 // simple.
3552 if (Ts.isDependent())
3553 return QualType();
3554 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3555 llvm::SmallVector<TemplateArgument> OutArgs;
3556 llvm::SmallDenseSet<QualType> Seen;
3557 // Synthesize a new template argument list, removing duplicates.
3558 for (auto T : Ts.getPackAsArray()) {
3559 assert(T.getKind() == clang::TemplateArgument::Type);
3560 if (!Seen.insert(V: T.getAsType().getCanonicalType()).second)
3561 continue;
3562 OutArgs.push_back(Elt: T);
3563 }
3564 return Context.getSubstBuiltinTemplatePack(
3565 ArgPack: TemplateArgument::CreatePackCopy(Context, Args: OutArgs));
3566 }
3567 }
3568 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3569}
3570
3571/// Determine whether this alias template is "enable_if_t".
3572/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3573static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3574 return AliasTemplate->getName() == "enable_if_t" ||
3575 AliasTemplate->getName() == "__enable_if_t";
3576}
3577
3578/// Collect all of the separable terms in the given condition, which
3579/// might be a conjunction.
3580///
3581/// FIXME: The right answer is to convert the logical expression into
3582/// disjunctive normal form, so we can find the first failed term
3583/// within each possible clause.
3584static void collectConjunctionTerms(Expr *Clause,
3585 SmallVectorImpl<Expr *> &Terms) {
3586 if (auto BinOp = dyn_cast<BinaryOperator>(Val: Clause->IgnoreParenImpCasts())) {
3587 if (BinOp->getOpcode() == BO_LAnd) {
3588 collectConjunctionTerms(Clause: BinOp->getLHS(), Terms);
3589 collectConjunctionTerms(Clause: BinOp->getRHS(), Terms);
3590 return;
3591 }
3592 }
3593
3594 Terms.push_back(Elt: Clause);
3595}
3596
3597// The ranges-v3 library uses an odd pattern of a top-level "||" with
3598// a left-hand side that is value-dependent but never true. Identify
3599// the idiom and ignore that term.
3600static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3601 // Top-level '||'.
3602 auto *BinOp = dyn_cast<BinaryOperator>(Val: Cond->IgnoreParenImpCasts());
3603 if (!BinOp) return Cond;
3604
3605 if (BinOp->getOpcode() != BO_LOr) return Cond;
3606
3607 // With an inner '==' that has a literal on the right-hand side.
3608 Expr *LHS = BinOp->getLHS();
3609 auto *InnerBinOp = dyn_cast<BinaryOperator>(Val: LHS->IgnoreParenImpCasts());
3610 if (!InnerBinOp) return Cond;
3611
3612 if (InnerBinOp->getOpcode() != BO_EQ ||
3613 !isa<IntegerLiteral>(Val: InnerBinOp->getRHS()))
3614 return Cond;
3615
3616 // If the inner binary operation came from a macro expansion named
3617 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3618 // of the '||', which is the real, user-provided condition.
3619 SourceLocation Loc = InnerBinOp->getExprLoc();
3620 if (!Loc.isMacroID()) return Cond;
3621
3622 StringRef MacroName = PP.getImmediateMacroName(Loc);
3623 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3624 return BinOp->getRHS();
3625
3626 return Cond;
3627}
3628
3629namespace {
3630
3631// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3632// within failing boolean expression, such as substituting template parameters
3633// for actual types.
3634class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3635public:
3636 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3637 : Policy(P) {}
3638
3639 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3640 const auto *DR = dyn_cast<DeclRefExpr>(Val: E);
3641 if (DR && DR->getQualifier()) {
3642 // If this is a qualified name, expand the template arguments in nested
3643 // qualifiers.
3644 DR->getQualifier().print(OS, Policy, ResolveTemplateArguments: true);
3645 // Then print the decl itself.
3646 const ValueDecl *VD = DR->getDecl();
3647 OS << VD->getName();
3648 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) {
3649 // This is a template variable, print the expanded template arguments.
3650 printTemplateArgumentList(
3651 OS, Args: IV->getTemplateArgs().asArray(), Policy,
3652 TPL: IV->getSpecializedTemplate()->getTemplateParameters());
3653 }
3654 return true;
3655 }
3656 return false;
3657 }
3658
3659private:
3660 const PrintingPolicy Policy;
3661};
3662
3663} // end anonymous namespace
3664
3665std::pair<Expr *, std::string>
3666Sema::findFailedBooleanCondition(Expr *Cond) {
3667 Cond = lookThroughRangesV3Condition(PP, Cond);
3668
3669 // Separate out all of the terms in a conjunction.
3670 SmallVector<Expr *, 4> Terms;
3671 collectConjunctionTerms(Clause: Cond, Terms);
3672
3673 // Determine which term failed.
3674 Expr *FailedCond = nullptr;
3675 for (Expr *Term : Terms) {
3676 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3677
3678 // Literals are uninteresting.
3679 if (isa<CXXBoolLiteralExpr>(Val: TermAsWritten) ||
3680 isa<IntegerLiteral>(Val: TermAsWritten))
3681 continue;
3682
3683 // The initialization of the parameter from the argument is
3684 // a constant-evaluated context.
3685 EnterExpressionEvaluationContext ConstantEvaluated(
3686 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3687
3688 bool Succeeded;
3689 if (Term->EvaluateAsBooleanCondition(Result&: Succeeded, Ctx: Context) &&
3690 !Succeeded) {
3691 FailedCond = TermAsWritten;
3692 break;
3693 }
3694 }
3695 if (!FailedCond)
3696 FailedCond = Cond->IgnoreParenImpCasts();
3697
3698 std::string Description;
3699 {
3700 llvm::raw_string_ostream Out(Description);
3701 PrintingPolicy Policy = getPrintingPolicy();
3702 Policy.PrintAsCanonical = true;
3703 FailedBooleanConditionPrinterHelper Helper(Policy);
3704 FailedCond->printPretty(OS&: Out, Helper: &Helper, Policy, Indentation: 0, NewlineSymbol: "\n", Context: nullptr);
3705 }
3706 return { FailedCond, Description };
3707}
3708
3709static TemplateName
3710resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope,
3711 const AssumedTemplateStorage *ATN,
3712 SourceLocation NameLoc) {
3713 // We assumed this undeclared identifier to be an (ADL-only) function
3714 // template name, but it was used in a context where a type was required.
3715 // Try to typo-correct it now.
3716 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3717 struct CandidateCallback : CorrectionCandidateCallback {
3718 bool ValidateCandidate(const TypoCorrection &TC) override {
3719 return TC.getCorrectionDecl() &&
3720 getAsTypeTemplateDecl(D: TC.getCorrectionDecl());
3721 }
3722 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3723 return std::make_unique<CandidateCallback>(args&: *this);
3724 }
3725 } FilterCCC;
3726
3727 TypoCorrection Corrected =
3728 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Scope,
3729 /*SS=*/nullptr, CCC&: FilterCCC, Mode: CorrectTypoKind::ErrorRecovery);
3730 if (Corrected && Corrected.getFoundDecl()) {
3731 S.diagnoseTypo(Correction: Corrected, TypoDiag: S.PDiag(DiagID: diag::err_no_template_suggest)
3732 << ATN->getDeclName());
3733 return S.Context.getQualifiedTemplateName(
3734 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3735 Template: TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()));
3736 }
3737
3738 return TemplateName();
3739}
3740
3741QualType Sema::CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
3742 TemplateName Name,
3743 SourceLocation TemplateLoc,
3744 TemplateArgumentListInfo &TemplateArgs,
3745 Scope *Scope, bool ForNestedNameSpecifier) {
3746 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3747
3748 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3749 if (!Template) {
3750 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3751 Template = S->getParameterPack();
3752 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3753 if (DTN->getName().getIdentifier())
3754 // When building a template-id where the template-name is dependent,
3755 // assume the template is a type template. Either our assumption is
3756 // correct, or the code is ill-formed and will be diagnosed when the
3757 // dependent name is substituted.
3758 return Context.getTemplateSpecializationType(Keyword, T: Name,
3759 SpecifiedArgs: TemplateArgs.arguments(),
3760 /*CanonicalArgs=*/{});
3761 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3762 if (TemplateName CorrectedName = ::resolveAssumedTemplateNameAsType(
3763 S&: *this, Scope, ATN, NameLoc: TemplateLoc);
3764 CorrectedName.isNull()) {
3765 Diag(Loc: TemplateLoc, DiagID: diag::err_no_template) << ATN->getDeclName();
3766 return QualType();
3767 } else {
3768 Name = CorrectedName;
3769 Template = Name.getAsTemplateDecl();
3770 }
3771 }
3772 }
3773 if (!Template ||
3774 isa<FunctionTemplateDecl, VarTemplateDecl, ConceptDecl>(Val: Template)) {
3775 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3776 if (ForNestedNameSpecifier)
3777 Diag(Loc: TemplateLoc, DiagID: diag::err_non_type_template_in_nested_name_specifier)
3778 << isa_and_nonnull<VarTemplateDecl>(Val: Template) << Name << R;
3779 else
3780 Diag(Loc: TemplateLoc, DiagID: diag::err_template_id_not_a_type) << Name << R;
3781 NoteAllFoundTemplates(Name);
3782 return QualType();
3783 }
3784
3785 // Check that the template argument list is well-formed for this
3786 // template.
3787 CheckTemplateArgumentInfo CTAI;
3788 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3789 DefaultArgs, /*PartialTemplateArgs=*/false,
3790 CTAI,
3791 /*UpdateArgsWithConversions=*/true))
3792 return QualType();
3793
3794 QualType CanonType;
3795
3796 if (isa<TemplateTemplateParmDecl>(Val: Template)) {
3797 // We might have a substituted template template parameter pack. If so,
3798 // build a template specialization type for it.
3799 } else if (TypeAliasTemplateDecl *AliasTemplate =
3800 dyn_cast<TypeAliasTemplateDecl>(Val: Template)) {
3801
3802 // C++0x [dcl.type.elab]p2:
3803 // If the identifier resolves to a typedef-name or the simple-template-id
3804 // resolves to an alias template specialization, the
3805 // elaborated-type-specifier is ill-formed.
3806 if (Keyword != ElaboratedTypeKeyword::None &&
3807 Keyword != ElaboratedTypeKeyword::Typename) {
3808 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_tag_reference_non_tag)
3809 << AliasTemplate << NonTagKind::TypeAliasTemplate
3810 << KeywordHelpers::getTagTypeKindForKeyword(Keyword);
3811 SemaRef.Diag(Loc: AliasTemplate->getLocation(), DiagID: diag::note_declared_at);
3812 }
3813
3814 // Find the canonical type for this type alias template specialization.
3815 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3816 if (Pattern->isInvalidDecl())
3817 return QualType();
3818
3819 // Only substitute for the innermost template argument list.
3820 MultiLevelTemplateArgumentList TemplateArgLists;
3821 TemplateArgLists.addOuterTemplateArguments(AssociatedDecl: Template, Args: CTAI.SugaredConverted,
3822 /*Final=*/true);
3823 TemplateArgLists.addOuterRetainedLevels(
3824 Num: AliasTemplate->getTemplateParameters()->getDepth());
3825
3826 LocalInstantiationScope Scope(*this);
3827
3828 // Diagnose uses of this alias.
3829 (void)DiagnoseUseOfDecl(D: AliasTemplate, Locs: TemplateLoc);
3830
3831 // FIXME: The TemplateArgs passed here are not used for the context note,
3832 // nor they should, because this note will be pointing to the specialization
3833 // anyway. These arguments are needed for a hack for instantiating lambdas
3834 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3835 // arguments will be used for collating the template arguments needed to
3836 // instantiate the lambda.
3837 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3838 /*Entity=*/AliasTemplate,
3839 /*TemplateArgs=*/CTAI.SugaredConverted);
3840 if (Inst.isInvalid())
3841 return QualType();
3842
3843 std::optional<ContextRAII> SavedContext;
3844 if (!AliasTemplate->getDeclContext()->isFileContext())
3845 SavedContext.emplace(args&: *this, args: AliasTemplate->getDeclContext());
3846
3847 CanonType =
3848 SubstType(T: Pattern->getUnderlyingType(), TemplateArgs: TemplateArgLists,
3849 Loc: AliasTemplate->getLocation(), Entity: AliasTemplate->getDeclName());
3850 if (CanonType.isNull()) {
3851 // If this was enable_if and we failed to find the nested type
3852 // within enable_if in a SFINAE context, dig out the specific
3853 // enable_if condition that failed and present that instead.
3854 if (isEnableIfAliasTemplate(AliasTemplate)) {
3855 if (SFINAETrap *Trap = getSFINAEContext();
3856 TemplateDeductionInfo *DeductionInfo =
3857 Trap ? Trap->getDeductionInfo() : nullptr) {
3858 if (DeductionInfo->hasSFINAEDiagnostic() &&
3859 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3860 diag::err_typename_nested_not_found_enable_if &&
3861 TemplateArgs[0].getArgument().getKind() ==
3862 TemplateArgument::Expression) {
3863 Expr *FailedCond;
3864 std::string FailedDescription;
3865 std::tie(args&: FailedCond, args&: FailedDescription) =
3866 findFailedBooleanCondition(Cond: TemplateArgs[0].getSourceExpression());
3867
3868 // Remove the old SFINAE diagnostic.
3869 PartialDiagnosticAt OldDiag =
3870 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3871 DeductionInfo->takeSFINAEDiagnostic(PD&: OldDiag);
3872
3873 // Add a new SFINAE diagnostic specifying which condition
3874 // failed.
3875 DeductionInfo->addSFINAEDiagnostic(
3876 Loc: OldDiag.first,
3877 PD: PDiag(DiagID: diag::err_typename_nested_not_found_requirement)
3878 << FailedDescription << FailedCond->getSourceRange());
3879 }
3880 }
3881 }
3882
3883 return QualType();
3884 }
3885 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Val: Template)) {
3886 CanonType = checkBuiltinTemplateIdType(
3887 SemaRef&: *this, Keyword, BTD, Converted: CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3888 } else if (Name.isDependent() ||
3889 TemplateSpecializationType::anyDependentTemplateArguments(
3890 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
3891 // This class template specialization is a dependent
3892 // type. Therefore, its canonical type is another class template
3893 // specialization type that contains all of the converted
3894 // arguments in canonical form. This ensures that, e.g., A<T> and
3895 // A<T, T> have identical types when A is declared as:
3896 //
3897 // template<typename T, typename U = T> struct A;
3898 CanonType = Context.getCanonicalTemplateSpecializationType(
3899 Keyword: ElaboratedTypeKeyword::None,
3900 T: Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3901 CanonicalArgs: CTAI.CanonicalConverted);
3902 assert(CanonType->isCanonicalUnqualified());
3903
3904 // This might work out to be a current instantiation, in which
3905 // case the canonical type needs to be the InjectedClassNameType.
3906 //
3907 // TODO: in theory this could be a simple hashtable lookup; most
3908 // changes to CurContext don't change the set of current
3909 // instantiations.
3910 if (isa<ClassTemplateDecl>(Val: Template)) {
3911 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3912 // If we get out to a namespace, we're done.
3913 if (Ctx->isFileContext()) break;
3914
3915 // If this isn't a record, keep looking.
3916 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Ctx);
3917 if (!Record) continue;
3918
3919 // Look for one of the two cases with InjectedClassNameTypes
3920 // and check whether it's the same template.
3921 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Record) &&
3922 !Record->getDescribedClassTemplate())
3923 continue;
3924
3925 // Fetch the injected class name type and check whether its
3926 // injected type is equal to the type we just built.
3927 CanQualType ICNT = Context.getCanonicalTagType(TD: Record);
3928 CanQualType Injected =
3929 Record->getCanonicalTemplateSpecializationType(Ctx: Context);
3930
3931 if (CanonType != Injected)
3932 continue;
3933
3934 // If so, the canonical type of this TST is the injected
3935 // class name type of the record we just found.
3936 CanonType = ICNT;
3937 break;
3938 }
3939 }
3940 } else if (ClassTemplateDecl *ClassTemplate =
3941 dyn_cast<ClassTemplateDecl>(Val: Template)) {
3942 // Find the class template specialization declaration that
3943 // corresponds to these arguments.
3944 void *InsertPos = nullptr;
3945 ClassTemplateSpecializationDecl *Decl =
3946 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
3947 if (!Decl) {
3948 // This is the first time we have referenced this class template
3949 // specialization. Create the canonical declaration and add it to
3950 // the set of specializations.
3951 Decl = ClassTemplateSpecializationDecl::Create(
3952 Context, TK: ClassTemplate->getTemplatedDecl()->getTagKind(),
3953 DC: ClassTemplate->getDeclContext(),
3954 StartLoc: ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3955 IdLoc: ClassTemplate->getLocation(), SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted,
3956 StrictPackMatch: CTAI.StrictPackMatch, PrevDecl: nullptr);
3957 ClassTemplate->AddSpecialization(D: Decl, InsertPos);
3958 if (ClassTemplate->isOutOfLine())
3959 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3960 }
3961
3962 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3963 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3964 NonSFINAEContext _(*this);
3965 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3966 if (!Inst.isInvalid()) {
3967 MultiLevelTemplateArgumentList TemplateArgLists(Template,
3968 CTAI.CanonicalConverted,
3969 /*Final=*/false);
3970 InstantiateAttrsForDecl(TemplateArgs: TemplateArgLists,
3971 Pattern: ClassTemplate->getTemplatedDecl(), Inst: Decl);
3972 }
3973 }
3974
3975 // Diagnose uses of this specialization.
3976 (void)DiagnoseUseOfDecl(D: Decl, Locs: TemplateLoc);
3977
3978 CanonType = Context.getCanonicalTagType(TD: Decl);
3979 assert(isa<RecordType>(CanonType) &&
3980 "type of non-dependent specialization is not a RecordType");
3981 } else {
3982 llvm_unreachable("Unhandled template kind");
3983 }
3984
3985 // Build the fully-sugared type for this class template
3986 // specialization, which refers back to the class template
3987 // specialization we created or found.
3988 return Context.getTemplateSpecializationType(
3989 Keyword, T: Name, SpecifiedArgs: TemplateArgs.arguments(), CanonicalArgs: CTAI.CanonicalConverted,
3990 Canon: CanonType);
3991}
3992
3993void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3994 TemplateNameKind &TNK,
3995 SourceLocation NameLoc,
3996 IdentifierInfo *&II) {
3997 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3998
3999 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4000 assert(ATN && "not an assumed template name");
4001 II = ATN->getDeclName().getAsIdentifierInfo();
4002
4003 if (TemplateName Name =
4004 ::resolveAssumedTemplateNameAsType(S&: *this, Scope: S, ATN, NameLoc);
4005 !Name.isNull()) {
4006 // Resolved to a type template name.
4007 ParsedName = TemplateTy::make(P: Name);
4008 TNK = TNK_Type_template;
4009 }
4010}
4011
4012TypeResult Sema::ActOnTemplateIdType(
4013 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4014 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4015 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4016 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4017 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4018 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4019 ImplicitTypenameContext AllowImplicitTypename) {
4020 if (SS.isInvalid())
4021 return true;
4022
4023 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4024 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4025
4026 // C++ [temp.res]p3:
4027 // A qualified-id that refers to a type and in which the
4028 // nested-name-specifier depends on a template-parameter (14.6.2)
4029 // shall be prefixed by the keyword typename to indicate that the
4030 // qualified-id denotes a type, forming an
4031 // elaborated-type-specifier (7.1.5.3).
4032 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4033 // C++2a relaxes some of those restrictions in [temp.res]p5.
4034 QualType DNT = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
4035 NNS: SS.getScopeRep(), Name: TemplateII);
4036 NestedNameSpecifier NNS(DNT.getTypePtr());
4037 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4038 auto DB = DiagCompat(Loc: SS.getBeginLoc(), CompatDiagId: diag_compat::implicit_typename)
4039 << NNS;
4040 if (!getLangOpts().CPlusPlus20)
4041 DB << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "typename ");
4042 } else
4043 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_typename_missing_template) << NNS;
4044
4045 // FIXME: This is not quite correct recovery as we don't transform SS
4046 // into the corresponding dependent form (and we don't diagnose missing
4047 // 'template' keywords within SS as a result).
4048 return ActOnTypenameType(S: nullptr, TypenameLoc: SourceLocation(), SS, TemplateLoc: TemplateKWLoc,
4049 TemplateName: TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4050 TemplateArgs: TemplateArgsIn, RAngleLoc);
4051 }
4052
4053 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4054 // it's not actually allowed to be used as a type in most cases. Because
4055 // we annotate it before we know whether it's valid, we have to check for
4056 // this case here.
4057 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
4058 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4059 Diag(Loc: TemplateIILoc,
4060 DiagID: TemplateKWLoc.isInvalid()
4061 ? diag::err_out_of_line_qualified_id_type_names_constructor
4062 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4063 << TemplateII << 0 /*injected-class-name used as template name*/
4064 << 1 /*if any keyword was present, it was 'template'*/;
4065 }
4066 }
4067
4068 // Translate the parser's template argument list in our AST format.
4069 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4070 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4071
4072 QualType SpecTy = CheckTemplateIdType(
4073 Keyword: ElaboratedKeyword, Name: TemplateD.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
4074 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4075 if (SpecTy.isNull())
4076 return true;
4077
4078 // Build type-source information.
4079 TypeLocBuilder TLB;
4080 TLB.push<TemplateSpecializationTypeLoc>(T: SpecTy).set(
4081 ElaboratedKeywordLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
4082 NameLoc: TemplateIILoc, TAL: TemplateArgs);
4083 return CreateParsedType(T: SpecTy, TInfo: TLB.getTypeSourceInfo(Context, T: SpecTy));
4084}
4085
4086TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
4087 TypeSpecifierType TagSpec,
4088 SourceLocation TagLoc,
4089 CXXScopeSpec &SS,
4090 SourceLocation TemplateKWLoc,
4091 TemplateTy TemplateD,
4092 SourceLocation TemplateLoc,
4093 SourceLocation LAngleLoc,
4094 ASTTemplateArgsPtr TemplateArgsIn,
4095 SourceLocation RAngleLoc) {
4096 if (SS.isInvalid())
4097 return TypeResult(true);
4098
4099 // Translate the parser's template argument list in our AST format.
4100 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4101 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4102
4103 // Determine the tag kind
4104 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
4105 ElaboratedTypeKeyword Keyword
4106 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
4107
4108 QualType Result =
4109 CheckTemplateIdType(Keyword, Name: TemplateD.get(), TemplateLoc, TemplateArgs,
4110 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4111 if (Result.isNull())
4112 return TypeResult(true);
4113
4114 // Check the tag kind
4115 if (const RecordType *RT = Result->getAs<RecordType>()) {
4116 RecordDecl *D = RT->getDecl();
4117
4118 IdentifierInfo *Id = D->getIdentifier();
4119 assert(Id && "templated class must have an identifier");
4120
4121 if (!isAcceptableTagRedeclaration(Previous: D, NewTag: TagKind, isDefinition: TUK == TagUseKind::Definition,
4122 NewTagLoc: TagLoc, Name: Id)) {
4123 Diag(Loc: TagLoc, DiagID: diag::err_use_with_wrong_tag)
4124 << Result
4125 << FixItHint::CreateReplacement(RemoveRange: SourceRange(TagLoc), Code: D->getKindName());
4126 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_use);
4127 }
4128 }
4129
4130 // Provide source-location information for the template specialization.
4131 TypeLocBuilder TLB;
4132 TLB.push<TemplateSpecializationTypeLoc>(T: Result).set(
4133 ElaboratedKeywordLoc: TagLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc, NameLoc: TemplateLoc,
4134 TAL: TemplateArgs);
4135 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
4136}
4137
4138static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4139 NamedDecl *PrevDecl,
4140 SourceLocation Loc,
4141 bool IsPartialSpecialization);
4142
4143static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4144
4145static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg,
4146 unsigned Depth,
4147 unsigned Index) {
4148 switch (Arg.getKind()) {
4149 case TemplateArgument::Null:
4150 case TemplateArgument::NullPtr:
4151 case TemplateArgument::Integral:
4152 case TemplateArgument::Declaration:
4153 case TemplateArgument::StructuralValue:
4154 case TemplateArgument::Pack:
4155 case TemplateArgument::TemplateExpansion:
4156 return false;
4157
4158 case TemplateArgument::Type: {
4159 QualType Type = Arg.getAsType();
4160 const TemplateTypeParmType *TPT =
4161 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4162 return TPT && !Type.hasQualifiers() &&
4163 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4164 }
4165
4166 case TemplateArgument::Expression: {
4167 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg.getAsExpr());
4168 if (!DRE || !DRE->getDecl())
4169 return false;
4170 const NonTypeTemplateParmDecl *NTTP =
4171 dyn_cast<NonTypeTemplateParmDecl>(Val: DRE->getDecl());
4172 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4173 }
4174
4175 case TemplateArgument::Template:
4176 const TemplateTemplateParmDecl *TTP =
4177 dyn_cast_or_null<TemplateTemplateParmDecl>(
4178 Val: Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4179 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4180 }
4181 llvm_unreachable("unexpected kind of template argument");
4182}
4183
4184static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4185 TemplateParameterList *SpecParams,
4186 ArrayRef<TemplateArgument> Args) {
4187 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4188 return false;
4189
4190 unsigned Depth = Params->getDepth();
4191
4192 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4193 TemplateArgument Arg = Args[I];
4194
4195 // If the parameter is a pack expansion, the argument must be a pack
4196 // whose only element is a pack expansion.
4197 if (Params->getParam(Idx: I)->isParameterPack()) {
4198 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4199 !Arg.pack_begin()->isPackExpansion())
4200 return false;
4201 Arg = Arg.pack_begin()->getPackExpansionPattern();
4202 }
4203
4204 if (!isTemplateArgumentTemplateParameter(Arg, Depth, Index: I))
4205 return false;
4206
4207 // For NTTPs further specialization is allowed via deduced types, so
4208 // we need to make sure to only reject here if primary template and
4209 // specialization use the same type for the NTTP.
4210 if (auto *SpecNTTP =
4211 dyn_cast<NonTypeTemplateParmDecl>(Val: SpecParams->getParam(Idx: I))) {
4212 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: I));
4213 if (!NTTP || NTTP->getType().getCanonicalType() !=
4214 SpecNTTP->getType().getCanonicalType())
4215 return false;
4216 }
4217 }
4218
4219 return true;
4220}
4221
4222template<typename PartialSpecDecl>
4223static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4224 if (Partial->getDeclContext()->isDependentContext())
4225 return;
4226
4227 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4228 // for non-substitution-failure issues?
4229 TemplateDeductionInfo Info(Partial->getLocation());
4230 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4231 return;
4232
4233 auto *Template = Partial->getSpecializedTemplate();
4234 S.Diag(Partial->getLocation(),
4235 diag::ext_partial_spec_not_more_specialized_than_primary)
4236 << isa<VarTemplateDecl>(Template);
4237
4238 if (Info.hasSFINAEDiagnostic()) {
4239 PartialDiagnosticAt Diag = {SourceLocation(),
4240 PartialDiagnostic::NullDiagnostic()};
4241 Info.takeSFINAEDiagnostic(PD&: Diag);
4242 SmallString<128> SFINAEArgString;
4243 Diag.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
4244 S.Diag(Loc: Diag.first,
4245 DiagID: diag::note_partial_spec_not_more_specialized_than_primary)
4246 << SFINAEArgString;
4247 }
4248
4249 S.NoteTemplateLocation(Decl: *Template);
4250 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4251 Template->getAssociatedConstraints(TemplateAC);
4252 Partial->getAssociatedConstraints(PartialAC);
4253 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Partial, AC1: PartialAC, D2: Template,
4254 AC2: TemplateAC);
4255}
4256
4257static void
4258noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4259 const llvm::SmallBitVector &DeducibleParams) {
4260 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4261 if (!DeducibleParams[I]) {
4262 NamedDecl *Param = TemplateParams->getParam(Idx: I);
4263 if (Param->getDeclName())
4264 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4265 << Param->getDeclName();
4266 else
4267 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4268 << "(anonymous)";
4269 }
4270 }
4271}
4272
4273
4274template<typename PartialSpecDecl>
4275static void checkTemplatePartialSpecialization(Sema &S,
4276 PartialSpecDecl *Partial) {
4277 // C++1z [temp.class.spec]p8: (DR1495)
4278 // - The specialization shall be more specialized than the primary
4279 // template (14.5.5.2).
4280 checkMoreSpecializedThanPrimary(S, Partial);
4281
4282 // C++ [temp.class.spec]p8: (DR1315)
4283 // - Each template-parameter shall appear at least once in the
4284 // template-id outside a non-deduced context.
4285 // C++1z [temp.class.spec.match]p3 (P0127R2)
4286 // If the template arguments of a partial specialization cannot be
4287 // deduced because of the structure of its template-parameter-list
4288 // and the template-id, the program is ill-formed.
4289 auto *TemplateParams = Partial->getTemplateParameters();
4290 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4291 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4292 TemplateParams->getDepth(), DeducibleParams);
4293
4294 if (!DeducibleParams.all()) {
4295 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4296 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4297 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4298 << (NumNonDeducible > 1)
4299 << SourceRange(Partial->getLocation(),
4300 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4301 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4302 }
4303}
4304
4305void Sema::CheckTemplatePartialSpecialization(
4306 ClassTemplatePartialSpecializationDecl *Partial) {
4307 checkTemplatePartialSpecialization(S&: *this, Partial);
4308}
4309
4310void Sema::CheckTemplatePartialSpecialization(
4311 VarTemplatePartialSpecializationDecl *Partial) {
4312 checkTemplatePartialSpecialization(S&: *this, Partial);
4313}
4314
4315void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4316 // C++1z [temp.param]p11:
4317 // A template parameter of a deduction guide template that does not have a
4318 // default-argument shall be deducible from the parameter-type-list of the
4319 // deduction guide template.
4320 auto *TemplateParams = TD->getTemplateParameters();
4321 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4322 MarkDeducedTemplateParameters(FunctionTemplate: TD, Deduced&: DeducibleParams);
4323 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4324 // A parameter pack is deducible (to an empty pack).
4325 auto *Param = TemplateParams->getParam(Idx: I);
4326 if (Param->isParameterPack() || hasVisibleDefaultArgument(D: Param))
4327 DeducibleParams[I] = true;
4328 }
4329
4330 if (!DeducibleParams.all()) {
4331 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4332 Diag(Loc: TD->getLocation(), DiagID: diag::err_deduction_guide_template_not_deducible)
4333 << (NumNonDeducible > 1);
4334 noteNonDeducibleParameters(S&: *this, TemplateParams, DeducibleParams);
4335 }
4336}
4337
4338DeclResult Sema::ActOnVarTemplateSpecialization(
4339 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
4340 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4341 StorageClass SC, bool IsPartialSpecialization) {
4342 // D must be variable template id.
4343 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4344 "Variable template specialization is declared with a template id.");
4345
4346 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4347 TemplateArgumentListInfo TemplateArgs =
4348 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TemplateId);
4349 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4350 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4351 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4352
4353 TemplateName Name = TemplateId->Template.get();
4354
4355 // The template-id must name a variable template.
4356 VarTemplateDecl *VarTemplate =
4357 dyn_cast_or_null<VarTemplateDecl>(Val: Name.getAsTemplateDecl());
4358 if (!VarTemplate) {
4359 NamedDecl *FnTemplate;
4360 if (auto *OTS = Name.getAsOverloadedTemplate())
4361 FnTemplate = *OTS->begin();
4362 else
4363 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Val: Name.getAsTemplateDecl());
4364 if (FnTemplate)
4365 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template_but_method)
4366 << FnTemplate->getDeclName();
4367 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template)
4368 << IsPartialSpecialization;
4369 }
4370
4371 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4372 auto Message = DSA->getMessage();
4373 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
4374 << VarTemplate << !Message.empty() << Message;
4375 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
4376 }
4377
4378 // Check for unexpanded parameter packs in any of the template arguments.
4379 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4380 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
4381 UPPC: IsPartialSpecialization
4382 ? UPPC_PartialSpecialization
4383 : UPPC_ExplicitSpecialization))
4384 return true;
4385
4386 // Check that the template argument list is well-formed for this
4387 // template.
4388 CheckTemplateArgumentInfo CTAI;
4389 if (CheckTemplateArgumentList(Template: VarTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
4390 /*DefaultArgs=*/{},
4391 /*PartialTemplateArgs=*/false, CTAI,
4392 /*UpdateArgsWithConversions=*/true))
4393 return true;
4394
4395 // Find the variable template (partial) specialization declaration that
4396 // corresponds to these arguments.
4397 if (IsPartialSpecialization) {
4398 if (CheckTemplatePartialSpecializationArgs(Loc: TemplateNameLoc, PrimaryTemplate: VarTemplate,
4399 NumExplicitArgs: TemplateArgs.size(),
4400 Args: CTAI.CanonicalConverted))
4401 return true;
4402
4403 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4404 // we also do them during instantiation.
4405 if (!Name.isDependent() &&
4406 !TemplateSpecializationType::anyDependentTemplateArguments(
4407 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4408 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
4409 << VarTemplate->getDeclName();
4410 IsPartialSpecialization = false;
4411 }
4412
4413 if (isSameAsPrimaryTemplate(Params: VarTemplate->getTemplateParameters(),
4414 SpecParams: TemplateParams, Args: CTAI.CanonicalConverted) &&
4415 (!Context.getLangOpts().CPlusPlus20 ||
4416 !TemplateParams->hasAssociatedConstraints())) {
4417 // C++ [temp.class.spec]p9b3:
4418 //
4419 // -- The argument list of the specialization shall not be identical
4420 // to the implicit argument list of the primary template.
4421 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
4422 << /*variable template*/ 1
4423 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4424 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
4425 // FIXME: Recover from this by treating the declaration as a
4426 // redeclaration of the primary template.
4427 return true;
4428 }
4429 }
4430
4431 void *InsertPos = nullptr;
4432 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4433
4434 if (IsPartialSpecialization)
4435 PrevDecl = VarTemplate->findPartialSpecialization(
4436 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertPos);
4437 else
4438 PrevDecl =
4439 VarTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
4440
4441 VarTemplateSpecializationDecl *Specialization = nullptr;
4442
4443 // Check whether we can declare a variable template specialization in
4444 // the current scope.
4445 if (CheckTemplateSpecializationScope(S&: *this, Specialized: VarTemplate, PrevDecl,
4446 Loc: TemplateNameLoc,
4447 IsPartialSpecialization))
4448 return true;
4449
4450 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4451 // Since the only prior variable template specialization with these
4452 // arguments was referenced but not declared, reuse that
4453 // declaration node as our own, updating its source location and
4454 // the list of outer template parameters to reflect our new declaration.
4455 Specialization = PrevDecl;
4456 Specialization->setLocation(TemplateNameLoc);
4457 PrevDecl = nullptr;
4458 } else if (IsPartialSpecialization) {
4459 // Create a new class template partial specialization declaration node.
4460 VarTemplatePartialSpecializationDecl *PrevPartial =
4461 cast_or_null<VarTemplatePartialSpecializationDecl>(Val: PrevDecl);
4462 VarTemplatePartialSpecializationDecl *Partial =
4463 VarTemplatePartialSpecializationDecl::Create(
4464 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc,
4465 IdLoc: TemplateNameLoc, Params: TemplateParams, SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI,
4466 S: SC, Args: CTAI.CanonicalConverted);
4467 Partial->setTemplateArgsAsWritten(TemplateArgs);
4468
4469 if (!PrevPartial)
4470 VarTemplate->AddPartialSpecialization(D: Partial, InsertPos);
4471 Specialization = Partial;
4472
4473 // If we are providing an explicit specialization of a member variable
4474 // template specialization, make a note of that.
4475 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4476 PrevPartial->setMemberSpecialization();
4477
4478 CheckTemplatePartialSpecialization(Partial);
4479 } else {
4480 // Create a new class template specialization declaration node for
4481 // this explicit specialization or friend declaration.
4482 Specialization = VarTemplateSpecializationDecl::Create(
4483 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc, IdLoc: TemplateNameLoc,
4484 SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI, S: SC, Args: CTAI.CanonicalConverted);
4485 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4486
4487 if (!PrevDecl)
4488 VarTemplate->AddSpecialization(D: Specialization, InsertPos);
4489 }
4490
4491 // C++ [temp.expl.spec]p6:
4492 // If a template, a member template or the member of a class template is
4493 // explicitly specialized then that specialization shall be declared
4494 // before the first use of that specialization that would cause an implicit
4495 // instantiation to take place, in every translation unit in which such a
4496 // use occurs; no diagnostic is required.
4497 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4498 bool Okay = false;
4499 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4500 // Is there any previous explicit specialization declaration?
4501 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
4502 Okay = true;
4503 break;
4504 }
4505 }
4506
4507 if (!Okay) {
4508 SourceRange Range(TemplateNameLoc, RAngleLoc);
4509 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
4510 << Name << Range;
4511
4512 Diag(Loc: PrevDecl->getPointOfInstantiation(),
4513 DiagID: diag::note_instantiation_required_here)
4514 << (PrevDecl->getTemplateSpecializationKind() !=
4515 TSK_ImplicitInstantiation);
4516 return true;
4517 }
4518 }
4519
4520 Specialization->setLexicalDeclContext(CurContext);
4521
4522 // Add the specialization into its lexical context, so that it can
4523 // be seen when iterating through the list of declarations in that
4524 // context. However, specializations are not found by name lookup.
4525 CurContext->addDecl(D: Specialization);
4526
4527 // Note that this is an explicit specialization.
4528 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4529
4530 Previous.clear();
4531 if (PrevDecl)
4532 Previous.addDecl(D: PrevDecl);
4533 else if (Specialization->isStaticDataMember() &&
4534 Specialization->isOutOfLine())
4535 Specialization->setAccess(VarTemplate->getAccess());
4536
4537 return Specialization;
4538}
4539
4540namespace {
4541/// A partial specialization whose template arguments have matched
4542/// a given template-id.
4543struct PartialSpecMatchResult {
4544 VarTemplatePartialSpecializationDecl *Partial;
4545 TemplateArgumentList *Args;
4546};
4547
4548// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4549// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4550static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4551 if (Var->getName() != "format_kind" ||
4552 !Var->getDeclContext()->isStdNamespace())
4553 return false;
4554
4555 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4556 // release in which users can access std::format_kind.
4557 // We can use 20250520 as the final date, see the following commits.
4558 // GCC releases/gcc-15 branch:
4559 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4560 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4561 // GCC master branch:
4562 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4563 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4564 return PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2025'05'20);
4565}
4566} // end anonymous namespace
4567
4568DeclResult
4569Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4570 SourceLocation TemplateNameLoc,
4571 const TemplateArgumentListInfo &TemplateArgs,
4572 bool SetWrittenArgs) {
4573 assert(Template && "A variable template id without template?");
4574
4575 // Check that the template argument list is well-formed for this template.
4576 CheckTemplateArgumentInfo CTAI;
4577 if (CheckTemplateArgumentList(
4578 Template, TemplateLoc: TemplateNameLoc,
4579 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4580 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4581 /*UpdateArgsWithConversions=*/true))
4582 return true;
4583
4584 // Produce a placeholder value if the specialization is dependent.
4585 if (Template->getDeclContext()->isDependentContext() ||
4586 TemplateSpecializationType::anyDependentTemplateArguments(
4587 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4588 if (ParsingInitForAutoVars.empty())
4589 return DeclResult();
4590
4591 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4592 const TemplateArgument &Arg2) {
4593 return Context.isSameTemplateArgument(Arg1, Arg2);
4594 };
4595
4596 if (VarDecl *Var = Template->getTemplatedDecl();
4597 ParsingInitForAutoVars.count(Ptr: Var) &&
4598 // See comments on this function definition
4599 !IsLibstdcxxStdFormatKind(PP, Var) &&
4600 llvm::equal(
4601 LRange&: CTAI.CanonicalConverted,
4602 RRange: Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4603 P: IsSameTemplateArg)) {
4604 Diag(Loc: TemplateNameLoc,
4605 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4606 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4607 return true;
4608 }
4609
4610 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4611 Template->getPartialSpecializations(PS&: PartialSpecs);
4612 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4613 if (ParsingInitForAutoVars.count(Ptr: Partial) &&
4614 llvm::equal(LRange&: CTAI.CanonicalConverted,
4615 RRange: Partial->getTemplateArgs().asArray(),
4616 P: IsSameTemplateArg)) {
4617 Diag(Loc: TemplateNameLoc,
4618 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4619 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4620 << Partial->getType();
4621 return true;
4622 }
4623
4624 return DeclResult();
4625 }
4626
4627 // Find the variable template specialization declaration that
4628 // corresponds to these arguments.
4629 void *InsertPos = nullptr;
4630 if (VarTemplateSpecializationDecl *Spec =
4631 Template->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos)) {
4632 checkSpecializationReachability(Loc: TemplateNameLoc, Spec);
4633 if (Spec->getType()->isUndeducedType()) {
4634 if (ParsingInitForAutoVars.count(Ptr: Spec))
4635 Diag(Loc: TemplateNameLoc,
4636 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4637 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4638 << Spec->getType();
4639 else
4640 // We are substituting the initializer of this variable template
4641 // specialization.
4642 Diag(Loc: TemplateNameLoc, DiagID: diag::err_var_template_spec_type_depends_on_self)
4643 << Spec << Spec->getType();
4644
4645 return true;
4646 }
4647 // If we already have a variable template specialization, return it.
4648 return Spec;
4649 }
4650
4651 // This is the first time we have referenced this variable template
4652 // specialization. Create the canonical declaration and add it to
4653 // the set of specializations, based on the closest partial specialization
4654 // that it represents. That is,
4655 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4656 const TemplateArgumentList *PartialSpecArgs = nullptr;
4657 bool AmbiguousPartialSpec = false;
4658 typedef PartialSpecMatchResult MatchResult;
4659 SmallVector<MatchResult, 4> Matched;
4660 SourceLocation PointOfInstantiation = TemplateNameLoc;
4661 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4662 /*ForTakingAddress=*/false);
4663
4664 // 1. Attempt to find the closest partial specialization that this
4665 // specializes, if any.
4666 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4667 // Perhaps better after unification of DeduceTemplateArguments() and
4668 // getMoreSpecializedPartialSpecialization().
4669 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4670 Template->getPartialSpecializations(PS&: PartialSpecs);
4671
4672 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4673 // C++ [temp.spec.partial.member]p2:
4674 // If the primary member template is explicitly specialized for a given
4675 // (implicit) specialization of the enclosing class template, the partial
4676 // specializations of the member template are ignored for this
4677 // specialization of the enclosing class template. If a partial
4678 // specialization of the member template is explicitly specialized for a
4679 // given (implicit) specialization of the enclosing class template, the
4680 // primary member template and its other partial specializations are still
4681 // considered for this specialization of the enclosing class template.
4682 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4683 !Partial->getMostRecentDecl()->isMemberSpecialization())
4684 continue;
4685
4686 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4687
4688 if (TemplateDeductionResult Result =
4689 DeduceTemplateArguments(Partial, TemplateArgs: CTAI.SugaredConverted, Info);
4690 Result != TemplateDeductionResult::Success) {
4691 // Store the failed-deduction information for use in diagnostics, later.
4692 // TODO: Actually use the failed-deduction info?
4693 FailedCandidates.addCandidate().set(
4694 Found: DeclAccessPair::make(D: Template, AS: AS_public), Spec: Partial,
4695 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
4696 (void)Result;
4697 } else {
4698 Matched.push_back(Elt: PartialSpecMatchResult());
4699 Matched.back().Partial = Partial;
4700 Matched.back().Args = Info.takeSugared();
4701 }
4702 }
4703
4704 if (Matched.size() >= 1) {
4705 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4706 if (Matched.size() == 1) {
4707 // -- If exactly one matching specialization is found, the
4708 // instantiation is generated from that specialization.
4709 // We don't need to do anything for this.
4710 } else {
4711 // -- If more than one matching specialization is found, the
4712 // partial order rules (14.5.4.2) are used to determine
4713 // whether one of the specializations is more specialized
4714 // than the others. If none of the specializations is more
4715 // specialized than all of the other matching
4716 // specializations, then the use of the variable template is
4717 // ambiguous and the program is ill-formed.
4718 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4719 PEnd = Matched.end();
4720 P != PEnd; ++P) {
4721 if (getMoreSpecializedPartialSpecialization(PS1: P->Partial, PS2: Best->Partial,
4722 Loc: PointOfInstantiation) ==
4723 P->Partial)
4724 Best = P;
4725 }
4726
4727 // Determine if the best partial specialization is more specialized than
4728 // the others.
4729 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4730 PEnd = Matched.end();
4731 P != PEnd; ++P) {
4732 if (P != Best && getMoreSpecializedPartialSpecialization(
4733 PS1: P->Partial, PS2: Best->Partial,
4734 Loc: PointOfInstantiation) != Best->Partial) {
4735 AmbiguousPartialSpec = true;
4736 break;
4737 }
4738 }
4739 }
4740
4741 // Instantiate using the best variable template partial specialization.
4742 InstantiationPattern = Best->Partial;
4743 PartialSpecArgs = Best->Args;
4744 } else {
4745 // -- If no match is found, the instantiation is generated
4746 // from the primary template.
4747 // InstantiationPattern = Template->getTemplatedDecl();
4748 }
4749
4750 // 2. Create the canonical declaration.
4751 // Note that we do not instantiate a definition until we see an odr-use
4752 // in DoMarkVarDeclReferenced().
4753 // FIXME: LateAttrs et al.?
4754 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4755 VarTemplate: Template, FromVar: InstantiationPattern, PartialSpecArgs, Converted&: CTAI.CanonicalConverted,
4756 PointOfInstantiation: TemplateNameLoc /*, LateAttrs, StartingScope*/);
4757 if (!Decl)
4758 return true;
4759 if (SetWrittenArgs)
4760 Decl->setTemplateArgsAsWritten(TemplateArgs);
4761
4762 if (AmbiguousPartialSpec) {
4763 // Partial ordering did not produce a clear winner. Complain.
4764 Decl->setInvalidDecl();
4765 Diag(Loc: PointOfInstantiation, DiagID: diag::err_partial_spec_ordering_ambiguous)
4766 << Decl;
4767
4768 // Print the matching partial specializations.
4769 for (MatchResult P : Matched)
4770 Diag(Loc: P.Partial->getLocation(), DiagID: diag::note_partial_spec_match)
4771 << getTemplateArgumentBindingsText(Params: P.Partial->getTemplateParameters(),
4772 Args: *P.Args);
4773 return true;
4774 }
4775
4776 if (VarTemplatePartialSpecializationDecl *D =
4777 dyn_cast<VarTemplatePartialSpecializationDecl>(Val: InstantiationPattern))
4778 Decl->setInstantiationOf(PartialSpec: D, TemplateArgs: PartialSpecArgs);
4779
4780 checkSpecializationReachability(Loc: TemplateNameLoc, Spec: Decl);
4781
4782 assert(Decl && "No variable template specialization?");
4783 return Decl;
4784}
4785
4786ExprResult Sema::CheckVarTemplateId(
4787 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4788 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4789 const TemplateArgumentListInfo *TemplateArgs) {
4790
4791 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, TemplateNameLoc: NameInfo.getLoc(),
4792 TemplateArgs: *TemplateArgs, /*SetWrittenArgs=*/false);
4793 if (Decl.isInvalid())
4794 return ExprError();
4795
4796 if (!Decl.get())
4797 return ExprResult();
4798
4799 VarDecl *Var = cast<VarDecl>(Val: Decl.get());
4800 if (!Var->getTemplateSpecializationKind())
4801 Var->setTemplateSpecializationKind(TSK: TSK_ImplicitInstantiation,
4802 PointOfInstantiation: NameInfo.getLoc());
4803
4804 // Build an ordinary singleton decl ref.
4805 return BuildDeclarationNameExpr(SS, NameInfo, D: Var, FoundD, TemplateArgs);
4806}
4807
4808ExprResult Sema::CheckVarOrConceptTemplateTemplateId(
4809 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4810 TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc,
4811 const TemplateArgumentListInfo *TemplateArgs) {
4812 assert(Template && "A variable template id without template?");
4813
4814 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4815 Template->templateParameterKind() !=
4816 TemplateNameKind::TNK_Concept_template)
4817 return ExprResult();
4818
4819 // Check that the template argument list is well-formed for this template.
4820 CheckTemplateArgumentInfo CTAI;
4821 if (CheckTemplateArgumentList(
4822 Template, TemplateLoc,
4823 // FIXME: TemplateArgs will not be modified because
4824 // UpdateArgsWithConversions is false, however, we should
4825 // CheckTemplateArgumentList to be const-correct.
4826 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4827 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4828 /*UpdateArgsWithConversions=*/false))
4829 return true;
4830
4831 UnresolvedSet<1> R;
4832 R.addDecl(D: Template);
4833
4834 // FIXME: We model references to variable template and concept parameters
4835 // as an UnresolvedLookupExpr. This is because they encapsulate the same
4836 // data, can generally be used in the same places and work the same way.
4837 // However, it might be cleaner to use a dedicated AST node in the long run.
4838 return UnresolvedLookupExpr::Create(
4839 Context: getASTContext(), NamingClass: nullptr, QualifierLoc: SS.getWithLocInContext(Context&: getASTContext()),
4840 TemplateKWLoc: SourceLocation(), NameInfo, RequiresADL: false, Args: TemplateArgs, Begin: R.begin(), End: R.end(),
4841 /*KnownDependent=*/false,
4842 /*KnownInstantiationDependent=*/false);
4843}
4844
4845void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4846 SourceLocation Loc) {
4847 Diag(Loc, DiagID: diag::err_template_missing_args)
4848 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4849 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4850 NoteTemplateLocation(Decl: *TD, ParamRange: TD->getTemplateParameters()->getSourceRange());
4851 }
4852}
4853
4854void Sema::diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
4855 bool TemplateKeyword,
4856 TemplateDecl *TD,
4857 SourceLocation Loc) {
4858 TemplateName Name = Context.getQualifiedTemplateName(
4859 Qualifier: SS.getScopeRep(), TemplateKeyword, Template: TemplateName(TD));
4860 diagnoseMissingTemplateArguments(Name, Loc);
4861}
4862
4863ExprResult Sema::CheckConceptTemplateId(
4864 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4865 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4866 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4867 bool DoCheckConstraintSatisfaction) {
4868 assert(NamedConcept && "A concept template id without a template?");
4869
4870 if (NamedConcept->isInvalidDecl())
4871 return ExprError();
4872
4873 CheckTemplateArgumentInfo CTAI;
4874 if (CheckTemplateArgumentList(
4875 Template: NamedConcept, TemplateLoc: ConceptNameInfo.getLoc(),
4876 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4877 /*DefaultArgs=*/{},
4878 /*PartialTemplateArgs=*/false, CTAI,
4879 /*UpdateArgsWithConversions=*/false))
4880 return ExprError();
4881
4882 DiagnoseUseOfDecl(D: NamedConcept, Locs: ConceptNameInfo.getLoc());
4883
4884 // There's a bug with CTAI.CanonicalConverted.
4885 // If the template argument contains a DependentDecltypeType that includes a
4886 // TypeAliasType, and the same written type had occurred previously in the
4887 // source, then the DependentDecltypeType would be canonicalized to that
4888 // previous type which would mess up the substitution.
4889 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4890 auto *CSD = ImplicitConceptSpecializationDecl::Create(
4891 C: Context, DC: NamedConcept->getDeclContext(), SL: NamedConcept->getLocation(),
4892 ConvertedArgs: CTAI.SugaredConverted);
4893 ConstraintSatisfaction Satisfaction;
4894 bool AreArgsDependent =
4895 TemplateSpecializationType::anyDependentTemplateArguments(
4896 *TemplateArgs, Converted: CTAI.SugaredConverted);
4897 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4898 /*Final=*/false);
4899 auto *CL = ConceptReference::Create(
4900 C: Context,
4901 NNS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4902 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4903 ArgsAsWritten: ASTTemplateArgumentListInfo::Create(C: Context, List: *TemplateArgs));
4904
4905 bool Error = false;
4906 if (const auto *Concept = dyn_cast<ConceptDecl>(Val: NamedConcept);
4907 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4908 DoCheckConstraintSatisfaction) {
4909
4910 LocalInstantiationScope Scope(*this);
4911
4912 EnterExpressionEvaluationContext EECtx{
4913 *this, ExpressionEvaluationContext::Unevaluated, CSD};
4914
4915 Error = CheckConstraintSatisfaction(
4916 Entity: NamedConcept, AssociatedConstraints: AssociatedConstraint(Concept->getConstraintExpr()), TemplateArgLists: MLTAL,
4917 TemplateIDRange: SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4918 TemplateArgs->getRAngleLoc()),
4919 Satisfaction, TopLevelConceptId: CL);
4920 Satisfaction.ContainsErrors = Error;
4921 }
4922
4923 if (Error)
4924 return ExprError();
4925
4926 return ConceptSpecializationExpr::Create(
4927 C: Context, ConceptRef: CL, SpecDecl: CSD, Satisfaction: AreArgsDependent ? nullptr : &Satisfaction);
4928}
4929
4930ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4931 SourceLocation TemplateKWLoc,
4932 LookupResult &R,
4933 bool RequiresADL,
4934 const TemplateArgumentListInfo *TemplateArgs) {
4935 // FIXME: Can we do any checking at this point? I guess we could check the
4936 // template arguments that we have against the template name, if the template
4937 // name refers to a single template. That's not a terribly common case,
4938 // though.
4939 // foo<int> could identify a single function unambiguously
4940 // This approach does NOT work, since f<int>(1);
4941 // gets resolved prior to resorting to overload resolution
4942 // i.e., template<class T> void f(double);
4943 // vs template<class T, class U> void f(U);
4944
4945 // These should be filtered out by our callers.
4946 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4947
4948 // Non-function templates require a template argument list.
4949 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4950 if (!TemplateArgs && !isa<FunctionTemplateDecl>(Val: TD)) {
4951 diagnoseMissingTemplateArguments(
4952 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, Loc: R.getNameLoc());
4953 return ExprError();
4954 }
4955 }
4956 bool KnownDependent = false;
4957 // In C++1y, check variable template ids.
4958 if (R.getAsSingle<VarTemplateDecl>()) {
4959 ExprResult Res = CheckVarTemplateId(
4960 SS, NameInfo: R.getLookupNameInfo(), Template: R.getAsSingle<VarTemplateDecl>(),
4961 FoundD: R.getRepresentativeDecl(), TemplateLoc: TemplateKWLoc, TemplateArgs);
4962 if (Res.isInvalid() || Res.isUsable())
4963 return Res;
4964 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4965 KnownDependent = true;
4966 }
4967
4968 // We don't want lookup warnings at this point.
4969 R.suppressDiagnostics();
4970
4971 if (R.getAsSingle<ConceptDecl>()) {
4972 return CheckConceptTemplateId(SS, TemplateKWLoc, ConceptNameInfo: R.getLookupNameInfo(),
4973 FoundDecl: R.getRepresentativeDecl(),
4974 NamedConcept: R.getAsSingle<ConceptDecl>(), TemplateArgs);
4975 }
4976
4977 // Check variable template ids (C++17) and concept template parameters
4978 // (C++26).
4979 UnresolvedLookupExpr *ULE;
4980 if (R.getAsSingle<TemplateTemplateParmDecl>())
4981 return CheckVarOrConceptTemplateTemplateId(
4982 SS, NameInfo: R.getLookupNameInfo(), Template: R.getAsSingle<TemplateTemplateParmDecl>(),
4983 TemplateLoc: TemplateKWLoc, TemplateArgs);
4984
4985 // Function templates
4986 ULE = UnresolvedLookupExpr::Create(
4987 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
4988 TemplateKWLoc, NameInfo: R.getLookupNameInfo(), RequiresADL, Args: TemplateArgs,
4989 Begin: R.begin(), End: R.end(), KnownDependent,
4990 /*KnownInstantiationDependent=*/false);
4991 // Model the templates with UnresolvedTemplateTy. The expression should then
4992 // either be transformed in an instantiation or be diagnosed in
4993 // CheckPlaceholderExpr.
4994 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4995 !R.getFoundDecl()->getAsFunction())
4996 ULE->setType(Context.UnresolvedTemplateTy);
4997
4998 return ULE;
4999}
5000
5001ExprResult Sema::BuildQualifiedTemplateIdExpr(
5002 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5003 const DeclarationNameInfo &NameInfo,
5004 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5005 assert(TemplateArgs || TemplateKWLoc.isValid());
5006
5007 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5008 if (LookupTemplateName(Found&: R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5009 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc))
5010 return ExprError();
5011
5012 if (R.isAmbiguous())
5013 return ExprError();
5014
5015 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5016 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5017
5018 if (R.empty()) {
5019 DeclContext *DC = computeDeclContext(SS);
5020 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
5021 << NameInfo.getName() << DC << SS.getRange();
5022 return ExprError();
5023 }
5024
5025 // If necessary, build an implicit class member access.
5026 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5027 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5028 /*S=*/nullptr);
5029
5030 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/RequiresADL: false, TemplateArgs);
5031}
5032
5033TemplateNameKind Sema::ActOnTemplateName(Scope *S,
5034 CXXScopeSpec &SS,
5035 SourceLocation TemplateKWLoc,
5036 const UnqualifiedId &Name,
5037 ParsedType ObjectType,
5038 bool EnteringContext,
5039 TemplateTy &Result,
5040 bool AllowInjectedClassName) {
5041 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5042 Diag(Loc: TemplateKWLoc,
5043 DiagID: getLangOpts().CPlusPlus11 ?
5044 diag::warn_cxx98_compat_template_outside_of_template :
5045 diag::ext_template_outside_of_template)
5046 << FixItHint::CreateRemoval(RemoveRange: TemplateKWLoc);
5047
5048 if (SS.isInvalid())
5049 return TNK_Non_template;
5050
5051 // Figure out where isTemplateName is going to look.
5052 DeclContext *LookupCtx = nullptr;
5053 if (SS.isNotEmpty())
5054 LookupCtx = computeDeclContext(SS, EnteringContext);
5055 else if (ObjectType)
5056 LookupCtx = computeDeclContext(T: GetTypeFromParser(Ty: ObjectType));
5057
5058 // C++0x [temp.names]p5:
5059 // If a name prefixed by the keyword template is not the name of
5060 // a template, the program is ill-formed. [Note: the keyword
5061 // template may not be applied to non-template members of class
5062 // templates. -end note ] [ Note: as is the case with the
5063 // typename prefix, the template prefix is allowed in cases
5064 // where it is not strictly necessary; i.e., when the
5065 // nested-name-specifier or the expression on the left of the ->
5066 // or . is not dependent on a template-parameter, or the use
5067 // does not appear in the scope of a template. -end note]
5068 //
5069 // Note: C++03 was more strict here, because it banned the use of
5070 // the "template" keyword prior to a template-name that was not a
5071 // dependent name. C++ DR468 relaxed this requirement (the
5072 // "template" keyword is now permitted). We follow the C++0x
5073 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5074 bool MemberOfUnknownSpecialization;
5075 TemplateNameKind TNK = isTemplateName(S, SS, hasTemplateKeyword: TemplateKWLoc.isValid(), Name,
5076 ObjectTypePtr: ObjectType, EnteringContext, TemplateResult&: Result,
5077 MemberOfUnknownSpecialization);
5078 if (TNK != TNK_Non_template) {
5079 // We resolved this to a (non-dependent) template name. Return it.
5080 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
5081 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5082 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5083 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5084 // C++14 [class.qual]p2:
5085 // In a lookup in which function names are not ignored and the
5086 // nested-name-specifier nominates a class C, if the name specified
5087 // [...] is the injected-class-name of C, [...] the name is instead
5088 // considered to name the constructor
5089 //
5090 // We don't get here if naming the constructor would be valid, so we
5091 // just reject immediately and recover by treating the
5092 // injected-class-name as naming the template.
5093 Diag(Loc: Name.getBeginLoc(),
5094 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
5095 << Name.Identifier
5096 << 0 /*injected-class-name used as template name*/
5097 << TemplateKWLoc.isValid();
5098 }
5099 return TNK;
5100 }
5101
5102 if (!MemberOfUnknownSpecialization) {
5103 // Didn't find a template name, and the lookup wasn't dependent.
5104 // Do the lookup again to determine if this is a "nothing found" case or
5105 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5106 // need to do this.
5107 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
5108 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5109 LookupOrdinaryName);
5110 // Tell LookupTemplateName that we require a template so that it diagnoses
5111 // cases where it finds a non-template.
5112 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5113 ? RequiredTemplateKind(TemplateKWLoc)
5114 : TemplateNameIsRequired;
5115 if (!LookupTemplateName(Found&: R, S, SS, ObjectType: ObjectType.get(), EnteringContext, RequiredTemplate: RTK,
5116 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5117 !R.isAmbiguous()) {
5118 if (LookupCtx)
5119 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_no_member)
5120 << DNI.getName() << LookupCtx << SS.getRange();
5121 else
5122 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_undeclared_use)
5123 << DNI.getName() << SS.getRange();
5124 }
5125 return TNK_Non_template;
5126 }
5127
5128 NestedNameSpecifier Qualifier = SS.getScopeRep();
5129
5130 switch (Name.getKind()) {
5131 case UnqualifiedIdKind::IK_Identifier:
5132 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5133 Name: {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5134 return TNK_Dependent_template_name;
5135
5136 case UnqualifiedIdKind::IK_OperatorFunctionId:
5137 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5138 Name: {Qualifier, Name.OperatorFunctionId.Operator,
5139 TemplateKWLoc.isValid()}));
5140 return TNK_Function_template;
5141
5142 case UnqualifiedIdKind::IK_LiteralOperatorId:
5143 // This is a kind of template name, but can never occur in a dependent
5144 // scope (literal operators can only be declared at namespace scope).
5145 break;
5146
5147 default:
5148 break;
5149 }
5150
5151 // This name cannot possibly name a dependent template. Diagnose this now
5152 // rather than building a dependent template name that can never be valid.
5153 Diag(Loc: Name.getBeginLoc(),
5154 DiagID: diag::err_template_kw_refers_to_dependent_non_template)
5155 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5156 << TemplateKWLoc.isValid() << TemplateKWLoc;
5157 return TNK_Non_template;
5158}
5159
5160bool Sema::CheckTemplateTypeArgument(
5161 TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
5162 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5163 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5164 const TemplateArgument &Arg = AL.getArgument();
5165 QualType ArgType;
5166 TypeSourceInfo *TSI = nullptr;
5167
5168 // Check template type parameter.
5169 switch(Arg.getKind()) {
5170 case TemplateArgument::Type:
5171 // C++ [temp.arg.type]p1:
5172 // A template-argument for a template-parameter which is a
5173 // type shall be a type-id.
5174 ArgType = Arg.getAsType();
5175 TSI = AL.getTypeSourceInfo();
5176 break;
5177 case TemplateArgument::Template:
5178 case TemplateArgument::TemplateExpansion: {
5179 // We have a template type parameter but the template argument
5180 // is a template without any arguments.
5181 SourceRange SR = AL.getSourceRange();
5182 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
5183 diagnoseMissingTemplateArguments(Name, Loc: SR.getEnd());
5184 return true;
5185 }
5186 case TemplateArgument::Expression: {
5187 // We have a template type parameter but the template argument is an
5188 // expression; see if maybe it is missing the "typename" keyword.
5189 CXXScopeSpec SS;
5190 DeclarationNameInfo NameInfo;
5191
5192 if (DependentScopeDeclRefExpr *ArgExpr =
5193 dyn_cast<DependentScopeDeclRefExpr>(Val: Arg.getAsExpr())) {
5194 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5195 NameInfo = ArgExpr->getNameInfo();
5196 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5197 dyn_cast<CXXDependentScopeMemberExpr>(Val: Arg.getAsExpr())) {
5198 if (ArgExpr->isImplicitAccess()) {
5199 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5200 NameInfo = ArgExpr->getMemberNameInfo();
5201 }
5202 }
5203
5204 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5205 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5206 LookupParsedName(R&: Result, S: CurScope, SS: &SS, /*ObjectType=*/QualType());
5207
5208 if (Result.getAsSingle<TypeDecl>() ||
5209 Result.wasNotFoundInCurrentInstantiation()) {
5210 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5211 // Suggest that the user add 'typename' before the NNS.
5212 SourceLocation Loc = AL.getSourceRange().getBegin();
5213 Diag(Loc, DiagID: getLangOpts().MSVCCompat
5214 ? diag::ext_ms_template_type_arg_missing_typename
5215 : diag::err_template_arg_must_be_type_suggest)
5216 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
5217 NoteTemplateParameterLocation(Decl: *Param);
5218
5219 // Recover by synthesizing a type using the location information that we
5220 // already have.
5221 ArgType = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
5222 NNS: SS.getScopeRep(), Name: II);
5223 TypeLocBuilder TLB;
5224 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: ArgType);
5225 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5226 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5227 TL.setNameLoc(NameInfo.getLoc());
5228 TSI = TLB.getTypeSourceInfo(Context, T: ArgType);
5229
5230 // Overwrite our input TemplateArgumentLoc so that we can recover
5231 // properly.
5232 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5233 TemplateArgumentLocInfo(TSI));
5234
5235 break;
5236 }
5237 }
5238 // fallthrough
5239 [[fallthrough]];
5240 }
5241 default: {
5242 // We allow instantiating a template with template argument packs when
5243 // building deduction guides or mapping constraint template parameters.
5244 if (Arg.getKind() == TemplateArgument::Pack &&
5245 (CodeSynthesisContexts.back().Kind ==
5246 Sema::CodeSynthesisContext::BuildingDeductionGuides ||
5247 inParameterMappingSubstitution())) {
5248 SugaredConverted.push_back(Elt: Arg);
5249 CanonicalConverted.push_back(Elt: Arg);
5250 return false;
5251 }
5252 // We have a template type parameter but the template argument
5253 // is not a type.
5254 SourceRange SR = AL.getSourceRange();
5255 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_type) << SR;
5256 NoteTemplateParameterLocation(Decl: *Param);
5257
5258 return true;
5259 }
5260 }
5261
5262 if (CheckTemplateArgument(Arg: TSI))
5263 return true;
5264
5265 // Objective-C ARC:
5266 // If an explicitly-specified template argument type is a lifetime type
5267 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5268 if (getLangOpts().ObjCAutoRefCount &&
5269 ArgType->isObjCLifetimeType() &&
5270 !ArgType.getObjCLifetime()) {
5271 Qualifiers Qs;
5272 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5273 ArgType = Context.getQualifiedType(T: ArgType, Qs);
5274 }
5275
5276 SugaredConverted.push_back(Elt: TemplateArgument(ArgType));
5277 CanonicalConverted.push_back(
5278 Elt: TemplateArgument(Context.getCanonicalType(T: ArgType)));
5279 return false;
5280}
5281
5282/// Substitute template arguments into the default template argument for
5283/// the given template type parameter.
5284///
5285/// \param SemaRef the semantic analysis object for which we are performing
5286/// the substitution.
5287///
5288/// \param Template the template that we are synthesizing template arguments
5289/// for.
5290///
5291/// \param TemplateLoc the location of the template name that started the
5292/// template-id we are checking.
5293///
5294/// \param RAngleLoc the location of the right angle bracket ('>') that
5295/// terminates the template-id.
5296///
5297/// \param Param the template template parameter whose default we are
5298/// substituting into.
5299///
5300/// \param Converted the list of template arguments provided for template
5301/// parameters that precede \p Param in the template parameter list.
5302///
5303/// \param Output the resulting substituted template argument.
5304///
5305/// \returns true if an error occurred.
5306static bool SubstDefaultTemplateArgument(
5307 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5308 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5309 ArrayRef<TemplateArgument> SugaredConverted,
5310 ArrayRef<TemplateArgument> CanonicalConverted,
5311 TemplateArgumentLoc &Output) {
5312 Output = Param->getDefaultArgument();
5313
5314 // If the argument type is dependent, instantiate it now based
5315 // on the previously-computed template arguments.
5316 if (Output.getArgument().isInstantiationDependent()) {
5317 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5318 SugaredConverted,
5319 SourceRange(TemplateLoc, RAngleLoc));
5320 if (Inst.isInvalid())
5321 return true;
5322
5323 // Only substitute for the innermost template argument list.
5324 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5325 /*Final=*/true);
5326 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5327 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5328
5329 bool ForLambdaCallOperator = false;
5330 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Val: Template->getDeclContext()))
5331 ForLambdaCallOperator = Rec->isLambda();
5332 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5333 !ForLambdaCallOperator);
5334
5335 if (SemaRef.SubstTemplateArgument(Input: Output, TemplateArgs: TemplateArgLists, Output,
5336 Loc: Param->getDefaultArgumentLoc(),
5337 Entity: Param->getDeclName()))
5338 return true;
5339 }
5340
5341 return false;
5342}
5343
5344/// Substitute template arguments into the default template argument for
5345/// the given non-type template parameter.
5346///
5347/// \param SemaRef the semantic analysis object for which we are performing
5348/// the substitution.
5349///
5350/// \param Template the template that we are synthesizing template arguments
5351/// for.
5352///
5353/// \param TemplateLoc the location of the template name that started the
5354/// template-id we are checking.
5355///
5356/// \param RAngleLoc the location of the right angle bracket ('>') that
5357/// terminates the template-id.
5358///
5359/// \param Param the non-type template parameter whose default we are
5360/// substituting into.
5361///
5362/// \param Converted the list of template arguments provided for template
5363/// parameters that precede \p Param in the template parameter list.
5364///
5365/// \returns the substituted template argument, or NULL if an error occurred.
5366static bool SubstDefaultTemplateArgument(
5367 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5368 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5369 ArrayRef<TemplateArgument> SugaredConverted,
5370 ArrayRef<TemplateArgument> CanonicalConverted,
5371 TemplateArgumentLoc &Output) {
5372 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5373 SugaredConverted,
5374 SourceRange(TemplateLoc, RAngleLoc));
5375 if (Inst.isInvalid())
5376 return true;
5377
5378 // Only substitute for the innermost template argument list.
5379 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5380 /*Final=*/true);
5381 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5382 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5383
5384 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5385 EnterExpressionEvaluationContext ConstantEvaluated(
5386 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5387 return SemaRef.SubstTemplateArgument(Input: Param->getDefaultArgument(),
5388 TemplateArgs: TemplateArgLists, Output);
5389}
5390
5391/// Substitute template arguments into the default template argument for
5392/// the given template template parameter.
5393///
5394/// \param SemaRef the semantic analysis object for which we are performing
5395/// the substitution.
5396///
5397/// \param Template the template that we are synthesizing template arguments
5398/// for.
5399///
5400/// \param TemplateLoc the location of the template name that started the
5401/// template-id we are checking.
5402///
5403/// \param RAngleLoc the location of the right angle bracket ('>') that
5404/// terminates the template-id.
5405///
5406/// \param Param the template template parameter whose default we are
5407/// substituting into.
5408///
5409/// \param Converted the list of template arguments provided for template
5410/// parameters that precede \p Param in the template parameter list.
5411///
5412/// \param QualifierLoc Will be set to the nested-name-specifier (with
5413/// source-location information) that precedes the template name.
5414///
5415/// \returns the substituted template argument, or NULL if an error occurred.
5416static TemplateName SubstDefaultTemplateArgument(
5417 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5418 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5419 TemplateTemplateParmDecl *Param,
5420 ArrayRef<TemplateArgument> SugaredConverted,
5421 ArrayRef<TemplateArgument> CanonicalConverted,
5422 NestedNameSpecifierLoc &QualifierLoc) {
5423 Sema::InstantiatingTemplate Inst(
5424 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5425 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5426 if (Inst.isInvalid())
5427 return TemplateName();
5428
5429 // Only substitute for the innermost template argument list.
5430 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5431 /*Final=*/true);
5432 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5433 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5434
5435 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5436
5437 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5438 QualifierLoc = A.getTemplateQualifierLoc();
5439 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5440 Name: A.getArgument().getAsTemplate(),
5441 NameLoc: A.getTemplateNameLoc(), TemplateArgs: TemplateArgLists);
5442}
5443
5444TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
5445 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5446 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5447 ArrayRef<TemplateArgument> SugaredConverted,
5448 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5449 HasDefaultArg = false;
5450
5451 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
5452 if (!hasReachableDefaultArgument(D: TypeParm))
5453 return TemplateArgumentLoc();
5454
5455 HasDefaultArg = true;
5456 TemplateArgumentLoc Output;
5457 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5458 RAngleLoc, Param: TypeParm, SugaredConverted,
5459 CanonicalConverted, Output))
5460 return TemplateArgumentLoc();
5461 return Output;
5462 }
5463
5464 if (NonTypeTemplateParmDecl *NonTypeParm
5465 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5466 if (!hasReachableDefaultArgument(D: NonTypeParm))
5467 return TemplateArgumentLoc();
5468
5469 HasDefaultArg = true;
5470 TemplateArgumentLoc Output;
5471 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5472 RAngleLoc, Param: NonTypeParm, SugaredConverted,
5473 CanonicalConverted, Output))
5474 return TemplateArgumentLoc();
5475 return Output;
5476 }
5477
5478 TemplateTemplateParmDecl *TempTempParm
5479 = cast<TemplateTemplateParmDecl>(Val: Param);
5480 if (!hasReachableDefaultArgument(D: TempTempParm))
5481 return TemplateArgumentLoc();
5482
5483 HasDefaultArg = true;
5484 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5485 NestedNameSpecifierLoc QualifierLoc;
5486 TemplateName TName = SubstDefaultTemplateArgument(
5487 SemaRef&: *this, Template, TemplateKWLoc, TemplateLoc: TemplateNameLoc, RAngleLoc, Param: TempTempParm,
5488 SugaredConverted, CanonicalConverted, QualifierLoc);
5489 if (TName.isNull())
5490 return TemplateArgumentLoc();
5491
5492 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5493 QualifierLoc, A.getTemplateNameLoc());
5494}
5495
5496/// Convert a template-argument that we parsed as a type into a template, if
5497/// possible. C++ permits injected-class-names to perform dual service as
5498/// template template arguments and as template type arguments.
5499static TemplateArgumentLoc
5500convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5501 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5502 if (!TagLoc)
5503 return TemplateArgumentLoc();
5504
5505 // If this type was written as an injected-class-name, it can be used as a
5506 // template template argument.
5507 // If this type was written as an injected-class-name, it may have been
5508 // converted to a RecordType during instantiation. If the RecordType is
5509 // *not* wrapped in a TemplateSpecializationType and denotes a class
5510 // template specialization, it must have come from an injected-class-name.
5511
5512 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Ctx: Context);
5513 if (Name.isNull())
5514 return TemplateArgumentLoc();
5515
5516 return TemplateArgumentLoc(Context, Name,
5517 /*TemplateKWLoc=*/SourceLocation(),
5518 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5519}
5520
5521bool Sema::CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &ArgLoc,
5522 NamedDecl *Template,
5523 SourceLocation TemplateLoc,
5524 SourceLocation RAngleLoc,
5525 unsigned ArgumentPackIndex,
5526 CheckTemplateArgumentInfo &CTAI,
5527 CheckTemplateArgumentKind CTAK) {
5528 // Check template type parameters.
5529 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param))
5530 return CheckTemplateTypeArgument(Param: TTP, AL&: ArgLoc, SugaredConverted&: CTAI.SugaredConverted,
5531 CanonicalConverted&: CTAI.CanonicalConverted);
5532
5533 const TemplateArgument &Arg = ArgLoc.getArgument();
5534 // Check non-type template parameters.
5535 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5536 // Do substitution on the type of the non-type template parameter
5537 // with the template arguments we've seen thus far. But if the
5538 // template has a dependent context then we cannot substitute yet.
5539 QualType NTTPType = NTTP->getType();
5540 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5541 NTTPType = NTTP->getExpansionType(I: ArgumentPackIndex);
5542
5543 if (NTTPType->isInstantiationDependentType()) {
5544 // Do substitution on the type of the non-type template parameter.
5545 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5546 CTAI.SugaredConverted,
5547 SourceRange(TemplateLoc, RAngleLoc));
5548 if (Inst.isInvalid())
5549 return true;
5550
5551 MultiLevelTemplateArgumentList MLTAL(Template, CTAI.SugaredConverted,
5552 /*Final=*/true);
5553 MLTAL.addOuterRetainedLevels(Num: NTTP->getDepth());
5554 // If the parameter is a pack expansion, expand this slice of the pack.
5555 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5556 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5557 NTTPType = SubstType(T: PET->getPattern(), TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5558 Entity: NTTP->getDeclName());
5559 } else {
5560 NTTPType = SubstType(T: NTTPType, TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5561 Entity: NTTP->getDeclName());
5562 }
5563
5564 // If that worked, check the non-type template parameter type
5565 // for validity.
5566 if (!NTTPType.isNull())
5567 NTTPType = CheckNonTypeTemplateParameterType(T: NTTPType,
5568 Loc: NTTP->getLocation());
5569 if (NTTPType.isNull())
5570 return true;
5571 }
5572
5573 auto checkExpr = [&](Expr *E) -> Expr * {
5574 TemplateArgument SugaredResult, CanonicalResult;
5575 ExprResult Res = CheckTemplateArgument(
5576 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E, SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5577 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5578 // If the current template argument causes an error, give up now.
5579 if (Res.isInvalid())
5580 return nullptr;
5581 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5582 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5583 return Res.get();
5584 };
5585
5586 switch (Arg.getKind()) {
5587 case TemplateArgument::Null:
5588 llvm_unreachable("Should never see a NULL template argument here");
5589
5590 case TemplateArgument::Expression: {
5591 Expr *E = Arg.getAsExpr();
5592 Expr *R = checkExpr(E);
5593 if (!R)
5594 return true;
5595 // If the resulting expression is new, then use it in place of the
5596 // old expression in the template argument.
5597 if (R != E) {
5598 TemplateArgument TA(R, /*IsCanonical=*/false);
5599 ArgLoc = TemplateArgumentLoc(TA, R);
5600 }
5601 break;
5602 }
5603
5604 // As for the converted NTTP kinds, they still might need another
5605 // conversion, as the new corresponding parameter might be different.
5606 // Ideally, we would always perform substitution starting with sugared types
5607 // and never need these, as we would still have expressions. Since these are
5608 // needed so rarely, it's probably a better tradeoff to just convert them
5609 // back to expressions.
5610 case TemplateArgument::Integral:
5611 case TemplateArgument::Declaration:
5612 case TemplateArgument::NullPtr:
5613 case TemplateArgument::StructuralValue: {
5614 // FIXME: StructuralValue is untested here.
5615 ExprResult R =
5616 BuildExpressionFromNonTypeTemplateArgument(Arg, Loc: SourceLocation());
5617 assert(R.isUsable());
5618 if (!checkExpr(R.get()))
5619 return true;
5620 break;
5621 }
5622
5623 case TemplateArgument::Template:
5624 case TemplateArgument::TemplateExpansion:
5625 // We were given a template template argument. It may not be ill-formed;
5626 // see below.
5627 if (DependentTemplateName *DTN = Arg.getAsTemplateOrTemplatePattern()
5628 .getAsDependentTemplateName()) {
5629 // We have a template argument such as \c T::template X, which we
5630 // parsed as a template template argument. However, since we now
5631 // know that we need a non-type template argument, convert this
5632 // template name into an expression.
5633
5634 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5635 ArgLoc.getTemplateNameLoc());
5636
5637 CXXScopeSpec SS;
5638 SS.Adopt(Other: ArgLoc.getTemplateQualifierLoc());
5639 // FIXME: the template-template arg was a DependentTemplateName,
5640 // so it was provided with a template keyword. However, its source
5641 // location is not stored in the template argument structure.
5642 SourceLocation TemplateKWLoc;
5643 ExprResult E = DependentScopeDeclRefExpr::Create(
5644 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5645 TemplateArgs: nullptr);
5646
5647 // If we parsed the template argument as a pack expansion, create a
5648 // pack expansion expression.
5649 if (Arg.getKind() == TemplateArgument::TemplateExpansion) {
5650 E = ActOnPackExpansion(Pattern: E.get(), EllipsisLoc: ArgLoc.getTemplateEllipsisLoc());
5651 if (E.isInvalid())
5652 return true;
5653 }
5654
5655 TemplateArgument SugaredResult, CanonicalResult;
5656 E = CheckTemplateArgument(
5657 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E.get(), SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5658 /*StrictCheck=*/CTAI.PartialOrdering, CTAK: CTAK_Specified);
5659 if (E.isInvalid())
5660 return true;
5661
5662 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5663 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5664 break;
5665 }
5666
5667 // We have a template argument that actually does refer to a class
5668 // template, alias template, or template template parameter, and
5669 // therefore cannot be a non-type template argument.
5670 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_expr)
5671 << ArgLoc.getSourceRange();
5672 NoteTemplateParameterLocation(Decl: *Param);
5673
5674 return true;
5675
5676 case TemplateArgument::Type: {
5677 // We have a non-type template parameter but the template
5678 // argument is a type.
5679
5680 // C++ [temp.arg]p2:
5681 // In a template-argument, an ambiguity between a type-id and
5682 // an expression is resolved to a type-id, regardless of the
5683 // form of the corresponding template-parameter.
5684 //
5685 // We warn specifically about this case, since it can be rather
5686 // confusing for users.
5687 QualType T = Arg.getAsType();
5688 SourceRange SR = ArgLoc.getSourceRange();
5689 if (T->isFunctionType())
5690 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_nontype_ambig) << SR << T;
5691 else
5692 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_expr) << SR;
5693 NoteTemplateParameterLocation(Decl: *Param);
5694 return true;
5695 }
5696
5697 case TemplateArgument::Pack:
5698 llvm_unreachable("Caller must expand template argument packs");
5699 }
5700
5701 return false;
5702 }
5703
5704
5705 // Check template template parameters.
5706 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Val: Param);
5707
5708 TemplateParameterList *Params = TempParm->getTemplateParameters();
5709 if (TempParm->isExpandedParameterPack())
5710 Params = TempParm->getExpansionTemplateParameters(I: ArgumentPackIndex);
5711
5712 // Substitute into the template parameter list of the template
5713 // template parameter, since previously-supplied template arguments
5714 // may appear within the template template parameter.
5715 //
5716 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5717 {
5718 // Set up a template instantiation context.
5719 LocalInstantiationScope Scope(*this);
5720 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5721 CTAI.SugaredConverted,
5722 SourceRange(TemplateLoc, RAngleLoc));
5723 if (Inst.isInvalid())
5724 return true;
5725
5726 Params = SubstTemplateParams(
5727 Params, Owner: CurContext,
5728 TemplateArgs: MultiLevelTemplateArgumentList(Template, CTAI.SugaredConverted,
5729 /*Final=*/true),
5730 /*EvaluateConstraints=*/false);
5731 if (!Params)
5732 return true;
5733 }
5734
5735 // C++1z [temp.local]p1: (DR1004)
5736 // When [the injected-class-name] is used [...] as a template-argument for
5737 // a template template-parameter [...] it refers to the class template
5738 // itself.
5739 if (Arg.getKind() == TemplateArgument::Type) {
5740 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5741 Context, TLoc: ArgLoc.getTypeSourceInfo()->getTypeLoc());
5742 if (!ConvertedArg.getArgument().isNull())
5743 ArgLoc = ConvertedArg;
5744 }
5745
5746 switch (Arg.getKind()) {
5747 case TemplateArgument::Null:
5748 llvm_unreachable("Should never see a NULL template argument here");
5749
5750 case TemplateArgument::Template:
5751 case TemplateArgument::TemplateExpansion:
5752 if (CheckTemplateTemplateArgument(Param: TempParm, Params, Arg&: ArgLoc,
5753 PartialOrdering: CTAI.PartialOrdering,
5754 StrictPackMatch: &CTAI.StrictPackMatch))
5755 return true;
5756
5757 CTAI.SugaredConverted.push_back(Elt: Arg);
5758 CTAI.CanonicalConverted.push_back(
5759 Elt: Context.getCanonicalTemplateArgument(Arg));
5760 break;
5761
5762 case TemplateArgument::Expression:
5763 case TemplateArgument::Type: {
5764 auto Kind = 0;
5765 switch (TempParm->templateParameterKind()) {
5766 case TemplateNameKind::TNK_Var_template:
5767 Kind = 1;
5768 break;
5769 case TemplateNameKind::TNK_Concept_template:
5770 Kind = 2;
5771 break;
5772 default:
5773 break;
5774 }
5775
5776 // We have a template template parameter but the template
5777 // argument does not refer to a template.
5778 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_template)
5779 << Kind << getLangOpts().CPlusPlus11;
5780 return true;
5781 }
5782
5783 case TemplateArgument::Declaration:
5784 case TemplateArgument::Integral:
5785 case TemplateArgument::StructuralValue:
5786 case TemplateArgument::NullPtr:
5787 llvm_unreachable("non-type argument with template template parameter");
5788
5789 case TemplateArgument::Pack:
5790 llvm_unreachable("Caller must expand template argument packs");
5791 }
5792
5793 return false;
5794}
5795
5796/// Diagnose a missing template argument.
5797template<typename TemplateParmDecl>
5798static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5799 TemplateDecl *TD,
5800 const TemplateParmDecl *D,
5801 TemplateArgumentListInfo &Args) {
5802 // Dig out the most recent declaration of the template parameter; there may be
5803 // declarations of the template that are more recent than TD.
5804 D = cast<TemplateParmDecl>(cast<TemplateDecl>(Val: TD->getMostRecentDecl())
5805 ->getTemplateParameters()
5806 ->getParam(D->getIndex()));
5807
5808 // If there's a default argument that's not reachable, diagnose that we're
5809 // missing a module import.
5810 llvm::SmallVector<Module*, 8> Modules;
5811 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, Modules: &Modules)) {
5812 S.diagnoseMissingImport(Loc, cast<NamedDecl>(Val: TD),
5813 D->getDefaultArgumentLoc(), Modules,
5814 Sema::MissingImportKind::DefaultArgument,
5815 /*Recover*/true);
5816 return true;
5817 }
5818
5819 // FIXME: If there's a more recent default argument that *is* visible,
5820 // diagnose that it was declared too late.
5821
5822 TemplateParameterList *Params = TD->getTemplateParameters();
5823
5824 S.Diag(Loc, DiagID: diag::err_template_arg_list_different_arity)
5825 << /*not enough args*/0
5826 << (int)S.getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
5827 << TD;
5828 S.NoteTemplateLocation(Decl: *TD, ParamRange: Params->getSourceRange());
5829 return true;
5830}
5831
5832/// Check that the given template argument list is well-formed
5833/// for specializing the given template.
5834bool Sema::CheckTemplateArgumentList(
5835 TemplateDecl *Template, SourceLocation TemplateLoc,
5836 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5837 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5838 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5839 return CheckTemplateArgumentList(
5840 Template, Params: GetTemplateParameterList(TD: Template), TemplateLoc, TemplateArgs,
5841 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5842 ConstraintsNotSatisfied);
5843}
5844
5845/// Check that the given template argument list is well-formed
5846/// for specializing the given template.
5847bool Sema::CheckTemplateArgumentList(
5848 TemplateDecl *Template, TemplateParameterList *Params,
5849 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5850 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5851 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5852 bool *ConstraintsNotSatisfied) {
5853
5854 if (ConstraintsNotSatisfied)
5855 *ConstraintsNotSatisfied = false;
5856
5857 // Make a copy of the template arguments for processing. Only make the
5858 // changes at the end when successful in matching the arguments to the
5859 // template.
5860 TemplateArgumentListInfo NewArgs = TemplateArgs;
5861
5862 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5863
5864 // C++23 [temp.arg.general]p1:
5865 // [...] The type and form of each template-argument specified in
5866 // a template-id shall match the type and form specified for the
5867 // corresponding parameter declared by the template in its
5868 // template-parameter-list.
5869 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Val: Template);
5870 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5871 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5872 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5873 LocalInstantiationScope InstScope(*this, true);
5874 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5875 ParamEnd = Params->end(),
5876 Param = ParamBegin;
5877 Param != ParamEnd;
5878 /* increment in loop */) {
5879 if (size_t ParamIdx = Param - ParamBegin;
5880 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5881 // All written arguments should have been consumed by this point.
5882 assert(ArgIdx == NumArgs && "bad default argument deduction");
5883 if (ParamIdx == DefaultArgs.StartPos) {
5884 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5885 // Default arguments from a DeducedTemplateName are already converted.
5886 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5887 CTAI.SugaredConverted.push_back(Elt: DefArg);
5888 CTAI.CanonicalConverted.push_back(
5889 Elt: Context.getCanonicalTemplateArgument(Arg: DefArg));
5890 ++Param;
5891 }
5892 continue;
5893 }
5894 }
5895
5896 // If we have an expanded parameter pack, make sure we don't have too
5897 // many arguments.
5898 if (UnsignedOrNone Expansions = getExpandedPackSize(Param: *Param)) {
5899 if (*Expansions == SugaredArgumentPack.size()) {
5900 // We're done with this parameter pack. Pack up its arguments and add
5901 // them to the list.
5902 CTAI.SugaredConverted.push_back(
5903 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
5904 SugaredArgumentPack.clear();
5905
5906 CTAI.CanonicalConverted.push_back(
5907 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
5908 CanonicalArgumentPack.clear();
5909
5910 // This argument is assigned to the next parameter.
5911 ++Param;
5912 continue;
5913 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5914 // Not enough arguments for this parameter pack.
5915 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
5916 << /*not enough args*/0
5917 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
5918 << Template;
5919 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
5920 return true;
5921 }
5922 }
5923
5924 // Check for builtins producing template packs in this context, we do not
5925 // support them yet.
5926 if (const NonTypeTemplateParmDecl *NTTP =
5927 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param);
5928 NTTP && NTTP->isPackExpansion()) {
5929 auto TL = NTTP->getTypeSourceInfo()
5930 ->getTypeLoc()
5931 .castAs<PackExpansionTypeLoc>();
5932 llvm::SmallVector<UnexpandedParameterPack> Unexpanded;
5933 collectUnexpandedParameterPacks(TL: TL.getPatternLoc(), Unexpanded);
5934 for (const auto &UPP : Unexpanded) {
5935 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5936 if (!TST)
5937 continue;
5938 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5939 // Expanding a built-in pack in this context is not yet supported.
5940 Diag(Loc: TL.getEllipsisLoc(),
5941 DiagID: diag::err_unsupported_builtin_template_pack_expansion)
5942 << TST->getTemplateName();
5943 return true;
5944 }
5945 }
5946
5947 if (ArgIdx < NumArgs) {
5948 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5949 bool NonPackParameter =
5950 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(Param: *Param);
5951 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5952
5953 if (ArgIsExpansion && CTAI.MatchingTTP) {
5954 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5955 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5956 ++Param) {
5957 TemplateArgument &Arg = Args[Param - First];
5958 Arg = ArgLoc.getArgument();
5959 if (!(*Param)->isTemplateParameterPack() ||
5960 getExpandedPackSize(Param: *Param))
5961 Arg = Arg.getPackExpansionPattern();
5962 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5963 SaveAndRestore _1(CTAI.PartialOrdering, false);
5964 SaveAndRestore _2(CTAI.MatchingTTP, true);
5965 if (CheckTemplateArgument(Param: *Param, ArgLoc&: NewArgLoc, Template, TemplateLoc,
5966 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
5967 CTAK: CTAK_Specified))
5968 return true;
5969 Arg = NewArgLoc.getArgument();
5970 CTAI.CanonicalConverted.back().setIsDefaulted(
5971 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg, Param: *Param,
5972 Args: CTAI.CanonicalConverted,
5973 Depth: Params->getDepth()));
5974 }
5975 ArgLoc =
5976 TemplateArgumentLoc(TemplateArgument::CreatePackCopy(Context, Args),
5977 ArgLoc.getLocInfo());
5978 } else {
5979 SaveAndRestore _1(CTAI.PartialOrdering, false);
5980 if (CheckTemplateArgument(Param: *Param, ArgLoc, Template, TemplateLoc,
5981 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
5982 CTAK: CTAK_Specified))
5983 return true;
5984 CTAI.CanonicalConverted.back().setIsDefaulted(
5985 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg: ArgLoc.getArgument(),
5986 Param: *Param, Args: CTAI.CanonicalConverted,
5987 Depth: Params->getDepth()));
5988 if (ArgIsExpansion && NonPackParameter) {
5989 // CWG1430/CWG2686: we have a pack expansion as an argument to an
5990 // alias template, builtin template, or concept, and it's not part of
5991 // a parameter pack. This can't be canonicalized, so reject it now.
5992 if (isa<TypeAliasTemplateDecl, ConceptDecl, BuiltinTemplateDecl>(
5993 Val: Template)) {
5994 unsigned DiagSelect = isa<ConceptDecl>(Val: Template) ? 1
5995 : isa<BuiltinTemplateDecl>(Val: Template) ? 2
5996 : 0;
5997 Diag(Loc: ArgLoc.getLocation(),
5998 DiagID: diag::err_template_expansion_into_fixed_list)
5999 << DiagSelect << ArgLoc.getSourceRange();
6000 NoteTemplateParameterLocation(Decl: **Param);
6001 return true;
6002 }
6003 }
6004 }
6005
6006 // We're now done with this argument.
6007 ++ArgIdx;
6008
6009 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6010 // Directly convert the remaining arguments, because we don't know what
6011 // parameters they'll match up with.
6012
6013 if (!SugaredArgumentPack.empty()) {
6014 // If we were part way through filling in an expanded parameter pack,
6015 // fall back to just producing individual arguments.
6016 CTAI.SugaredConverted.insert(I: CTAI.SugaredConverted.end(),
6017 From: SugaredArgumentPack.begin(),
6018 To: SugaredArgumentPack.end());
6019 SugaredArgumentPack.clear();
6020
6021 CTAI.CanonicalConverted.insert(I: CTAI.CanonicalConverted.end(),
6022 From: CanonicalArgumentPack.begin(),
6023 To: CanonicalArgumentPack.end());
6024 CanonicalArgumentPack.clear();
6025 }
6026
6027 while (ArgIdx < NumArgs) {
6028 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6029 CTAI.SugaredConverted.push_back(Elt: Arg);
6030 CTAI.CanonicalConverted.push_back(
6031 Elt: Context.getCanonicalTemplateArgument(Arg));
6032 ++ArgIdx;
6033 }
6034
6035 return false;
6036 }
6037
6038 if ((*Param)->isTemplateParameterPack()) {
6039 // The template parameter was a template parameter pack, so take the
6040 // deduced argument and place it on the argument pack. Note that we
6041 // stay on the same template parameter so that we can deduce more
6042 // arguments.
6043 SugaredArgumentPack.push_back(Elt: CTAI.SugaredConverted.pop_back_val());
6044 CanonicalArgumentPack.push_back(Elt: CTAI.CanonicalConverted.pop_back_val());
6045 } else {
6046 // Move to the next template parameter.
6047 ++Param;
6048 }
6049 continue;
6050 }
6051
6052 // If we're checking a partial template argument list, we're done.
6053 if (PartialTemplateArgs) {
6054 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6055 CTAI.SugaredConverted.push_back(
6056 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6057 CTAI.CanonicalConverted.push_back(
6058 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6059 }
6060 return false;
6061 }
6062
6063 // If we have a template parameter pack with no more corresponding
6064 // arguments, just break out now and we'll fill in the argument pack below.
6065 if ((*Param)->isTemplateParameterPack()) {
6066 assert(!getExpandedPackSize(*Param) &&
6067 "Should have dealt with this already");
6068
6069 // A non-expanded parameter pack before the end of the parameter list
6070 // only occurs for an ill-formed template parameter list, unless we've
6071 // got a partial argument list for a function template, so just bail out.
6072 if (Param + 1 != ParamEnd) {
6073 assert(
6074 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6075 "Concept templates must have parameter packs at the end.");
6076 return true;
6077 }
6078
6079 CTAI.SugaredConverted.push_back(
6080 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6081 SugaredArgumentPack.clear();
6082
6083 CTAI.CanonicalConverted.push_back(
6084 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6085 CanonicalArgumentPack.clear();
6086
6087 ++Param;
6088 continue;
6089 }
6090
6091 // Check whether we have a default argument.
6092 bool HasDefaultArg;
6093
6094 // Retrieve the default template argument from the template
6095 // parameter. For each kind of template parameter, we substitute the
6096 // template arguments provided thus far and any "outer" template arguments
6097 // (when the template parameter was part of a nested template) into
6098 // the default argument.
6099 TemplateArgumentLoc Arg = SubstDefaultTemplateArgumentIfAvailable(
6100 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateNameLoc: TemplateLoc, RAngleLoc,
6101 Param: *Param, SugaredConverted: CTAI.SugaredConverted, CanonicalConverted: CTAI.CanonicalConverted, HasDefaultArg);
6102
6103 if (Arg.getArgument().isNull()) {
6104 if (!HasDefaultArg) {
6105 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *Param))
6106 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: TTP,
6107 Args&: NewArgs);
6108 if (NonTypeTemplateParmDecl *NTTP =
6109 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param))
6110 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: NTTP,
6111 Args&: NewArgs);
6112 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template,
6113 D: cast<TemplateTemplateParmDecl>(Val: *Param),
6114 Args&: NewArgs);
6115 }
6116 return true;
6117 }
6118
6119 // Introduce an instantiation record that describes where we are using
6120 // the default template argument. We're not actually instantiating a
6121 // template here, we just create this object to put a note into the
6122 // context stack.
6123 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6124 CTAI.SugaredConverted,
6125 SourceRange(TemplateLoc, RAngleLoc));
6126 if (Inst.isInvalid())
6127 return true;
6128
6129 SaveAndRestore _1(CTAI.PartialOrdering, false);
6130 SaveAndRestore _2(CTAI.MatchingTTP, false);
6131 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6132 // Check the default template argument.
6133 if (CheckTemplateArgument(Param: *Param, ArgLoc&: Arg, Template, TemplateLoc, RAngleLoc, ArgumentPackIndex: 0,
6134 CTAI, CTAK: CTAK_Specified))
6135 return true;
6136
6137 CTAI.SugaredConverted.back().setIsDefaulted(true);
6138 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6139
6140 // Core issue 150 (assumed resolution): if this is a template template
6141 // parameter, keep track of the default template arguments from the
6142 // template definition.
6143 if (isTemplateTemplateParameter)
6144 NewArgs.addArgument(Loc: Arg);
6145
6146 // Move to the next template parameter and argument.
6147 ++Param;
6148 ++ArgIdx;
6149 }
6150
6151 // If we're performing a partial argument substitution, allow any trailing
6152 // pack expansions; they might be empty. This can happen even if
6153 // PartialTemplateArgs is false (the list of arguments is complete but
6154 // still dependent).
6155 if (CTAI.MatchingTTP ||
6156 (CurrentInstantiationScope &&
6157 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6158 while (ArgIdx < NumArgs &&
6159 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6160 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6161 CTAI.SugaredConverted.push_back(Elt: Arg);
6162 CTAI.CanonicalConverted.push_back(
6163 Elt: Context.getCanonicalTemplateArgument(Arg));
6164 }
6165 }
6166
6167 // If we have any leftover arguments, then there were too many arguments.
6168 // Complain and fail.
6169 if (ArgIdx < NumArgs) {
6170 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
6171 << /*too many args*/1
6172 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
6173 << Template
6174 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6175 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
6176 return true;
6177 }
6178
6179 // No problems found with the new argument list, propagate changes back
6180 // to caller.
6181 if (UpdateArgsWithConversions)
6182 TemplateArgs = std::move(NewArgs);
6183
6184 if (!PartialTemplateArgs) {
6185 // Setup the context/ThisScope for the case where we are needing to
6186 // re-instantiate constraints outside of normal instantiation.
6187 DeclContext *NewContext = Template->getDeclContext();
6188
6189 // If this template is in a template, make sure we extract the templated
6190 // decl.
6191 if (auto *TD = dyn_cast<TemplateDecl>(Val: NewContext))
6192 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6193 auto *RD = dyn_cast<CXXRecordDecl>(Val: NewContext);
6194
6195 Qualifiers ThisQuals;
6196 if (const auto *Method =
6197 dyn_cast_or_null<CXXMethodDecl>(Val: Template->getTemplatedDecl()))
6198 ThisQuals = Method->getMethodQualifiers();
6199
6200 ContextRAII Context(*this, NewContext);
6201 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6202
6203 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
6204 D: Template, DC: NewContext, /*Final=*/true, Innermost: CTAI.SugaredConverted,
6205 /*RelativeToPrimary=*/true,
6206 /*Pattern=*/nullptr,
6207 /*ForConceptInstantiation=*/ForConstraintInstantiation: true);
6208 if (!isa<ConceptDecl>(Val: Template) &&
6209 EnsureTemplateArgumentListConstraints(
6210 Template, TemplateArgs: MLTAL,
6211 TemplateIDRange: SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6212 if (ConstraintsNotSatisfied)
6213 *ConstraintsNotSatisfied = true;
6214 return true;
6215 }
6216 }
6217
6218 return false;
6219}
6220
6221namespace {
6222 class UnnamedLocalNoLinkageFinder
6223 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6224 {
6225 Sema &S;
6226 SourceRange SR;
6227
6228 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
6229
6230 public:
6231 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6232
6233 bool Visit(QualType T) {
6234 return T.isNull() ? false : inherited::Visit(T: T.getTypePtr());
6235 }
6236
6237#define TYPE(Class, Parent) \
6238 bool Visit##Class##Type(const Class##Type *);
6239#define ABSTRACT_TYPE(Class, Parent) \
6240 bool Visit##Class##Type(const Class##Type *) { return false; }
6241#define NON_CANONICAL_TYPE(Class, Parent) \
6242 bool Visit##Class##Type(const Class##Type *) { return false; }
6243#include "clang/AST/TypeNodes.inc"
6244
6245 bool VisitTagDecl(const TagDecl *Tag);
6246 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6247 };
6248} // end anonymous namespace
6249
6250bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6251 return false;
6252}
6253
6254bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6255 return Visit(T: T->getElementType());
6256}
6257
6258bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6259 return Visit(T: T->getPointeeType());
6260}
6261
6262bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6263 const BlockPointerType* T) {
6264 return Visit(T: T->getPointeeType());
6265}
6266
6267bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6268 const LValueReferenceType* T) {
6269 return Visit(T: T->getPointeeType());
6270}
6271
6272bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6273 const RValueReferenceType* T) {
6274 return Visit(T: T->getPointeeType());
6275}
6276
6277bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6278 const MemberPointerType *T) {
6279 if (Visit(T: T->getPointeeType()))
6280 return true;
6281 if (auto *RD = T->getMostRecentCXXRecordDecl())
6282 return VisitTagDecl(Tag: RD);
6283 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6284}
6285
6286bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6287 const ConstantArrayType* T) {
6288 return Visit(T: T->getElementType());
6289}
6290
6291bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6292 const IncompleteArrayType* T) {
6293 return Visit(T: T->getElementType());
6294}
6295
6296bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6297 const VariableArrayType* T) {
6298 return Visit(T: T->getElementType());
6299}
6300
6301bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6302 const DependentSizedArrayType* T) {
6303 return Visit(T: T->getElementType());
6304}
6305
6306bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6307 const DependentSizedExtVectorType* T) {
6308 return Visit(T: T->getElementType());
6309}
6310
6311bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6312 const DependentSizedMatrixType *T) {
6313 return Visit(T: T->getElementType());
6314}
6315
6316bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6317 const DependentAddressSpaceType *T) {
6318 return Visit(T: T->getPointeeType());
6319}
6320
6321bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6322 return Visit(T: T->getElementType());
6323}
6324
6325bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6326 const DependentVectorType *T) {
6327 return Visit(T: T->getElementType());
6328}
6329
6330bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6331 return Visit(T: T->getElementType());
6332}
6333
6334bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6335 const ConstantMatrixType *T) {
6336 return Visit(T: T->getElementType());
6337}
6338
6339bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6340 const FunctionProtoType* T) {
6341 for (const auto &A : T->param_types()) {
6342 if (Visit(T: A))
6343 return true;
6344 }
6345
6346 return Visit(T: T->getReturnType());
6347}
6348
6349bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6350 const FunctionNoProtoType* T) {
6351 return Visit(T: T->getReturnType());
6352}
6353
6354bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6355 const UnresolvedUsingType*) {
6356 return false;
6357}
6358
6359bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6360 return false;
6361}
6362
6363bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6364 return Visit(T: T->getUnmodifiedType());
6365}
6366
6367bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6368 return false;
6369}
6370
6371bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6372 const PackIndexingType *) {
6373 return false;
6374}
6375
6376bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6377 const UnaryTransformType*) {
6378 return false;
6379}
6380
6381bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6382 return Visit(T: T->getDeducedType());
6383}
6384
6385bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6386 const DeducedTemplateSpecializationType *T) {
6387 return Visit(T: T->getDeducedType());
6388}
6389
6390bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6391 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6392}
6393
6394bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6395 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6396}
6397
6398bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6399 const TemplateTypeParmType*) {
6400 return false;
6401}
6402
6403bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6404 const SubstTemplateTypeParmPackType *) {
6405 return false;
6406}
6407
6408bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6409 const SubstBuiltinTemplatePackType *) {
6410 return false;
6411}
6412
6413bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6414 const TemplateSpecializationType*) {
6415 return false;
6416}
6417
6418bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6419 const InjectedClassNameType* T) {
6420 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6421}
6422
6423bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6424 const DependentNameType* T) {
6425 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6426}
6427
6428bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6429 const PackExpansionType* T) {
6430 return Visit(T: T->getPattern());
6431}
6432
6433bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6434 return false;
6435}
6436
6437bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6438 const ObjCInterfaceType *) {
6439 return false;
6440}
6441
6442bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6443 const ObjCObjectPointerType *) {
6444 return false;
6445}
6446
6447bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6448 return Visit(T: T->getValueType());
6449}
6450
6451bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6452 const OverflowBehaviorType *T) {
6453 return Visit(T: T->getUnderlyingType());
6454}
6455
6456bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6457 return false;
6458}
6459
6460bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6461 return false;
6462}
6463
6464bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6465 const ArrayParameterType *T) {
6466 return VisitConstantArrayType(T);
6467}
6468
6469bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6470 const DependentBitIntType *T) {
6471 return false;
6472}
6473
6474bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6475 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6476 S.Diag(Loc: SR.getBegin(), DiagID: S.getLangOpts().CPlusPlus11
6477 ? diag::warn_cxx98_compat_template_arg_local_type
6478 : diag::ext_template_arg_local_type)
6479 << S.Context.getCanonicalTagType(TD: Tag) << SR;
6480 return true;
6481 }
6482
6483 if (!Tag->hasNameForLinkage()) {
6484 S.Diag(Loc: SR.getBegin(),
6485 DiagID: S.getLangOpts().CPlusPlus11 ?
6486 diag::warn_cxx98_compat_template_arg_unnamed_type :
6487 diag::ext_template_arg_unnamed_type) << SR;
6488 S.Diag(Loc: Tag->getLocation(), DiagID: diag::note_template_unnamed_type_here);
6489 return true;
6490 }
6491
6492 return false;
6493}
6494
6495bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6496 NestedNameSpecifier NNS) {
6497 switch (NNS.getKind()) {
6498 case NestedNameSpecifier::Kind::Null:
6499 case NestedNameSpecifier::Kind::Namespace:
6500 case NestedNameSpecifier::Kind::Global:
6501 case NestedNameSpecifier::Kind::MicrosoftSuper:
6502 return false;
6503 case NestedNameSpecifier::Kind::Type:
6504 return Visit(T: QualType(NNS.getAsType(), 0));
6505 }
6506 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6507}
6508
6509bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6510 const HLSLAttributedResourceType *T) {
6511 if (T->hasContainedType() && Visit(T: T->getContainedType()))
6512 return true;
6513 return Visit(T: T->getWrappedType());
6514}
6515
6516bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6517 const HLSLInlineSpirvType *T) {
6518 for (auto &Operand : T->getOperands())
6519 if (Operand.isConstant() && Operand.isLiteral())
6520 if (Visit(T: Operand.getResultType()))
6521 return true;
6522 return false;
6523}
6524
6525bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6526 assert(ArgInfo && "invalid TypeSourceInfo");
6527 QualType Arg = ArgInfo->getType();
6528 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6529 QualType CanonArg = Context.getCanonicalType(T: Arg);
6530
6531 if (CanonArg->isVariablyModifiedType()) {
6532 return Diag(Loc: SR.getBegin(), DiagID: diag::err_variably_modified_template_arg) << Arg;
6533 } else if (Context.hasSameUnqualifiedType(T1: Arg, T2: Context.OverloadTy)) {
6534 return Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_overload_type) << SR;
6535 }
6536
6537 // C++03 [temp.arg.type]p2:
6538 // A local type, a type with no linkage, an unnamed type or a type
6539 // compounded from any of these types shall not be used as a
6540 // template-argument for a template type-parameter.
6541 //
6542 // C++11 allows these, and even in C++03 we allow them as an extension with
6543 // a warning.
6544 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6545 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6546 (void)Finder.Visit(T: CanonArg);
6547 }
6548
6549 return false;
6550}
6551
6552enum NullPointerValueKind {
6553 NPV_NotNullPointer,
6554 NPV_NullPointer,
6555 NPV_Error
6556};
6557
6558/// Determine whether the given template argument is a null pointer
6559/// value of the appropriate type.
6560static NullPointerValueKind
6561isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param,
6562 QualType ParamType, Expr *Arg,
6563 Decl *Entity = nullptr) {
6564 if (Arg->isValueDependent() || Arg->isTypeDependent())
6565 return NPV_NotNullPointer;
6566
6567 // dllimport'd entities aren't constant but are available inside of template
6568 // arguments.
6569 if (Entity && Entity->hasAttr<DLLImportAttr>())
6570 return NPV_NotNullPointer;
6571
6572 if (!S.isCompleteType(Loc: Arg->getExprLoc(), T: ParamType))
6573 llvm_unreachable(
6574 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6575
6576 if (!S.getLangOpts().CPlusPlus11)
6577 return NPV_NotNullPointer;
6578
6579 // Determine whether we have a constant expression.
6580 ExprResult ArgRV = S.DefaultFunctionArrayConversion(E: Arg);
6581 if (ArgRV.isInvalid())
6582 return NPV_Error;
6583 Arg = ArgRV.get();
6584
6585 Expr::EvalResult EvalResult;
6586 SmallVector<PartialDiagnosticAt, 8> Notes;
6587 EvalResult.Diag = &Notes;
6588 if (!Arg->EvaluateAsRValue(Result&: EvalResult, Ctx: S.Context) ||
6589 EvalResult.HasSideEffects) {
6590 SourceLocation DiagLoc = Arg->getExprLoc();
6591
6592 // If our only note is the usual "invalid subexpression" note, just point
6593 // the caret at its location rather than producing an essentially
6594 // redundant note.
6595 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6596 diag::note_invalid_subexpr_in_const_expr) {
6597 DiagLoc = Notes[0].first;
6598 Notes.clear();
6599 }
6600
6601 S.Diag(Loc: DiagLoc, DiagID: diag::err_template_arg_not_address_constant)
6602 << Arg->getType() << Arg->getSourceRange();
6603 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6604 S.Diag(Loc: Notes[I].first, PD: Notes[I].second);
6605
6606 S.NoteTemplateParameterLocation(Decl: *Param);
6607 return NPV_Error;
6608 }
6609
6610 // C++11 [temp.arg.nontype]p1:
6611 // - an address constant expression of type std::nullptr_t
6612 if (Arg->getType()->isNullPtrType())
6613 return NPV_NullPointer;
6614
6615 // - a constant expression that evaluates to a null pointer value (4.10); or
6616 // - a constant expression that evaluates to a null member pointer value
6617 // (4.11); or
6618 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6619 (EvalResult.Val.isMemberPointer() &&
6620 !EvalResult.Val.getMemberPointerDecl())) {
6621 // If our expression has an appropriate type, we've succeeded.
6622 bool ObjCLifetimeConversion;
6623 if (S.Context.hasSameUnqualifiedType(T1: Arg->getType(), T2: ParamType) ||
6624 S.IsQualificationConversion(FromType: Arg->getType(), ToType: ParamType, CStyle: false,
6625 ObjCLifetimeConversion))
6626 return NPV_NullPointer;
6627
6628 // The types didn't match, but we know we got a null pointer; complain,
6629 // then recover as if the types were correct.
6630 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_wrongtype_null_constant)
6631 << Arg->getType() << ParamType << Arg->getSourceRange();
6632 S.NoteTemplateParameterLocation(Decl: *Param);
6633 return NPV_NullPointer;
6634 }
6635
6636 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6637 // We found a pointer that isn't null, but doesn't refer to an object.
6638 // We could just return NPV_NotNullPointer, but we can print a better
6639 // message with the information we have here.
6640 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_invalid)
6641 << EvalResult.Val.getAsString(Ctx: S.Context, Ty: ParamType);
6642 S.NoteTemplateParameterLocation(Decl: *Param);
6643 return NPV_Error;
6644 }
6645
6646 // If we don't have a null pointer value, but we do have a NULL pointer
6647 // constant, suggest a cast to the appropriate type.
6648 if (Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_NeverValueDependent)) {
6649 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6650 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_untyped_null_constant)
6651 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code)
6652 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: Arg->getEndLoc()),
6653 Code: ")");
6654 S.NoteTemplateParameterLocation(Decl: *Param);
6655 return NPV_NullPointer;
6656 }
6657
6658 // FIXME: If we ever want to support general, address-constant expressions
6659 // as non-type template arguments, we should return the ExprResult here to
6660 // be interpreted by the caller.
6661 return NPV_NotNullPointer;
6662}
6663
6664/// Checks whether the given template argument is compatible with its
6665/// template parameter.
6666static bool
6667CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param,
6668 QualType ParamType, Expr *ArgIn,
6669 Expr *Arg, QualType ArgType) {
6670 bool ObjCLifetimeConversion;
6671 if (ParamType->isPointerType() &&
6672 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6673 S.IsQualificationConversion(FromType: ArgType, ToType: ParamType, CStyle: false,
6674 ObjCLifetimeConversion)) {
6675 // For pointer-to-object types, qualification conversions are
6676 // permitted.
6677 } else {
6678 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6679 if (!ParamRef->getPointeeType()->isFunctionType()) {
6680 // C++ [temp.arg.nontype]p5b3:
6681 // For a non-type template-parameter of type reference to
6682 // object, no conversions apply. The type referred to by the
6683 // reference may be more cv-qualified than the (otherwise
6684 // identical) type of the template- argument. The
6685 // template-parameter is bound directly to the
6686 // template-argument, which shall be an lvalue.
6687
6688 // FIXME: Other qualifiers?
6689 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6690 unsigned ArgQuals = ArgType.getCVRQualifiers();
6691
6692 if ((ParamQuals | ArgQuals) != ParamQuals) {
6693 S.Diag(Loc: Arg->getBeginLoc(),
6694 DiagID: diag::err_template_arg_ref_bind_ignores_quals)
6695 << ParamType << Arg->getType() << Arg->getSourceRange();
6696 S.NoteTemplateParameterLocation(Decl: *Param);
6697 return true;
6698 }
6699 }
6700 }
6701
6702 // At this point, the template argument refers to an object or
6703 // function with external linkage. We now need to check whether the
6704 // argument and parameter types are compatible.
6705 if (!S.Context.hasSameUnqualifiedType(T1: ArgType,
6706 T2: ParamType.getNonReferenceType())) {
6707 // We can't perform this conversion or binding.
6708 if (ParamType->isReferenceType())
6709 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_no_ref_bind)
6710 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6711 else
6712 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
6713 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6714 S.NoteTemplateParameterLocation(Decl: *Param);
6715 return true;
6716 }
6717 }
6718
6719 return false;
6720}
6721
6722/// Checks whether the given template argument is the address
6723/// of an object or function according to C++ [temp.arg.nontype]p1.
6724static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6725 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6726 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6727 bool Invalid = false;
6728 Expr *Arg = ArgIn;
6729 QualType ArgType = Arg->getType();
6730
6731 bool AddressTaken = false;
6732 SourceLocation AddrOpLoc;
6733 if (S.getLangOpts().MicrosoftExt) {
6734 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6735 // dereference and address-of operators.
6736 Arg = Arg->IgnoreParenCasts();
6737
6738 bool ExtWarnMSTemplateArg = false;
6739 UnaryOperatorKind FirstOpKind;
6740 SourceLocation FirstOpLoc;
6741 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6742 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6743 if (UnOpKind == UO_Deref)
6744 ExtWarnMSTemplateArg = true;
6745 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6746 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6747 if (!AddrOpLoc.isValid()) {
6748 FirstOpKind = UnOpKind;
6749 FirstOpLoc = UnOp->getOperatorLoc();
6750 }
6751 } else
6752 break;
6753 }
6754 if (FirstOpLoc.isValid()) {
6755 if (ExtWarnMSTemplateArg)
6756 S.Diag(Loc: ArgIn->getBeginLoc(), DiagID: diag::ext_ms_deref_template_argument)
6757 << ArgIn->getSourceRange();
6758
6759 if (FirstOpKind == UO_AddrOf)
6760 AddressTaken = true;
6761 else if (Arg->getType()->isPointerType()) {
6762 // We cannot let pointers get dereferenced here, that is obviously not a
6763 // constant expression.
6764 assert(FirstOpKind == UO_Deref);
6765 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6766 << Arg->getSourceRange();
6767 }
6768 }
6769 } else {
6770 // See through any implicit casts we added to fix the type.
6771 Arg = Arg->IgnoreImpCasts();
6772
6773 // C++ [temp.arg.nontype]p1:
6774 //
6775 // A template-argument for a non-type, non-template
6776 // template-parameter shall be one of: [...]
6777 //
6778 // -- the address of an object or function with external
6779 // linkage, including function templates and function
6780 // template-ids but excluding non-static class members,
6781 // expressed as & id-expression where the & is optional if
6782 // the name refers to a function or array, or if the
6783 // corresponding template-parameter is a reference; or
6784
6785 // In C++98/03 mode, give an extension warning on any extra parentheses.
6786 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6787 bool ExtraParens = false;
6788 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
6789 if (!Invalid && !ExtraParens) {
6790 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_extra_parens)
6791 << Arg->getSourceRange();
6792 ExtraParens = true;
6793 }
6794
6795 Arg = Parens->getSubExpr();
6796 }
6797
6798 while (SubstNonTypeTemplateParmExpr *subst =
6799 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6800 Arg = subst->getReplacement()->IgnoreImpCasts();
6801
6802 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6803 if (UnOp->getOpcode() == UO_AddrOf) {
6804 Arg = UnOp->getSubExpr();
6805 AddressTaken = true;
6806 AddrOpLoc = UnOp->getOperatorLoc();
6807 }
6808 }
6809
6810 while (SubstNonTypeTemplateParmExpr *subst =
6811 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6812 Arg = subst->getReplacement()->IgnoreImpCasts();
6813 }
6814
6815 ValueDecl *Entity = nullptr;
6816 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg))
6817 Entity = DRE->getDecl();
6818 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Val: Arg))
6819 Entity = CUE->getGuidDecl();
6820
6821 // If our parameter has pointer type, check for a null template value.
6822 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6823 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ArgIn,
6824 Entity)) {
6825 case NPV_NullPointer:
6826 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
6827 SugaredConverted = TemplateArgument(ParamType,
6828 /*isNullPtr=*/true);
6829 CanonicalConverted =
6830 TemplateArgument(S.Context.getCanonicalType(T: ParamType),
6831 /*isNullPtr=*/true);
6832 return false;
6833
6834 case NPV_Error:
6835 return true;
6836
6837 case NPV_NotNullPointer:
6838 break;
6839 }
6840 }
6841
6842 // Stop checking the precise nature of the argument if it is value dependent,
6843 // it should be checked when instantiated.
6844 if (Arg->isValueDependent()) {
6845 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6846 CanonicalConverted =
6847 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
6848 return false;
6849 }
6850
6851 if (!Entity) {
6852 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6853 << Arg->getSourceRange();
6854 S.NoteTemplateParameterLocation(Decl: *Param);
6855 return true;
6856 }
6857
6858 // Cannot refer to non-static data members
6859 if (isa<FieldDecl>(Val: Entity) || isa<IndirectFieldDecl>(Val: Entity)) {
6860 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_field)
6861 << Entity << Arg->getSourceRange();
6862 S.NoteTemplateParameterLocation(Decl: *Param);
6863 return true;
6864 }
6865
6866 // Cannot refer to non-static member functions
6867 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Entity)) {
6868 if (!Method->isStatic()) {
6869 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_method)
6870 << Method << Arg->getSourceRange();
6871 S.NoteTemplateParameterLocation(Decl: *Param);
6872 return true;
6873 }
6874 }
6875
6876 FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Entity);
6877 VarDecl *Var = dyn_cast<VarDecl>(Val: Entity);
6878 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Val: Entity);
6879
6880 // A non-type template argument must refer to an object or function.
6881 if (!Func && !Var && !Guid) {
6882 // We found something, but we don't know specifically what it is.
6883 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_object_or_func)
6884 << Arg->getSourceRange();
6885 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_refers_here);
6886 return true;
6887 }
6888
6889 // Address / reference template args must have external linkage in C++98.
6890 if (Entity->getFormalLinkage() == Linkage::Internal) {
6891 S.Diag(Loc: Arg->getBeginLoc(),
6892 DiagID: S.getLangOpts().CPlusPlus11
6893 ? diag::warn_cxx98_compat_template_arg_object_internal
6894 : diag::ext_template_arg_object_internal)
6895 << !Func << Entity << Arg->getSourceRange();
6896 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6897 << !Func;
6898 } else if (!Entity->hasLinkage()) {
6899 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_object_no_linkage)
6900 << !Func << Entity << Arg->getSourceRange();
6901 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6902 << !Func;
6903 return true;
6904 }
6905
6906 if (Var) {
6907 // A value of reference type is not an object.
6908 if (Var->getType()->isReferenceType()) {
6909 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_reference_var)
6910 << Var->getType() << Arg->getSourceRange();
6911 S.NoteTemplateParameterLocation(Decl: *Param);
6912 return true;
6913 }
6914
6915 // A template argument must have static storage duration.
6916 if (Var->getTLSKind()) {
6917 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_thread_local)
6918 << Arg->getSourceRange();
6919 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_template_arg_refers_here);
6920 return true;
6921 }
6922 }
6923
6924 if (AddressTaken && ParamType->isReferenceType()) {
6925 // If we originally had an address-of operator, but the
6926 // parameter has reference type, complain and (if things look
6927 // like they will work) drop the address-of operator.
6928 if (!S.Context.hasSameUnqualifiedType(T1: Entity->getType(),
6929 T2: ParamType.getNonReferenceType())) {
6930 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6931 << ParamType;
6932 S.NoteTemplateParameterLocation(Decl: *Param);
6933 return true;
6934 }
6935
6936 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6937 << ParamType
6938 << FixItHint::CreateRemoval(RemoveRange: AddrOpLoc);
6939 S.NoteTemplateParameterLocation(Decl: *Param);
6940
6941 ArgType = Entity->getType();
6942 }
6943
6944 // If the template parameter has pointer type, either we must have taken the
6945 // address or the argument must decay to a pointer.
6946 if (!AddressTaken && ParamType->isPointerType()) {
6947 if (Func) {
6948 // Function-to-pointer decay.
6949 ArgType = S.Context.getPointerType(T: Func->getType());
6950 } else if (Entity->getType()->isArrayType()) {
6951 // Array-to-pointer decay.
6952 ArgType = S.Context.getArrayDecayedType(T: Entity->getType());
6953 } else {
6954 // If the template parameter has pointer type but the address of
6955 // this object was not taken, complain and (possibly) recover by
6956 // taking the address of the entity.
6957 ArgType = S.Context.getPointerType(T: Entity->getType());
6958 if (!S.Context.hasSameUnqualifiedType(T1: ArgType, T2: ParamType)) {
6959 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
6960 << ParamType;
6961 S.NoteTemplateParameterLocation(Decl: *Param);
6962 return true;
6963 }
6964
6965 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
6966 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code: "&");
6967
6968 S.NoteTemplateParameterLocation(Decl: *Param);
6969 }
6970 }
6971
6972 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6973 Arg, ArgType))
6974 return true;
6975
6976 // Create the template argument.
6977 SugaredConverted = TemplateArgument(Entity, ParamType);
6978 CanonicalConverted =
6979 TemplateArgument(cast<ValueDecl>(Val: Entity->getCanonicalDecl()),
6980 S.Context.getCanonicalType(T: ParamType));
6981 S.MarkAnyDeclReferenced(Loc: Arg->getBeginLoc(), D: Entity, MightBeOdrUse: false);
6982 return false;
6983}
6984
6985/// Checks whether the given template argument is a pointer to
6986/// member constant according to C++ [temp.arg.nontype]p1.
6987static bool CheckTemplateArgumentPointerToMember(
6988 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
6989 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6990 bool Invalid = false;
6991
6992 Expr *Arg = ResultArg;
6993 bool ObjCLifetimeConversion;
6994
6995 // C++ [temp.arg.nontype]p1:
6996 //
6997 // A template-argument for a non-type, non-template
6998 // template-parameter shall be one of: [...]
6999 //
7000 // -- a pointer to member expressed as described in 5.3.1.
7001 DeclRefExpr *DRE = nullptr;
7002
7003 // In C++98/03 mode, give an extension warning on any extra parentheses.
7004 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7005 bool ExtraParens = false;
7006 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
7007 if (!Invalid && !ExtraParens) {
7008 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_extra_parens)
7009 << Arg->getSourceRange();
7010 ExtraParens = true;
7011 }
7012
7013 Arg = Parens->getSubExpr();
7014 }
7015
7016 while (SubstNonTypeTemplateParmExpr *subst =
7017 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
7018 Arg = subst->getReplacement()->IgnoreImpCasts();
7019
7020 // A pointer-to-member constant written &Class::member.
7021 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
7022 if (UnOp->getOpcode() == UO_AddrOf) {
7023 DRE = dyn_cast<DeclRefExpr>(Val: UnOp->getSubExpr());
7024 if (DRE && !DRE->getQualifier())
7025 DRE = nullptr;
7026 }
7027 }
7028 // A constant of pointer-to-member type.
7029 else if ((DRE = dyn_cast<DeclRefExpr>(Val: Arg))) {
7030 ValueDecl *VD = DRE->getDecl();
7031 if (VD->getType()->isMemberPointerType()) {
7032 if (isa<NonTypeTemplateParmDecl>(Val: VD)) {
7033 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7034 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7035 CanonicalConverted =
7036 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7037 } else {
7038 SugaredConverted = TemplateArgument(VD, ParamType);
7039 CanonicalConverted =
7040 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7041 S.Context.getCanonicalType(T: ParamType));
7042 }
7043 return Invalid;
7044 }
7045 }
7046
7047 DRE = nullptr;
7048 }
7049
7050 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7051
7052 // Check for a null pointer value.
7053 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ResultArg,
7054 Entity)) {
7055 case NPV_Error:
7056 return true;
7057 case NPV_NullPointer:
7058 S.Diag(Loc: ResultArg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7059 SugaredConverted = TemplateArgument(ParamType,
7060 /*isNullPtr*/ true);
7061 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(T: ParamType),
7062 /*isNullPtr*/ true);
7063 return false;
7064 case NPV_NotNullPointer:
7065 break;
7066 }
7067
7068 if (S.IsQualificationConversion(FromType: ResultArg->getType(),
7069 ToType: ParamType.getNonReferenceType(), CStyle: false,
7070 ObjCLifetimeConversion)) {
7071 ResultArg = S.ImpCastExprToType(E: ResultArg, Type: ParamType, CK: CK_NoOp,
7072 VK: ResultArg->getValueKind())
7073 .get();
7074 } else if (!S.Context.hasSameUnqualifiedType(
7075 T1: ResultArg->getType(), T2: ParamType.getNonReferenceType())) {
7076 // We can't perform this conversion.
7077 S.Diag(Loc: ResultArg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
7078 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7079 S.NoteTemplateParameterLocation(Decl: *Param);
7080 return true;
7081 }
7082
7083 if (!DRE)
7084 return S.Diag(Loc: Arg->getBeginLoc(),
7085 DiagID: diag::err_template_arg_not_pointer_to_member_form)
7086 << Arg->getSourceRange();
7087
7088 if (isa<FieldDecl>(Val: DRE->getDecl()) ||
7089 isa<IndirectFieldDecl>(Val: DRE->getDecl()) ||
7090 isa<CXXMethodDecl>(Val: DRE->getDecl())) {
7091 assert((isa<FieldDecl>(DRE->getDecl()) ||
7092 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7093 cast<CXXMethodDecl>(DRE->getDecl())
7094 ->isImplicitObjectMemberFunction()) &&
7095 "Only non-static member pointers can make it here");
7096
7097 // Okay: this is the address of a non-static member, and therefore
7098 // a member pointer constant.
7099 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7100 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7101 CanonicalConverted =
7102 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7103 } else {
7104 ValueDecl *D = DRE->getDecl();
7105 SugaredConverted = TemplateArgument(D, ParamType);
7106 CanonicalConverted =
7107 TemplateArgument(cast<ValueDecl>(Val: D->getCanonicalDecl()),
7108 S.Context.getCanonicalType(T: ParamType));
7109 }
7110 return Invalid;
7111 }
7112
7113 // We found something else, but we don't know specifically what it is.
7114 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_pointer_to_member_form)
7115 << Arg->getSourceRange();
7116 S.Diag(Loc: DRE->getDecl()->getLocation(), DiagID: diag::note_template_arg_refers_here);
7117 return true;
7118}
7119
7120/// Check a template argument against its corresponding
7121/// non-type template parameter.
7122///
7123/// This routine implements the semantics of C++ [temp.arg.nontype].
7124/// If an error occurred, it returns ExprError(); otherwise, it
7125/// returns the converted template argument. \p ParamType is the
7126/// type of the non-type template parameter after it has been instantiated.
7127ExprResult Sema::CheckTemplateArgument(NamedDecl *Param, QualType ParamType,
7128 Expr *Arg,
7129 TemplateArgument &SugaredConverted,
7130 TemplateArgument &CanonicalConverted,
7131 bool StrictCheck,
7132 CheckTemplateArgumentKind CTAK) {
7133 SourceLocation StartLoc = Arg->getBeginLoc();
7134 auto *ArgPE = dyn_cast<PackExpansionExpr>(Val: Arg);
7135 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7136 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7137 DeductionArg = NewDeductionArg;
7138 if (ArgPE) {
7139 // Recreate a pack expansion if we unwrapped one.
7140 Arg = new (Context) PackExpansionExpr(
7141 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7142 } else {
7143 Arg = DeductionArg;
7144 }
7145 };
7146
7147 // If the parameter type somehow involves auto, deduce the type now.
7148 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7149 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7150 if (IsDeduced) {
7151 // When checking a deduced template argument, deduce from its type even if
7152 // the type is dependent, in order to check the types of non-type template
7153 // arguments line up properly in partial ordering.
7154 TypeSourceInfo *TSI =
7155 Context.getTrivialTypeSourceInfo(T: ParamType, Loc: Param->getLocation());
7156 if (isa<DeducedTemplateSpecializationType>(Val: DeducedT)) {
7157 InitializedEntity Entity =
7158 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7159 InitializationKind Kind = InitializationKind::CreateForInit(
7160 Loc: DeductionArg->getBeginLoc(), /*DirectInit*/false, Init: DeductionArg);
7161 Expr *Inits[1] = {DeductionArg};
7162 ParamType =
7163 DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind, Init: Inits);
7164 if (ParamType.isNull())
7165 return ExprError();
7166 } else {
7167 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7168 Param->getTemplateDepth() + 1);
7169 ParamType = QualType();
7170 TemplateDeductionResult Result =
7171 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeductionArg, Result&: ParamType, Info,
7172 /*DependentDeduction=*/true,
7173 // We do not check constraints right now because the
7174 // immediately-declared constraint of the auto type is
7175 // also an associated constraint, and will be checked
7176 // along with the other associated constraints after
7177 // checking the template argument list.
7178 /*IgnoreConstraints=*/true);
7179 if (Result != TemplateDeductionResult::Success) {
7180 ParamType = TSI->getType();
7181 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7182 if (Result == TemplateDeductionResult::AlreadyDiagnosed)
7183 return ExprError();
7184 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param))
7185 Diag(Loc: Arg->getExprLoc(),
7186 DiagID: diag::err_non_type_template_parm_type_deduction_failure)
7187 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7188 << Arg->getSourceRange();
7189 NoteTemplateParameterLocation(Decl: *Param);
7190 return ExprError();
7191 }
7192 ParamType = SubstAutoTypeDependent(TypeWithAuto: ParamType);
7193 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7194 }
7195 }
7196 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7197 // an error. The error message normally references the parameter
7198 // declaration, but here we'll pass the argument location because that's
7199 // where the parameter type is deduced.
7200 ParamType = CheckNonTypeTemplateParameterType(T: ParamType, Loc: Arg->getExprLoc());
7201 if (ParamType.isNull()) {
7202 NoteTemplateParameterLocation(Decl: *Param);
7203 return ExprError();
7204 }
7205 }
7206
7207 // We should have already dropped all cv-qualifiers by now.
7208 assert(!ParamType.hasQualifiers() &&
7209 "non-type template parameter type cannot be qualified");
7210
7211 // If either the parameter has a dependent type or the argument is
7212 // type-dependent, there's nothing we can check now.
7213 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7214 // Force the argument to the type of the parameter to maintain invariants.
7215 if (!IsDeduced) {
7216 ExprResult E = ImpCastExprToType(
7217 E: DeductionArg, Type: ParamType.getNonLValueExprType(Context), CK: CK_Dependent,
7218 VK: ParamType->isLValueReferenceType() ? VK_LValue
7219 : ParamType->isRValueReferenceType() ? VK_XValue
7220 : VK_PRValue);
7221 if (E.isInvalid())
7222 return ExprError();
7223 setDeductionArg(E.get());
7224 }
7225 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7226 CanonicalConverted = TemplateArgument(
7227 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7228 return Arg;
7229 }
7230
7231 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7232 if (CTAK == CTAK_Deduced && !StrictCheck &&
7233 (ParamType->isReferenceType()
7234 ? !Context.hasSameType(T1: ParamType.getNonReferenceType(),
7235 T2: DeductionArg->getType())
7236 : !Context.hasSameUnqualifiedType(T1: ParamType,
7237 T2: DeductionArg->getType()))) {
7238 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7239 // we should actually be checking the type of the template argument in P,
7240 // not the type of the template argument deduced from A, against the
7241 // template parameter type.
7242 Diag(Loc: StartLoc, DiagID: diag::err_deduced_non_type_template_arg_type_mismatch)
7243 << Arg->getType() << ParamType.getUnqualifiedType();
7244 NoteTemplateParameterLocation(Decl: *Param);
7245 return ExprError();
7246 }
7247
7248 // If the argument is a pack expansion, we don't know how many times it would
7249 // expand. If we continue checking the argument, this will make the template
7250 // definition ill-formed if it would be ill-formed for any number of
7251 // expansions during instantiation time. When partial ordering or matching
7252 // template template parameters, this is exactly what we want. Otherwise, the
7253 // normal template rules apply: we accept the template if it would be valid
7254 // for any number of expansions (i.e. none).
7255 if (ArgPE && !StrictCheck) {
7256 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7257 CanonicalConverted = TemplateArgument(
7258 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7259 return Arg;
7260 }
7261
7262 // Avoid making a copy when initializing a template parameter of class type
7263 // from a template parameter object of the same type. This is going beyond
7264 // the standard, but is required for soundness: in
7265 // template<A a> struct X { X *p; X<a> *q; };
7266 // ... we need p and q to have the same type.
7267 //
7268 // Similarly, don't inject a call to a copy constructor when initializing
7269 // from a template parameter of the same type.
7270 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7271 if (ParamType->isRecordType() && isa<DeclRefExpr>(Val: InnerArg) &&
7272 Context.hasSameUnqualifiedType(T1: ParamType, T2: InnerArg->getType())) {
7273 NamedDecl *ND = cast<DeclRefExpr>(Val: InnerArg)->getDecl();
7274 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(Val: ND)) {
7275
7276 SugaredConverted = TemplateArgument(TPO, ParamType);
7277 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7278 ParamType.getCanonicalType());
7279 return Arg;
7280 }
7281 if (isa<NonTypeTemplateParmDecl>(Val: ND)) {
7282 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7283 CanonicalConverted =
7284 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7285 return Arg;
7286 }
7287 }
7288
7289 // The initialization of the parameter from the argument is
7290 // a constant-evaluated context.
7291 EnterExpressionEvaluationContext ConstantEvaluated(
7292 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7293
7294 bool IsConvertedConstantExpression = true;
7295 if (isa<InitListExpr>(Val: DeductionArg) || ParamType->isRecordType()) {
7296 InitializationKind Kind = InitializationKind::CreateForInit(
7297 Loc: StartLoc, /*DirectInit=*/false, Init: DeductionArg);
7298 Expr *Inits[1] = {DeductionArg};
7299 InitializedEntity Entity =
7300 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7301 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7302 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Inits);
7303 if (Result.isInvalid() || !Result.get())
7304 return ExprError();
7305 Result = ActOnConstantExpression(Res: Result.get());
7306 if (Result.isInvalid() || !Result.get())
7307 return ExprError();
7308 setDeductionArg(ActOnFinishFullExpr(Expr: Result.get(), CC: Arg->getBeginLoc(),
7309 /*DiscardedValue=*/false,
7310 /*IsConstexpr=*/true,
7311 /*IsTemplateArgument=*/true)
7312 .get());
7313 IsConvertedConstantExpression = false;
7314 }
7315
7316 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7317 // C++17 [temp.arg.nontype]p1:
7318 // A template-argument for a non-type template parameter shall be
7319 // a converted constant expression of the type of the template-parameter.
7320 APValue Value;
7321 ExprResult ArgResult;
7322 if (IsConvertedConstantExpression) {
7323 ArgResult = BuildConvertedConstantExpression(
7324 From: DeductionArg, T: ParamType,
7325 CCE: StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Dest: Param);
7326 assert(!ArgResult.isUnset());
7327 if (ArgResult.isInvalid()) {
7328 NoteTemplateParameterLocation(Decl: *Param);
7329 return ExprError();
7330 }
7331 } else {
7332 ArgResult = DeductionArg;
7333 }
7334
7335 // For a value-dependent argument, CheckConvertedConstantExpression is
7336 // permitted (and expected) to be unable to determine a value.
7337 if (ArgResult.get()->isValueDependent()) {
7338 setDeductionArg(ArgResult.get());
7339 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7340 CanonicalConverted =
7341 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7342 return Arg;
7343 }
7344
7345 APValue PreNarrowingValue;
7346 ArgResult = EvaluateConvertedConstantExpression(
7347 E: ArgResult.get(), T: ParamType, Value, CCE: CCEKind::TemplateArg, /*RequireInt=*/
7348 false, PreNarrowingValue);
7349 if (ArgResult.isInvalid())
7350 return ExprError();
7351 setDeductionArg(ArgResult.get());
7352
7353 if (Value.isLValue()) {
7354 APValue::LValueBase Base = Value.getLValueBase();
7355 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7356 // For a non-type template-parameter of pointer or reference type,
7357 // the value of the constant expression shall not refer to
7358 assert(ParamType->isPointerOrReferenceType() ||
7359 ParamType->isNullPtrType());
7360 // -- a temporary object
7361 // -- a string literal
7362 // -- the result of a typeid expression, or
7363 // -- a predefined __func__ variable
7364 if (Base &&
7365 (!VD ||
7366 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(Val: VD))) {
7367 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
7368 << Arg->getSourceRange();
7369 return ExprError();
7370 }
7371
7372 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7373 VD->getType()->isArrayType() &&
7374 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7375 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7376 if (ArgPE) {
7377 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7378 CanonicalConverted =
7379 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7380 } else {
7381 SugaredConverted = TemplateArgument(VD, ParamType);
7382 CanonicalConverted =
7383 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7384 ParamType.getCanonicalType());
7385 }
7386 return Arg;
7387 }
7388
7389 // -- a subobject [until C++20]
7390 if (!getLangOpts().CPlusPlus20) {
7391 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7392 Value.isLValueOnePastTheEnd()) {
7393 Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_subobject)
7394 << Value.getAsString(Ctx: Context, Ty: ParamType);
7395 return ExprError();
7396 }
7397 assert((VD || !ParamType->isReferenceType()) &&
7398 "null reference should not be a constant expression");
7399 assert((!VD || !ParamType->isNullPtrType()) &&
7400 "non-null value of type nullptr_t?");
7401 }
7402 }
7403
7404 if (Value.isAddrLabelDiff())
7405 return Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_addr_label_diff);
7406
7407 if (ArgPE) {
7408 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7409 CanonicalConverted =
7410 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7411 } else {
7412 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7413 CanonicalConverted =
7414 TemplateArgument(Context, ParamType.getCanonicalType(), Value);
7415 }
7416 return Arg;
7417 }
7418
7419 // These should have all been handled above using the C++17 rules.
7420 assert(!ArgPE && !StrictCheck);
7421
7422 // C++ [temp.arg.nontype]p5:
7423 // The following conversions are performed on each expression used
7424 // as a non-type template-argument. If a non-type
7425 // template-argument cannot be converted to the type of the
7426 // corresponding template-parameter then the program is
7427 // ill-formed.
7428 if (ParamType->isIntegralOrEnumerationType()) {
7429 // C++11:
7430 // -- for a non-type template-parameter of integral or
7431 // enumeration type, conversions permitted in a converted
7432 // constant expression are applied.
7433 //
7434 // C++98:
7435 // -- for a non-type template-parameter of integral or
7436 // enumeration type, integral promotions (4.5) and integral
7437 // conversions (4.7) are applied.
7438
7439 if (getLangOpts().CPlusPlus11) {
7440 // C++ [temp.arg.nontype]p1:
7441 // A template-argument for a non-type, non-template template-parameter
7442 // shall be one of:
7443 //
7444 // -- for a non-type template-parameter of integral or enumeration
7445 // type, a converted constant expression of the type of the
7446 // template-parameter; or
7447 llvm::APSInt Value;
7448 ExprResult ArgResult = CheckConvertedConstantExpression(
7449 From: Arg, T: ParamType, Value, CCE: CCEKind::TemplateArg);
7450 if (ArgResult.isInvalid())
7451 return ExprError();
7452 Arg = ArgResult.get();
7453
7454 // We can't check arbitrary value-dependent arguments.
7455 if (Arg->isValueDependent()) {
7456 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7457 CanonicalConverted =
7458 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7459 return Arg;
7460 }
7461
7462 // Widen the argument value to sizeof(parameter type). This is almost
7463 // always a no-op, except when the parameter type is bool. In
7464 // that case, this may extend the argument from 1 bit to 8 bits.
7465 QualType IntegerType = ParamType;
7466 if (const auto *ED = IntegerType->getAsEnumDecl())
7467 IntegerType = ED->getIntegerType();
7468 Value = Value.extOrTrunc(width: IntegerType->isBitIntType()
7469 ? Context.getIntWidth(T: IntegerType)
7470 : Context.getTypeSize(T: IntegerType));
7471
7472 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7473 CanonicalConverted =
7474 TemplateArgument(Context, Value, Context.getCanonicalType(T: ParamType));
7475 return Arg;
7476 }
7477
7478 ExprResult ArgResult = DefaultLvalueConversion(E: Arg);
7479 if (ArgResult.isInvalid())
7480 return ExprError();
7481 Arg = ArgResult.get();
7482
7483 QualType ArgType = Arg->getType();
7484
7485 // C++ [temp.arg.nontype]p1:
7486 // A template-argument for a non-type, non-template
7487 // template-parameter shall be one of:
7488 //
7489 // -- an integral constant-expression of integral or enumeration
7490 // type; or
7491 // -- the name of a non-type template-parameter; or
7492 llvm::APSInt Value;
7493 if (!ArgType->isIntegralOrEnumerationType()) {
7494 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_integral_or_enumeral)
7495 << ArgType << Arg->getSourceRange();
7496 NoteTemplateParameterLocation(Decl: *Param);
7497 return ExprError();
7498 }
7499 if (!Arg->isValueDependent()) {
7500 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7501 QualType T;
7502
7503 public:
7504 TmplArgICEDiagnoser(QualType T) : T(T) { }
7505
7506 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7507 SourceLocation Loc) override {
7508 return S.Diag(Loc, DiagID: diag::err_template_arg_not_ice) << T;
7509 }
7510 } Diagnoser(ArgType);
7511
7512 Arg = VerifyIntegerConstantExpression(E: Arg, Result: &Value, Diagnoser).get();
7513 if (!Arg)
7514 return ExprError();
7515 }
7516
7517 // From here on out, all we care about is the unqualified form
7518 // of the argument type.
7519 ArgType = ArgType.getUnqualifiedType();
7520
7521 // Try to convert the argument to the parameter's type.
7522 if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
7523 // Okay: no conversion necessary
7524 } else if (ParamType->isBooleanType()) {
7525 // This is an integral-to-boolean conversion.
7526 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralToBoolean).get();
7527 } else if (IsIntegralPromotion(From: Arg, FromType: ArgType, ToType: ParamType) ||
7528 !ParamType->isEnumeralType()) {
7529 // This is an integral promotion or conversion.
7530 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralCast).get();
7531 } else {
7532 // We can't perform this conversion.
7533 Diag(Loc: StartLoc, DiagID: diag::err_template_arg_not_convertible)
7534 << Arg->getType() << ParamType << Arg->getSourceRange();
7535 NoteTemplateParameterLocation(Decl: *Param);
7536 return ExprError();
7537 }
7538
7539 // Add the value of this argument to the list of converted
7540 // arguments. We use the bitwidth and signedness of the template
7541 // parameter.
7542 if (Arg->isValueDependent()) {
7543 // The argument is value-dependent. Create a new
7544 // TemplateArgument with the converted expression.
7545 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7546 CanonicalConverted =
7547 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7548 return Arg;
7549 }
7550
7551 QualType IntegerType = ParamType;
7552 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7553 IntegerType = ED->getIntegerType();
7554 }
7555
7556 if (ParamType->isBooleanType()) {
7557 // Value must be zero or one.
7558 Value = Value != 0;
7559 unsigned AllowedBits = Context.getTypeSize(T: IntegerType);
7560 if (Value.getBitWidth() != AllowedBits)
7561 Value = Value.extOrTrunc(width: AllowedBits);
7562 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7563 } else {
7564 llvm::APSInt OldValue = Value;
7565
7566 // Coerce the template argument's value to the value it will have
7567 // based on the template parameter's type.
7568 unsigned AllowedBits = IntegerType->isBitIntType()
7569 ? Context.getIntWidth(T: IntegerType)
7570 : Context.getTypeSize(T: IntegerType);
7571 if (Value.getBitWidth() != AllowedBits)
7572 Value = Value.extOrTrunc(width: AllowedBits);
7573 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7574
7575 // Complain if an unsigned parameter received a negative value.
7576 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7577 (OldValue.isSigned() && OldValue.isNegative())) {
7578 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_negative)
7579 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7580 << Arg->getSourceRange();
7581 NoteTemplateParameterLocation(Decl: *Param);
7582 }
7583
7584 // Complain if we overflowed the template parameter's type.
7585 unsigned RequiredBits;
7586 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7587 RequiredBits = OldValue.getActiveBits();
7588 else if (OldValue.isUnsigned())
7589 RequiredBits = OldValue.getActiveBits() + 1;
7590 else
7591 RequiredBits = OldValue.getSignificantBits();
7592 if (RequiredBits > AllowedBits) {
7593 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_too_large)
7594 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7595 << Arg->getSourceRange();
7596 NoteTemplateParameterLocation(Decl: *Param);
7597 }
7598 }
7599
7600 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7601 SugaredConverted = TemplateArgument(Context, Value, T);
7602 CanonicalConverted =
7603 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7604 return Arg;
7605 }
7606
7607 QualType ArgType = Arg->getType();
7608 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7609
7610 // Handle pointer-to-function, reference-to-function, and
7611 // pointer-to-member-function all in (roughly) the same way.
7612 if (// -- For a non-type template-parameter of type pointer to
7613 // function, only the function-to-pointer conversion (4.3) is
7614 // applied. If the template-argument represents a set of
7615 // overloaded functions (or a pointer to such), the matching
7616 // function is selected from the set (13.4).
7617 (ParamType->isPointerType() &&
7618 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7619 // -- For a non-type template-parameter of type reference to
7620 // function, no conversions apply. If the template-argument
7621 // represents a set of overloaded functions, the matching
7622 // function is selected from the set (13.4).
7623 (ParamType->isReferenceType() &&
7624 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7625 // -- For a non-type template-parameter of type pointer to
7626 // member function, no conversions apply. If the
7627 // template-argument represents a set of overloaded member
7628 // functions, the matching member function is selected from
7629 // the set (13.4).
7630 (ParamType->isMemberPointerType() &&
7631 ParamType->castAs<MemberPointerType>()->getPointeeType()
7632 ->isFunctionType())) {
7633
7634 if (Arg->getType() == Context.OverloadTy) {
7635 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg, TargetType: ParamType,
7636 Complain: true,
7637 Found&: FoundResult)) {
7638 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7639 return ExprError();
7640
7641 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7642 if (Res.isInvalid())
7643 return ExprError();
7644 Arg = Res.get();
7645 ArgType = Arg->getType();
7646 } else
7647 return ExprError();
7648 }
7649
7650 if (!ParamType->isMemberPointerType()) {
7651 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7652 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted,
7653 CanonicalConverted))
7654 return ExprError();
7655 return Arg;
7656 }
7657
7658 if (CheckTemplateArgumentPointerToMember(
7659 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7660 return ExprError();
7661 return Arg;
7662 }
7663
7664 if (ParamType->isPointerType()) {
7665 // -- for a non-type template-parameter of type pointer to
7666 // object, qualification conversions (4.4) and the
7667 // array-to-pointer conversion (4.2) are applied.
7668 // C++0x also allows a value of std::nullptr_t.
7669 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7670 "Only object pointers allowed here");
7671
7672 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7673 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted, CanonicalConverted))
7674 return ExprError();
7675 return Arg;
7676 }
7677
7678 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7679 // -- For a non-type template-parameter of type reference to
7680 // object, no conversions apply. The type referred to by the
7681 // reference may be more cv-qualified than the (otherwise
7682 // identical) type of the template-argument. The
7683 // template-parameter is bound directly to the
7684 // template-argument, which must be an lvalue.
7685 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7686 "Only object references allowed here");
7687
7688 if (Arg->getType() == Context.OverloadTy) {
7689 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg,
7690 TargetType: ParamRefType->getPointeeType(),
7691 Complain: true,
7692 Found&: FoundResult)) {
7693 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7694 return ExprError();
7695 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7696 if (Res.isInvalid())
7697 return ExprError();
7698 Arg = Res.get();
7699 ArgType = Arg->getType();
7700 } else
7701 return ExprError();
7702 }
7703
7704 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7705 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted, CanonicalConverted))
7706 return ExprError();
7707 return Arg;
7708 }
7709
7710 // Deal with parameters of type std::nullptr_t.
7711 if (ParamType->isNullPtrType()) {
7712 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7713 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7714 CanonicalConverted =
7715 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7716 return Arg;
7717 }
7718
7719 switch (isNullPointerValueTemplateArgument(S&: *this, Param, ParamType, Arg)) {
7720 case NPV_NotNullPointer:
7721 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_not_convertible)
7722 << Arg->getType() << ParamType;
7723 NoteTemplateParameterLocation(Decl: *Param);
7724 return ExprError();
7725
7726 case NPV_Error:
7727 return ExprError();
7728
7729 case NPV_NullPointer:
7730 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7731 SugaredConverted = TemplateArgument(ParamType,
7732 /*isNullPtr=*/true);
7733 CanonicalConverted = TemplateArgument(Context.getCanonicalType(T: ParamType),
7734 /*isNullPtr=*/true);
7735 return Arg;
7736 }
7737 }
7738
7739 // -- For a non-type template-parameter of type pointer to data
7740 // member, qualification conversions (4.4) are applied.
7741 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7742
7743 if (CheckTemplateArgumentPointerToMember(
7744 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7745 return ExprError();
7746 return Arg;
7747}
7748
7749static void DiagnoseTemplateParameterListArityMismatch(
7750 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7751 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7752
7753bool Sema::CheckDeclCompatibleWithTemplateTemplate(
7754 TemplateDecl *Template, TemplateTemplateParmDecl *Param,
7755 const TemplateArgumentLoc &Arg) {
7756 // C++0x [temp.arg.template]p1:
7757 // A template-argument for a template template-parameter shall be
7758 // the name of a class template or an alias template, expressed as an
7759 // id-expression. When the template-argument names a class template, only
7760 // primary class templates are considered when matching the
7761 // template template argument with the corresponding parameter;
7762 // partial specializations are not considered even if their
7763 // parameter lists match that of the template template parameter.
7764 //
7765
7766 TemplateNameKind Kind = TNK_Non_template;
7767 unsigned DiagFoundKind = 0;
7768
7769 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Val: Template)) {
7770 switch (TTP->templateParameterKind()) {
7771 case TemplateNameKind::TNK_Concept_template:
7772 DiagFoundKind = 3;
7773 break;
7774 case TemplateNameKind::TNK_Var_template:
7775 DiagFoundKind = 2;
7776 break;
7777 default:
7778 DiagFoundKind = 1;
7779 break;
7780 }
7781 Kind = TTP->templateParameterKind();
7782 } else if (isa<ConceptDecl>(Val: Template)) {
7783 Kind = TemplateNameKind::TNK_Concept_template;
7784 DiagFoundKind = 3;
7785 } else if (isa<FunctionTemplateDecl>(Val: Template)) {
7786 Kind = TemplateNameKind::TNK_Function_template;
7787 DiagFoundKind = 0;
7788 } else if (isa<VarTemplateDecl>(Val: Template)) {
7789 Kind = TemplateNameKind::TNK_Var_template;
7790 DiagFoundKind = 2;
7791 } else if (isa<ClassTemplateDecl>(Val: Template) ||
7792 isa<TypeAliasTemplateDecl>(Val: Template) ||
7793 isa<BuiltinTemplateDecl>(Val: Template)) {
7794 Kind = TemplateNameKind::TNK_Type_template;
7795 DiagFoundKind = 1;
7796 } else {
7797 assert(false && "Unexpected Decl");
7798 }
7799
7800 if (Kind == Param->templateParameterKind()) {
7801 return true;
7802 }
7803
7804 unsigned DiagKind = 0;
7805 switch (Param->templateParameterKind()) {
7806 case TemplateNameKind::TNK_Concept_template:
7807 DiagKind = 2;
7808 break;
7809 case TemplateNameKind::TNK_Var_template:
7810 DiagKind = 1;
7811 break;
7812 default:
7813 DiagKind = 0;
7814 break;
7815 }
7816 Diag(Loc: Arg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
7817 << DiagKind;
7818 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_arg_refers_to_template_here)
7819 << DiagFoundKind << Template;
7820 return false;
7821}
7822
7823/// Check a template argument against its corresponding
7824/// template template parameter.
7825///
7826/// This routine implements the semantics of C++ [temp.arg.template].
7827/// It returns true if an error occurred, and false otherwise.
7828bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7829 TemplateParameterList *Params,
7830 TemplateArgumentLoc &Arg,
7831 bool PartialOrdering,
7832 bool *StrictPackMatch) {
7833 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7834 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7835 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7836 if (!Template) {
7837 // FIXME: Handle AssumedTemplateNames
7838 // Any dependent template name is fine.
7839 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7840 return false;
7841 }
7842
7843 if (Template->isInvalidDecl())
7844 return true;
7845
7846 if (!CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg)) {
7847 return true;
7848 }
7849
7850 // C++1z [temp.arg.template]p3: (DR 150)
7851 // A template-argument matches a template template-parameter P when P
7852 // is at least as specialized as the template-argument A.
7853 if (!isTemplateTemplateParameterAtLeastAsSpecializedAs(
7854 PParam: Params, PArg: Param, AArg: Template, DefaultArgs, ArgLoc: Arg.getLocation(),
7855 PartialOrdering, StrictPackMatch))
7856 return true;
7857 // P2113
7858 // C++20[temp.func.order]p2
7859 // [...] If both deductions succeed, the partial ordering selects the
7860 // more constrained template (if one exists) as determined below.
7861 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7862 Params->getAssociatedConstraints(AC&: ParamsAC);
7863 // C++20[temp.arg.template]p3
7864 // [...] In this comparison, if P is unconstrained, the constraints on A
7865 // are not considered.
7866 if (ParamsAC.empty())
7867 return false;
7868
7869 Template->getAssociatedConstraints(AC&: TemplateAC);
7870
7871 bool IsParamAtLeastAsConstrained;
7872 if (IsAtLeastAsConstrained(D1: Param, AC1: ParamsAC, D2: Template, AC2: TemplateAC,
7873 Result&: IsParamAtLeastAsConstrained))
7874 return true;
7875 if (!IsParamAtLeastAsConstrained) {
7876 Diag(Loc: Arg.getLocation(),
7877 DiagID: diag::err_template_template_parameter_not_at_least_as_constrained)
7878 << Template << Param << Arg.getSourceRange();
7879 Diag(Loc: Param->getLocation(), DiagID: diag::note_entity_declared_at) << Param;
7880 Diag(Loc: Template->getLocation(), DiagID: diag::note_entity_declared_at) << Template;
7881 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Param, AC1: ParamsAC, D2: Template,
7882 AC2: TemplateAC);
7883 return true;
7884 }
7885 return false;
7886}
7887
7888static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7889 unsigned HereDiagID,
7890 unsigned ExternalDiagID) {
7891 if (Decl.getLocation().isValid())
7892 return S.Diag(Loc: Decl.getLocation(), DiagID: HereDiagID);
7893
7894 SmallString<128> Str;
7895 llvm::raw_svector_ostream Out(Str);
7896 PrintingPolicy PP = S.getPrintingPolicy();
7897 PP.TerseOutput = 1;
7898 Decl.print(Out, Policy: PP);
7899 return S.Diag(Loc: Decl.getLocation(), DiagID: ExternalDiagID) << Out.str();
7900}
7901
7902void Sema::NoteTemplateLocation(const NamedDecl &Decl,
7903 std::optional<SourceRange> ParamRange) {
7904 SemaDiagnosticBuilder DB =
7905 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_decl_here,
7906 ExternalDiagID: diag::note_template_decl_external);
7907 if (ParamRange && ParamRange->isValid()) {
7908 assert(Decl.getLocation().isValid() &&
7909 "Parameter range has location when Decl does not");
7910 DB << *ParamRange;
7911 }
7912}
7913
7914void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
7915 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_param_here,
7916 ExternalDiagID: diag::note_template_param_external);
7917}
7918
7919/// Given a non-type template argument that refers to a
7920/// declaration and the type of its corresponding non-type template
7921/// parameter, produce an expression that properly refers to that
7922/// declaration.
7923ExprResult Sema::BuildExpressionFromDeclTemplateArgument(
7924 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7925 NamedDecl *TemplateParam) {
7926 // C++ [temp.param]p8:
7927 //
7928 // A non-type template-parameter of type "array of T" or
7929 // "function returning T" is adjusted to be of type "pointer to
7930 // T" or "pointer to function returning T", respectively.
7931 if (ParamType->isArrayType())
7932 ParamType = Context.getArrayDecayedType(T: ParamType);
7933 else if (ParamType->isFunctionType())
7934 ParamType = Context.getPointerType(T: ParamType);
7935
7936 // For a NULL non-type template argument, return nullptr casted to the
7937 // parameter's type.
7938 if (Arg.getKind() == TemplateArgument::NullPtr) {
7939 return ImpCastExprToType(
7940 E: new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7941 Type: ParamType,
7942 CK: ParamType->getAs<MemberPointerType>()
7943 ? CK_NullToMemberPointer
7944 : CK_NullToPointer);
7945 }
7946 assert(Arg.getKind() == TemplateArgument::Declaration &&
7947 "Only declaration template arguments permitted here");
7948
7949 ValueDecl *VD = Arg.getAsDecl();
7950
7951 CXXScopeSpec SS;
7952 if (ParamType->isMemberPointerType()) {
7953 // If this is a pointer to member, we need to use a qualified name to
7954 // form a suitable pointer-to-member constant.
7955 assert(VD->getDeclContext()->isRecord() &&
7956 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7957 isa<IndirectFieldDecl>(VD)));
7958 CanQualType ClassType =
7959 Context.getCanonicalTagType(TD: cast<RecordDecl>(Val: VD->getDeclContext()));
7960 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7961 SS.MakeTrivial(Context, Qualifier, R: Loc);
7962 }
7963
7964 ExprResult RefExpr = BuildDeclarationNameExpr(
7965 SS, NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
7966 if (RefExpr.isInvalid())
7967 return ExprError();
7968
7969 // For a pointer, the argument declaration is the pointee. Take its address.
7970 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7971 if (ParamType->isPointerType() && !ElemT.isNull() &&
7972 Context.hasSimilarType(T1: ElemT, T2: ParamType->getPointeeType())) {
7973 // Decay an array argument if we want a pointer to its first element.
7974 RefExpr = DefaultFunctionArrayConversion(E: RefExpr.get());
7975 if (RefExpr.isInvalid())
7976 return ExprError();
7977 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7978 // For any other pointer, take the address (or form a pointer-to-member).
7979 RefExpr = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_AddrOf, InputExpr: RefExpr.get());
7980 if (RefExpr.isInvalid())
7981 return ExprError();
7982 } else if (ParamType->isRecordType()) {
7983 assert(isa<TemplateParamObjectDecl>(VD) &&
7984 "arg for class template param not a template parameter object");
7985 // No conversions apply in this case.
7986 return RefExpr;
7987 } else {
7988 assert(ParamType->isReferenceType() &&
7989 "unexpected type for decl template argument");
7990 if (NonTypeTemplateParmDecl *NTTP =
7991 dyn_cast_if_present<NonTypeTemplateParmDecl>(Val: TemplateParam)) {
7992 QualType TemplateParamType = NTTP->getType();
7993 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7994 if (AT && AT->isDecltypeAuto()) {
7995 RefExpr = new (getASTContext()) SubstNonTypeTemplateParmExpr(
7996 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7997 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7998 /*PackIndex=*/std::nullopt,
7999 /*RefParam=*/true, /*Final=*/true);
8000 }
8001 }
8002 }
8003
8004 // At this point we should have the right value category.
8005 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8006 "value kind mismatch for non-type template argument");
8007
8008 // The type of the template parameter can differ from the type of the
8009 // argument in various ways; convert it now if necessary.
8010 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8011 if (!Context.hasSameType(T1: RefExpr.get()->getType(), T2: DestExprType)) {
8012 CastKind CK;
8013 if (Context.hasSimilarType(T1: RefExpr.get()->getType(), T2: DestExprType) ||
8014 IsFunctionConversion(FromType: RefExpr.get()->getType(), ToType: DestExprType)) {
8015 CK = CK_NoOp;
8016 } else if (ParamType->isVoidPointerType() &&
8017 RefExpr.get()->getType()->isPointerType()) {
8018 CK = CK_BitCast;
8019 } else {
8020 // FIXME: Pointers to members can need conversion derived-to-base or
8021 // base-to-derived conversions. We currently don't retain enough
8022 // information to convert properly (we need to track a cast path or
8023 // subobject number in the template argument).
8024 llvm_unreachable(
8025 "unexpected conversion required for non-type template argument");
8026 }
8027 RefExpr = ImpCastExprToType(E: RefExpr.get(), Type: DestExprType, CK,
8028 VK: RefExpr.get()->getValueKind());
8029 }
8030
8031 return RefExpr;
8032}
8033
8034/// Construct a new expression that refers to the given
8035/// integral template argument with the given source-location
8036/// information.
8037///
8038/// This routine takes care of the mapping from an integral template
8039/// argument (which may have any integral type) to the appropriate
8040/// literal value.
8041static Expr *BuildExpressionFromIntegralTemplateArgumentValue(
8042 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8043 assert(OrigT->isIntegralOrEnumerationType());
8044
8045 // If this is an enum type that we're instantiating, we need to use an integer
8046 // type the same size as the enumerator. We don't want to build an
8047 // IntegerLiteral with enum type. The integer type of an enum type can be of
8048 // any integral type with C++11 enum classes, make sure we create the right
8049 // type of literal for it.
8050 QualType T = OrigT;
8051 if (const auto *ED = OrigT->getAsEnumDecl())
8052 T = ED->getIntegerType();
8053
8054 Expr *E;
8055 if (T->isAnyCharacterType()) {
8056 CharacterLiteralKind Kind;
8057 if (T->isWideCharType())
8058 Kind = CharacterLiteralKind::Wide;
8059 else if (T->isChar8Type() && S.getLangOpts().Char8)
8060 Kind = CharacterLiteralKind::UTF8;
8061 else if (T->isChar16Type())
8062 Kind = CharacterLiteralKind::UTF16;
8063 else if (T->isChar32Type())
8064 Kind = CharacterLiteralKind::UTF32;
8065 else
8066 Kind = CharacterLiteralKind::Ascii;
8067
8068 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8069 } else if (T->isBooleanType()) {
8070 E = CXXBoolLiteralExpr::Create(C: S.Context, Val: Int.getBoolValue(), Ty: T, Loc);
8071 } else {
8072 E = IntegerLiteral::Create(C: S.Context, V: Int, type: T, l: Loc);
8073 }
8074
8075 if (OrigT->isEnumeralType()) {
8076 // FIXME: This is a hack. We need a better way to handle substituted
8077 // non-type template parameters.
8078 E = CStyleCastExpr::Create(Context: S.Context, T: OrigT, VK: VK_PRValue, K: CK_IntegralCast, Op: E,
8079 BasePath: nullptr, FPO: S.CurFPFeatureOverrides(),
8080 WrittenTy: S.Context.getTrivialTypeSourceInfo(T: OrigT, Loc),
8081 L: Loc, R: Loc);
8082 }
8083
8084 return E;
8085}
8086
8087static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(
8088 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8089 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8090 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
8091 ILE->setType(T);
8092 return ILE;
8093 };
8094
8095 switch (Val.getKind()) {
8096 case APValue::AddrLabelDiff:
8097 // This cannot occur in a template argument at all.
8098 case APValue::Array:
8099 case APValue::Struct:
8100 case APValue::Union:
8101 // These can only occur within a template parameter object, which is
8102 // represented as a TemplateArgument::Declaration.
8103 llvm_unreachable("unexpected template argument value");
8104
8105 case APValue::Int:
8106 return BuildExpressionFromIntegralTemplateArgumentValue(S, OrigT: T, Int: Val.getInt(),
8107 Loc);
8108
8109 case APValue::Float:
8110 return FloatingLiteral::Create(C: S.Context, V: Val.getFloat(), /*IsExact=*/isexact: true,
8111 Type: T, L: Loc);
8112
8113 case APValue::FixedPoint:
8114 return FixedPointLiteral::CreateFromRawInt(
8115 C: S.Context, V: Val.getFixedPoint().getValue(), type: T, l: Loc,
8116 Scale: Val.getFixedPoint().getScale());
8117
8118 case APValue::ComplexInt: {
8119 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8120 return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(
8121 S, OrigT: ElemT, Int: Val.getComplexIntReal(), Loc),
8122 BuildExpressionFromIntegralTemplateArgumentValue(
8123 S, OrigT: ElemT, Int: Val.getComplexIntImag(), Loc)});
8124 }
8125
8126 case APValue::ComplexFloat: {
8127 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8128 return MakeInitList(
8129 {FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatReal(), isexact: true,
8130 Type: ElemT, L: Loc),
8131 FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatImag(), isexact: true,
8132 Type: ElemT, L: Loc)});
8133 }
8134
8135 case APValue::Vector: {
8136 QualType ElemT = T->castAs<VectorType>()->getElementType();
8137 llvm::SmallVector<Expr *, 8> Elts;
8138 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8139 Elts.push_back(Elt: BuildExpressionFromNonTypeTemplateArgumentValue(
8140 S, T: ElemT, Val: Val.getVectorElt(I), Loc));
8141 return MakeInitList(Elts);
8142 }
8143
8144 case APValue::Matrix:
8145 llvm_unreachable("Matrix template argument expression not yet supported");
8146
8147 case APValue::None:
8148 case APValue::Indeterminate:
8149 llvm_unreachable("Unexpected APValue kind.");
8150 case APValue::LValue:
8151 case APValue::MemberPointer:
8152 // There isn't necessarily a valid equivalent source-level syntax for
8153 // these; in particular, a naive lowering might violate access control.
8154 // So for now we lower to a ConstantExpr holding the value, wrapped around
8155 // an OpaqueValueExpr.
8156 // FIXME: We should have a better representation for this.
8157 ExprValueKind VK = VK_PRValue;
8158 if (T->isReferenceType()) {
8159 T = T->getPointeeType();
8160 VK = VK_LValue;
8161 }
8162 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8163 return ConstantExpr::Create(Context: S.Context, E: OVE, Result: Val);
8164 }
8165 llvm_unreachable("Unhandled APValue::ValueKind enum");
8166}
8167
8168ExprResult
8169Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
8170 SourceLocation Loc) {
8171 switch (Arg.getKind()) {
8172 case TemplateArgument::Null:
8173 case TemplateArgument::Type:
8174 case TemplateArgument::Template:
8175 case TemplateArgument::TemplateExpansion:
8176 case TemplateArgument::Pack:
8177 llvm_unreachable("not a non-type template argument");
8178
8179 case TemplateArgument::Expression:
8180 return Arg.getAsExpr();
8181
8182 case TemplateArgument::NullPtr:
8183 case TemplateArgument::Declaration:
8184 return BuildExpressionFromDeclTemplateArgument(
8185 Arg, ParamType: Arg.getNonTypeTemplateArgumentType(), Loc);
8186
8187 case TemplateArgument::Integral:
8188 return BuildExpressionFromIntegralTemplateArgumentValue(
8189 S&: *this, OrigT: Arg.getIntegralType(), Int: Arg.getAsIntegral(), Loc);
8190
8191 case TemplateArgument::StructuralValue:
8192 return BuildExpressionFromNonTypeTemplateArgumentValue(
8193 S&: *this, T: Arg.getStructuralValueType(), Val: Arg.getAsStructuralValue(), Loc);
8194 }
8195 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8196}
8197
8198/// Match two template parameters within template parameter lists.
8199static bool MatchTemplateParameterKind(
8200 Sema &S, NamedDecl *New,
8201 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8202 const NamedDecl *OldInstFrom, bool Complain,
8203 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8204 // Check the actual kind (type, non-type, template).
8205 if (Old->getKind() != New->getKind()) {
8206 if (Complain) {
8207 unsigned NextDiag = diag::err_template_param_different_kind;
8208 if (TemplateArgLoc.isValid()) {
8209 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8210 NextDiag = diag::note_template_param_different_kind;
8211 }
8212 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8213 << (Kind != Sema::TPL_TemplateMatch);
8214 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_prev_declaration)
8215 << (Kind != Sema::TPL_TemplateMatch);
8216 }
8217
8218 return false;
8219 }
8220
8221 // Check that both are parameter packs or neither are parameter packs.
8222 // However, if we are matching a template template argument to a
8223 // template template parameter, the template template parameter can have
8224 // a parameter pack where the template template argument does not.
8225 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8226 if (Complain) {
8227 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8228 if (TemplateArgLoc.isValid()) {
8229 S.Diag(Loc: TemplateArgLoc,
8230 DiagID: diag::err_template_arg_template_params_mismatch);
8231 NextDiag = diag::note_template_parameter_pack_non_pack;
8232 }
8233
8234 unsigned ParamKind = isa<TemplateTypeParmDecl>(Val: New)? 0
8235 : isa<NonTypeTemplateParmDecl>(Val: New)? 1
8236 : 2;
8237 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8238 << ParamKind << New->isParameterPack();
8239 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_parameter_pack_here)
8240 << ParamKind << Old->isParameterPack();
8241 }
8242
8243 return false;
8244 }
8245 // For non-type template parameters, check the type of the parameter.
8246 if (NonTypeTemplateParmDecl *OldNTTP =
8247 dyn_cast<NonTypeTemplateParmDecl>(Val: Old)) {
8248 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(Val: New);
8249
8250 // If we are matching a template template argument to a template
8251 // template parameter and one of the non-type template parameter types
8252 // is dependent, then we must wait until template instantiation time
8253 // to actually compare the arguments.
8254 if (Kind != Sema::TPL_TemplateTemplateParmMatch ||
8255 (!OldNTTP->getType()->isDependentType() &&
8256 !NewNTTP->getType()->isDependentType())) {
8257 // C++20 [temp.over.link]p6:
8258 // Two [non-type] template-parameters are equivalent [if] they have
8259 // equivalent types ignoring the use of type-constraints for
8260 // placeholder types
8261 QualType OldType = S.Context.getUnconstrainedType(T: OldNTTP->getType());
8262 QualType NewType = S.Context.getUnconstrainedType(T: NewNTTP->getType());
8263 if (!S.Context.hasSameType(T1: OldType, T2: NewType)) {
8264 if (Complain) {
8265 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8266 if (TemplateArgLoc.isValid()) {
8267 S.Diag(Loc: TemplateArgLoc,
8268 DiagID: diag::err_template_arg_template_params_mismatch);
8269 NextDiag = diag::note_template_nontype_parm_different_type;
8270 }
8271 S.Diag(Loc: NewNTTP->getLocation(), DiagID: NextDiag)
8272 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8273 S.Diag(Loc: OldNTTP->getLocation(),
8274 DiagID: diag::note_template_nontype_parm_prev_declaration)
8275 << OldNTTP->getType();
8276 }
8277 return false;
8278 }
8279 }
8280 }
8281 // For template template parameters, check the template parameter types.
8282 // The template parameter lists of template template
8283 // parameters must agree.
8284 else if (TemplateTemplateParmDecl *OldTTP =
8285 dyn_cast<TemplateTemplateParmDecl>(Val: Old)) {
8286 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(Val: New);
8287 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8288 return false;
8289 if (!S.TemplateParameterListsAreEqual(
8290 NewInstFrom, New: NewTTP->getTemplateParameters(), OldInstFrom,
8291 Old: OldTTP->getTemplateParameters(), Complain,
8292 Kind: (Kind == Sema::TPL_TemplateMatch
8293 ? Sema::TPL_TemplateTemplateParmMatch
8294 : Kind),
8295 TemplateArgLoc))
8296 return false;
8297 }
8298
8299 if (Kind != Sema::TPL_TemplateParamsEquivalent &&
8300 Kind != Sema::TPL_TemplateTemplateParmMatch &&
8301 !isa<TemplateTemplateParmDecl>(Val: Old)) {
8302 const Expr *NewC = nullptr, *OldC = nullptr;
8303
8304 if (isa<TemplateTypeParmDecl>(Val: New)) {
8305 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: New)->getTypeConstraint())
8306 NewC = TC->getImmediatelyDeclaredConstraint();
8307 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: Old)->getTypeConstraint())
8308 OldC = TC->getImmediatelyDeclaredConstraint();
8309 } else if (isa<NonTypeTemplateParmDecl>(Val: New)) {
8310 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: New)
8311 ->getPlaceholderTypeConstraint())
8312 NewC = E;
8313 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: Old)
8314 ->getPlaceholderTypeConstraint())
8315 OldC = E;
8316 } else
8317 llvm_unreachable("unexpected template parameter type");
8318
8319 auto Diagnose = [&] {
8320 S.Diag(Loc: NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8321 DiagID: diag::err_template_different_type_constraint);
8322 S.Diag(Loc: OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8323 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8324 };
8325
8326 if (!NewC != !OldC) {
8327 if (Complain)
8328 Diagnose();
8329 return false;
8330 }
8331
8332 if (NewC) {
8333 if (!S.AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldC, New: NewInstFrom,
8334 NewConstr: NewC)) {
8335 if (Complain)
8336 Diagnose();
8337 return false;
8338 }
8339 }
8340 }
8341
8342 return true;
8343}
8344
8345/// Diagnose a known arity mismatch when comparing template argument
8346/// lists.
8347static
8348void DiagnoseTemplateParameterListArityMismatch(Sema &S,
8349 TemplateParameterList *New,
8350 TemplateParameterList *Old,
8351 Sema::TemplateParameterListEqualKind Kind,
8352 SourceLocation TemplateArgLoc) {
8353 unsigned NextDiag = diag::err_template_param_list_different_arity;
8354 if (TemplateArgLoc.isValid()) {
8355 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8356 NextDiag = diag::note_template_param_list_different_arity;
8357 }
8358 S.Diag(Loc: New->getTemplateLoc(), DiagID: NextDiag)
8359 << (New->size() > Old->size())
8360 << (Kind != Sema::TPL_TemplateMatch)
8361 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8362 S.Diag(Loc: Old->getTemplateLoc(), DiagID: diag::note_template_prev_declaration)
8363 << (Kind != Sema::TPL_TemplateMatch)
8364 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8365}
8366
8367bool Sema::TemplateParameterListsAreEqual(
8368 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8369 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8370 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8371 if (Old->size() != New->size()) {
8372 if (Complain)
8373 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8374 TemplateArgLoc);
8375
8376 return false;
8377 }
8378
8379 // C++0x [temp.arg.template]p3:
8380 // A template-argument matches a template template-parameter (call it P)
8381 // when each of the template parameters in the template-parameter-list of
8382 // the template-argument's corresponding class template or alias template
8383 // (call it A) matches the corresponding template parameter in the
8384 // template-parameter-list of P. [...]
8385 TemplateParameterList::iterator NewParm = New->begin();
8386 TemplateParameterList::iterator NewParmEnd = New->end();
8387 for (TemplateParameterList::iterator OldParm = Old->begin(),
8388 OldParmEnd = Old->end();
8389 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8390 if (NewParm == NewParmEnd) {
8391 if (Complain)
8392 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8393 TemplateArgLoc);
8394 return false;
8395 }
8396 if (!MatchTemplateParameterKind(S&: *this, New: *NewParm, NewInstFrom, Old: *OldParm,
8397 OldInstFrom, Complain, Kind,
8398 TemplateArgLoc))
8399 return false;
8400 }
8401
8402 // Make sure we exhausted all of the arguments.
8403 if (NewParm != NewParmEnd) {
8404 if (Complain)
8405 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8406 TemplateArgLoc);
8407
8408 return false;
8409 }
8410
8411 if (Kind != TPL_TemplateParamsEquivalent) {
8412 const Expr *NewRC = New->getRequiresClause();
8413 const Expr *OldRC = Old->getRequiresClause();
8414
8415 auto Diagnose = [&] {
8416 Diag(Loc: NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8417 DiagID: diag::err_template_different_requires_clause);
8418 Diag(Loc: OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8419 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8420 };
8421
8422 if (!NewRC != !OldRC) {
8423 if (Complain)
8424 Diagnose();
8425 return false;
8426 }
8427
8428 if (NewRC) {
8429 if (!AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldRC, New: NewInstFrom,
8430 NewConstr: NewRC)) {
8431 if (Complain)
8432 Diagnose();
8433 return false;
8434 }
8435 }
8436 }
8437
8438 return true;
8439}
8440
8441bool
8442Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
8443 if (!S)
8444 return false;
8445
8446 // Find the nearest enclosing declaration scope.
8447 S = S->getDeclParent();
8448
8449 // C++ [temp.pre]p6: [P2096]
8450 // A template, explicit specialization, or partial specialization shall not
8451 // have C linkage.
8452 DeclContext *Ctx = S->getEntity();
8453 if (Ctx && Ctx->isExternCContext()) {
8454 SourceRange Range =
8455 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8456 ? TemplateParams->getParam(Idx: 0)->getSourceRange()
8457 : TemplateParams->getSourceRange();
8458 Diag(Loc: Range.getBegin(), DiagID: diag::err_template_linkage) << Range;
8459 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8460 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
8461 return true;
8462 }
8463 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8464
8465 // C++ [temp]p2:
8466 // A template-declaration can appear only as a namespace scope or
8467 // class scope declaration.
8468 // C++ [temp.expl.spec]p3:
8469 // An explicit specialization may be declared in any scope in which the
8470 // corresponding primary template may be defined.
8471 // C++ [temp.class.spec]p6: [P2096]
8472 // A partial specialization may be declared in any scope in which the
8473 // corresponding primary template may be defined.
8474 if (Ctx) {
8475 if (Ctx->isFileContext())
8476 return false;
8477 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Ctx)) {
8478 // C++ [temp.mem]p2:
8479 // A local class shall not have member templates.
8480 if (RD->isLocalClass())
8481 return Diag(Loc: TemplateParams->getTemplateLoc(),
8482 DiagID: diag::err_template_inside_local_class)
8483 << TemplateParams->getSourceRange();
8484 else
8485 return false;
8486 }
8487 }
8488
8489 return Diag(Loc: TemplateParams->getTemplateLoc(),
8490 DiagID: diag::err_template_outside_namespace_or_class_scope)
8491 << TemplateParams->getSourceRange();
8492}
8493
8494/// Determine what kind of template specialization the given declaration
8495/// is.
8496static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8497 if (!D)
8498 return TSK_Undeclared;
8499
8500 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D))
8501 return Record->getTemplateSpecializationKind();
8502 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D))
8503 return Function->getTemplateSpecializationKind();
8504 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D))
8505 return Var->getTemplateSpecializationKind();
8506
8507 return TSK_Undeclared;
8508}
8509
8510/// Check whether a specialization is well-formed in the current
8511/// context.
8512///
8513/// This routine determines whether a template specialization can be declared
8514/// in the current context (C++ [temp.expl.spec]p2).
8515///
8516/// \param S the semantic analysis object for which this check is being
8517/// performed.
8518///
8519/// \param Specialized the entity being specialized or instantiated, which
8520/// may be a kind of template (class template, function template, etc.) or
8521/// a member of a class template (member function, static data member,
8522/// member class).
8523///
8524/// \param PrevDecl the previous declaration of this entity, if any.
8525///
8526/// \param Loc the location of the explicit specialization or instantiation of
8527/// this entity.
8528///
8529/// \param IsPartialSpecialization whether this is a partial specialization of
8530/// a class template.
8531///
8532/// \returns true if there was an error that we cannot recover from, false
8533/// otherwise.
8534static bool CheckTemplateSpecializationScope(Sema &S,
8535 NamedDecl *Specialized,
8536 NamedDecl *PrevDecl,
8537 SourceLocation Loc,
8538 bool IsPartialSpecialization) {
8539 // Keep these "kind" numbers in sync with the %select statements in the
8540 // various diagnostics emitted by this routine.
8541 int EntityKind = 0;
8542 if (isa<ClassTemplateDecl>(Val: Specialized))
8543 EntityKind = IsPartialSpecialization? 1 : 0;
8544 else if (isa<VarTemplateDecl>(Val: Specialized))
8545 EntityKind = IsPartialSpecialization ? 3 : 2;
8546 else if (isa<FunctionTemplateDecl>(Val: Specialized))
8547 EntityKind = 4;
8548 else if (isa<CXXMethodDecl>(Val: Specialized))
8549 EntityKind = 5;
8550 else if (isa<VarDecl>(Val: Specialized))
8551 EntityKind = 6;
8552 else if (isa<RecordDecl>(Val: Specialized))
8553 EntityKind = 7;
8554 else if (isa<EnumDecl>(Val: Specialized) && S.getLangOpts().CPlusPlus11)
8555 EntityKind = 8;
8556 else {
8557 S.Diag(Loc, DiagID: diag::err_template_spec_unknown_kind)
8558 << S.getLangOpts().CPlusPlus11;
8559 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8560 return true;
8561 }
8562
8563 // C++ [temp.expl.spec]p2:
8564 // An explicit specialization may be declared in any scope in which
8565 // the corresponding primary template may be defined.
8566 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8567 S.Diag(Loc, DiagID: diag::err_template_spec_decl_function_scope)
8568 << Specialized;
8569 return true;
8570 }
8571
8572 // C++ [temp.class.spec]p6:
8573 // A class template partial specialization may be declared in any
8574 // scope in which the primary template may be defined.
8575 DeclContext *SpecializedContext =
8576 Specialized->getDeclContext()->getRedeclContext();
8577 DeclContext *DC = S.CurContext->getRedeclContext();
8578
8579 // Make sure that this redeclaration (or definition) occurs in the same
8580 // scope or an enclosing namespace.
8581 if (!(DC->isFileContext() ? DC->Encloses(DC: SpecializedContext)
8582 : DC->Equals(DC: SpecializedContext))) {
8583 if (isa<TranslationUnitDecl>(Val: SpecializedContext))
8584 S.Diag(Loc, DiagID: diag::err_template_spec_redecl_global_scope)
8585 << EntityKind << Specialized;
8586 else {
8587 auto *ND = cast<NamedDecl>(Val: SpecializedContext);
8588 int Diag = diag::err_template_spec_redecl_out_of_scope;
8589 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8590 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8591 S.Diag(Loc, DiagID: Diag) << EntityKind << Specialized
8592 << ND << isa<CXXRecordDecl>(Val: ND);
8593 }
8594
8595 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8596
8597 // Don't allow specializing in the wrong class during error recovery.
8598 // Otherwise, things can go horribly wrong.
8599 if (DC->isRecord())
8600 return true;
8601 }
8602
8603 return false;
8604}
8605
8606static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8607 if (!E->isTypeDependent())
8608 return SourceLocation();
8609 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8610 Checker.TraverseStmt(S: E);
8611 if (Checker.MatchLoc.isInvalid())
8612 return E->getSourceRange();
8613 return Checker.MatchLoc;
8614}
8615
8616static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8617 if (!TL.getType()->isDependentType())
8618 return SourceLocation();
8619 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8620 Checker.TraverseTypeLoc(TL);
8621 if (Checker.MatchLoc.isInvalid())
8622 return TL.getSourceRange();
8623 return Checker.MatchLoc;
8624}
8625
8626/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8627/// that checks non-type template partial specialization arguments.
8628static bool CheckNonTypeTemplatePartialSpecializationArgs(
8629 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8630 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8631 bool HasError = false;
8632 for (unsigned I = 0; I != NumArgs; ++I) {
8633 if (Args[I].getKind() == TemplateArgument::Pack) {
8634 if (CheckNonTypeTemplatePartialSpecializationArgs(
8635 S, TemplateNameLoc, Param, Args: Args[I].pack_begin(),
8636 NumArgs: Args[I].pack_size(), IsDefaultArgument))
8637 return true;
8638
8639 continue;
8640 }
8641
8642 if (Args[I].getKind() != TemplateArgument::Expression)
8643 continue;
8644
8645 Expr *ArgExpr = Args[I].getAsExpr();
8646 if (ArgExpr->containsErrors()) {
8647 HasError = true;
8648 continue;
8649 }
8650
8651 // We can have a pack expansion of any of the bullets below.
8652 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Val: ArgExpr))
8653 ArgExpr = Expansion->getPattern();
8654
8655 // Strip off any implicit casts we added as part of type checking.
8656 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
8657 ArgExpr = ICE->getSubExpr();
8658
8659 // C++ [temp.class.spec]p8:
8660 // A non-type argument is non-specialized if it is the name of a
8661 // non-type parameter. All other non-type arguments are
8662 // specialized.
8663 //
8664 // Below, we check the two conditions that only apply to
8665 // specialized non-type arguments, so skip any non-specialized
8666 // arguments.
8667 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ArgExpr))
8668 if (isa<NonTypeTemplateParmDecl>(Val: DRE->getDecl()))
8669 continue;
8670
8671 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ArgExpr);
8672 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8673 continue;
8674 }
8675
8676 // C++ [temp.class.spec]p9:
8677 // Within the argument list of a class template partial
8678 // specialization, the following restrictions apply:
8679 // -- A partially specialized non-type argument expression
8680 // shall not involve a template parameter of the partial
8681 // specialization except when the argument expression is a
8682 // simple identifier.
8683 // -- The type of a template parameter corresponding to a
8684 // specialized non-type argument shall not be dependent on a
8685 // parameter of the specialization.
8686 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8687 // We implement a compromise between the original rules and DR1315:
8688 // -- A specialized non-type template argument shall not be
8689 // type-dependent and the corresponding template parameter
8690 // shall have a non-dependent type.
8691 SourceRange ParamUseRange =
8692 findTemplateParameterInType(Depth: Param->getDepth(), E: ArgExpr);
8693 if (ParamUseRange.isValid()) {
8694 if (IsDefaultArgument) {
8695 S.Diag(Loc: TemplateNameLoc,
8696 DiagID: diag::err_dependent_non_type_arg_in_partial_spec);
8697 S.Diag(Loc: ParamUseRange.getBegin(),
8698 DiagID: diag::note_dependent_non_type_default_arg_in_partial_spec)
8699 << ParamUseRange;
8700 } else {
8701 S.Diag(Loc: ParamUseRange.getBegin(),
8702 DiagID: diag::err_dependent_non_type_arg_in_partial_spec)
8703 << ParamUseRange;
8704 }
8705 return true;
8706 }
8707
8708 ParamUseRange = findTemplateParameter(
8709 Depth: Param->getDepth(), TL: Param->getTypeSourceInfo()->getTypeLoc());
8710 if (ParamUseRange.isValid()) {
8711 S.Diag(Loc: IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8712 DiagID: diag::err_dependent_typed_non_type_arg_in_partial_spec)
8713 << Param->getType();
8714 S.NoteTemplateParameterLocation(Decl: *Param);
8715 return true;
8716 }
8717 }
8718
8719 return HasError;
8720}
8721
8722bool Sema::CheckTemplatePartialSpecializationArgs(
8723 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8724 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8725 // We have to be conservative when checking a template in a dependent
8726 // context.
8727 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8728 return false;
8729
8730 TemplateParameterList *TemplateParams =
8731 PrimaryTemplate->getTemplateParameters();
8732 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8733 NonTypeTemplateParmDecl *Param
8734 = dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: I));
8735 if (!Param)
8736 continue;
8737
8738 if (CheckNonTypeTemplatePartialSpecializationArgs(S&: *this, TemplateNameLoc,
8739 Param, Args: &TemplateArgs[I],
8740 NumArgs: 1, IsDefaultArgument: I >= NumExplicit))
8741 return true;
8742 }
8743
8744 return false;
8745}
8746
8747DeclResult Sema::ActOnClassTemplateSpecialization(
8748 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8749 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8750 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8751 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8752 assert(TUK != TagUseKind::Reference && "References are not specializations");
8753
8754 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8755 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8756 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8757
8758 // Find the class template we're specializing
8759 TemplateName Name = TemplateId.Template.get();
8760 ClassTemplateDecl *ClassTemplate
8761 = dyn_cast_or_null<ClassTemplateDecl>(Val: Name.getAsTemplateDecl());
8762
8763 if (!ClassTemplate) {
8764 Diag(Loc: TemplateNameLoc, DiagID: diag::err_not_class_template_specialization)
8765 << (Name.getAsTemplateDecl() &&
8766 isa<TemplateTemplateParmDecl>(Val: Name.getAsTemplateDecl()));
8767 return true;
8768 }
8769
8770 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8771 auto Message = DSA->getMessage();
8772 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
8773 << ClassTemplate << !Message.empty() << Message;
8774 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
8775 }
8776
8777 if (S->isTemplateParamScope())
8778 EnterTemplatedContext(S, DC: ClassTemplate->getTemplatedDecl());
8779
8780 DeclContext *DC = ClassTemplate->getDeclContext();
8781
8782 bool isMemberSpecialization = false;
8783 bool isPartialSpecialization = false;
8784
8785 if (SS.isSet()) {
8786 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8787 diagnoseQualifiedDeclaration(SS, DC, Name: ClassTemplate->getDeclName(),
8788 Loc: TemplateNameLoc, TemplateId: &TemplateId,
8789 /*IsMemberSpecialization=*/false))
8790 return true;
8791 }
8792
8793 // Check the validity of the template headers that introduce this
8794 // template.
8795 // FIXME: We probably shouldn't complain about these headers for
8796 // friend declarations.
8797 bool Invalid = false;
8798 TemplateParameterList *TemplateParams =
8799 MatchTemplateParametersToScopeSpecifier(
8800 DeclStartLoc: KWLoc, DeclLoc: TemplateNameLoc, SS, TemplateId: &TemplateId, ParamLists: TemplateParameterLists,
8801 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
8802 if (Invalid)
8803 return true;
8804
8805 // Check that we can declare a template specialization here.
8806 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8807 return true;
8808
8809 if (TemplateParams && DC->isDependentContext()) {
8810 ContextRAII SavedContext(*this, DC);
8811 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
8812 return true;
8813 }
8814
8815 if (TemplateParams && TemplateParams->size() > 0) {
8816 isPartialSpecialization = true;
8817
8818 if (TUK == TagUseKind::Friend) {
8819 Diag(Loc: KWLoc, DiagID: diag::err_partial_specialization_friend)
8820 << SourceRange(LAngleLoc, RAngleLoc);
8821 return true;
8822 }
8823
8824 // C++ [temp.class.spec]p10:
8825 // The template parameter list of a specialization shall not
8826 // contain default template argument values.
8827 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8828 Decl *Param = TemplateParams->getParam(Idx: I);
8829 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
8830 if (TTP->hasDefaultArgument()) {
8831 Diag(Loc: TTP->getDefaultArgumentLoc(),
8832 DiagID: diag::err_default_arg_in_partial_spec);
8833 TTP->removeDefaultArgument();
8834 }
8835 } else if (NonTypeTemplateParmDecl *NTTP
8836 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
8837 if (NTTP->hasDefaultArgument()) {
8838 Diag(Loc: NTTP->getDefaultArgumentLoc(),
8839 DiagID: diag::err_default_arg_in_partial_spec)
8840 << NTTP->getDefaultArgument().getSourceRange();
8841 NTTP->removeDefaultArgument();
8842 }
8843 } else {
8844 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
8845 if (TTP->hasDefaultArgument()) {
8846 Diag(Loc: TTP->getDefaultArgument().getLocation(),
8847 DiagID: diag::err_default_arg_in_partial_spec)
8848 << TTP->getDefaultArgument().getSourceRange();
8849 TTP->removeDefaultArgument();
8850 }
8851 }
8852 }
8853 } else if (TemplateParams) {
8854 if (TUK == TagUseKind::Friend)
8855 Diag(Loc: KWLoc, DiagID: diag::err_template_spec_friend)
8856 << FixItHint::CreateRemoval(
8857 RemoveRange: SourceRange(TemplateParams->getTemplateLoc(),
8858 TemplateParams->getRAngleLoc()))
8859 << SourceRange(LAngleLoc, RAngleLoc);
8860 } else {
8861 assert(TUK == TagUseKind::Friend &&
8862 "should have a 'template<>' for this decl");
8863 }
8864
8865 // Check that the specialization uses the same tag kind as the
8866 // original template.
8867 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
8868 assert(Kind != TagTypeKind::Enum &&
8869 "Invalid enum tag in class template spec!");
8870 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(), NewTag: Kind,
8871 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
8872 Name: ClassTemplate->getIdentifier())) {
8873 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
8874 << ClassTemplate
8875 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
8876 Code: ClassTemplate->getTemplatedDecl()->getKindName());
8877 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
8878 DiagID: diag::note_previous_use);
8879 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8880 }
8881
8882 // Translate the parser's template argument list in our AST format.
8883 TemplateArgumentListInfo TemplateArgs =
8884 makeTemplateArgumentListInfo(S&: *this, TemplateId);
8885
8886 // Check for unexpanded parameter packs in any of the template arguments.
8887 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8888 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
8889 UPPC: isPartialSpecialization
8890 ? UPPC_PartialSpecialization
8891 : UPPC_ExplicitSpecialization))
8892 return true;
8893
8894 // Check that the template argument list is well-formed for this
8895 // template.
8896 CheckTemplateArgumentInfo CTAI;
8897 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
8898 /*DefaultArgs=*/{},
8899 /*PartialTemplateArgs=*/false, CTAI,
8900 /*UpdateArgsWithConversions=*/true))
8901 return true;
8902
8903 // Find the class template (partial) specialization declaration that
8904 // corresponds to these arguments.
8905 if (isPartialSpecialization) {
8906 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, PrimaryTemplate: ClassTemplate,
8907 NumExplicit: TemplateArgs.size(),
8908 TemplateArgs: CTAI.CanonicalConverted))
8909 return true;
8910
8911 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8912 // also do it during instantiation.
8913 if (!Name.isDependent() &&
8914 !TemplateSpecializationType::anyDependentTemplateArguments(
8915 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
8916 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
8917 << ClassTemplate->getDeclName();
8918 isPartialSpecialization = false;
8919 Invalid = true;
8920 }
8921 }
8922
8923 void *InsertPos = nullptr;
8924 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8925
8926 if (isPartialSpecialization)
8927 PrevDecl = ClassTemplate->findPartialSpecialization(
8928 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertPos);
8929 else
8930 PrevDecl =
8931 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
8932
8933 ClassTemplateSpecializationDecl *Specialization = nullptr;
8934
8935 // Check whether we can declare a class template specialization in
8936 // the current scope.
8937 if (TUK != TagUseKind::Friend &&
8938 CheckTemplateSpecializationScope(S&: *this, Specialized: ClassTemplate, PrevDecl,
8939 Loc: TemplateNameLoc,
8940 IsPartialSpecialization: isPartialSpecialization))
8941 return true;
8942
8943 if (!isPartialSpecialization) {
8944 // Create a new class template specialization declaration node for
8945 // this explicit specialization or friend declaration.
8946 Specialization = ClassTemplateSpecializationDecl::Create(
8947 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
8948 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
8949 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8950 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
8951 if (TemplateParameterLists.size() > 0) {
8952 Specialization->setTemplateParameterListsInfo(Context,
8953 TPLists: TemplateParameterLists);
8954 }
8955
8956 if (!PrevDecl)
8957 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
8958 } else {
8959 CanQualType CanonType = CanQualType::CreateUnsafe(
8960 Other: Context.getCanonicalTemplateSpecializationType(
8961 Keyword: ElaboratedTypeKeyword::None,
8962 T: TemplateName(ClassTemplate->getCanonicalDecl()),
8963 CanonicalArgs: CTAI.CanonicalConverted));
8964 if (Context.hasSameType(
8965 T1: CanonType,
8966 T2: ClassTemplate->getCanonicalInjectedSpecializationType(Ctx: Context)) &&
8967 (!Context.getLangOpts().CPlusPlus20 ||
8968 !TemplateParams->hasAssociatedConstraints())) {
8969 // C++ [temp.class.spec]p9b3:
8970 //
8971 // -- The argument list of the specialization shall not be identical
8972 // to the implicit argument list of the primary template.
8973 //
8974 // This rule has since been removed, because it's redundant given DR1495,
8975 // but we keep it because it produces better diagnostics and recovery.
8976 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
8977 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8978 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
8979 return CheckClassTemplate(
8980 S, TagSpec, TUK, KWLoc, SS, Name: ClassTemplate->getIdentifier(),
8981 NameLoc: TemplateNameLoc, Attr, TemplateParams, AS: AS_none,
8982 /*ModulePrivateLoc=*/SourceLocation(),
8983 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
8984 OuterTemplateParamLists: TemplateParameterLists.data());
8985 }
8986
8987 // Create a new class template partial specialization declaration node.
8988 ClassTemplatePartialSpecializationDecl *PrevPartial =
8989 cast_or_null<ClassTemplatePartialSpecializationDecl>(Val: PrevDecl);
8990 ClassTemplatePartialSpecializationDecl *Partial =
8991 ClassTemplatePartialSpecializationDecl::Create(
8992 Context, TK: Kind, DC, StartLoc: KWLoc, IdLoc: TemplateNameLoc, Params: TemplateParams,
8993 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, CanonInjectedTST: CanonType, PrevDecl: PrevPartial);
8994 Partial->setTemplateArgsAsWritten(TemplateArgs);
8995 SetNestedNameSpecifier(S&: *this, T: Partial, SS);
8996 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8997 Partial->setTemplateParameterListsInfo(
8998 Context, TPLists: TemplateParameterLists.drop_back(N: 1));
8999 }
9000
9001 if (!PrevPartial)
9002 ClassTemplate->AddPartialSpecialization(D: Partial, InsertPos);
9003 Specialization = Partial;
9004
9005 // If we are providing an explicit specialization of a member class
9006 // template specialization, make a note of that.
9007 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
9008 PrevPartial->setMemberSpecialization();
9009
9010 CheckTemplatePartialSpecialization(Partial);
9011 }
9012
9013 // C++ [temp.expl.spec]p6:
9014 // If a template, a member template or the member of a class template is
9015 // explicitly specialized then that specialization shall be declared
9016 // before the first use of that specialization that would cause an implicit
9017 // instantiation to take place, in every translation unit in which such a
9018 // use occurs; no diagnostic is required.
9019 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9020 bool Okay = false;
9021 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9022 // Is there any previous explicit specialization declaration?
9023 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9024 Okay = true;
9025 break;
9026 }
9027 }
9028
9029 if (!Okay) {
9030 SourceRange Range(TemplateNameLoc, RAngleLoc);
9031 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
9032 << Context.getCanonicalTagType(TD: Specialization) << Range;
9033
9034 Diag(Loc: PrevDecl->getPointOfInstantiation(),
9035 DiagID: diag::note_instantiation_required_here)
9036 << (PrevDecl->getTemplateSpecializationKind()
9037 != TSK_ImplicitInstantiation);
9038 return true;
9039 }
9040 }
9041
9042 // If this is not a friend, note that this is an explicit specialization.
9043 if (TUK != TagUseKind::Friend)
9044 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9045
9046 // Check that this isn't a redefinition of this specialization.
9047 if (TUK == TagUseKind::Definition) {
9048 RecordDecl *Def = Specialization->getDefinition();
9049 NamedDecl *Hidden = nullptr;
9050 bool HiddenDefVisible = false;
9051 if (Def && SkipBody &&
9052 isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible)) {
9053 SkipBody->ShouldSkip = true;
9054 SkipBody->Previous = Def;
9055 if (!HiddenDefVisible && Hidden)
9056 makeMergedDefinitionVisible(ND: Hidden);
9057 } else if (Def) {
9058 SourceRange Range(TemplateNameLoc, RAngleLoc);
9059 Diag(Loc: TemplateNameLoc, DiagID: diag::err_redefinition) << Specialization << Range;
9060 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
9061 Specialization->setInvalidDecl();
9062 return true;
9063 }
9064 }
9065
9066 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
9067 ProcessAPINotes(D: Specialization);
9068
9069 // Add alignment attributes if necessary; these attributes are checked when
9070 // the ASTContext lays out the structure.
9071 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9072 if (LangOpts.HLSL)
9073 Specialization->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
9074 AddAlignmentAttributesForRecord(RD: Specialization);
9075 AddMsStructLayoutForRecord(RD: Specialization);
9076 }
9077
9078 if (ModulePrivateLoc.isValid())
9079 Diag(Loc: Specialization->getLocation(), DiagID: diag::err_module_private_specialization)
9080 << (isPartialSpecialization? 1 : 0)
9081 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
9082
9083 // C++ [temp.expl.spec]p9:
9084 // A template explicit specialization is in the scope of the
9085 // namespace in which the template was defined.
9086 //
9087 // We actually implement this paragraph where we set the semantic
9088 // context (in the creation of the ClassTemplateSpecializationDecl),
9089 // but we also maintain the lexical context where the actual
9090 // definition occurs.
9091 Specialization->setLexicalDeclContext(CurContext);
9092
9093 // We may be starting the definition of this specialization.
9094 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9095 Specialization->startDefinition();
9096
9097 if (TUK == TagUseKind::Friend) {
9098 CanQualType CanonType = Context.getCanonicalTagType(TD: Specialization);
9099 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9100 Keyword: ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9101 QualifierLoc: SS.getWithLocInContext(Context),
9102 /*TemplateKeywordLoc=*/SourceLocation(), T: Name, TLoc: TemplateNameLoc,
9103 SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted, Canon: CanonType);
9104
9105 // Build the fully-sugared type for this class template
9106 // specialization as the user wrote in the specialization
9107 // itself. This means that we'll pretty-print the type retrieved
9108 // from the specialization's declaration the way that the user
9109 // actually wrote the specialization, rather than formatting the
9110 // name based on the "canonical" representation used to store the
9111 // template arguments in the specialization.
9112 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext,
9113 L: TemplateNameLoc,
9114 Friend_: WrittenTy,
9115 /*FIXME:*/FriendL: KWLoc);
9116 Friend->setAccess(AS_public);
9117 CurContext->addDecl(D: Friend);
9118 } else {
9119 // Add the specialization into its lexical context, so that it can
9120 // be seen when iterating through the list of declarations in that
9121 // context. However, specializations are not found by name lookup.
9122 CurContext->addDecl(D: Specialization);
9123 }
9124
9125 if (SkipBody && SkipBody->ShouldSkip)
9126 return SkipBody->Previous;
9127
9128 Specialization->setInvalidDecl(Invalid);
9129 inferGslOwnerPointerAttribute(Record: Specialization);
9130 return Specialization;
9131}
9132
9133Decl *Sema::ActOnTemplateDeclarator(Scope *S,
9134 MultiTemplateParamsArg TemplateParameterLists,
9135 Declarator &D) {
9136 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9137 ActOnDocumentableDecl(D: NewDecl);
9138 return NewDecl;
9139}
9140
9141ConceptDecl *Sema::ActOnStartConceptDefinition(
9142 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9143 const IdentifierInfo *Name, SourceLocation NameLoc) {
9144 DeclContext *DC = CurContext;
9145
9146 if (!DC->getRedeclContext()->isFileContext()) {
9147 Diag(Loc: NameLoc,
9148 DiagID: diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9149 return nullptr;
9150 }
9151
9152 if (TemplateParameterLists.size() > 1) {
9153 Diag(Loc: NameLoc, DiagID: diag::err_concept_extra_headers);
9154 return nullptr;
9155 }
9156
9157 TemplateParameterList *Params = TemplateParameterLists.front();
9158
9159 if (Params->size() == 0) {
9160 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_parameters);
9161 return nullptr;
9162 }
9163
9164 // Ensure that the parameter pack, if present, is the last parameter in the
9165 // template.
9166 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9167 ParamEnd = Params->end();
9168 ParamIt != ParamEnd; ++ParamIt) {
9169 Decl const *Param = *ParamIt;
9170 if (Param->isParameterPack()) {
9171 if (++ParamIt == ParamEnd)
9172 break;
9173 Diag(Loc: Param->getLocation(),
9174 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
9175 return nullptr;
9176 }
9177 }
9178
9179 ConceptDecl *NewDecl =
9180 ConceptDecl::Create(C&: Context, DC, L: NameLoc, Name, Params);
9181
9182 if (NewDecl->hasAssociatedConstraints()) {
9183 // C++2a [temp.concept]p4:
9184 // A concept shall not have associated constraints.
9185 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_associated_constraints);
9186 NewDecl->setInvalidDecl();
9187 }
9188
9189 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9190 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9191 forRedeclarationInCurContext());
9192 LookupName(R&: Previous, S);
9193 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9194 /*AllowInlineNamespace*/ false);
9195
9196 // We cannot properly handle redeclarations until we parse the constraint
9197 // expression, so only inject the name if we are sure we are not redeclaring a
9198 // symbol
9199 if (Previous.empty())
9200 PushOnScopeChains(D: NewDecl, S, AddToContext: true);
9201
9202 return NewDecl;
9203}
9204
9205static bool RemoveLookupResult(LookupResult &R, NamedDecl *C) {
9206 bool Found = false;
9207 LookupResult::Filter F = R.makeFilter();
9208 while (F.hasNext()) {
9209 NamedDecl *D = F.next();
9210 if (D == C) {
9211 F.erase();
9212 Found = true;
9213 break;
9214 }
9215 }
9216 F.done();
9217 return Found;
9218}
9219
9220ConceptDecl *
9221Sema::ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
9222 Expr *ConstraintExpr,
9223 const ParsedAttributesView &Attrs) {
9224 assert(!C->hasDefinition() && "Concept already defined");
9225 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr)) {
9226 C->setInvalidDecl();
9227 return nullptr;
9228 }
9229 C->setDefinition(ConstraintExpr);
9230 ProcessDeclAttributeList(S, D: C, AttrList: Attrs);
9231
9232 // Check for conflicting previous declaration.
9233 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9234 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9235 forRedeclarationInCurContext());
9236 LookupName(R&: Previous, S);
9237 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9238 /*AllowInlineNamespace*/ false);
9239 bool WasAlreadyAdded = RemoveLookupResult(R&: Previous, C);
9240 bool AddToScope = true;
9241 CheckConceptRedefinition(NewDecl: C, Previous, AddToScope);
9242
9243 ActOnDocumentableDecl(D: C);
9244 if (!WasAlreadyAdded && AddToScope)
9245 PushOnScopeChains(D: C, S);
9246
9247 return C;
9248}
9249
9250void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
9251 LookupResult &Previous, bool &AddToScope) {
9252 AddToScope = true;
9253
9254 if (Previous.empty())
9255 return;
9256
9257 auto *OldConcept = dyn_cast<ConceptDecl>(Val: Previous.getRepresentativeDecl()->getUnderlyingDecl());
9258 if (!OldConcept) {
9259 auto *Old = Previous.getRepresentativeDecl();
9260 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_kind)
9261 << NewDecl->getDeclName();
9262 notePreviousDefinition(Old, New: NewDecl->getLocation());
9263 AddToScope = false;
9264 return;
9265 }
9266 // Check if we can merge with a concept declaration.
9267 bool IsSame = Context.isSameEntity(X: NewDecl, Y: OldConcept);
9268 if (!IsSame) {
9269 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_concept)
9270 << NewDecl->getDeclName();
9271 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9272 AddToScope = false;
9273 return;
9274 }
9275 if (hasReachableDefinition(D: OldConcept) &&
9276 IsRedefinitionInModule(New: NewDecl, Old: OldConcept)) {
9277 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition)
9278 << NewDecl->getDeclName();
9279 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9280 AddToScope = false;
9281 return;
9282 }
9283 if (!Previous.isSingleResult()) {
9284 // FIXME: we should produce an error in case of ambig and failed lookups.
9285 // Other decls (e.g. namespaces) also have this shortcoming.
9286 return;
9287 }
9288 // We unwrap canonical decl late to check for module visibility.
9289 Context.setPrimaryMergedDecl(D: NewDecl, Primary: OldConcept->getCanonicalDecl());
9290}
9291
9292bool Sema::CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc) {
9293 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Val: Concept);
9294 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9295 Diag(Loc, DiagID: diag::err_recursive_concept) << CE;
9296 Diag(Loc: CE->getLocation(), DiagID: diag::note_declared_at);
9297 return true;
9298 }
9299 // Concept template parameters don't have a definition and can't
9300 // be defined recursively.
9301 return false;
9302}
9303
9304/// \brief Strips various properties off an implicit instantiation
9305/// that has just been explicitly specialized.
9306static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9307 if (MinGW || (isa<FunctionDecl>(Val: D) &&
9308 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization()))
9309 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9310
9311 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D))
9312 FD->setInlineSpecified(false);
9313}
9314
9315/// Compute the diagnostic location for an explicit instantiation
9316// declaration or definition.
9317static SourceLocation DiagLocForExplicitInstantiation(
9318 NamedDecl* D, SourceLocation PointOfInstantiation) {
9319 // Explicit instantiations following a specialization have no effect and
9320 // hence no PointOfInstantiation. In that case, walk decl backwards
9321 // until a valid name loc is found.
9322 SourceLocation PrevDiagLoc = PointOfInstantiation;
9323 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9324 Prev = Prev->getPreviousDecl()) {
9325 PrevDiagLoc = Prev->getLocation();
9326 }
9327 assert(PrevDiagLoc.isValid() &&
9328 "Explicit instantiation without point of instantiation?");
9329 return PrevDiagLoc;
9330}
9331
9332bool
9333Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
9334 TemplateSpecializationKind NewTSK,
9335 NamedDecl *PrevDecl,
9336 TemplateSpecializationKind PrevTSK,
9337 SourceLocation PrevPointOfInstantiation,
9338 bool &HasNoEffect) {
9339 HasNoEffect = false;
9340
9341 switch (NewTSK) {
9342 case TSK_Undeclared:
9343 case TSK_ImplicitInstantiation:
9344 assert(
9345 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9346 "previous declaration must be implicit!");
9347 return false;
9348
9349 case TSK_ExplicitSpecialization:
9350 switch (PrevTSK) {
9351 case TSK_Undeclared:
9352 case TSK_ExplicitSpecialization:
9353 // Okay, we're just specializing something that is either already
9354 // explicitly specialized or has merely been mentioned without any
9355 // instantiation.
9356 return false;
9357
9358 case TSK_ImplicitInstantiation:
9359 if (PrevPointOfInstantiation.isInvalid()) {
9360 // The declaration itself has not actually been instantiated, so it is
9361 // still okay to specialize it.
9362 StripImplicitInstantiation(
9363 D: PrevDecl, MinGW: Context.getTargetInfo().getTriple().isOSCygMing());
9364 return false;
9365 }
9366 // Fall through
9367 [[fallthrough]];
9368
9369 case TSK_ExplicitInstantiationDeclaration:
9370 case TSK_ExplicitInstantiationDefinition:
9371 assert((PrevTSK == TSK_ImplicitInstantiation ||
9372 PrevPointOfInstantiation.isValid()) &&
9373 "Explicit instantiation without point of instantiation?");
9374
9375 // C++ [temp.expl.spec]p6:
9376 // If a template, a member template or the member of a class template
9377 // is explicitly specialized then that specialization shall be declared
9378 // before the first use of that specialization that would cause an
9379 // implicit instantiation to take place, in every translation unit in
9380 // which such a use occurs; no diagnostic is required.
9381 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9382 // Is there any previous explicit specialization declaration?
9383 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization)
9384 return false;
9385 }
9386
9387 Diag(Loc: NewLoc, DiagID: diag::err_specialization_after_instantiation)
9388 << PrevDecl;
9389 Diag(Loc: PrevPointOfInstantiation, DiagID: diag::note_instantiation_required_here)
9390 << (PrevTSK != TSK_ImplicitInstantiation);
9391
9392 return true;
9393 }
9394 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9395
9396 case TSK_ExplicitInstantiationDeclaration:
9397 switch (PrevTSK) {
9398 case TSK_ExplicitInstantiationDeclaration:
9399 // This explicit instantiation declaration is redundant (that's okay).
9400 HasNoEffect = true;
9401 return false;
9402
9403 case TSK_Undeclared:
9404 case TSK_ImplicitInstantiation:
9405 // We're explicitly instantiating something that may have already been
9406 // implicitly instantiated; that's fine.
9407 return false;
9408
9409 case TSK_ExplicitSpecialization:
9410 // C++0x [temp.explicit]p4:
9411 // For a given set of template parameters, if an explicit instantiation
9412 // of a template appears after a declaration of an explicit
9413 // specialization for that template, the explicit instantiation has no
9414 // effect.
9415 HasNoEffect = true;
9416 return false;
9417
9418 case TSK_ExplicitInstantiationDefinition:
9419 // C++0x [temp.explicit]p10:
9420 // If an entity is the subject of both an explicit instantiation
9421 // declaration and an explicit instantiation definition in the same
9422 // translation unit, the definition shall follow the declaration.
9423 Diag(Loc: NewLoc,
9424 DiagID: diag::err_explicit_instantiation_declaration_after_definition);
9425
9426 // Explicit instantiations following a specialization have no effect and
9427 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9428 // until a valid name loc is found.
9429 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9430 DiagID: diag::note_explicit_instantiation_definition_here);
9431 HasNoEffect = true;
9432 return false;
9433 }
9434 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9435
9436 case TSK_ExplicitInstantiationDefinition:
9437 switch (PrevTSK) {
9438 case TSK_Undeclared:
9439 case TSK_ImplicitInstantiation:
9440 // We're explicitly instantiating something that may have already been
9441 // implicitly instantiated; that's fine.
9442 return false;
9443
9444 case TSK_ExplicitSpecialization:
9445 // C++ DR 259, C++0x [temp.explicit]p4:
9446 // For a given set of template parameters, if an explicit
9447 // instantiation of a template appears after a declaration of
9448 // an explicit specialization for that template, the explicit
9449 // instantiation has no effect.
9450 Diag(Loc: NewLoc, DiagID: diag::warn_explicit_instantiation_after_specialization)
9451 << PrevDecl;
9452 Diag(Loc: PrevDecl->getLocation(),
9453 DiagID: diag::note_previous_template_specialization);
9454 HasNoEffect = true;
9455 return false;
9456
9457 case TSK_ExplicitInstantiationDeclaration:
9458 // We're explicitly instantiating a definition for something for which we
9459 // were previously asked to suppress instantiations. That's fine.
9460
9461 // C++0x [temp.explicit]p4:
9462 // For a given set of template parameters, if an explicit instantiation
9463 // of a template appears after a declaration of an explicit
9464 // specialization for that template, the explicit instantiation has no
9465 // effect.
9466 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9467 // Is there any previous explicit specialization declaration?
9468 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9469 HasNoEffect = true;
9470 break;
9471 }
9472 }
9473
9474 return false;
9475
9476 case TSK_ExplicitInstantiationDefinition:
9477 // C++0x [temp.spec]p5:
9478 // For a given template and a given set of template-arguments,
9479 // - an explicit instantiation definition shall appear at most once
9480 // in a program,
9481
9482 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9483 Diag(Loc: NewLoc, DiagID: (getLangOpts().MSVCCompat)
9484 ? diag::ext_explicit_instantiation_duplicate
9485 : diag::err_explicit_instantiation_duplicate)
9486 << PrevDecl;
9487 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9488 DiagID: diag::note_previous_explicit_instantiation);
9489 HasNoEffect = true;
9490 return false;
9491 }
9492 }
9493
9494 llvm_unreachable("Missing specialization/instantiation case?");
9495}
9496
9497bool Sema::CheckDependentFunctionTemplateSpecialization(
9498 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9499 LookupResult &Previous) {
9500 // Remove anything from Previous that isn't a function template in
9501 // the correct context.
9502 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9503 LookupResult::Filter F = Previous.makeFilter();
9504 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9505 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9506 while (F.hasNext()) {
9507 NamedDecl *D = F.next()->getUnderlyingDecl();
9508 if (!isa<FunctionTemplateDecl>(Val: D)) {
9509 F.erase();
9510 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAFunctionTemplate, y&: D));
9511 continue;
9512 }
9513
9514 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9515 NS: D->getDeclContext()->getRedeclContext())) {
9516 F.erase();
9517 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAMemberOfEnclosing, y&: D));
9518 continue;
9519 }
9520 }
9521 F.done();
9522
9523 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9524 if (Previous.empty()) {
9525 Diag(Loc: FD->getLocation(), DiagID: diag::err_dependent_function_template_spec_no_match)
9526 << IsFriend;
9527 for (auto &P : DiscardedCandidates)
9528 Diag(Loc: P.second->getLocation(),
9529 DiagID: diag::note_dependent_function_template_spec_discard_reason)
9530 << P.first << IsFriend;
9531 return true;
9532 }
9533
9534 FD->setDependentTemplateSpecialization(Context, Templates: Previous.asUnresolvedSet(),
9535 TemplateArgs: ExplicitTemplateArgs);
9536 return false;
9537}
9538
9539bool Sema::CheckFunctionTemplateSpecialization(
9540 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9541 LookupResult &Previous, bool QualifiedFriend) {
9542 // The set of function template specializations that could match this
9543 // explicit function template specialization.
9544 UnresolvedSet<8> Candidates;
9545 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9546 /*ForTakingAddress=*/false);
9547
9548 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9549 ConvertedTemplateArgs;
9550
9551 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9552 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9553 I != E; ++I) {
9554 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9555 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Ovl)) {
9556 // Only consider templates found within the same semantic lookup scope as
9557 // FD.
9558 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9559 NS: Ovl->getDeclContext()->getRedeclContext()))
9560 continue;
9561
9562 QualType FT = FD->getType();
9563 // C++11 [dcl.constexpr]p8:
9564 // A constexpr specifier for a non-static member function that is not
9565 // a constructor declares that member function to be const.
9566 //
9567 // When matching a constexpr member function template specialization
9568 // against the primary template, we don't yet know whether the
9569 // specialization has an implicit 'const' (because we don't know whether
9570 // it will be a static member function until we know which template it
9571 // specializes). This rule was removed in C++14.
9572 if (auto *NewMD = dyn_cast<CXXMethodDecl>(Val: FD);
9573 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9574 !isa<CXXConstructorDecl, CXXDestructorDecl>(Val: NewMD)) {
9575 auto *OldMD = dyn_cast<CXXMethodDecl>(Val: FunTmpl->getTemplatedDecl());
9576 if (OldMD && OldMD->isConst()) {
9577 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9578 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9579 EPI.TypeQuals.addConst();
9580 FT = Context.getFunctionType(ResultTy: FPT->getReturnType(),
9581 Args: FPT->getParamTypes(), EPI);
9582 }
9583 }
9584
9585 TemplateArgumentListInfo Args;
9586 if (ExplicitTemplateArgs)
9587 Args = *ExplicitTemplateArgs;
9588
9589 // C++ [temp.expl.spec]p11:
9590 // A trailing template-argument can be left unspecified in the
9591 // template-id naming an explicit function template specialization
9592 // provided it can be deduced from the function argument type.
9593 // Perform template argument deduction to determine whether we may be
9594 // specializing this template.
9595 // FIXME: It is somewhat wasteful to build
9596 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9597 FunctionDecl *Specialization = nullptr;
9598 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9599 FunctionTemplate: cast<FunctionTemplateDecl>(Val: FunTmpl->getFirstDecl()),
9600 ExplicitTemplateArgs: ExplicitTemplateArgs ? &Args : nullptr, ArgFunctionType: FT, Specialization, Info);
9601 TDK != TemplateDeductionResult::Success) {
9602 // Template argument deduction failed; record why it failed, so
9603 // that we can provide nifty diagnostics.
9604 FailedCandidates.addCandidate().set(
9605 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9606 Info: MakeDeductionFailureInfo(Context, TDK, Info));
9607 (void)TDK;
9608 continue;
9609 }
9610
9611 // Target attributes are part of the cuda function signature, so
9612 // the deduced template's cuda target must match that of the
9613 // specialization. Given that C++ template deduction does not
9614 // take target attributes into account, we reject candidates
9615 // here that have a different target.
9616 if (LangOpts.CUDA &&
9617 CUDA().IdentifyTarget(D: Specialization,
9618 /* IgnoreImplicitHDAttr = */ true) !=
9619 CUDA().IdentifyTarget(D: FD, /* IgnoreImplicitHDAttr = */ true)) {
9620 FailedCandidates.addCandidate().set(
9621 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9622 Info: MakeDeductionFailureInfo(
9623 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
9624 continue;
9625 }
9626
9627 // Record this candidate.
9628 if (ExplicitTemplateArgs)
9629 ConvertedTemplateArgs[Specialization] = std::move(Args);
9630 Candidates.addDecl(D: Specialization, AS: I.getAccess());
9631 }
9632 }
9633
9634 // For a qualified friend declaration (with no explicit marker to indicate
9635 // that a template specialization was intended), note all (template and
9636 // non-template) candidates.
9637 if (QualifiedFriend && Candidates.empty()) {
9638 Diag(Loc: FD->getLocation(), DiagID: diag::err_qualified_friend_no_match)
9639 << FD->getDeclName() << FDLookupContext;
9640 // FIXME: We should form a single candidate list and diagnose all
9641 // candidates at once, to get proper sorting and limiting.
9642 for (auto *OldND : Previous) {
9643 if (auto *OldFD = dyn_cast<FunctionDecl>(Val: OldND->getUnderlyingDecl()))
9644 NoteOverloadCandidate(Found: OldND, Fn: OldFD, RewriteKind: CRK_None, DestType: FD->getType(), TakingAddress: false);
9645 }
9646 FailedCandidates.NoteCandidates(S&: *this, Loc: FD->getLocation());
9647 return true;
9648 }
9649
9650 // Find the most specialized function template.
9651 UnresolvedSetIterator Result = getMostSpecialized(
9652 SBegin: Candidates.begin(), SEnd: Candidates.end(), FailedCandidates, Loc: FD->getLocation(),
9653 NoneDiag: PDiag(DiagID: diag::err_function_template_spec_no_match) << FD->getDeclName(),
9654 AmbigDiag: PDiag(DiagID: diag::err_function_template_spec_ambiguous)
9655 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9656 CandidateDiag: PDiag(DiagID: diag::note_function_template_spec_matched));
9657
9658 if (Result == Candidates.end())
9659 return true;
9660
9661 // Ignore access information; it doesn't figure into redeclaration checking.
9662 FunctionDecl *Specialization = cast<FunctionDecl>(Val: *Result);
9663
9664 if (const auto *PT = Specialization->getPrimaryTemplate();
9665 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9666 auto Message = DSA->getMessage();
9667 Diag(Loc: FD->getLocation(), DiagID: diag::warn_invalid_specialization)
9668 << PT << !Message.empty() << Message;
9669 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
9670 }
9671
9672 // C++23 [except.spec]p13:
9673 // An exception specification is considered to be needed when:
9674 // - [...]
9675 // - the exception specification is compared to that of another declaration
9676 // (e.g., an explicit specialization or an overriding virtual function);
9677 // - [...]
9678 //
9679 // The exception specification of a defaulted function is evaluated as
9680 // described above only when needed; similarly, the noexcept-specifier of a
9681 // specialization of a function template or member function of a class
9682 // template is instantiated only when needed.
9683 //
9684 // The standard doesn't specify what the "comparison with another declaration"
9685 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9686 // not state which properties of an explicit specialization must match the
9687 // primary template.
9688 //
9689 // We assume that an explicit specialization must correspond with (per
9690 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9691 // the declaration produced by substitution into the function template.
9692 //
9693 // Since the determination whether two function declarations correspond does
9694 // not consider exception specification, we only need to instantiate it once
9695 // we determine the primary template when comparing types per
9696 // [basic.link]p11.1.
9697 auto *SpecializationFPT =
9698 Specialization->getType()->castAs<FunctionProtoType>();
9699 // If the function has a dependent exception specification, resolve it after
9700 // we have selected the primary template so we can check whether it matches.
9701 if (getLangOpts().CPlusPlus17 &&
9702 isUnresolvedExceptionSpec(ESpecType: SpecializationFPT->getExceptionSpecType()) &&
9703 !ResolveExceptionSpec(Loc: FD->getLocation(), FPT: SpecializationFPT))
9704 return true;
9705
9706 FunctionTemplateSpecializationInfo *SpecInfo
9707 = Specialization->getTemplateSpecializationInfo();
9708 assert(SpecInfo && "Function template specialization info missing?");
9709
9710 // Note: do not overwrite location info if previous template
9711 // specialization kind was explicit.
9712 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9713 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9714 Specialization->setLocation(FD->getLocation());
9715 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9716 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9717 // function can differ from the template declaration with respect to
9718 // the constexpr specifier.
9719 // FIXME: We need an update record for this AST mutation.
9720 // FIXME: What if there are multiple such prior declarations (for instance,
9721 // from different modules)?
9722 Specialization->setConstexprKind(FD->getConstexprKind());
9723 }
9724
9725 // FIXME: Check if the prior specialization has a point of instantiation.
9726 // If so, we have run afoul of .
9727
9728 // If this is a friend declaration, then we're not really declaring
9729 // an explicit specialization.
9730 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9731
9732 // Check the scope of this explicit specialization.
9733 if (!isFriend &&
9734 CheckTemplateSpecializationScope(S&: *this,
9735 Specialized: Specialization->getPrimaryTemplate(),
9736 PrevDecl: Specialization, Loc: FD->getLocation(),
9737 IsPartialSpecialization: false))
9738 return true;
9739
9740 // C++ [temp.expl.spec]p6:
9741 // If a template, a member template or the member of a class template is
9742 // explicitly specialized then that specialization shall be declared
9743 // before the first use of that specialization that would cause an implicit
9744 // instantiation to take place, in every translation unit in which such a
9745 // use occurs; no diagnostic is required.
9746 bool HasNoEffect = false;
9747 if (!isFriend &&
9748 CheckSpecializationInstantiationRedecl(NewLoc: FD->getLocation(),
9749 NewTSK: TSK_ExplicitSpecialization,
9750 PrevDecl: Specialization,
9751 PrevTSK: SpecInfo->getTemplateSpecializationKind(),
9752 PrevPointOfInstantiation: SpecInfo->getPointOfInstantiation(),
9753 HasNoEffect))
9754 return true;
9755
9756 // Mark the prior declaration as an explicit specialization, so that later
9757 // clients know that this is an explicit specialization.
9758 // A dependent friend specialization which has a definition should be treated
9759 // as explicit specialization, despite being invalid.
9760 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9761 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9762 // Since explicit specializations do not inherit '=delete' from their
9763 // primary function template - check if the 'specialization' that was
9764 // implicitly generated (during template argument deduction for partial
9765 // ordering) from the most specialized of all the function templates that
9766 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9767 // first check that it was implicitly generated during template argument
9768 // deduction by making sure it wasn't referenced, and then reset the deleted
9769 // flag to not-deleted, so that we can inherit that information from 'FD'.
9770 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9771 !Specialization->getCanonicalDecl()->isReferenced()) {
9772 // FIXME: This assert will not hold in the presence of modules.
9773 assert(
9774 Specialization->getCanonicalDecl() == Specialization &&
9775 "This must be the only existing declaration of this specialization");
9776 // FIXME: We need an update record for this AST mutation.
9777 Specialization->setDeletedAsWritten(D: false);
9778 }
9779 // FIXME: We need an update record for this AST mutation.
9780 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9781 MarkUnusedFileScopedDecl(D: Specialization);
9782 }
9783
9784 // Turn the given function declaration into a function template
9785 // specialization, with the template arguments from the previous
9786 // specialization.
9787 // Take copies of (semantic and syntactic) template argument lists.
9788 TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy(
9789 Context, Args: Specialization->getTemplateSpecializationArgs()->asArray());
9790 FD->setFunctionTemplateSpecialization(
9791 Template: Specialization->getPrimaryTemplate(), TemplateArgs: TemplArgs, /*InsertPos=*/nullptr,
9792 TSK: SpecInfo->getTemplateSpecializationKind(),
9793 TemplateArgsAsWritten: ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9794
9795 // A function template specialization inherits the target attributes
9796 // of its template. (We require the attributes explicitly in the
9797 // code to match, but a template may have implicit attributes by
9798 // virtue e.g. of being constexpr, and it passes these implicit
9799 // attributes on to its specializations.)
9800 if (LangOpts.CUDA)
9801 CUDA().inheritTargetAttrs(FD, TD: *Specialization->getPrimaryTemplate());
9802
9803 // The "previous declaration" for this function template specialization is
9804 // the prior function template specialization.
9805 Previous.clear();
9806 Previous.addDecl(D: Specialization);
9807 return false;
9808}
9809
9810bool
9811Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9812 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9813 "Only for non-template members");
9814
9815 // Try to find the member we are instantiating.
9816 NamedDecl *FoundInstantiation = nullptr;
9817 NamedDecl *Instantiation = nullptr;
9818 NamedDecl *InstantiatedFrom = nullptr;
9819 MemberSpecializationInfo *MSInfo = nullptr;
9820
9821 if (Previous.empty()) {
9822 // Nowhere to look anyway.
9823 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Member)) {
9824 UnresolvedSet<8> Candidates;
9825 for (NamedDecl *Candidate : Previous) {
9826 auto *Method = dyn_cast<CXXMethodDecl>(Val: Candidate->getUnderlyingDecl());
9827 // Ignore any candidates that aren't member functions.
9828 if (!Method)
9829 continue;
9830
9831 QualType Adjusted = Function->getType();
9832 if (!hasExplicitCallingConv(T: Adjusted))
9833 Adjusted = adjustCCAndNoReturn(ArgFunctionType: Adjusted, FunctionType: Method->getType());
9834 // Ignore any candidates with the wrong type.
9835 // This doesn't handle deduced return types, but both function
9836 // declarations should be undeduced at this point.
9837 // FIXME: The exception specification should probably be ignored when
9838 // comparing the types.
9839 if (!Context.hasSameType(T1: Adjusted, T2: Method->getType()))
9840 continue;
9841
9842 // Ignore any candidates with unsatisfied constraints.
9843 if (ConstraintSatisfaction Satisfaction;
9844 Method->getTrailingRequiresClause() &&
9845 (CheckFunctionConstraints(FD: Method, Satisfaction,
9846 /*UsageLoc=*/Member->getLocation(),
9847 /*ForOverloadResolution=*/true) ||
9848 !Satisfaction.IsSatisfied))
9849 continue;
9850
9851 Candidates.addDecl(D: Candidate);
9852 }
9853
9854 // If we have no viable candidates left after filtering, we are done.
9855 if (Candidates.empty())
9856 return false;
9857
9858 // Find the function that is more constrained than every other function it
9859 // has been compared to.
9860 UnresolvedSetIterator Best = Candidates.begin();
9861 CXXMethodDecl *BestMethod = nullptr;
9862 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9863 I != E; ++I) {
9864 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9865 if (I == Best ||
9866 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) == Method) {
9867 Best = I;
9868 BestMethod = Method;
9869 }
9870 }
9871
9872 FoundInstantiation = *Best;
9873 Instantiation = BestMethod;
9874 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9875 MSInfo = BestMethod->getMemberSpecializationInfo();
9876
9877 // Make sure the best candidate is more constrained than all of the others.
9878 bool Ambiguous = false;
9879 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9880 I != E; ++I) {
9881 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9882 if (I != Best &&
9883 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) != BestMethod) {
9884 Ambiguous = true;
9885 break;
9886 }
9887 }
9888
9889 if (Ambiguous) {
9890 Diag(Loc: Member->getLocation(), DiagID: diag::err_function_member_spec_ambiguous)
9891 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9892 for (NamedDecl *Candidate : Candidates) {
9893 Candidate = Candidate->getUnderlyingDecl();
9894 Diag(Loc: Candidate->getLocation(), DiagID: diag::note_function_member_spec_matched)
9895 << Candidate;
9896 }
9897 return true;
9898 }
9899 } else if (isa<VarDecl>(Val: Member)) {
9900 VarDecl *PrevVar;
9901 if (Previous.isSingleResult() &&
9902 (PrevVar = dyn_cast<VarDecl>(Val: Previous.getFoundDecl())))
9903 if (PrevVar->isStaticDataMember()) {
9904 FoundInstantiation = Previous.getRepresentativeDecl();
9905 Instantiation = PrevVar;
9906 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9907 MSInfo = PrevVar->getMemberSpecializationInfo();
9908 }
9909 } else if (isa<RecordDecl>(Val: Member)) {
9910 CXXRecordDecl *PrevRecord;
9911 if (Previous.isSingleResult() &&
9912 (PrevRecord = dyn_cast<CXXRecordDecl>(Val: Previous.getFoundDecl()))) {
9913 FoundInstantiation = Previous.getRepresentativeDecl();
9914 Instantiation = PrevRecord;
9915 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9916 MSInfo = PrevRecord->getMemberSpecializationInfo();
9917 }
9918 } else if (isa<EnumDecl>(Val: Member)) {
9919 EnumDecl *PrevEnum;
9920 if (Previous.isSingleResult() &&
9921 (PrevEnum = dyn_cast<EnumDecl>(Val: Previous.getFoundDecl()))) {
9922 FoundInstantiation = Previous.getRepresentativeDecl();
9923 Instantiation = PrevEnum;
9924 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9925 MSInfo = PrevEnum->getMemberSpecializationInfo();
9926 }
9927 }
9928
9929 if (!Instantiation) {
9930 // There is no previous declaration that matches. Since member
9931 // specializations are always out-of-line, the caller will complain about
9932 // this mismatch later.
9933 return false;
9934 }
9935
9936 // A member specialization in a friend declaration isn't really declaring
9937 // an explicit specialization, just identifying a specific (possibly implicit)
9938 // specialization. Don't change the template specialization kind.
9939 //
9940 // FIXME: Is this really valid? Other compilers reject.
9941 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9942 // Preserve instantiation information.
9943 if (InstantiatedFrom && isa<CXXMethodDecl>(Val: Member)) {
9944 cast<CXXMethodDecl>(Val: Member)->setInstantiationOfMemberFunction(
9945 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom),
9946 TSK: cast<CXXMethodDecl>(Val: Instantiation)->getTemplateSpecializationKind());
9947 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Val: Member)) {
9948 cast<CXXRecordDecl>(Val: Member)->setInstantiationOfMemberClass(
9949 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom),
9950 TSK: cast<CXXRecordDecl>(Val: Instantiation)->getTemplateSpecializationKind());
9951 }
9952
9953 Previous.clear();
9954 Previous.addDecl(D: FoundInstantiation);
9955 return false;
9956 }
9957
9958 // Make sure that this is a specialization of a member.
9959 if (!InstantiatedFrom) {
9960 Diag(Loc: Member->getLocation(), DiagID: diag::err_spec_member_not_instantiated)
9961 << Member;
9962 Diag(Loc: Instantiation->getLocation(), DiagID: diag::note_specialized_decl);
9963 return true;
9964 }
9965
9966 // C++ [temp.expl.spec]p6:
9967 // If a template, a member template or the member of a class template is
9968 // explicitly specialized then that specialization shall be declared
9969 // before the first use of that specialization that would cause an implicit
9970 // instantiation to take place, in every translation unit in which such a
9971 // use occurs; no diagnostic is required.
9972 assert(MSInfo && "Member specialization info missing?");
9973
9974 bool HasNoEffect = false;
9975 if (CheckSpecializationInstantiationRedecl(NewLoc: Member->getLocation(),
9976 NewTSK: TSK_ExplicitSpecialization,
9977 PrevDecl: Instantiation,
9978 PrevTSK: MSInfo->getTemplateSpecializationKind(),
9979 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
9980 HasNoEffect))
9981 return true;
9982
9983 // Check the scope of this explicit specialization.
9984 if (CheckTemplateSpecializationScope(S&: *this,
9985 Specialized: InstantiatedFrom,
9986 PrevDecl: Instantiation, Loc: Member->getLocation(),
9987 IsPartialSpecialization: false))
9988 return true;
9989
9990 // Note that this member specialization is an "instantiation of" the
9991 // corresponding member of the original template.
9992 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Val: Member)) {
9993 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Val: Instantiation);
9994 if (InstantiationFunction->getTemplateSpecializationKind() ==
9995 TSK_ImplicitInstantiation) {
9996 // Explicit specializations of member functions of class templates do not
9997 // inherit '=delete' from the member function they are specializing.
9998 if (InstantiationFunction->isDeleted()) {
9999 // FIXME: This assert will not hold in the presence of modules.
10000 assert(InstantiationFunction->getCanonicalDecl() ==
10001 InstantiationFunction);
10002 // FIXME: We need an update record for this AST mutation.
10003 InstantiationFunction->setDeletedAsWritten(D: false);
10004 }
10005 }
10006
10007 MemberFunction->setInstantiationOfMemberFunction(
10008 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10009 } else if (auto *MemberVar = dyn_cast<VarDecl>(Val: Member)) {
10010 MemberVar->setInstantiationOfStaticDataMember(
10011 VD: cast<VarDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10012 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Val: Member)) {
10013 MemberClass->setInstantiationOfMemberClass(
10014 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10015 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Val: Member)) {
10016 MemberEnum->setInstantiationOfMemberEnum(
10017 ED: cast<EnumDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10018 } else {
10019 llvm_unreachable("unknown member specialization kind");
10020 }
10021
10022 // Save the caller the trouble of having to figure out which declaration
10023 // this specialization matches.
10024 Previous.clear();
10025 Previous.addDecl(D: FoundInstantiation);
10026 return false;
10027}
10028
10029/// Complete the explicit specialization of a member of a class template by
10030/// updating the instantiated member to be marked as an explicit specialization.
10031///
10032/// \param OrigD The member declaration instantiated from the template.
10033/// \param Loc The location of the explicit specialization of the member.
10034template<typename DeclT>
10035static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10036 SourceLocation Loc) {
10037 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10038 return;
10039
10040 // FIXME: Inform AST mutation listeners of this AST mutation.
10041 // FIXME: If there are multiple in-class declarations of the member (from
10042 // multiple modules, or a declaration and later definition of a member type),
10043 // should we update all of them?
10044 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10045 OrigD->setLocation(Loc);
10046}
10047
10048void Sema::CompleteMemberSpecialization(NamedDecl *Member,
10049 LookupResult &Previous) {
10050 NamedDecl *Instantiation = cast<NamedDecl>(Val: Member->getCanonicalDecl());
10051 if (Instantiation == Member)
10052 return;
10053
10054 if (auto *Function = dyn_cast<CXXMethodDecl>(Val: Instantiation))
10055 completeMemberSpecializationImpl(S&: *this, OrigD: Function, Loc: Member->getLocation());
10056 else if (auto *Var = dyn_cast<VarDecl>(Val: Instantiation))
10057 completeMemberSpecializationImpl(S&: *this, OrigD: Var, Loc: Member->getLocation());
10058 else if (auto *Record = dyn_cast<CXXRecordDecl>(Val: Instantiation))
10059 completeMemberSpecializationImpl(S&: *this, OrigD: Record, Loc: Member->getLocation());
10060 else if (auto *Enum = dyn_cast<EnumDecl>(Val: Instantiation))
10061 completeMemberSpecializationImpl(S&: *this, OrigD: Enum, Loc: Member->getLocation());
10062 else
10063 llvm_unreachable("unknown member specialization kind");
10064}
10065
10066/// Check the scope of an explicit instantiation.
10067///
10068/// \returns true if a serious error occurs, false otherwise.
10069static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
10070 SourceLocation InstLoc,
10071 bool WasQualifiedName) {
10072 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
10073 DeclContext *CurContext = S.CurContext->getRedeclContext();
10074
10075 if (CurContext->isRecord()) {
10076 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_in_class)
10077 << D;
10078 return true;
10079 }
10080
10081 // C++11 [temp.explicit]p3:
10082 // An explicit instantiation shall appear in an enclosing namespace of its
10083 // template. If the name declared in the explicit instantiation is an
10084 // unqualified name, the explicit instantiation shall appear in the
10085 // namespace where its template is declared or, if that namespace is inline
10086 // (7.3.1), any namespace from its enclosing namespace set.
10087 //
10088 // This is DR275, which we do not retroactively apply to C++98/03.
10089 if (WasQualifiedName) {
10090 if (CurContext->Encloses(DC: OrigContext))
10091 return false;
10092 } else {
10093 if (CurContext->InEnclosingNamespaceSetOf(NS: OrigContext))
10094 return false;
10095 }
10096
10097 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: OrigContext)) {
10098 if (WasQualifiedName)
10099 S.Diag(Loc: InstLoc,
10100 DiagID: S.getLangOpts().CPlusPlus11?
10101 diag::err_explicit_instantiation_out_of_scope :
10102 diag::warn_explicit_instantiation_out_of_scope_0x)
10103 << D << NS;
10104 else
10105 S.Diag(Loc: InstLoc,
10106 DiagID: S.getLangOpts().CPlusPlus11?
10107 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10108 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10109 << D << NS;
10110 } else
10111 S.Diag(Loc: InstLoc,
10112 DiagID: S.getLangOpts().CPlusPlus11?
10113 diag::err_explicit_instantiation_must_be_global :
10114 diag::warn_explicit_instantiation_must_be_global_0x)
10115 << D;
10116 S.Diag(Loc: D->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10117 return false;
10118}
10119
10120/// Common checks for whether an explicit instantiation of \p D is valid.
10121static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
10122 SourceLocation InstLoc,
10123 bool WasQualifiedName,
10124 TemplateSpecializationKind TSK) {
10125 // C++ [temp.explicit]p13:
10126 // An explicit instantiation declaration shall not name a specialization of
10127 // a template with internal linkage.
10128 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10129 D->getFormalLinkage() == Linkage::Internal) {
10130 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_internal_linkage) << D;
10131 return true;
10132 }
10133
10134 // C++11 [temp.explicit]p3: [DR 275]
10135 // An explicit instantiation shall appear in an enclosing namespace of its
10136 // template.
10137 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10138 return true;
10139
10140 return false;
10141}
10142
10143/// Determine whether the given scope specifier has a template-id in it.
10144static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
10145 // C++11 [temp.explicit]p3:
10146 // If the explicit instantiation is for a member function, a member class
10147 // or a static data member of a class template specialization, the name of
10148 // the class template specialization in the qualified-id for the member
10149 // name shall be a simple-template-id.
10150 //
10151 // C++98 has the same restriction, just worded differently.
10152 for (NestedNameSpecifier NNS = SS.getScopeRep();
10153 NNS.getKind() == NestedNameSpecifier::Kind::Type;
10154 /**/) {
10155 const Type *T = NNS.getAsType();
10156 if (isa<TemplateSpecializationType>(Val: T))
10157 return true;
10158 NNS = T->getPrefix();
10159 }
10160 return false;
10161}
10162
10163/// Make a dllexport or dllimport attr on a class template specialization take
10164/// effect.
10165static void dllExportImportClassTemplateSpecialization(
10166 Sema &S, ClassTemplateSpecializationDecl *Def) {
10167 auto *A = cast_or_null<InheritableAttr>(Val: getDLLAttr(D: Def));
10168 assert(A && "dllExportImportClassTemplateSpecialization called "
10169 "on Def without dllexport or dllimport");
10170
10171 // We reject explicit instantiations in class scope, so there should
10172 // never be any delayed exported classes to worry about.
10173 assert(S.DelayedDllExportClasses.empty() &&
10174 "delayed exports present at explicit instantiation");
10175 S.checkClassLevelDLLAttribute(Class: Def);
10176
10177 // Propagate attribute to base class templates.
10178 for (auto &B : Def->bases()) {
10179 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10180 Val: B.getType()->getAsCXXRecordDecl()))
10181 S.propagateDLLAttrToBaseClassTemplate(Class: Def, ClassAttr: A, BaseTemplateSpec: BT, BaseLoc: B.getBeginLoc());
10182 }
10183
10184 S.referenceDLLExportedClassMethods();
10185}
10186
10187DeclResult Sema::ActOnExplicitInstantiation(
10188 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10189 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10190 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10191 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10192 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10193 // Find the class template we're specializing
10194 TemplateName Name = TemplateD.get();
10195 TemplateDecl *TD = Name.getAsTemplateDecl();
10196 // Check that the specialization uses the same tag kind as the
10197 // original template.
10198 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10199 assert(Kind != TagTypeKind::Enum &&
10200 "Invalid enum tag in class template explicit instantiation!");
10201
10202 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: TD);
10203
10204 if (!ClassTemplate) {
10205 NonTagKind NTK = getNonTagTypeDeclKind(D: TD, TTK: Kind);
10206 Diag(Loc: TemplateNameLoc, DiagID: diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10207 Diag(Loc: TD->getLocation(), DiagID: diag::note_previous_use);
10208 return true;
10209 }
10210
10211 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(),
10212 NewTag: Kind, /*isDefinition*/false, NewTagLoc: KWLoc,
10213 Name: ClassTemplate->getIdentifier())) {
10214 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
10215 << ClassTemplate
10216 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
10217 Code: ClassTemplate->getTemplatedDecl()->getKindName());
10218 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
10219 DiagID: diag::note_previous_use);
10220 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10221 }
10222
10223 // C++0x [temp.explicit]p2:
10224 // There are two forms of explicit instantiation: an explicit instantiation
10225 // definition and an explicit instantiation declaration. An explicit
10226 // instantiation declaration begins with the extern keyword. [...]
10227 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10228 ? TSK_ExplicitInstantiationDefinition
10229 : TSK_ExplicitInstantiationDeclaration;
10230
10231 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10232 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10233 // Check for dllexport class template instantiation declarations,
10234 // except for MinGW mode.
10235 for (const ParsedAttr &AL : Attr) {
10236 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10237 Diag(Loc: ExternLoc,
10238 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10239 Diag(Loc: AL.getLoc(), DiagID: diag::note_attribute);
10240 break;
10241 }
10242 }
10243
10244 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10245 Diag(Loc: ExternLoc,
10246 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10247 Diag(Loc: A->getLocation(), DiagID: diag::note_attribute);
10248 }
10249 }
10250
10251 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10252 // instantiation declarations for most purposes.
10253 bool DLLImportExplicitInstantiationDef = false;
10254 if (TSK == TSK_ExplicitInstantiationDefinition &&
10255 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10256 // Check for dllimport class template instantiation definitions.
10257 bool DLLImport =
10258 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10259 for (const ParsedAttr &AL : Attr) {
10260 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10261 DLLImport = true;
10262 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10263 // dllexport trumps dllimport here.
10264 DLLImport = false;
10265 break;
10266 }
10267 }
10268 if (DLLImport) {
10269 TSK = TSK_ExplicitInstantiationDeclaration;
10270 DLLImportExplicitInstantiationDef = true;
10271 }
10272 }
10273
10274 // Translate the parser's template argument list in our AST format.
10275 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10276 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10277
10278 // Check that the template argument list is well-formed for this
10279 // template.
10280 CheckTemplateArgumentInfo CTAI;
10281 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
10282 /*DefaultArgs=*/{}, PartialTemplateArgs: false, CTAI,
10283 /*UpdateArgsWithConversions=*/true,
10284 /*ConstraintsNotSatisfied=*/nullptr))
10285 return true;
10286
10287 // Find the class template specialization declaration that
10288 // corresponds to these arguments.
10289 void *InsertPos = nullptr;
10290 ClassTemplateSpecializationDecl *PrevDecl =
10291 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
10292
10293 TemplateSpecializationKind PrevDecl_TSK
10294 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10295
10296 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10297 Context.getTargetInfo().getTriple().isOSCygMing()) {
10298 // Check for dllexport class template instantiation definitions in MinGW
10299 // mode, if a previous declaration of the instantiation was seen.
10300 for (const ParsedAttr &AL : Attr) {
10301 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10302 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10303 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attr_dllexport_explicit_inst_def);
10304 } else {
10305 Diag(Loc: AL.getLoc(),
10306 DiagID: diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10307 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_prev_decl_missing_dllexport);
10308 }
10309 break;
10310 }
10311 }
10312 }
10313
10314 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10315 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10316 llvm::none_of(Range: Attr, P: [](const ParsedAttr &AL) {
10317 return AL.getKind() == ParsedAttr::AT_DLLExport;
10318 })) {
10319 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10320 Diag(Loc: TemplateLoc, DiagID: diag::warn_dllexport_on_decl_ignored);
10321 Diag(Loc: DEA->getLoc(), DiagID: diag::note_dllexport_on_decl);
10322 }
10323 }
10324
10325 if (CheckExplicitInstantiation(S&: *this, D: ClassTemplate, InstLoc: TemplateNameLoc,
10326 WasQualifiedName: SS.isSet(), TSK))
10327 return true;
10328
10329 ClassTemplateSpecializationDecl *Specialization = nullptr;
10330
10331 bool HasNoEffect = false;
10332 if (PrevDecl) {
10333 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateNameLoc, NewTSK: TSK,
10334 PrevDecl, PrevTSK: PrevDecl_TSK,
10335 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
10336 HasNoEffect))
10337 return PrevDecl;
10338
10339 // Even though HasNoEffect == true means that this explicit instantiation
10340 // has no effect on semantics, we go on to put its syntax in the AST.
10341
10342 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10343 PrevDecl_TSK == TSK_Undeclared) {
10344 // Since the only prior class template specialization with these
10345 // arguments was referenced but not declared, reuse that
10346 // declaration node as our own, updating the source location
10347 // for the template name to reflect our new declaration.
10348 // (Other source locations will be updated later.)
10349 Specialization = PrevDecl;
10350 Specialization->setLocation(TemplateNameLoc);
10351 PrevDecl = nullptr;
10352 }
10353
10354 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10355 DLLImportExplicitInstantiationDef) {
10356 // The new specialization might add a dllimport attribute.
10357 HasNoEffect = false;
10358 }
10359 }
10360
10361 if (!Specialization) {
10362 // Create a new class template specialization declaration node for
10363 // this explicit specialization.
10364 Specialization = ClassTemplateSpecializationDecl::Create(
10365 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
10366 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
10367 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
10368
10369 // A MSInheritanceAttr attached to the previous declaration must be
10370 // propagated to the new node prior to instantiation.
10371 if (PrevDecl) {
10372 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10373 auto *Clone = A->clone(C&: getASTContext());
10374 Clone->setInherited(true);
10375 Specialization->addAttr(A: Clone);
10376 Consumer.AssignInheritanceModel(RD: Specialization);
10377 }
10378 }
10379
10380 if (!HasNoEffect && !PrevDecl) {
10381 // Insert the new specialization.
10382 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
10383 }
10384 }
10385
10386 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10387
10388 // Set source locations for keywords.
10389 Specialization->setExternKeywordLoc(ExternLoc);
10390 Specialization->setTemplateKeywordLoc(TemplateLoc);
10391 Specialization->setBraceRange(SourceRange());
10392
10393 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10394 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
10395 ProcessAPINotes(D: Specialization);
10396
10397 // Add the explicit instantiation into its lexical context. However,
10398 // since explicit instantiations are never found by name lookup, we
10399 // just put it into the declaration context directly.
10400 Specialization->setLexicalDeclContext(CurContext);
10401 CurContext->addDecl(D: Specialization);
10402
10403 // Syntax is now OK, so return if it has no other effect on semantics.
10404 if (HasNoEffect) {
10405 // Set the template specialization kind.
10406 Specialization->setTemplateSpecializationKind(TSK);
10407 return Specialization;
10408 }
10409
10410 // C++ [temp.explicit]p3:
10411 // A definition of a class template or class member template
10412 // shall be in scope at the point of the explicit instantiation of
10413 // the class template or class member template.
10414 //
10415 // This check comes when we actually try to perform the
10416 // instantiation.
10417 ClassTemplateSpecializationDecl *Def
10418 = cast_or_null<ClassTemplateSpecializationDecl>(
10419 Val: Specialization->getDefinition());
10420 if (!Def)
10421 InstantiateClassTemplateSpecialization(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Specialization, TSK,
10422 /*Complain=*/true,
10423 PrimaryStrictPackMatch: CTAI.StrictPackMatch);
10424 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10425 MarkVTableUsed(Loc: TemplateNameLoc, Class: Specialization, DefinitionRequired: true);
10426 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10427 }
10428
10429 // Instantiate the members of this class template specialization.
10430 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10431 Val: Specialization->getDefinition());
10432 if (Def) {
10433 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
10434 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10435 // TSK_ExplicitInstantiationDefinition
10436 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10437 (TSK == TSK_ExplicitInstantiationDefinition ||
10438 DLLImportExplicitInstantiationDef)) {
10439 // FIXME: Need to notify the ASTMutationListener that we did this.
10440 Def->setTemplateSpecializationKind(TSK);
10441
10442 if (!getDLLAttr(D: Def) && getDLLAttr(D: Specialization) &&
10443 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10444 // An explicit instantiation definition can add a dll attribute to a
10445 // template with a previous instantiation declaration. MinGW doesn't
10446 // allow this.
10447 auto *A = cast<InheritableAttr>(
10448 Val: getDLLAttr(D: Specialization)->clone(C&: getASTContext()));
10449 A->setInherited(true);
10450 Def->addAttr(A);
10451 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10452 }
10453 }
10454
10455 // Fix a TSK_ImplicitInstantiation followed by a
10456 // TSK_ExplicitInstantiationDefinition
10457 bool NewlyDLLExported =
10458 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10459 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10460 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10461 // An explicit instantiation definition can add a dll attribute to a
10462 // template with a previous implicit instantiation. MinGW doesn't allow
10463 // this. We limit clang to only adding dllexport, to avoid potentially
10464 // strange codegen behavior. For example, if we extend this conditional
10465 // to dllimport, and we have a source file calling a method on an
10466 // implicitly instantiated template class instance and then declaring a
10467 // dllimport explicit instantiation definition for the same template
10468 // class, the codegen for the method call will not respect the dllimport,
10469 // while it will with cl. The Def will already have the DLL attribute,
10470 // since the Def and Specialization will be the same in the case of
10471 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10472 // attribute to the Specialization; we just need to make it take effect.
10473 assert(Def == Specialization &&
10474 "Def and Specialization should match for implicit instantiation");
10475 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10476 }
10477
10478 // In MinGW mode, export the template instantiation if the declaration
10479 // was marked dllexport.
10480 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10481 Context.getTargetInfo().getTriple().isOSCygMing() &&
10482 PrevDecl->hasAttr<DLLExportAttr>()) {
10483 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10484 }
10485
10486 // Set the template specialization kind. Make sure it is set before
10487 // instantiating the members which will trigger ASTConsumer callbacks.
10488 Specialization->setTemplateSpecializationKind(TSK);
10489 InstantiateClassTemplateSpecializationMembers(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Def, TSK);
10490 } else {
10491
10492 // Set the template specialization kind.
10493 Specialization->setTemplateSpecializationKind(TSK);
10494 }
10495
10496 return Specialization;
10497}
10498
10499DeclResult
10500Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10501 SourceLocation TemplateLoc, unsigned TagSpec,
10502 SourceLocation KWLoc, CXXScopeSpec &SS,
10503 IdentifierInfo *Name, SourceLocation NameLoc,
10504 const ParsedAttributesView &Attr) {
10505
10506 bool Owned = false;
10507 bool IsDependent = false;
10508 Decl *TagD =
10509 ActOnTag(S, TagSpec, TUK: TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10510 Attr, AS: AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10511 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent, ScopedEnumKWLoc: SourceLocation(),
10512 ScopedEnumUsesClassTag: false, UnderlyingType: TypeResult(), /*IsTypeSpecifier*/ false,
10513 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10514 .get();
10515 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10516
10517 if (!TagD)
10518 return true;
10519
10520 TagDecl *Tag = cast<TagDecl>(Val: TagD);
10521 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10522
10523 if (Tag->isInvalidDecl())
10524 return true;
10525
10526 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: Tag);
10527 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10528 if (!Pattern) {
10529 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_nontemplate_type)
10530 << Context.getCanonicalTagType(TD: Record);
10531 Diag(Loc: Record->getLocation(), DiagID: diag::note_nontemplate_decl_here);
10532 return true;
10533 }
10534
10535 // C++0x [temp.explicit]p2:
10536 // If the explicit instantiation is for a class or member class, the
10537 // elaborated-type-specifier in the declaration shall include a
10538 // simple-template-id.
10539 //
10540 // C++98 has the same restriction, just worded differently.
10541 if (!ScopeSpecifierHasTemplateId(SS))
10542 Diag(Loc: TemplateLoc, DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10543 << Record << SS.getRange();
10544
10545 // C++0x [temp.explicit]p2:
10546 // There are two forms of explicit instantiation: an explicit instantiation
10547 // definition and an explicit instantiation declaration. An explicit
10548 // instantiation declaration begins with the extern keyword. [...]
10549 TemplateSpecializationKind TSK
10550 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10551 : TSK_ExplicitInstantiationDeclaration;
10552
10553 CheckExplicitInstantiation(S&: *this, D: Record, InstLoc: NameLoc, WasQualifiedName: true, TSK);
10554
10555 // Verify that it is okay to explicitly instantiate here.
10556 CXXRecordDecl *PrevDecl
10557 = cast_or_null<CXXRecordDecl>(Val: Record->getPreviousDecl());
10558 if (!PrevDecl && Record->getDefinition())
10559 PrevDecl = Record;
10560 if (PrevDecl) {
10561 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10562 bool HasNoEffect = false;
10563 assert(MSInfo && "No member specialization information?");
10564 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateLoc, NewTSK: TSK,
10565 PrevDecl,
10566 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10567 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10568 HasNoEffect))
10569 return true;
10570 if (HasNoEffect)
10571 return TagD;
10572 }
10573
10574 CXXRecordDecl *RecordDef
10575 = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10576 if (!RecordDef) {
10577 // C++ [temp.explicit]p3:
10578 // A definition of a member class of a class template shall be in scope
10579 // at the point of an explicit instantiation of the member class.
10580 CXXRecordDecl *Def
10581 = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition());
10582 if (!Def) {
10583 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_undefined_member)
10584 << 0 << Record->getDeclName() << Record->getDeclContext();
10585 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_forward_declaration)
10586 << Pattern;
10587 return true;
10588 } else {
10589 if (InstantiateClass(PointOfInstantiation: NameLoc, Instantiation: Record, Pattern: Def,
10590 TemplateArgs: getTemplateInstantiationArgs(D: Record),
10591 TSK))
10592 return true;
10593
10594 RecordDef = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10595 if (!RecordDef)
10596 return true;
10597 }
10598 }
10599
10600 // Instantiate all of the members of the class.
10601 InstantiateClassMembers(PointOfInstantiation: NameLoc, Instantiation: RecordDef,
10602 TemplateArgs: getTemplateInstantiationArgs(D: Record), TSK);
10603
10604 if (TSK == TSK_ExplicitInstantiationDefinition)
10605 MarkVTableUsed(Loc: NameLoc, Class: RecordDef, DefinitionRequired: true);
10606
10607 // FIXME: We don't have any representation for explicit instantiations of
10608 // member classes. Such a representation is not needed for compilation, but it
10609 // should be available for clients that want to see all of the declarations in
10610 // the source code.
10611 return TagD;
10612}
10613
10614DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10615 SourceLocation ExternLoc,
10616 SourceLocation TemplateLoc,
10617 Declarator &D) {
10618 // Explicit instantiations always require a name.
10619 // TODO: check if/when DNInfo should replace Name.
10620 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10621 DeclarationName Name = NameInfo.getName();
10622 if (!Name) {
10623 if (!D.isInvalidType())
10624 Diag(Loc: D.getDeclSpec().getBeginLoc(),
10625 DiagID: diag::err_explicit_instantiation_requires_name)
10626 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10627
10628 return true;
10629 }
10630
10631 // Get the innermost enclosing declaration scope.
10632 S = S->getDeclParent();
10633
10634 // Determine the type of the declaration.
10635 TypeSourceInfo *T = GetTypeForDeclarator(D);
10636 QualType R = T->getType();
10637 if (R.isNull())
10638 return true;
10639
10640 // C++ [dcl.stc]p1:
10641 // A storage-class-specifier shall not be specified in [...] an explicit
10642 // instantiation (14.7.2) directive.
10643 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10644 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_of_typedef)
10645 << Name;
10646 return true;
10647 } else if (D.getDeclSpec().getStorageClassSpec()
10648 != DeclSpec::SCS_unspecified) {
10649 // Complain about then remove the storage class specifier.
10650 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_storage_class)
10651 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10652
10653 D.getMutableDeclSpec().ClearStorageClassSpecs();
10654 }
10655
10656 // C++0x [temp.explicit]p1:
10657 // [...] An explicit instantiation of a function template shall not use the
10658 // inline or constexpr specifiers.
10659 // Presumably, this also applies to member functions of class templates as
10660 // well.
10661 if (D.getDeclSpec().isInlineSpecified())
10662 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10663 DiagID: getLangOpts().CPlusPlus11 ?
10664 diag::err_explicit_instantiation_inline :
10665 diag::warn_explicit_instantiation_inline_0x)
10666 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10667 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10668 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10669 // not already specified.
10670 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10671 DiagID: diag::err_explicit_instantiation_constexpr);
10672
10673 // A deduction guide is not on the list of entities that can be explicitly
10674 // instantiated.
10675 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10676 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
10677 << /*explicit instantiation*/ 0;
10678 return true;
10679 }
10680
10681 // C++0x [temp.explicit]p2:
10682 // There are two forms of explicit instantiation: an explicit instantiation
10683 // definition and an explicit instantiation declaration. An explicit
10684 // instantiation declaration begins with the extern keyword. [...]
10685 TemplateSpecializationKind TSK
10686 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10687 : TSK_ExplicitInstantiationDeclaration;
10688
10689 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10690 LookupParsedName(R&: Previous, S, SS: &D.getCXXScopeSpec(),
10691 /*ObjectType=*/QualType());
10692
10693 if (!R->isFunctionType()) {
10694 // C++ [temp.explicit]p1:
10695 // A [...] static data member of a class template can be explicitly
10696 // instantiated from the member definition associated with its class
10697 // template.
10698 // C++1y [temp.explicit]p1:
10699 // A [...] variable [...] template specialization can be explicitly
10700 // instantiated from its template.
10701 if (Previous.isAmbiguous())
10702 return true;
10703
10704 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10705 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10706
10707 if (!PrevTemplate) {
10708 if (!Prev || !Prev->isStaticDataMember()) {
10709 // We expect to see a static data member here.
10710 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_not_known)
10711 << Name;
10712 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10713 P != PEnd; ++P)
10714 Diag(Loc: (*P)->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10715 return true;
10716 }
10717
10718 if (!Prev->getInstantiatedFromStaticDataMember()) {
10719 // FIXME: Check for explicit specialization?
10720 Diag(Loc: D.getIdentifierLoc(),
10721 DiagID: diag::err_explicit_instantiation_data_member_not_instantiated)
10722 << Prev;
10723 Diag(Loc: Prev->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10724 // FIXME: Can we provide a note showing where this was declared?
10725 return true;
10726 }
10727 } else {
10728 // Explicitly instantiate a variable template.
10729
10730 // C++1y [dcl.spec.auto]p6:
10731 // ... A program that uses auto or decltype(auto) in a context not
10732 // explicitly allowed in this section is ill-formed.
10733 //
10734 // This includes auto-typed variable template instantiations.
10735 if (R->isUndeducedType()) {
10736 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10737 DiagID: diag::err_auto_not_allowed_var_inst);
10738 return true;
10739 }
10740
10741 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10742 // C++1y [temp.explicit]p3:
10743 // If the explicit instantiation is for a variable, the unqualified-id
10744 // in the declaration shall be a template-id.
10745 Diag(Loc: D.getIdentifierLoc(),
10746 DiagID: diag::err_explicit_instantiation_without_template_id)
10747 << PrevTemplate;
10748 Diag(Loc: PrevTemplate->getLocation(),
10749 DiagID: diag::note_explicit_instantiation_here);
10750 return true;
10751 }
10752
10753 // Translate the parser's template argument list into our AST format.
10754 TemplateArgumentListInfo TemplateArgs =
10755 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10756
10757 DeclResult Res =
10758 CheckVarTemplateId(Template: PrevTemplate, TemplateLoc, TemplateNameLoc: D.getIdentifierLoc(),
10759 TemplateArgs, /*SetWrittenArgs=*/true);
10760 if (Res.isInvalid())
10761 return true;
10762
10763 if (!Res.isUsable()) {
10764 // We somehow specified dependent template arguments in an explicit
10765 // instantiation. This should probably only happen during error
10766 // recovery.
10767 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_dependent);
10768 return true;
10769 }
10770
10771 // Ignore access control bits, we don't need them for redeclaration
10772 // checking.
10773 Prev = cast<VarDecl>(Val: Res.get());
10774 }
10775
10776 // C++0x [temp.explicit]p2:
10777 // If the explicit instantiation is for a member function, a member class
10778 // or a static data member of a class template specialization, the name of
10779 // the class template specialization in the qualified-id for the member
10780 // name shall be a simple-template-id.
10781 //
10782 // C++98 has the same restriction, just worded differently.
10783 //
10784 // This does not apply to variable template specializations, where the
10785 // template-id is in the unqualified-id instead.
10786 if (!ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()) && !PrevTemplate)
10787 Diag(Loc: D.getIdentifierLoc(),
10788 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10789 << Prev << D.getCXXScopeSpec().getRange();
10790
10791 CheckExplicitInstantiation(S&: *this, D: Prev, InstLoc: D.getIdentifierLoc(), WasQualifiedName: true, TSK);
10792
10793 // Verify that it is okay to explicitly instantiate here.
10794 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10795 SourceLocation POI = Prev->getPointOfInstantiation();
10796 bool HasNoEffect = false;
10797 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK, PrevDecl: Prev,
10798 PrevTSK, PrevPointOfInstantiation: POI, HasNoEffect))
10799 return true;
10800
10801 if (!HasNoEffect) {
10802 // Instantiate static data member or variable template.
10803 Prev->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
10804 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: Prev)) {
10805 VTSD->setExternKeywordLoc(ExternLoc);
10806 VTSD->setTemplateKeywordLoc(TemplateLoc);
10807 }
10808
10809 // Merge attributes.
10810 ProcessDeclAttributeList(S, D: Prev, AttrList: D.getDeclSpec().getAttributes());
10811 if (PrevTemplate)
10812 ProcessAPINotes(D: Prev);
10813
10814 if (TSK == TSK_ExplicitInstantiationDefinition)
10815 InstantiateVariableDefinition(PointOfInstantiation: D.getIdentifierLoc(), Var: Prev);
10816 }
10817
10818 // Check the new variable specialization against the parsed input.
10819 if (PrevTemplate && !Context.hasSameType(T1: Prev->getType(), T2: R)) {
10820 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10821 DiagID: diag::err_invalid_var_template_spec_type)
10822 << 0 << PrevTemplate << R << Prev->getType();
10823 Diag(Loc: PrevTemplate->getLocation(), DiagID: diag::note_template_declared_here)
10824 << 2 << PrevTemplate->getDeclName();
10825 return true;
10826 }
10827
10828 // FIXME: Create an ExplicitInstantiation node?
10829 return (Decl*) nullptr;
10830 }
10831
10832 // If the declarator is a template-id, translate the parser's template
10833 // argument list into our AST format.
10834 bool HasExplicitTemplateArgs = false;
10835 TemplateArgumentListInfo TemplateArgs;
10836 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10837 TemplateArgs = makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10838 HasExplicitTemplateArgs = true;
10839 }
10840
10841 // C++ [temp.explicit]p1:
10842 // A [...] function [...] can be explicitly instantiated from its template.
10843 // A member function [...] of a class template can be explicitly
10844 // instantiated from the member definition associated with its class
10845 // template.
10846 UnresolvedSet<8> TemplateMatches;
10847 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10848 OverloadCandidateSet::CSK_Normal);
10849 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10850 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10851 P != PEnd; ++P) {
10852 NamedDecl *Prev = *P;
10853 if (!HasExplicitTemplateArgs) {
10854 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Prev)) {
10855 QualType Adjusted = adjustCCAndNoReturn(ArgFunctionType: R, FunctionType: Method->getType(),
10856 /*AdjustExceptionSpec*/true);
10857 if (Context.hasSameUnqualifiedType(T1: Method->getType(), T2: Adjusted)) {
10858 if (Method->getPrimaryTemplate()) {
10859 TemplateMatches.addDecl(D: Method, AS: P.getAccess());
10860 } else {
10861 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10862 C.FoundDecl = P.getPair();
10863 C.Function = Method;
10864 C.Viable = true;
10865 ConstraintSatisfaction S;
10866 if (Method->getTrailingRequiresClause() &&
10867 (CheckFunctionConstraints(FD: Method, Satisfaction&: S, UsageLoc: D.getIdentifierLoc(),
10868 /*ForOverloadResolution=*/true) ||
10869 !S.IsSatisfied)) {
10870 C.Viable = false;
10871 C.FailureKind = ovl_fail_constraints_not_satisfied;
10872 }
10873 }
10874 }
10875 }
10876 }
10877
10878 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Prev);
10879 if (!FunTmpl)
10880 continue;
10881
10882 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10883 FunctionDecl *Specialization = nullptr;
10884 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
10885 FunctionTemplate: FunTmpl, ExplicitTemplateArgs: (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), ArgFunctionType: R,
10886 Specialization, Info);
10887 TDK != TemplateDeductionResult::Success) {
10888 // Keep track of almost-matches.
10889 FailedTemplateCandidates.addCandidate().set(
10890 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
10891 Info: MakeDeductionFailureInfo(Context, TDK, Info));
10892 (void)TDK;
10893 continue;
10894 }
10895
10896 // Target attributes are part of the cuda function signature, so
10897 // the cuda target of the instantiated function must match that of its
10898 // template. Given that C++ template deduction does not take
10899 // target attributes into account, we reject candidates here that
10900 // have a different target.
10901 if (LangOpts.CUDA &&
10902 CUDA().IdentifyTarget(D: Specialization,
10903 /* IgnoreImplicitHDAttr = */ true) !=
10904 CUDA().IdentifyTarget(Attrs: D.getDeclSpec().getAttributes())) {
10905 FailedTemplateCandidates.addCandidate().set(
10906 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
10907 Info: MakeDeductionFailureInfo(
10908 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
10909 continue;
10910 }
10911
10912 TemplateMatches.addDecl(D: Specialization, AS: P.getAccess());
10913 }
10914
10915 FunctionDecl *Specialization = nullptr;
10916 if (!NonTemplateMatches.empty()) {
10917 unsigned Msg = 0;
10918 OverloadCandidateDisplayKind DisplayKind;
10919 OverloadCandidateSet::iterator Best;
10920 switch (NonTemplateMatches.BestViableFunction(S&: *this, Loc: D.getIdentifierLoc(),
10921 Best)) {
10922 case OR_Success:
10923 case OR_Deleted:
10924 Specialization = cast<FunctionDecl>(Val: Best->Function);
10925 break;
10926 case OR_Ambiguous:
10927 Msg = diag::err_explicit_instantiation_ambiguous;
10928 DisplayKind = OCD_AmbiguousCandidates;
10929 break;
10930 case OR_No_Viable_Function:
10931 Msg = diag::err_explicit_instantiation_no_candidate;
10932 DisplayKind = OCD_AllCandidates;
10933 break;
10934 }
10935 if (Msg) {
10936 PartialDiagnostic Diag = PDiag(DiagID: Msg) << Name;
10937 NonTemplateMatches.NoteCandidates(
10938 PA: PartialDiagnosticAt(D.getIdentifierLoc(), Diag), S&: *this, OCD: DisplayKind,
10939 Args: {});
10940 return true;
10941 }
10942 }
10943
10944 if (!Specialization) {
10945 // Find the most specialized function template specialization.
10946 UnresolvedSetIterator Result = getMostSpecialized(
10947 SBegin: TemplateMatches.begin(), SEnd: TemplateMatches.end(),
10948 FailedCandidates&: FailedTemplateCandidates, Loc: D.getIdentifierLoc(),
10949 NoneDiag: PDiag(DiagID: diag::err_explicit_instantiation_not_known) << Name,
10950 AmbigDiag: PDiag(DiagID: diag::err_explicit_instantiation_ambiguous) << Name,
10951 CandidateDiag: PDiag(DiagID: diag::note_explicit_instantiation_candidate));
10952
10953 if (Result == TemplateMatches.end())
10954 return true;
10955
10956 // Ignore access control bits, we don't need them for redeclaration checking.
10957 Specialization = cast<FunctionDecl>(Val: *Result);
10958 }
10959
10960 // C++11 [except.spec]p4
10961 // In an explicit instantiation an exception-specification may be specified,
10962 // but is not required.
10963 // If an exception-specification is specified in an explicit instantiation
10964 // directive, it shall be compatible with the exception-specifications of
10965 // other declarations of that function.
10966 if (auto *FPT = R->getAs<FunctionProtoType>())
10967 if (FPT->hasExceptionSpec()) {
10968 unsigned DiagID =
10969 diag::err_mismatched_exception_spec_explicit_instantiation;
10970 if (getLangOpts().MicrosoftExt)
10971 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10972 bool Result = CheckEquivalentExceptionSpec(
10973 DiagID: PDiag(DiagID) << Specialization->getType(),
10974 NoteID: PDiag(DiagID: diag::note_explicit_instantiation_here),
10975 Old: Specialization->getType()->getAs<FunctionProtoType>(),
10976 OldLoc: Specialization->getLocation(), New: FPT, NewLoc: D.getBeginLoc());
10977 // In Microsoft mode, mismatching exception specifications just cause a
10978 // warning.
10979 if (!getLangOpts().MicrosoftExt && Result)
10980 return true;
10981 }
10982
10983 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10984 Diag(Loc: D.getIdentifierLoc(),
10985 DiagID: diag::err_explicit_instantiation_member_function_not_instantiated)
10986 << Specialization
10987 << (Specialization->getTemplateSpecializationKind() ==
10988 TSK_ExplicitSpecialization);
10989 Diag(Loc: Specialization->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10990 return true;
10991 }
10992
10993 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10994 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10995 PrevDecl = Specialization;
10996
10997 if (PrevDecl) {
10998 bool HasNoEffect = false;
10999 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK,
11000 PrevDecl,
11001 PrevTSK: PrevDecl->getTemplateSpecializationKind(),
11002 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
11003 HasNoEffect))
11004 return true;
11005
11006 // FIXME: We may still want to build some representation of this
11007 // explicit specialization.
11008 if (HasNoEffect)
11009 return (Decl*) nullptr;
11010 }
11011
11012 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11013 // functions
11014 // valarray<size_t>::valarray(size_t) and
11015 // valarray<size_t>::~valarray()
11016 // that it declared to have internal linkage with the internal_linkage
11017 // attribute. Ignore the explicit instantiation declaration in this case.
11018 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11019 TSK == TSK_ExplicitInstantiationDeclaration) {
11020 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Specialization->getDeclContext()))
11021 if (RD->getIdentifier() && RD->getIdentifier()->isStr(Str: "valarray") &&
11022 RD->isInStdNamespace())
11023 return (Decl*) nullptr;
11024 }
11025
11026 ProcessDeclAttributeList(S, D: Specialization, AttrList: D.getDeclSpec().getAttributes());
11027 ProcessAPINotes(D: Specialization);
11028
11029 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11030 // instantiation declarations.
11031 if (TSK == TSK_ExplicitInstantiationDefinition &&
11032 Specialization->hasAttr<DLLImportAttr>() &&
11033 Context.getTargetInfo().getCXXABI().isMicrosoft())
11034 TSK = TSK_ExplicitInstantiationDeclaration;
11035
11036 Specialization->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
11037
11038 if (Specialization->isDefined()) {
11039 // Let the ASTConsumer know that this function has been explicitly
11040 // instantiated now, and its linkage might have changed.
11041 Consumer.HandleTopLevelDecl(D: DeclGroupRef(Specialization));
11042 } else if (TSK == TSK_ExplicitInstantiationDefinition)
11043 InstantiateFunctionDefinition(PointOfInstantiation: D.getIdentifierLoc(), Function: Specialization);
11044
11045 // C++0x [temp.explicit]p2:
11046 // If the explicit instantiation is for a member function, a member class
11047 // or a static data member of a class template specialization, the name of
11048 // the class template specialization in the qualified-id for the member
11049 // name shall be a simple-template-id.
11050 //
11051 // C++98 has the same restriction, just worded differently.
11052 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11053 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11054 D.getCXXScopeSpec().isSet() &&
11055 !ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()))
11056 Diag(Loc: D.getIdentifierLoc(),
11057 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
11058 << Specialization << D.getCXXScopeSpec().getRange();
11059
11060 CheckExplicitInstantiation(
11061 S&: *this,
11062 D: FunTmpl ? (NamedDecl *)FunTmpl
11063 : Specialization->getInstantiatedFromMemberFunction(),
11064 InstLoc: D.getIdentifierLoc(), WasQualifiedName: D.getCXXScopeSpec().isSet(), TSK);
11065
11066 // FIXME: Create some kind of ExplicitInstantiationDecl here.
11067 return (Decl*) nullptr;
11068}
11069
11070TypeResult Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11071 const CXXScopeSpec &SS,
11072 const IdentifierInfo *Name,
11073 SourceLocation TagLoc,
11074 SourceLocation NameLoc) {
11075 // This has to hold, because SS is expected to be defined.
11076 assert(Name && "Expected a name in a dependent tag");
11077
11078 NestedNameSpecifier NNS = SS.getScopeRep();
11079 if (!NNS)
11080 return true;
11081
11082 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
11083
11084 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11085 Diag(Loc: NameLoc, DiagID: diag::err_dependent_tag_decl)
11086 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11087 return true;
11088 }
11089
11090 // Create the resulting type.
11091 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
11092 QualType Result = Context.getDependentNameType(Keyword: Kwd, NNS, Name);
11093
11094 // Create type-source location information for this type.
11095 TypeLocBuilder TLB;
11096 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: Result);
11097 TL.setElaboratedKeywordLoc(TagLoc);
11098 TL.setQualifierLoc(SS.getWithLocInContext(Context));
11099 TL.setNameLoc(NameLoc);
11100 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
11101}
11102
11103TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11104 const CXXScopeSpec &SS,
11105 const IdentifierInfo &II,
11106 SourceLocation IdLoc,
11107 ImplicitTypenameContext IsImplicitTypename) {
11108 if (SS.isInvalid())
11109 return true;
11110
11111 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11112 DiagCompat(Loc: TypenameLoc, CompatDiagId: diag_compat::typename_outside_of_template)
11113 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11114
11115 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11116 TypeSourceInfo *TSI = nullptr;
11117 QualType T =
11118 CheckTypenameType(Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11119 : ElaboratedTypeKeyword::None,
11120 KeywordLoc: TypenameLoc, QualifierLoc, II, IILoc: IdLoc, TSI: &TSI,
11121 /*DeducedTSTContext=*/true);
11122 if (T.isNull())
11123 return true;
11124 return CreateParsedType(T, TInfo: TSI);
11125}
11126
11127TypeResult
11128Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11129 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11130 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11131 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11132 ASTTemplateArgsPtr TemplateArgsIn,
11133 SourceLocation RAngleLoc) {
11134 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11135 Diag(Loc: TypenameLoc, DiagID: getLangOpts().CPlusPlus11
11136 ? diag::compat_cxx11_typename_outside_of_template
11137 : diag::compat_pre_cxx11_typename_outside_of_template)
11138 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11139
11140 // Strangely, non-type results are not ignored by this lookup, so the
11141 // program is ill-formed if it finds an injected-class-name.
11142 if (TypenameLoc.isValid()) {
11143 auto *LookupRD =
11144 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: false));
11145 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11146 Diag(Loc: TemplateIILoc,
11147 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
11148 << TemplateII << 0 /*injected-class-name used as template name*/
11149 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11150 }
11151 }
11152
11153 // Translate the parser's template argument list in our AST format.
11154 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11155 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11156
11157 QualType T = CheckTemplateIdType(
11158 Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11159 : ElaboratedTypeKeyword::None,
11160 Name: TemplateIn.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
11161 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11162 if (T.isNull())
11163 return true;
11164
11165 // Provide source-location information for the template specialization type.
11166 TypeLocBuilder Builder;
11167 TemplateSpecializationTypeLoc SpecTL
11168 = Builder.push<TemplateSpecializationTypeLoc>(T);
11169 SpecTL.set(ElaboratedKeywordLoc: TypenameLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
11170 NameLoc: TemplateIILoc, TAL: TemplateArgs);
11171 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11172 return CreateParsedType(T, TInfo: TSI);
11173}
11174
11175/// Determine whether this failed name lookup should be treated as being
11176/// disabled by a usage of std::enable_if.
11177static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
11178 SourceRange &CondRange, Expr *&Cond) {
11179 // We must be looking for a ::type...
11180 if (!II.isStr(Str: "type"))
11181 return false;
11182
11183 // ... within an explicitly-written template specialization...
11184 if (NNS.getNestedNameSpecifier().getKind() != NestedNameSpecifier::Kind::Type)
11185 return false;
11186
11187 // FIXME: Look through sugar.
11188 auto EnableIfTSTLoc =
11189 NNS.castAsTypeLoc().getAs<TemplateSpecializationTypeLoc>();
11190 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11191 return false;
11192 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11193
11194 // ... which names a complete class template declaration...
11195 const TemplateDecl *EnableIfDecl =
11196 EnableIfTST->getTemplateName().getAsTemplateDecl();
11197 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11198 return false;
11199
11200 // ... called "enable_if".
11201 const IdentifierInfo *EnableIfII =
11202 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11203 if (!EnableIfII || !EnableIfII->isStr(Str: "enable_if"))
11204 return false;
11205
11206 // Assume the first template argument is the condition.
11207 CondRange = EnableIfTSTLoc.getArgLoc(i: 0).getSourceRange();
11208
11209 // Dig out the condition.
11210 Cond = nullptr;
11211 if (EnableIfTSTLoc.getArgLoc(i: 0).getArgument().getKind()
11212 != TemplateArgument::Expression)
11213 return true;
11214
11215 Cond = EnableIfTSTLoc.getArgLoc(i: 0).getSourceExpression();
11216
11217 // Ignore Boolean literals; they add no value.
11218 if (isa<CXXBoolLiteralExpr>(Val: Cond->IgnoreParenCasts()))
11219 Cond = nullptr;
11220
11221 return true;
11222}
11223
11224QualType
11225Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11226 SourceLocation KeywordLoc,
11227 NestedNameSpecifierLoc QualifierLoc,
11228 const IdentifierInfo &II,
11229 SourceLocation IILoc,
11230 TypeSourceInfo **TSI,
11231 bool DeducedTSTContext) {
11232 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11233 DeducedTSTContext);
11234 if (T.isNull())
11235 return QualType();
11236
11237 TypeLocBuilder TLB;
11238 if (isa<DependentNameType>(Val: T)) {
11239 auto TL = TLB.push<DependentNameTypeLoc>(T);
11240 TL.setElaboratedKeywordLoc(KeywordLoc);
11241 TL.setQualifierLoc(QualifierLoc);
11242 TL.setNameLoc(IILoc);
11243 } else if (isa<DeducedTemplateSpecializationType>(Val: T)) {
11244 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
11245 TL.setElaboratedKeywordLoc(KeywordLoc);
11246 TL.setQualifierLoc(QualifierLoc);
11247 TL.setNameLoc(IILoc);
11248 } else if (isa<TemplateTypeParmType>(Val: T)) {
11249 // FIXME: There might be a 'typename' keyword here, but we just drop it
11250 // as it can't be represented.
11251 assert(!QualifierLoc);
11252 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11253 } else if (isa<TagType>(Val: T)) {
11254 auto TL = TLB.push<TagTypeLoc>(T);
11255 TL.setElaboratedKeywordLoc(KeywordLoc);
11256 TL.setQualifierLoc(QualifierLoc);
11257 TL.setNameLoc(IILoc);
11258 } else if (isa<TypedefType>(Val: T)) {
11259 TLB.push<TypedefTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11260 } else {
11261 TLB.push<UnresolvedUsingTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11262 }
11263 *TSI = TLB.getTypeSourceInfo(Context, T);
11264 return T;
11265}
11266
11267/// Build the type that describes a C++ typename specifier,
11268/// e.g., "typename T::type".
11269QualType
11270Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11271 SourceLocation KeywordLoc,
11272 NestedNameSpecifierLoc QualifierLoc,
11273 const IdentifierInfo &II,
11274 SourceLocation IILoc, bool DeducedTSTContext) {
11275 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11276
11277 CXXScopeSpec SS;
11278 SS.Adopt(Other: QualifierLoc);
11279
11280 DeclContext *Ctx = nullptr;
11281 if (QualifierLoc) {
11282 Ctx = computeDeclContext(SS);
11283 if (!Ctx) {
11284 // If the nested-name-specifier is dependent and couldn't be
11285 // resolved to a type, build a typename type.
11286 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11287 return Context.getDependentNameType(Keyword,
11288 NNS: QualifierLoc.getNestedNameSpecifier(),
11289 Name: &II);
11290 }
11291
11292 // If the nested-name-specifier refers to the current instantiation,
11293 // the "typename" keyword itself is superfluous. In C++03, the
11294 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11295 // allows such extraneous "typename" keywords, and we retroactively
11296 // apply this DR to C++03 code with only a warning. In any case we continue.
11297
11298 if (RequireCompleteDeclContext(SS, DC: Ctx))
11299 return QualType();
11300 }
11301
11302 DeclarationName Name(&II);
11303 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11304 if (Ctx)
11305 LookupQualifiedName(R&: Result, LookupCtx: Ctx, SS);
11306 else
11307 LookupName(R&: Result, S: CurScope);
11308 unsigned DiagID = 0;
11309 Decl *Referenced = nullptr;
11310 switch (Result.getResultKind()) {
11311 case LookupResultKind::NotFound: {
11312 // If we're looking up 'type' within a template named 'enable_if', produce
11313 // a more specific diagnostic.
11314 SourceRange CondRange;
11315 Expr *Cond = nullptr;
11316 if (Ctx && isEnableIf(NNS: QualifierLoc, II, CondRange, Cond)) {
11317 // If we have a condition, narrow it down to the specific failed
11318 // condition.
11319 if (Cond) {
11320 Expr *FailedCond;
11321 std::string FailedDescription;
11322 std::tie(args&: FailedCond, args&: FailedDescription) =
11323 findFailedBooleanCondition(Cond);
11324
11325 Diag(Loc: FailedCond->getExprLoc(),
11326 DiagID: diag::err_typename_nested_not_found_requirement)
11327 << FailedDescription
11328 << FailedCond->getSourceRange();
11329 return QualType();
11330 }
11331
11332 Diag(Loc: CondRange.getBegin(),
11333 DiagID: diag::err_typename_nested_not_found_enable_if)
11334 << Ctx << CondRange;
11335 return QualType();
11336 }
11337
11338 DiagID = Ctx ? diag::err_typename_nested_not_found
11339 : diag::err_unknown_typename;
11340 break;
11341 }
11342
11343 case LookupResultKind::FoundUnresolvedValue: {
11344 // We found a using declaration that is a value. Most likely, the using
11345 // declaration itself is meant to have the 'typename' keyword.
11346 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11347 IILoc);
11348 Diag(Loc: IILoc, DiagID: diag::err_typename_refers_to_using_value_decl)
11349 << Name << Ctx << FullRange;
11350 if (UnresolvedUsingValueDecl *Using
11351 = dyn_cast<UnresolvedUsingValueDecl>(Val: Result.getRepresentativeDecl())){
11352 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11353 Diag(Loc, DiagID: diag::note_using_value_decl_missing_typename)
11354 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
11355 }
11356 }
11357 // Fall through to create a dependent typename type, from which we can
11358 // recover better.
11359 [[fallthrough]];
11360
11361 case LookupResultKind::NotFoundInCurrentInstantiation:
11362 // Okay, it's a member of an unknown instantiation.
11363 return Context.getDependentNameType(Keyword,
11364 NNS: QualifierLoc.getNestedNameSpecifier(),
11365 Name: &II);
11366
11367 case LookupResultKind::Found:
11368 // FXIME: Missing support for UsingShadowDecl on this path?
11369 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: Result.getFoundDecl())) {
11370 // C++ [class.qual]p2:
11371 // In a lookup in which function names are not ignored and the
11372 // nested-name-specifier nominates a class C, if the name specified
11373 // after the nested-name-specifier, when looked up in C, is the
11374 // injected-class-name of C [...] then the name is instead considered
11375 // to name the constructor of class C.
11376 //
11377 // Unlike in an elaborated-type-specifier, function names are not ignored
11378 // in typename-specifier lookup. However, they are ignored in all the
11379 // contexts where we form a typename type with no keyword (that is, in
11380 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11381 //
11382 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11383 // ignore functions, but that appears to be an oversight.
11384 checkTypeDeclType(LookupCtx: Ctx,
11385 DCK: Keyword == ElaboratedTypeKeyword::Typename
11386 ? DiagCtorKind::Typename
11387 : DiagCtorKind::None,
11388 TD: Type, NameLoc: IILoc);
11389 // FIXME: This appears to be the only case where a template type parameter
11390 // can have an elaborated keyword. We should preserve it somehow.
11391 if (isa<TemplateTypeParmDecl>(Val: Type)) {
11392 assert(Keyword == ElaboratedTypeKeyword::Typename);
11393 assert(!QualifierLoc);
11394 Keyword = ElaboratedTypeKeyword::None;
11395 }
11396 return Context.getTypeDeclType(
11397 Keyword, Qualifier: QualifierLoc.getNestedNameSpecifier(), Decl: Type);
11398 }
11399
11400 // C++ [dcl.type.simple]p2:
11401 // A type-specifier of the form
11402 // typename[opt] nested-name-specifier[opt] template-name
11403 // is a placeholder for a deduced class type [...].
11404 if (getLangOpts().CPlusPlus17) {
11405 if (auto *TD = getAsTypeTemplateDecl(D: Result.getFoundDecl())) {
11406 if (!DeducedTSTContext) {
11407 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11408 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11409 Diag(Loc: IILoc, DiagID: diag::err_dependent_deduced_tst)
11410 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
11411 << QualType(Qualifier.getAsType(), 0);
11412 else
11413 Diag(Loc: IILoc, DiagID: diag::err_deduced_tst)
11414 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD));
11415 NoteTemplateLocation(Decl: *TD);
11416 return QualType();
11417 }
11418 TemplateName Name = Context.getQualifiedTemplateName(
11419 Qualifier: QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11420 Template: TemplateName(TD));
11421 return Context.getDeducedTemplateSpecializationType(
11422 DK: DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11423 Template: Name);
11424 }
11425 }
11426
11427 DiagID = Ctx ? diag::err_typename_nested_not_type
11428 : diag::err_typename_not_type;
11429 Referenced = Result.getFoundDecl();
11430 break;
11431
11432 case LookupResultKind::FoundOverloaded:
11433 DiagID = Ctx ? diag::err_typename_nested_not_type
11434 : diag::err_typename_not_type;
11435 Referenced = *Result.begin();
11436 break;
11437
11438 case LookupResultKind::Ambiguous:
11439 return QualType();
11440 }
11441
11442 // If we get here, it's because name lookup did not find a
11443 // type. Emit an appropriate diagnostic and return an error.
11444 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11445 IILoc);
11446 if (Ctx)
11447 Diag(Loc: IILoc, DiagID) << FullRange << Name << Ctx;
11448 else
11449 Diag(Loc: IILoc, DiagID) << FullRange << Name;
11450 if (Referenced)
11451 Diag(Loc: Referenced->getLocation(),
11452 DiagID: Ctx ? diag::note_typename_member_refers_here
11453 : diag::note_typename_refers_here)
11454 << Name;
11455 return QualType();
11456}
11457
11458namespace {
11459 // See Sema::RebuildTypeInCurrentInstantiation
11460 class CurrentInstantiationRebuilder
11461 : public TreeTransform<CurrentInstantiationRebuilder> {
11462 SourceLocation Loc;
11463 DeclarationName Entity;
11464
11465 public:
11466 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11467
11468 CurrentInstantiationRebuilder(Sema &SemaRef,
11469 SourceLocation Loc,
11470 DeclarationName Entity)
11471 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11472 Loc(Loc), Entity(Entity) { }
11473
11474 /// Determine whether the given type \p T has already been
11475 /// transformed.
11476 ///
11477 /// For the purposes of type reconstruction, a type has already been
11478 /// transformed if it is NULL or if it is not dependent.
11479 bool AlreadyTransformed(QualType T) {
11480 return T.isNull() || !T->isInstantiationDependentType();
11481 }
11482
11483 /// Returns the location of the entity whose type is being
11484 /// rebuilt.
11485 SourceLocation getBaseLocation() { return Loc; }
11486
11487 /// Returns the name of the entity whose type is being rebuilt.
11488 DeclarationName getBaseEntity() { return Entity; }
11489
11490 /// Sets the "base" location and entity when that
11491 /// information is known based on another transformation.
11492 void setBase(SourceLocation Loc, DeclarationName Entity) {
11493 this->Loc = Loc;
11494 this->Entity = Entity;
11495 }
11496
11497 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11498 // Lambdas never need to be transformed.
11499 return E;
11500 }
11501 };
11502} // end anonymous namespace
11503
11504TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11505 SourceLocation Loc,
11506 DeclarationName Name) {
11507 if (!T || !T->getType()->isInstantiationDependentType())
11508 return T;
11509
11510 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11511 return Rebuilder.TransformType(TSI: T);
11512}
11513
11514ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11515 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11516 DeclarationName());
11517 return Rebuilder.TransformExpr(E);
11518}
11519
11520bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11521 if (SS.isInvalid())
11522 return true;
11523
11524 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11525 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11526 DeclarationName());
11527 NestedNameSpecifierLoc Rebuilt
11528 = Rebuilder.TransformNestedNameSpecifierLoc(NNS: QualifierLoc);
11529 if (!Rebuilt)
11530 return true;
11531
11532 SS.Adopt(Other: Rebuilt);
11533 return false;
11534}
11535
11536bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11537 TemplateParameterList *Params) {
11538 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11539 Decl *Param = Params->getParam(Idx: I);
11540
11541 // There is nothing to rebuild in a type parameter.
11542 if (isa<TemplateTypeParmDecl>(Val: Param))
11543 continue;
11544
11545 // Rebuild the template parameter list of a template template parameter.
11546 if (TemplateTemplateParmDecl *TTP
11547 = dyn_cast<TemplateTemplateParmDecl>(Val: Param)) {
11548 if (RebuildTemplateParamsInCurrentInstantiation(
11549 Params: TTP->getTemplateParameters()))
11550 return true;
11551
11552 continue;
11553 }
11554
11555 // Rebuild the type of a non-type template parameter.
11556 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Val: Param);
11557 TypeSourceInfo *NewTSI
11558 = RebuildTypeInCurrentInstantiation(T: NTTP->getTypeSourceInfo(),
11559 Loc: NTTP->getLocation(),
11560 Name: NTTP->getDeclName());
11561 if (!NewTSI)
11562 return true;
11563
11564 if (NewTSI->getType()->isUndeducedType()) {
11565 // C++17 [temp.dep.expr]p3:
11566 // An id-expression is type-dependent if it contains
11567 // - an identifier associated by name lookup with a non-type
11568 // template-parameter declared with a type that contains a
11569 // placeholder type (7.1.7.4),
11570 NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: NewTSI);
11571 }
11572
11573 if (NewTSI != NTTP->getTypeSourceInfo()) {
11574 NTTP->setTypeSourceInfo(NewTSI);
11575 NTTP->setType(NewTSI->getType());
11576 }
11577 }
11578
11579 return false;
11580}
11581
11582std::string
11583Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11584 const TemplateArgumentList &Args) {
11585 return getTemplateArgumentBindingsText(Params, Args: Args.data(), NumArgs: Args.size());
11586}
11587
11588std::string
11589Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11590 const TemplateArgument *Args,
11591 unsigned NumArgs) {
11592 SmallString<128> Str;
11593 llvm::raw_svector_ostream Out(Str);
11594
11595 if (!Params || Params->size() == 0 || NumArgs == 0)
11596 return std::string();
11597
11598 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11599 if (I >= NumArgs)
11600 break;
11601
11602 if (I == 0)
11603 Out << "[with ";
11604 else
11605 Out << ", ";
11606
11607 if (const IdentifierInfo *Id = Params->getParam(Idx: I)->getIdentifier()) {
11608 Out << Id->getName();
11609 } else {
11610 Out << '$' << I;
11611 }
11612
11613 Out << " = ";
11614 Args[I].print(Policy: getPrintingPolicy(), Out,
11615 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
11616 Policy: getPrintingPolicy(), TPL: Params, Idx: I));
11617 }
11618
11619 Out << ']';
11620 return std::string(Out.str());
11621}
11622
11623void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11624 CachedTokens &Toks) {
11625 if (!FD)
11626 return;
11627
11628 auto LPT = std::make_unique<LateParsedTemplate>();
11629
11630 // Take tokens to avoid allocations
11631 LPT->Toks.swap(RHS&: Toks);
11632 LPT->D = FnD;
11633 LPT->FPO = getCurFPFeatures();
11634 LateParsedTemplateMap.insert(KV: std::make_pair(x&: FD, y: std::move(LPT)));
11635
11636 FD->setLateTemplateParsed(true);
11637}
11638
11639void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11640 if (!FD)
11641 return;
11642 FD->setLateTemplateParsed(false);
11643}
11644
11645bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11646 DeclContext *DC = CurContext;
11647
11648 while (DC) {
11649 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
11650 const FunctionDecl *FD = RD->isLocalClass();
11651 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11652 } else if (DC->isTranslationUnit() || DC->isNamespace())
11653 return false;
11654
11655 DC = DC->getParent();
11656 }
11657 return false;
11658}
11659
11660namespace {
11661/// Walk the path from which a declaration was instantiated, and check
11662/// that every explicit specialization along that path is visible. This enforces
11663/// C++ [temp.expl.spec]/6:
11664///
11665/// If a template, a member template or a member of a class template is
11666/// explicitly specialized then that specialization shall be declared before
11667/// the first use of that specialization that would cause an implicit
11668/// instantiation to take place, in every translation unit in which such a
11669/// use occurs; no diagnostic is required.
11670///
11671/// and also C++ [temp.class.spec]/1:
11672///
11673/// A partial specialization shall be declared before the first use of a
11674/// class template specialization that would make use of the partial
11675/// specialization as the result of an implicit or explicit instantiation
11676/// in every translation unit in which such a use occurs; no diagnostic is
11677/// required.
11678class ExplicitSpecializationVisibilityChecker {
11679 Sema &S;
11680 SourceLocation Loc;
11681 llvm::SmallVector<Module *, 8> Modules;
11682 Sema::AcceptableKind Kind;
11683
11684public:
11685 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11686 Sema::AcceptableKind Kind)
11687 : S(S), Loc(Loc), Kind(Kind) {}
11688
11689 void check(NamedDecl *ND) {
11690 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
11691 return checkImpl(Spec: FD);
11692 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
11693 return checkImpl(Spec: RD);
11694 if (auto *VD = dyn_cast<VarDecl>(Val: ND))
11695 return checkImpl(Spec: VD);
11696 if (auto *ED = dyn_cast<EnumDecl>(Val: ND))
11697 return checkImpl(Spec: ED);
11698 }
11699
11700private:
11701 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11702 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11703 : Sema::MissingImportKind::ExplicitSpecialization;
11704 const bool Recover = true;
11705
11706 // If we got a custom set of modules (because only a subset of the
11707 // declarations are interesting), use them, otherwise let
11708 // diagnoseMissingImport intelligently pick some.
11709 if (Modules.empty())
11710 S.diagnoseMissingImport(Loc, Decl: D, MIK: Kind, Recover);
11711 else
11712 S.diagnoseMissingImport(Loc, Decl: D, DeclLoc: D->getLocation(), Modules, MIK: Kind, Recover);
11713 }
11714
11715 bool CheckMemberSpecialization(const NamedDecl *D) {
11716 return Kind == Sema::AcceptableKind::Visible
11717 ? S.hasVisibleMemberSpecialization(D)
11718 : S.hasReachableMemberSpecialization(D);
11719 }
11720
11721 bool CheckExplicitSpecialization(const NamedDecl *D) {
11722 return Kind == Sema::AcceptableKind::Visible
11723 ? S.hasVisibleExplicitSpecialization(D)
11724 : S.hasReachableExplicitSpecialization(D);
11725 }
11726
11727 bool CheckDeclaration(const NamedDecl *D) {
11728 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11729 : S.hasReachableDeclaration(D);
11730 }
11731
11732 // Check a specific declaration. There are three problematic cases:
11733 //
11734 // 1) The declaration is an explicit specialization of a template
11735 // specialization.
11736 // 2) The declaration is an explicit specialization of a member of an
11737 // templated class.
11738 // 3) The declaration is an instantiation of a template, and that template
11739 // is an explicit specialization of a member of a templated class.
11740 //
11741 // We don't need to go any deeper than that, as the instantiation of the
11742 // surrounding class / etc is not triggered by whatever triggered this
11743 // instantiation, and thus should be checked elsewhere.
11744 template<typename SpecDecl>
11745 void checkImpl(SpecDecl *Spec) {
11746 bool IsHiddenExplicitSpecialization = false;
11747 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11748 // Some invalid friend declarations are written as specializations but are
11749 // instantiated implicitly.
11750 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11751 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11752 if (SpecKind == TSK_ExplicitSpecialization) {
11753 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11754 ? !CheckMemberSpecialization(D: Spec)
11755 : !CheckExplicitSpecialization(D: Spec);
11756 } else {
11757 checkInstantiated(Spec);
11758 }
11759
11760 if (IsHiddenExplicitSpecialization)
11761 diagnose(D: Spec->getMostRecentDecl(), IsPartialSpec: false);
11762 }
11763
11764 void checkInstantiated(FunctionDecl *FD) {
11765 if (auto *TD = FD->getPrimaryTemplate())
11766 checkTemplate(TD);
11767 }
11768
11769 void checkInstantiated(CXXRecordDecl *RD) {
11770 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD);
11771 if (!SD)
11772 return;
11773
11774 auto From = SD->getSpecializedTemplateOrPartial();
11775 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11776 checkTemplate(TD);
11777 else if (auto *TD =
11778 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11779 if (!CheckDeclaration(D: TD))
11780 diagnose(D: TD, IsPartialSpec: true);
11781 checkTemplate(TD);
11782 }
11783 }
11784
11785 void checkInstantiated(VarDecl *RD) {
11786 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(Val: RD);
11787 if (!SD)
11788 return;
11789
11790 auto From = SD->getSpecializedTemplateOrPartial();
11791 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11792 checkTemplate(TD);
11793 else if (auto *TD =
11794 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11795 if (!CheckDeclaration(D: TD))
11796 diagnose(D: TD, IsPartialSpec: true);
11797 checkTemplate(TD);
11798 }
11799 }
11800
11801 void checkInstantiated(EnumDecl *FD) {}
11802
11803 template<typename TemplDecl>
11804 void checkTemplate(TemplDecl *TD) {
11805 if (TD->isMemberSpecialization()) {
11806 if (!CheckMemberSpecialization(D: TD))
11807 diagnose(D: TD->getMostRecentDecl(), IsPartialSpec: false);
11808 }
11809 }
11810};
11811} // end anonymous namespace
11812
11813void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
11814 if (!getLangOpts().Modules)
11815 return;
11816
11817 ExplicitSpecializationVisibilityChecker(*this, Loc,
11818 Sema::AcceptableKind::Visible)
11819 .check(ND: Spec);
11820}
11821
11822void Sema::checkSpecializationReachability(SourceLocation Loc,
11823 NamedDecl *Spec) {
11824 if (!getLangOpts().CPlusPlusModules)
11825 return checkSpecializationVisibility(Loc, Spec);
11826
11827 ExplicitSpecializationVisibilityChecker(*this, Loc,
11828 Sema::AcceptableKind::Reachable)
11829 .check(ND: Spec);
11830}
11831
11832SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
11833 if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
11834 return N->getLocation();
11835 if (const auto *FD = dyn_cast<FunctionDecl>(Val: N)) {
11836 if (!FD->isFunctionTemplateSpecialization())
11837 return FD->getLocation();
11838 } else if (!isa<ClassTemplateSpecializationDecl,
11839 VarTemplateSpecializationDecl>(Val: N)) {
11840 return N->getLocation();
11841 }
11842 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11843 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11844 continue;
11845 return CSC.PointOfInstantiation;
11846 }
11847 return N->getLocation();
11848}
11849