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 QualifiedLookupValidatorCCC FilterCCC(!SS.isEmpty());
523 FilterCCC.WantTypeSpecifiers = false;
524 FilterCCC.WantExpressionKeywords = false;
525 FilterCCC.WantRemainingKeywords = false;
526 FilterCCC.WantCXXNamedCasts = true;
527 if (TypoCorrection Corrected = CorrectTypo(
528 Typo: Found.getLookupNameInfo(), LookupKind: Found.getLookupKind(), S, SS: &SS, CCC&: FilterCCC,
529 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
530 if (auto *ND = Corrected.getFoundDecl())
531 Found.addDecl(D: ND);
532 FilterAcceptableTemplateNames(R&: Found);
533 if (Found.isAmbiguous()) {
534 Found.clear();
535 } else if (!Found.empty()) {
536 // Do not erase the typo-corrected result to avoid duplicated
537 // diagnostics.
538 AllowFunctionTemplatesInLookup = true;
539 Found.setLookupName(Corrected.getCorrection());
540 if (LookupCtx) {
541 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
542 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
543 Name.getAsString() == CorrectedStr;
544 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_template_suggest)
545 << Name << LookupCtx << DroppedSpecifier
546 << SS.getRange());
547 } else {
548 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_template_suggest) << Name);
549 }
550 }
551 }
552 }
553
554 NamedDecl *ExampleLookupResult =
555 Found.empty() ? nullptr : Found.getRepresentativeDecl();
556 FilterAcceptableTemplateNames(R&: Found, AllowFunctionTemplates: AllowFunctionTemplatesInLookup);
557 if (Found.empty()) {
558 if (IsDependent) {
559 Found.setNotFoundInCurrentInstantiation();
560 return false;
561 }
562
563 // If a 'template' keyword was used, a lookup that finds only non-template
564 // names is an error.
565 if (ExampleLookupResult && RequiredTemplate) {
566 Diag(Loc: Found.getNameLoc(), DiagID: diag::err_template_kw_refers_to_non_template)
567 << Found.getLookupName() << SS.getRange()
568 << RequiredTemplate.hasTemplateKeyword()
569 << RequiredTemplate.getTemplateKeywordLoc();
570 Diag(Loc: ExampleLookupResult->getUnderlyingDecl()->getLocation(),
571 DiagID: diag::note_template_kw_refers_to_non_template)
572 << Found.getLookupName();
573 return true;
574 }
575
576 return false;
577 }
578
579 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
580 !getLangOpts().CPlusPlus11) {
581 // C++03 [basic.lookup.classref]p1:
582 // [...] If the lookup in the class of the object expression finds a
583 // template, the name is also looked up in the context of the entire
584 // postfix-expression and [...]
585 //
586 // Note: C++11 does not perform this second lookup.
587 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
588 LookupOrdinaryName);
589 FoundOuter.setTemplateNameLookup(true);
590 LookupName(R&: FoundOuter, S);
591 // FIXME: We silently accept an ambiguous lookup here, in violation of
592 // [basic.lookup]/1.
593 FilterAcceptableTemplateNames(R&: FoundOuter, /*AllowFunctionTemplates=*/false);
594
595 NamedDecl *OuterTemplate;
596 if (FoundOuter.empty()) {
597 // - if the name is not found, the name found in the class of the
598 // object expression is used, otherwise
599 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
600 !(OuterTemplate =
601 getAsTemplateNameDecl(D: FoundOuter.getFoundDecl()))) {
602 // - if the name is found in the context of the entire
603 // postfix-expression and does not name a class template, the name
604 // found in the class of the object expression is used, otherwise
605 FoundOuter.clear();
606 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
607 // - if the name found is a class template, it must refer to the same
608 // entity as the one found in the class of the object expression,
609 // otherwise the program is ill-formed.
610 if (!Found.isSingleResult() ||
611 getAsTemplateNameDecl(D: Found.getFoundDecl())->getCanonicalDecl() !=
612 OuterTemplate->getCanonicalDecl()) {
613 Diag(Loc: Found.getNameLoc(),
614 DiagID: diag::ext_nested_name_member_ref_lookup_ambiguous)
615 << Found.getLookupName()
616 << ObjectType;
617 Diag(Loc: Found.getRepresentativeDecl()->getLocation(),
618 DiagID: diag::note_ambig_member_ref_object_type)
619 << ObjectType;
620 Diag(Loc: FoundOuter.getFoundDecl()->getLocation(),
621 DiagID: diag::note_ambig_member_ref_scope);
622
623 // Recover by taking the template that we found in the object
624 // expression's type.
625 }
626 }
627 }
628
629 return false;
630}
631
632void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
633 SourceLocation Less,
634 SourceLocation Greater) {
635 if (TemplateName.isInvalid())
636 return;
637
638 DeclarationNameInfo NameInfo;
639 CXXScopeSpec SS;
640 LookupNameKind LookupKind;
641
642 DeclContext *LookupCtx = nullptr;
643 NamedDecl *Found = nullptr;
644 bool MissingTemplateKeyword = false;
645
646 // Figure out what name we looked up.
647 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: TemplateName.get())) {
648 NameInfo = DRE->getNameInfo();
649 SS.Adopt(Other: DRE->getQualifierLoc());
650 LookupKind = LookupOrdinaryName;
651 Found = DRE->getFoundDecl();
652 } else if (auto *ME = dyn_cast<MemberExpr>(Val: TemplateName.get())) {
653 NameInfo = ME->getMemberNameInfo();
654 SS.Adopt(Other: ME->getQualifierLoc());
655 LookupKind = LookupMemberName;
656 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
657 Found = ME->getMemberDecl();
658 } else if (auto *DSDRE =
659 dyn_cast<DependentScopeDeclRefExpr>(Val: TemplateName.get())) {
660 NameInfo = DSDRE->getNameInfo();
661 SS.Adopt(Other: DSDRE->getQualifierLoc());
662 MissingTemplateKeyword = true;
663 } else if (auto *DSME =
664 dyn_cast<CXXDependentScopeMemberExpr>(Val: TemplateName.get())) {
665 NameInfo = DSME->getMemberNameInfo();
666 SS.Adopt(Other: DSME->getQualifierLoc());
667 MissingTemplateKeyword = true;
668 } else {
669 llvm_unreachable("unexpected kind of potential template name");
670 }
671
672 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
673 // was missing.
674 if (MissingTemplateKeyword) {
675 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_template_kw_missing)
676 << NameInfo.getName() << SourceRange(Less, Greater);
677 return;
678 }
679
680 // Try to correct the name by looking for templates and C++ named casts.
681 struct TemplateCandidateFilter : CorrectionCandidateCallback {
682 Sema &S;
683 TemplateCandidateFilter(Sema &S) : S(S) {
684 WantTypeSpecifiers = false;
685 WantExpressionKeywords = false;
686 WantRemainingKeywords = false;
687 WantCXXNamedCasts = true;
688 };
689 bool ValidateCandidate(const TypoCorrection &Candidate) override {
690 if (auto *ND = Candidate.getCorrectionDecl())
691 return S.getAsTemplateNameDecl(D: ND);
692 return Candidate.isKeyword();
693 }
694
695 std::unique_ptr<CorrectionCandidateCallback> clone() override {
696 return std::make_unique<TemplateCandidateFilter>(args&: *this);
697 }
698 };
699
700 DeclarationName Name = NameInfo.getName();
701 TemplateCandidateFilter CCC(*this);
702 if (TypoCorrection Corrected =
703 CorrectTypo(Typo: NameInfo, LookupKind, S, SS: &SS, CCC,
704 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
705 auto *ND = Corrected.getFoundDecl();
706 if (ND)
707 ND = getAsTemplateNameDecl(D: ND);
708 if (ND || Corrected.isKeyword()) {
709 if (LookupCtx) {
710 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
711 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
712 Name.getAsString() == CorrectedStr;
713 diagnoseTypo(Correction: Corrected,
714 TypoDiag: PDiag(DiagID: diag::err_non_template_in_member_template_id_suggest)
715 << Name << LookupCtx << DroppedSpecifier
716 << SS.getRange(), ErrorRecovery: false);
717 } else {
718 diagnoseTypo(Correction: Corrected,
719 TypoDiag: PDiag(DiagID: diag::err_non_template_in_template_id_suggest)
720 << Name, ErrorRecovery: false);
721 }
722 if (Found)
723 Diag(Loc: Found->getLocation(),
724 DiagID: diag::note_non_template_in_template_id_found);
725 return;
726 }
727 }
728
729 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_non_template_in_template_id)
730 << Name << SourceRange(Less, Greater);
731 if (Found)
732 Diag(Loc: Found->getLocation(), DiagID: diag::note_non_template_in_template_id_found);
733}
734
735ExprResult
736Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
737 SourceLocation TemplateKWLoc,
738 const DeclarationNameInfo &NameInfo,
739 bool isAddressOfOperand,
740 const TemplateArgumentListInfo *TemplateArgs) {
741 if (SS.isEmpty()) {
742 // FIXME: This codepath is only used by dependent unqualified names
743 // (e.g. a dependent conversion-function-id, or operator= once we support
744 // it). It doesn't quite do the right thing, and it will silently fail if
745 // getCurrentThisType() returns null.
746 QualType ThisType = getCurrentThisType();
747 if (ThisType.isNull())
748 return ExprError();
749
750 return CXXDependentScopeMemberExpr::Create(
751 Ctx: Context, /*Base=*/nullptr, BaseType: ThisType,
752 /*IsArrow=*/!Context.getLangOpts().HLSL,
753 /*OperatorLoc=*/SourceLocation(),
754 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
755 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
756 }
757 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
758}
759
760ExprResult
761Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
762 SourceLocation TemplateKWLoc,
763 const DeclarationNameInfo &NameInfo,
764 const TemplateArgumentListInfo *TemplateArgs) {
765 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
766 if (!SS.isValid())
767 return CreateRecoveryExpr(
768 Begin: SS.getBeginLoc(),
769 End: TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), SubExprs: {});
770
771 return DependentScopeDeclRefExpr::Create(
772 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
773 TemplateArgs);
774}
775
776ExprResult Sema::BuildSubstNonTypeTemplateParmExpr(
777 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *NTTP,
778 SourceLocation Loc, TemplateArgument Arg, UnsignedOrNone PackIndex,
779 bool Final) {
780 // The template argument itself might be an expression, in which case we just
781 // return that expression. This happens when substituting into an alias
782 // template.
783 Expr *Replacement;
784 bool refParam = true;
785 if (Arg.getKind() == TemplateArgument::Expression) {
786 Replacement = Arg.getAsExpr();
787 refParam = Replacement->isLValue();
788 if (refParam && Replacement->getType()->isRecordType()) {
789 QualType ParamType =
790 NTTP->isExpandedParameterPack()
791 ? NTTP->getExpansionType(I: *SemaRef.ArgPackSubstIndex)
792 : NTTP->getType();
793 if (const auto *PET = dyn_cast<PackExpansionType>(Val&: ParamType))
794 ParamType = PET->getPattern();
795 refParam = ParamType->isReferenceType();
796 }
797 } else {
798 ExprResult result =
799 SemaRef.BuildExpressionFromNonTypeTemplateArgument(Arg, Loc);
800 if (result.isInvalid())
801 return ExprError();
802 Replacement = result.get();
803 refParam = Arg.getNonTypeTemplateArgumentType()->isReferenceType();
804 }
805 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
806 Replacement->getType(), Replacement->getValueKind(), Loc, Replacement,
807 AssociatedDecl, NTTP->getIndex(), PackIndex, refParam, Final);
808}
809
810bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
811 NamedDecl *Instantiation,
812 bool InstantiatedFromMember,
813 const NamedDecl *Pattern,
814 const NamedDecl *PatternDef,
815 TemplateSpecializationKind TSK,
816 bool Complain, bool *Unreachable) {
817 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
818 isa<VarDecl>(Instantiation));
819
820 bool IsEntityBeingDefined = false;
821 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(Val: PatternDef))
822 IsEntityBeingDefined = TD->isBeingDefined();
823
824 if (PatternDef && !IsEntityBeingDefined) {
825 NamedDecl *SuggestedDef = nullptr;
826 if (!hasReachableDefinition(D: const_cast<NamedDecl *>(PatternDef),
827 Suggested: &SuggestedDef,
828 /*OnlyNeedComplete*/ false)) {
829 if (Unreachable)
830 *Unreachable = true;
831 // If we're allowed to diagnose this and recover, do so.
832 bool Recover = Complain && !isSFINAEContext();
833 if (Complain)
834 diagnoseMissingImport(Loc: PointOfInstantiation, Decl: SuggestedDef,
835 MIK: Sema::MissingImportKind::Definition, Recover);
836 return !Recover;
837 }
838 return false;
839 }
840
841 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
842 return true;
843
844 CanQualType InstantiationTy;
845 if (TagDecl *TD = dyn_cast<TagDecl>(Val: Instantiation))
846 InstantiationTy = Context.getCanonicalTagType(TD);
847 if (PatternDef) {
848 Diag(Loc: PointOfInstantiation,
849 DiagID: diag::err_template_instantiate_within_definition)
850 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
851 << InstantiationTy;
852 // Not much point in noting the template declaration here, since
853 // we're lexically inside it.
854 Instantiation->setInvalidDecl();
855 } else if (InstantiatedFromMember) {
856 if (isa<FunctionDecl>(Val: Instantiation)) {
857 Diag(Loc: PointOfInstantiation,
858 DiagID: diag::err_explicit_instantiation_undefined_member)
859 << /*member function*/ 1 << Instantiation->getDeclName()
860 << Instantiation->getDeclContext();
861 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
862 } else {
863 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
864 Diag(Loc: PointOfInstantiation,
865 DiagID: diag::err_implicit_instantiate_member_undefined)
866 << InstantiationTy;
867 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_member_declared_at);
868 }
869 } else {
870 if (isa<FunctionDecl>(Val: Instantiation)) {
871 Diag(Loc: PointOfInstantiation,
872 DiagID: diag::err_explicit_instantiation_undefined_func_template)
873 << Pattern;
874 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
875 } else if (isa<TagDecl>(Val: Instantiation)) {
876 Diag(Loc: PointOfInstantiation, DiagID: diag::err_template_instantiate_undefined)
877 << (TSK != TSK_ImplicitInstantiation)
878 << InstantiationTy;
879 NoteTemplateLocation(Decl: *Pattern);
880 } else {
881 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
882 if (isa<VarTemplateSpecializationDecl>(Val: Instantiation)) {
883 Diag(Loc: PointOfInstantiation,
884 DiagID: diag::err_explicit_instantiation_undefined_var_template)
885 << Instantiation;
886 Instantiation->setInvalidDecl();
887 } else
888 Diag(Loc: PointOfInstantiation,
889 DiagID: diag::err_explicit_instantiation_undefined_member)
890 << /*static data member*/ 2 << Instantiation->getDeclName()
891 << Instantiation->getDeclContext();
892 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
893 }
894 }
895
896 // In general, Instantiation isn't marked invalid to get more than one
897 // error for multiple undefined instantiations. But the code that does
898 // explicit declaration -> explicit definition conversion can't handle
899 // invalid declarations, so mark as invalid in that case.
900 if (TSK == TSK_ExplicitInstantiationDeclaration)
901 Instantiation->setInvalidDecl();
902 return true;
903}
904
905void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
906 bool SupportedForCompatibility) {
907 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
908
909 // C++23 [temp.local]p6:
910 // The name of a template-parameter shall not be bound to any following.
911 // declaration whose locus is contained by the scope to which the
912 // template-parameter belongs.
913 //
914 // When MSVC compatibility is enabled, the diagnostic is always a warning
915 // by default. Otherwise, it an error unless SupportedForCompatibility is
916 // true, in which case it is a default-to-error warning.
917 unsigned DiagId =
918 getLangOpts().MSVCCompat
919 ? diag::ext_template_param_shadow
920 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
921 : diag::err_template_param_shadow);
922 const auto *ND = cast<NamedDecl>(Val: PrevDecl);
923 Diag(Loc, DiagID: DiagId) << ND->getDeclName();
924 NoteTemplateParameterLocation(Decl: *ND);
925}
926
927TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
928 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(Val: D)) {
929 D = Temp->getTemplatedDecl();
930 return Temp;
931 }
932 return nullptr;
933}
934
935ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
936 SourceLocation EllipsisLoc) const {
937 assert(Kind == Template &&
938 "Only template template arguments can be pack expansions here");
939 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
940 "Template template argument pack expansion without packs");
941 ParsedTemplateArgument Result(*this);
942 Result.EllipsisLoc = EllipsisLoc;
943 return Result;
944}
945
946static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
947 const ParsedTemplateArgument &Arg) {
948
949 switch (Arg.getKind()) {
950 case ParsedTemplateArgument::Type: {
951 TypeSourceInfo *TSI;
952 QualType T = SemaRef.GetTypeFromParser(Ty: Arg.getAsType(), TInfo: &TSI);
953 if (!TSI)
954 TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc: Arg.getNameLoc());
955 return TemplateArgumentLoc(TemplateArgument(T), TSI);
956 }
957
958 case ParsedTemplateArgument::NonType: {
959 Expr *E = Arg.getAsExpr();
960 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
961 }
962
963 case ParsedTemplateArgument::Template: {
964 TemplateName Template = Arg.getAsTemplate().get();
965 TemplateArgument TArg;
966 if (Arg.getEllipsisLoc().isValid())
967 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
968 else
969 TArg = Template;
970 return TemplateArgumentLoc(
971 SemaRef.Context, TArg, Arg.getTemplateKwLoc(),
972 Arg.getScopeSpec().getWithLocInContext(Context&: SemaRef.Context),
973 Arg.getNameLoc(), Arg.getEllipsisLoc());
974 }
975 }
976
977 llvm_unreachable("Unhandled parsed template argument");
978}
979
980void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
981 TemplateArgumentListInfo &TemplateArgs) {
982 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
983 TemplateArgs.addArgument(Loc: translateTemplateArgument(SemaRef&: *this,
984 Arg: TemplateArgsIn[I]));
985}
986
987static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
988 SourceLocation Loc,
989 const IdentifierInfo *Name) {
990 NamedDecl *PrevDecl =
991 SemaRef.LookupSingleName(S, Name, Loc, NameKind: Sema::LookupOrdinaryName,
992 Redecl: RedeclarationKind::ForVisibleRedeclaration);
993 if (PrevDecl && PrevDecl->isTemplateParameter())
994 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
995}
996
997ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
998 TypeSourceInfo *TInfo;
999 QualType T = GetTypeFromParser(Ty: ParsedType.get(), TInfo: &TInfo);
1000 if (T.isNull())
1001 return ParsedTemplateArgument();
1002 assert(TInfo && "template argument with no location");
1003
1004 // If we might have formed a deduced template specialization type, convert
1005 // it to a template template argument.
1006 if (getLangOpts().CPlusPlus17) {
1007 TypeLoc TL = TInfo->getTypeLoc();
1008 SourceLocation EllipsisLoc;
1009 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
1010 EllipsisLoc = PET.getEllipsisLoc();
1011 TL = PET.getPatternLoc();
1012 }
1013
1014 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1015 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1016 CXXScopeSpec SS;
1017 SS.Adopt(Other: DTST.getQualifierLoc());
1018 ParsedTemplateArgument Result(/*TemplateKwLoc=*/SourceLocation(), SS,
1019 TemplateTy::make(P: Name),
1020 DTST.getTemplateNameLoc());
1021 if (EllipsisLoc.isValid())
1022 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1023 return Result;
1024 }
1025 }
1026
1027 // This is a normal type template argument. Note, if the type template
1028 // argument is an injected-class-name for a template, it has a dual nature
1029 // and can be used as either a type or a template. We handle that in
1030 // convertTypeTemplateArgumentToTemplate.
1031 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1032 ParsedType.get().getAsOpaquePtr(),
1033 TInfo->getTypeLoc().getBeginLoc());
1034}
1035
1036NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
1037 SourceLocation EllipsisLoc,
1038 SourceLocation KeyLoc,
1039 IdentifierInfo *ParamName,
1040 SourceLocation ParamNameLoc,
1041 unsigned Depth, unsigned Position,
1042 SourceLocation EqualLoc,
1043 ParsedType DefaultArg,
1044 bool HasTypeConstraint) {
1045 assert(S->isTemplateParamScope() &&
1046 "Template type parameter not in template parameter scope!");
1047
1048 bool IsParameterPack = EllipsisLoc.isValid();
1049 TemplateTypeParmDecl *Param
1050 = TemplateTypeParmDecl::Create(C: Context, DC: Context.getTranslationUnitDecl(),
1051 KeyLoc, NameLoc: ParamNameLoc, D: Depth, P: Position,
1052 Id: ParamName, Typename, ParameterPack: IsParameterPack,
1053 HasTypeConstraint);
1054 Param->setAccess(AS_public);
1055
1056 if (Param->isParameterPack())
1057 if (auto *CSI = getEnclosingLambdaOrBlock())
1058 CSI->LocalPacks.push_back(Elt: Param);
1059
1060 if (ParamName) {
1061 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: ParamNameLoc, Name: ParamName);
1062
1063 // Add the template parameter into the current scope.
1064 S->AddDecl(D: Param);
1065 IdResolver.AddDecl(D: Param);
1066 }
1067
1068 // C++0x [temp.param]p9:
1069 // A default template-argument may be specified for any kind of
1070 // template-parameter that is not a template parameter pack.
1071 if (DefaultArg && IsParameterPack) {
1072 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1073 DefaultArg = nullptr;
1074 }
1075
1076 // Handle the default argument, if provided.
1077 if (DefaultArg) {
1078 TypeSourceInfo *DefaultTInfo;
1079 GetTypeFromParser(Ty: DefaultArg, TInfo: &DefaultTInfo);
1080
1081 assert(DefaultTInfo && "expected source information for type");
1082
1083 // Check for unexpanded parameter packs.
1084 if (DiagnoseUnexpandedParameterPack(Loc: ParamNameLoc, T: DefaultTInfo,
1085 UPPC: UPPC_DefaultArgument))
1086 return Param;
1087
1088 // Check the template argument itself.
1089 if (CheckTemplateArgument(Arg: DefaultTInfo)) {
1090 Param->setInvalidDecl();
1091 return Param;
1092 }
1093
1094 Param->setDefaultArgument(
1095 C: Context, DefArg: TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1096 }
1097
1098 return Param;
1099}
1100
1101/// Convert the parser's template argument list representation into our form.
1102static TemplateArgumentListInfo
1103makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1104 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1105 TemplateId.RAngleLoc);
1106 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1107 TemplateId.NumArgs);
1108 S.translateTemplateArguments(TemplateArgsIn: TemplateArgsPtr, TemplateArgs);
1109 return TemplateArgs;
1110}
1111
1112bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {
1113
1114 TemplateName TN = TypeConstr->Template.get();
1115 NamedDecl *CD = nullptr;
1116 bool IsTypeConcept = false;
1117 bool RequiresArguments = false;
1118 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: TN.getAsTemplateDecl())) {
1119 IsTypeConcept = TTP->isTypeConceptTemplateParam();
1120 RequiresArguments =
1121 TTP->getTemplateParameters()->getMinRequiredArguments() > 1;
1122 CD = TTP;
1123 } else {
1124 CD = TN.getAsTemplateDecl();
1125 IsTypeConcept = cast<ConceptDecl>(Val: CD)->isTypeConcept();
1126 RequiresArguments = cast<ConceptDecl>(Val: CD)
1127 ->getTemplateParameters()
1128 ->getMinRequiredArguments() > 1;
1129 }
1130
1131 // C++2a [temp.param]p4:
1132 // [...] The concept designated by a type-constraint shall be a type
1133 // concept ([temp.concept]).
1134 if (!IsTypeConcept) {
1135 Diag(Loc: TypeConstr->TemplateNameLoc,
1136 DiagID: diag::err_type_constraint_non_type_concept);
1137 return true;
1138 }
1139
1140 if (CheckConceptUseInDefinition(Concept: CD, Loc: TypeConstr->TemplateNameLoc))
1141 return true;
1142
1143 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1144
1145 if (!WereArgsSpecified && RequiresArguments) {
1146 Diag(Loc: TypeConstr->TemplateNameLoc,
1147 DiagID: diag::err_type_constraint_missing_arguments)
1148 << CD;
1149 return true;
1150 }
1151 return false;
1152}
1153
1154bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1155 TemplateIdAnnotation *TypeConstr,
1156 TemplateTypeParmDecl *ConstrainedParameter,
1157 SourceLocation EllipsisLoc) {
1158 return BuildTypeConstraint(SS, TypeConstraint: TypeConstr, ConstrainedParameter, EllipsisLoc,
1159 AllowUnexpandedPack: false);
1160}
1161
1162bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1163 TemplateIdAnnotation *TypeConstr,
1164 TemplateTypeParmDecl *ConstrainedParameter,
1165 SourceLocation EllipsisLoc,
1166 bool AllowUnexpandedPack) {
1167
1168 if (CheckTypeConstraint(TypeConstr))
1169 return true;
1170
1171 TemplateName TN = TypeConstr->Template.get();
1172 TemplateDecl *CD = cast<TemplateDecl>(Val: TN.getAsTemplateDecl());
1173 UsingShadowDecl *USD = TN.getAsUsingShadowDecl();
1174
1175 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1176 TypeConstr->TemplateNameLoc);
1177
1178 TemplateArgumentListInfo TemplateArgs;
1179 if (TypeConstr->LAngleLoc.isValid()) {
1180 TemplateArgs =
1181 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TypeConstr);
1182
1183 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1184 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1185 if (DiagnoseUnexpandedParameterPack(Arg, UPPC: UPPC_TypeConstraint))
1186 return true;
1187 }
1188 }
1189 }
1190 return AttachTypeConstraint(
1191 NS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1192 NameInfo: ConceptName, NamedConcept: CD, /*FoundDecl=*/USD ? cast<NamedDecl>(Val: USD) : CD,
1193 TemplateArgs: TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1194 ConstrainedParameter, EllipsisLoc);
1195}
1196
1197template <typename ArgumentLocAppender>
1198static ExprResult formImmediatelyDeclaredConstraint(
1199 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1200 NamedDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1201 SourceLocation RAngleLoc, QualType ConstrainedType,
1202 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1203 SourceLocation EllipsisLoc) {
1204
1205 TemplateArgumentListInfo ConstraintArgs;
1206 ConstraintArgs.addArgument(
1207 Loc: S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(ConstrainedType),
1208 /*NTTPType=*/QualType(), Loc: ParamNameLoc));
1209
1210 ConstraintArgs.setRAngleLoc(RAngleLoc);
1211 ConstraintArgs.setLAngleLoc(LAngleLoc);
1212 Appender(ConstraintArgs);
1213
1214 // C++2a [temp.param]p4:
1215 // [...] This constraint-expression E is called the immediately-declared
1216 // constraint of T. [...]
1217 CXXScopeSpec SS;
1218 SS.Adopt(Other: NS);
1219 ExprResult ImmediatelyDeclaredConstraint;
1220 if (auto *CD = dyn_cast<ConceptDecl>(Val: NamedConcept)) {
1221 ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1222 SS, /*TemplateKWLoc=*/SourceLocation(), ConceptNameInfo: NameInfo,
1223 /*FoundDecl=*/FoundDecl ? FoundDecl : CD, NamedConcept: CD, TemplateArgs: &ConstraintArgs,
1224 /*DoCheckConstraintSatisfaction=*/
1225 !S.inParameterMappingSubstitution());
1226 }
1227 // We have a template template parameter
1228 else {
1229 auto *CDT = dyn_cast<TemplateTemplateParmDecl>(Val: NamedConcept);
1230 ImmediatelyDeclaredConstraint = S.CheckVarOrConceptTemplateTemplateId(
1231 SS, NameInfo, Template: CDT, TemplateLoc: SourceLocation(), TemplateArgs: &ConstraintArgs);
1232 }
1233 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1234 return ImmediatelyDeclaredConstraint;
1235
1236 // C++2a [temp.param]p4:
1237 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1238 //
1239 // We have the following case:
1240 //
1241 // template<typename T> concept C1 = true;
1242 // template<C1... T> struct s1;
1243 //
1244 // The constraint: (C1<T> && ...)
1245 //
1246 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1247 // any unqualified lookups for 'operator&&' here.
1248 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/Callee: nullptr,
1249 /*LParenLoc=*/SourceLocation(),
1250 LHS: ImmediatelyDeclaredConstraint.get(), Operator: BO_LAnd,
1251 EllipsisLoc, /*RHS=*/nullptr,
1252 /*RParenLoc=*/SourceLocation(),
1253 /*NumExpansions=*/std::nullopt);
1254}
1255
1256bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1257 DeclarationNameInfo NameInfo,
1258 TemplateDecl *NamedConcept,
1259 NamedDecl *FoundDecl,
1260 const TemplateArgumentListInfo *TemplateArgs,
1261 TemplateTypeParmDecl *ConstrainedParameter,
1262 SourceLocation EllipsisLoc) {
1263 // C++2a [temp.param]p4:
1264 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1265 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1266 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1267 TemplateArgs ? ASTTemplateArgumentListInfo::Create(C: Context,
1268 List: *TemplateArgs) : nullptr;
1269
1270 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1271
1272 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1273 S&: *this, NS, NameInfo, NamedConcept, FoundDecl,
1274 LAngleLoc: TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1275 RAngleLoc: TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1276 ConstrainedType: ParamAsArgument, ParamNameLoc: ConstrainedParameter->getLocation(),
1277 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1278 if (TemplateArgs)
1279 for (const auto &ArgLoc : TemplateArgs->arguments())
1280 ConstraintArgs.addArgument(Loc: ArgLoc);
1281 },
1282 EllipsisLoc);
1283 if (ImmediatelyDeclaredConstraint.isInvalid())
1284 return true;
1285
1286 auto *CL = ConceptReference::Create(C: Context, /*NNS=*/NS,
1287 /*TemplateKWLoc=*/SourceLocation{},
1288 /*ConceptNameInfo=*/NameInfo,
1289 /*FoundDecl=*/FoundDecl,
1290 /*NamedConcept=*/NamedConcept,
1291 /*ArgsWritten=*/ArgsAsWritten);
1292 ConstrainedParameter->setTypeConstraint(
1293 CR: CL, ImmediatelyDeclaredConstraint: ImmediatelyDeclaredConstraint.get(), ArgPackSubstIndex: std::nullopt);
1294 return false;
1295}
1296
1297bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
1298 NonTypeTemplateParmDecl *NewConstrainedParm,
1299 NonTypeTemplateParmDecl *OrigConstrainedParm,
1300 SourceLocation EllipsisLoc) {
1301 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1302 TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1303 Diag(Loc: NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1304 DiagID: diag::err_unsupported_placeholder_constraint)
1305 << NewConstrainedParm->getTypeSourceInfo()
1306 ->getTypeLoc()
1307 .getSourceRange();
1308 return true;
1309 }
1310 // FIXME: Concepts: This should be the type of the placeholder, but this is
1311 // unclear in the wording right now.
1312 DeclRefExpr *Ref =
1313 BuildDeclRefExpr(D: OrigConstrainedParm, Ty: OrigConstrainedParm->getType(),
1314 VK: VK_PRValue, Loc: OrigConstrainedParm->getLocation());
1315 if (!Ref)
1316 return true;
1317 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1318 S&: *this, NS: TL.getNestedNameSpecifierLoc(), NameInfo: TL.getConceptNameInfo(),
1319 NamedConcept: TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), LAngleLoc: TL.getLAngleLoc(),
1320 RAngleLoc: TL.getRAngleLoc(), ConstrainedType: BuildDecltypeType(E: Ref),
1321 ParamNameLoc: OrigConstrainedParm->getLocation(),
1322 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1323 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1324 ConstraintArgs.addArgument(Loc: TL.getArgLoc(i: I));
1325 },
1326 EllipsisLoc);
1327 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1328 !ImmediatelyDeclaredConstraint.isUsable())
1329 return true;
1330
1331 NewConstrainedParm->setPlaceholderTypeConstraint(
1332 ImmediatelyDeclaredConstraint.get());
1333 return false;
1334}
1335
1336QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1337 SourceLocation Loc) {
1338 if (TSI->getType()->isUndeducedType()) {
1339 // C++17 [temp.dep.expr]p3:
1340 // An id-expression is type-dependent if it contains
1341 // - an identifier associated by name lookup with a non-type
1342 // template-parameter declared with a type that contains a
1343 // placeholder type (7.1.7.4),
1344 TypeSourceInfo *NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSI);
1345 if (!NewTSI)
1346 return QualType();
1347 TSI = NewTSI;
1348 }
1349
1350 return CheckNonTypeTemplateParameterType(T: TSI->getType(), Loc);
1351}
1352
1353bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1354 if (T->isDependentType())
1355 return false;
1356
1357 if (RequireCompleteType(Loc, T, DiagID: diag::err_template_nontype_parm_incomplete))
1358 return true;
1359
1360 if (T->isStructuralType())
1361 return false;
1362
1363 // Structural types are required to be object types or lvalue references.
1364 if (T->isRValueReferenceType()) {
1365 Diag(Loc, DiagID: diag::err_template_nontype_parm_rvalue_ref) << T;
1366 return true;
1367 }
1368
1369 // Don't mention structural types in our diagnostic prior to C++20. Also,
1370 // there's not much more we can say about non-scalar non-class types --
1371 // because we can't see functions or arrays here, those can only be language
1372 // extensions.
1373 if (!getLangOpts().CPlusPlus20 ||
1374 (!T->isScalarType() && !T->isRecordType())) {
1375 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_type) << T;
1376 return true;
1377 }
1378
1379 // Structural types are required to be literal types.
1380 if (RequireLiteralType(Loc, T, DiagID: diag::err_template_nontype_parm_not_literal))
1381 return true;
1382
1383 Diag(Loc, DiagID: diag::err_template_nontype_parm_not_structural) << T;
1384
1385 // Drill down into the reason why the class is non-structural.
1386 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1387 // All members are required to be public and non-mutable, and can't be of
1388 // rvalue reference type. Check these conditions first to prefer a "local"
1389 // reason over a more distant one.
1390 for (const FieldDecl *FD : RD->fields()) {
1391 if (FD->getAccess() != AS_public) {
1392 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_non_public) << T << 0;
1393 return true;
1394 }
1395 if (FD->isMutable()) {
1396 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_mutable_field) << T;
1397 return true;
1398 }
1399 if (FD->getType()->isRValueReferenceType()) {
1400 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_rvalue_ref_field)
1401 << T;
1402 return true;
1403 }
1404 }
1405
1406 // All bases are required to be public.
1407 for (const auto &BaseSpec : RD->bases()) {
1408 if (BaseSpec.getAccessSpecifier() != AS_public) {
1409 Diag(Loc: BaseSpec.getBaseTypeLoc(), DiagID: diag::note_not_structural_non_public)
1410 << T << 1;
1411 return true;
1412 }
1413 }
1414
1415 // All subobjects are required to be of structural types.
1416 SourceLocation SubLoc;
1417 QualType SubType;
1418 int Kind = -1;
1419
1420 for (const FieldDecl *FD : RD->fields()) {
1421 QualType T = Context.getBaseElementType(QT: FD->getType());
1422 if (!T->isStructuralType()) {
1423 SubLoc = FD->getLocation();
1424 SubType = T;
1425 Kind = 0;
1426 break;
1427 }
1428 }
1429
1430 if (Kind == -1) {
1431 for (const auto &BaseSpec : RD->bases()) {
1432 QualType T = BaseSpec.getType();
1433 if (!T->isStructuralType()) {
1434 SubLoc = BaseSpec.getBaseTypeLoc();
1435 SubType = T;
1436 Kind = 1;
1437 break;
1438 }
1439 }
1440 }
1441
1442 assert(Kind != -1 && "couldn't find reason why type is not structural");
1443 Diag(Loc: SubLoc, DiagID: diag::note_not_structural_subobject)
1444 << T << Kind << SubType;
1445 T = SubType;
1446 RD = T->getAsCXXRecordDecl();
1447 }
1448
1449 return true;
1450}
1451
1452QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1453 SourceLocation Loc) {
1454 // We don't allow variably-modified types as the type of non-type template
1455 // parameters.
1456 if (T->isVariablyModifiedType()) {
1457 Diag(Loc, DiagID: diag::err_variably_modified_nontype_template_param)
1458 << T;
1459 return QualType();
1460 }
1461
1462 if (T->isBlockPointerType()) {
1463 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_type) << T;
1464 return QualType();
1465 }
1466
1467 // C++ [temp.param]p4:
1468 //
1469 // A non-type template-parameter shall have one of the following
1470 // (optionally cv-qualified) types:
1471 //
1472 // -- integral or enumeration type,
1473 if (T->isIntegralOrEnumerationType() ||
1474 // -- pointer to object or pointer to function,
1475 T->isPointerType() ||
1476 // -- lvalue reference to object or lvalue reference to function,
1477 T->isLValueReferenceType() ||
1478 // -- pointer to member,
1479 T->isMemberPointerType() ||
1480 // -- std::nullptr_t, or
1481 T->isNullPtrType() ||
1482 // -- a type that contains a placeholder type.
1483 T->isUndeducedType()) {
1484 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1485 // are ignored when determining its type.
1486 return T.getUnqualifiedType();
1487 }
1488
1489 // C++ [temp.param]p8:
1490 //
1491 // A non-type template-parameter of type "array of T" or
1492 // "function returning T" is adjusted to be of type "pointer to
1493 // T" or "pointer to function returning T", respectively.
1494 if (T->isArrayType() || T->isFunctionType())
1495 return Context.getDecayedType(T);
1496
1497 // If T is a dependent type, we can't do the check now, so we
1498 // assume that it is well-formed. Note that stripping off the
1499 // qualifiers here is not really correct if T turns out to be
1500 // an array type, but we'll recompute the type everywhere it's
1501 // used during instantiation, so that should be OK. (Using the
1502 // qualified type is equally wrong.)
1503 if (T->isDependentType())
1504 return T.getUnqualifiedType();
1505
1506 // C++20 [temp.param]p6:
1507 // -- a structural type
1508 if (RequireStructuralType(T, Loc))
1509 return QualType();
1510
1511 if (!getLangOpts().CPlusPlus20) {
1512 // FIXME: Consider allowing structural types as an extension in C++17. (In
1513 // earlier language modes, the template argument evaluation rules are too
1514 // inflexible.)
1515 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_structural_type) << T;
1516 return QualType();
1517 }
1518
1519 Diag(Loc, DiagID: diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1520 return T.getUnqualifiedType();
1521}
1522
1523NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1524 unsigned Depth,
1525 unsigned Position,
1526 SourceLocation EqualLoc,
1527 Expr *Default) {
1528 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
1529
1530 // Check that we have valid decl-specifiers specified.
1531 auto CheckValidDeclSpecifiers = [this, &D] {
1532 // C++ [temp.param]
1533 // p1
1534 // template-parameter:
1535 // ...
1536 // parameter-declaration
1537 // p2
1538 // ... A storage class shall not be specified in a template-parameter
1539 // declaration.
1540 // [dcl.typedef]p1:
1541 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1542 // of a parameter-declaration
1543 const DeclSpec &DS = D.getDeclSpec();
1544 auto EmitDiag = [this](SourceLocation Loc) {
1545 Diag(Loc, DiagID: diag::err_invalid_decl_specifier_in_nontype_parm)
1546 << FixItHint::CreateRemoval(RemoveRange: Loc);
1547 };
1548 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1549 EmitDiag(DS.getStorageClassSpecLoc());
1550
1551 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1552 EmitDiag(DS.getThreadStorageClassSpecLoc());
1553
1554 // [dcl.inline]p1:
1555 // The inline specifier can be applied only to the declaration or
1556 // definition of a variable or function.
1557
1558 if (DS.isInlineSpecified())
1559 EmitDiag(DS.getInlineSpecLoc());
1560
1561 // [dcl.constexpr]p1:
1562 // The constexpr specifier shall be applied only to the definition of a
1563 // variable or variable template or the declaration of a function or
1564 // function template.
1565
1566 if (DS.hasConstexprSpecifier())
1567 EmitDiag(DS.getConstexprSpecLoc());
1568
1569 // [dcl.fct.spec]p1:
1570 // Function-specifiers can be used only in function declarations.
1571
1572 if (DS.isVirtualSpecified())
1573 EmitDiag(DS.getVirtualSpecLoc());
1574
1575 if (DS.hasExplicitSpecifier())
1576 EmitDiag(DS.getExplicitSpecLoc());
1577
1578 if (DS.isNoreturnSpecified())
1579 EmitDiag(DS.getNoreturnSpecLoc());
1580 };
1581
1582 CheckValidDeclSpecifiers();
1583
1584 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1585 if (isa<AutoType>(Val: T))
1586 Diag(Loc: D.getIdentifierLoc(),
1587 DiagID: diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1588 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1589
1590 assert(S->isTemplateParamScope() &&
1591 "Non-type template parameter not in template parameter scope!");
1592 bool Invalid = false;
1593
1594 QualType T = CheckNonTypeTemplateParameterType(TSI&: TInfo, Loc: D.getIdentifierLoc());
1595 if (T.isNull()) {
1596 T = Context.IntTy; // Recover with an 'int' type.
1597 Invalid = true;
1598 }
1599
1600 CheckFunctionOrTemplateParamDeclarator(S, D);
1601
1602 const IdentifierInfo *ParamName = D.getIdentifier();
1603 bool IsParameterPack = D.hasEllipsis();
1604 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1605 C: Context, DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
1606 IdLoc: D.getIdentifierLoc(), D: Depth, P: Position, Id: ParamName, T, ParameterPack: IsParameterPack,
1607 TInfo);
1608 Param->setAccess(AS_public);
1609
1610 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1611 if (TL.isConstrained()) {
1612 if (D.getEllipsisLoc().isInvalid() &&
1613 T->containsUnexpandedParameterPack()) {
1614 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1615 for (auto &Loc :
1616 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1617 Invalid |= DiagnoseUnexpandedParameterPack(
1618 Arg: Loc, UPPC: UnexpandedParameterPackContext::UPPC_TypeConstraint);
1619 }
1620 if (!Invalid &&
1621 AttachTypeConstraint(TL, NewConstrainedParm: Param, OrigConstrainedParm: Param, EllipsisLoc: D.getEllipsisLoc()))
1622 Invalid = true;
1623 }
1624
1625 if (Invalid)
1626 Param->setInvalidDecl();
1627
1628 if (Param->isParameterPack())
1629 if (auto *CSI = getEnclosingLambdaOrBlock())
1630 CSI->LocalPacks.push_back(Elt: Param);
1631
1632 if (ParamName) {
1633 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: D.getIdentifierLoc(),
1634 Name: ParamName);
1635
1636 // Add the template parameter into the current scope.
1637 S->AddDecl(D: Param);
1638 IdResolver.AddDecl(D: Param);
1639 }
1640
1641 // C++0x [temp.param]p9:
1642 // A default template-argument may be specified for any kind of
1643 // template-parameter that is not a template parameter pack.
1644 if (Default && IsParameterPack) {
1645 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1646 Default = nullptr;
1647 }
1648
1649 // Check the well-formedness of the default template argument, if provided.
1650 if (Default) {
1651 // Check for unexpanded parameter packs.
1652 if (DiagnoseUnexpandedParameterPack(E: Default, UPPC: UPPC_DefaultArgument))
1653 return Param;
1654
1655 Param->setDefaultArgument(
1656 C: Context, DefArg: getTrivialTemplateArgumentLoc(
1657 Arg: TemplateArgument(Default, /*IsCanonical=*/false),
1658 NTTPType: QualType(), Loc: SourceLocation()));
1659 }
1660
1661 return Param;
1662}
1663
1664/// ActOnTemplateTemplateParameter - Called when a C++ template template
1665/// parameter (e.g. T in template <template \<typename> class T> class array)
1666/// has been parsed. S is the current scope.
1667NamedDecl *Sema::ActOnTemplateTemplateParameter(
1668 Scope *S, SourceLocation TmpLoc, TemplateNameKind Kind, bool Typename,
1669 TemplateParameterList *Params, SourceLocation EllipsisLoc,
1670 IdentifierInfo *Name, SourceLocation NameLoc, unsigned Depth,
1671 unsigned Position, SourceLocation EqualLoc,
1672 ParsedTemplateArgument Default) {
1673 assert(S->isTemplateParamScope() &&
1674 "Template template parameter not in template parameter scope!");
1675
1676 bool IsParameterPack = EllipsisLoc.isValid();
1677
1678 bool Invalid = false;
1679 if (CheckTemplateParameterList(
1680 NewParams: Params,
1681 /*OldParams=*/nullptr,
1682 TPC: IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1683 Invalid = true;
1684
1685 // Construct the parameter object.
1686 TemplateTemplateParmDecl *Param = TemplateTemplateParmDecl::Create(
1687 C: Context, DC: Context.getTranslationUnitDecl(),
1688 L: NameLoc.isInvalid() ? TmpLoc : NameLoc, D: Depth, P: Position, ParameterPack: IsParameterPack,
1689 Id: Name, ParameterKind: Kind, Typename, Params);
1690 Param->setAccess(AS_public);
1691
1692 if (Param->isParameterPack())
1693 if (auto *LSI = getEnclosingLambdaOrBlock())
1694 LSI->LocalPacks.push_back(Elt: Param);
1695
1696 // If the template template parameter has a name, then link the identifier
1697 // into the scope and lookup mechanisms.
1698 if (Name) {
1699 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: NameLoc, Name);
1700
1701 S->AddDecl(D: Param);
1702 IdResolver.AddDecl(D: Param);
1703 }
1704
1705 if (Params->size() == 0) {
1706 Diag(Loc: Param->getLocation(), DiagID: diag::err_template_template_parm_no_parms)
1707 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1708 Invalid = true;
1709 }
1710
1711 if (Invalid)
1712 Param->setInvalidDecl();
1713
1714 // C++0x [temp.param]p9:
1715 // A default template-argument may be specified for any kind of
1716 // template-parameter that is not a template parameter pack.
1717 if (IsParameterPack && !Default.isInvalid()) {
1718 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1719 Default = ParsedTemplateArgument();
1720 }
1721
1722 if (!Default.isInvalid()) {
1723 // Check only that we have a template template argument. We don't want to
1724 // try to check well-formedness now, because our template template parameter
1725 // might have dependent types in its template parameters, which we wouldn't
1726 // be able to match now.
1727 //
1728 // If none of the template template parameter's template arguments mention
1729 // other template parameters, we could actually perform more checking here.
1730 // However, it isn't worth doing.
1731 TemplateArgumentLoc DefaultArg = translateTemplateArgument(SemaRef&: *this, Arg: Default);
1732 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1733 Diag(Loc: DefaultArg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
1734 << DefaultArg.getSourceRange();
1735 return Param;
1736 }
1737
1738 TemplateName Name =
1739 DefaultArg.getArgument().getAsTemplateOrTemplatePattern();
1740 TemplateDecl *Template = Name.getAsTemplateDecl();
1741 if (Template &&
1742 !CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg: DefaultArg)) {
1743 return Param;
1744 }
1745
1746 // Check for unexpanded parameter packs.
1747 if (DiagnoseUnexpandedParameterPack(Loc: DefaultArg.getLocation(),
1748 Template: DefaultArg.getArgument().getAsTemplate(),
1749 UPPC: UPPC_DefaultArgument))
1750 return Param;
1751
1752 Param->setDefaultArgument(C: Context, DefArg: DefaultArg);
1753 }
1754
1755 return Param;
1756}
1757
1758namespace {
1759class ConstraintRefersToContainingTemplateChecker
1760 : public ConstDynamicRecursiveASTVisitor {
1761 using inherited = ConstDynamicRecursiveASTVisitor;
1762 bool Result = false;
1763 const FunctionDecl *Friend = nullptr;
1764 unsigned TemplateDepth = 0;
1765
1766 // Check a record-decl that we've seen to see if it is a lexical parent of the
1767 // Friend, likely because it was referred to without its template arguments.
1768 bool CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1769 CheckingRD = CheckingRD->getMostRecentDecl();
1770 if (!CheckingRD->isTemplated())
1771 return true;
1772
1773 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1774 DC && !DC->isFileContext(); DC = DC->getParent())
1775 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
1776 if (CheckingRD == RD->getMostRecentDecl()) {
1777 Result = true;
1778 return false;
1779 }
1780
1781 return true;
1782 }
1783
1784 bool CheckNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
1785 if (D->getDepth() < TemplateDepth)
1786 Result = true;
1787
1788 // Necessary because the type of the NTTP might be what refers to the parent
1789 // constriant.
1790 return TraverseType(T: D->getType());
1791 }
1792
1793public:
1794 ConstraintRefersToContainingTemplateChecker(const FunctionDecl *Friend,
1795 unsigned TemplateDepth)
1796 : Friend(Friend), TemplateDepth(TemplateDepth) {}
1797
1798 bool getResult() const { return Result; }
1799
1800 // This should be the only template parm type that we have to deal with.
1801 // SubstTemplateTypeParmPack, SubstNonTypeTemplateParmPack, and
1802 // FunctionParmPackExpr are all partially substituted, which cannot happen
1803 // with concepts at this point in translation.
1804 bool VisitTemplateTypeParmType(const TemplateTypeParmType *Type) override {
1805 if (Type->getDecl()->getDepth() < TemplateDepth) {
1806 Result = true;
1807 return false;
1808 }
1809 return true;
1810 }
1811
1812 bool TraverseDeclRefExpr(const DeclRefExpr *E) override {
1813 return TraverseDecl(D: E->getDecl());
1814 }
1815
1816 bool TraverseTypedefType(const TypedefType *TT,
1817 bool /*TraverseQualifier*/) override {
1818 return TraverseType(T: TT->desugar());
1819 }
1820
1821 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier) override {
1822 // We don't care about TypeLocs. So traverse Types instead.
1823 return TraverseType(T: TL.getType(), TraverseQualifier);
1824 }
1825
1826 bool VisitTagType(const TagType *T) override {
1827 return TraverseDecl(D: T->getDecl());
1828 }
1829
1830 bool TraverseDecl(const Decl *D) override {
1831 assert(D);
1832 // FIXME : This is possibly an incomplete list, but it is unclear what other
1833 // Decl kinds could be used to refer to the template parameters. This is a
1834 // best guess so far based on examples currently available, but the
1835 // unreachable should catch future instances/cases.
1836 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
1837 return TraverseType(T: TD->getUnderlyingType());
1838 if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Val: D))
1839 return CheckNonTypeTemplateParmDecl(D: NTTPD);
1840 if (auto *VD = dyn_cast<ValueDecl>(Val: D))
1841 return TraverseType(T: VD->getType());
1842 if (isa<TemplateDecl>(Val: D))
1843 return true;
1844 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1845 return CheckIfContainingRecord(CheckingRD: RD);
1846
1847 if (isa<NamedDecl, RequiresExprBodyDecl>(Val: D)) {
1848 // No direct types to visit here I believe.
1849 } else
1850 llvm_unreachable("Don't know how to handle this declaration type yet");
1851 return true;
1852 }
1853};
1854} // namespace
1855
1856bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1857 const FunctionDecl *Friend, unsigned TemplateDepth,
1858 const Expr *Constraint) {
1859 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1860 ConstraintRefersToContainingTemplateChecker Checker(Friend, TemplateDepth);
1861 Checker.TraverseStmt(S: Constraint);
1862 return Checker.getResult();
1863}
1864
1865TemplateParameterList *
1866Sema::ActOnTemplateParameterList(unsigned Depth,
1867 SourceLocation ExportLoc,
1868 SourceLocation TemplateLoc,
1869 SourceLocation LAngleLoc,
1870 ArrayRef<NamedDecl *> Params,
1871 SourceLocation RAngleLoc,
1872 Expr *RequiresClause) {
1873 if (ExportLoc.isValid())
1874 Diag(Loc: ExportLoc, DiagID: diag::warn_template_export_unsupported);
1875
1876 for (NamedDecl *P : Params)
1877 warnOnReservedIdentifier(D: P);
1878
1879 return TemplateParameterList::Create(C: Context, TemplateLoc, LAngleLoc,
1880 Params: llvm::ArrayRef(Params), RAngleLoc,
1881 RequiresClause);
1882}
1883
1884static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1885 const CXXScopeSpec &SS) {
1886 if (SS.isSet())
1887 T->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
1888}
1889
1890// Returns the template parameter list with all default template argument
1891// information.
1892TemplateParameterList *Sema::GetTemplateParameterList(TemplateDecl *TD) {
1893 // Make sure we get the template parameter list from the most
1894 // recent declaration, since that is the only one that is guaranteed to
1895 // have all the default template argument information.
1896 Decl *D = TD->getMostRecentDecl();
1897 // C++11 N3337 [temp.param]p12:
1898 // A default template argument shall not be specified in a friend class
1899 // template declaration.
1900 //
1901 // Skip past friend *declarations* because they are not supposed to contain
1902 // default template arguments. Moreover, these declarations may introduce
1903 // template parameters living in different template depths than the
1904 // corresponding template parameters in TD, causing unmatched constraint
1905 // substitution.
1906 //
1907 // FIXME: Diagnose such cases within a class template:
1908 // template <class T>
1909 // struct S {
1910 // template <class = void> friend struct C;
1911 // };
1912 // template struct S<int>;
1913 while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
1914 D->getPreviousDecl())
1915 D = D->getPreviousDecl();
1916 return cast<TemplateDecl>(Val: D)->getTemplateParameters();
1917}
1918
1919DeclResult Sema::CheckClassTemplate(
1920 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1921 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1922 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1923 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1924 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1925 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1926 assert(TemplateParams && TemplateParams->size() > 0 &&
1927 "No template parameters");
1928 assert(TUK != TagUseKind::Reference &&
1929 "Can only declare or define class templates");
1930 bool Invalid = false;
1931
1932 // Check that we can declare a template here.
1933 if (CheckTemplateDeclScope(S, TemplateParams))
1934 return true;
1935
1936 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
1937 assert(Kind != TagTypeKind::Enum &&
1938 "can't build template of enumerated type");
1939
1940 // There is no such thing as an unnamed class template.
1941 if (!Name) {
1942 Diag(Loc: KWLoc, DiagID: diag::err_template_unnamed_class);
1943 return true;
1944 }
1945
1946 // Find any previous declaration with this name. For a friend with no
1947 // scope explicitly specified, we only look for tag declarations (per
1948 // C++11 [basic.lookup.elab]p2).
1949 DeclContext *SemanticContext;
1950 LookupResult Previous(*this, Name, NameLoc,
1951 (SS.isEmpty() && TUK == TagUseKind::Friend)
1952 ? LookupTagName
1953 : LookupOrdinaryName,
1954 forRedeclarationInCurContext());
1955 if (SS.isNotEmpty() && !SS.isInvalid()) {
1956 SemanticContext = computeDeclContext(SS, EnteringContext: true);
1957 if (!SemanticContext) {
1958 // FIXME: Horrible, horrible hack! We can't currently represent this
1959 // in the AST, and historically we have just ignored such friend
1960 // class templates, so don't complain here.
1961 Diag(Loc: NameLoc, DiagID: TUK == TagUseKind::Friend
1962 ? diag::warn_template_qualified_friend_ignored
1963 : diag::err_template_qualified_declarator_no_match)
1964 << SS.getScopeRep() << SS.getRange();
1965 return TUK != TagUseKind::Friend;
1966 }
1967
1968 if (RequireCompleteDeclContext(SS, DC: SemanticContext))
1969 return true;
1970
1971 // If we're adding a template to a dependent context, we may need to
1972 // rebuilding some of the types used within the template parameter list,
1973 // now that we know what the current instantiation is.
1974 if (SemanticContext->isDependentContext()) {
1975 ContextRAII SavedContext(*this, SemanticContext);
1976 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
1977 Invalid = true;
1978 }
1979
1980 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1981 diagnoseQualifiedDeclaration(SS, DC: SemanticContext, Name, Loc: NameLoc,
1982 /*TemplateId-*/ TemplateId: nullptr,
1983 /*IsMemberSpecialization*/ false);
1984
1985 LookupQualifiedName(R&: Previous, LookupCtx: SemanticContext);
1986 } else {
1987 SemanticContext = CurContext;
1988
1989 // C++14 [class.mem]p14:
1990 // If T is the name of a class, then each of the following shall have a
1991 // name different from T:
1992 // -- every member template of class T
1993 if (TUK != TagUseKind::Friend &&
1994 DiagnoseClassNameShadow(DC: SemanticContext,
1995 Info: DeclarationNameInfo(Name, NameLoc)))
1996 return true;
1997
1998 LookupName(R&: Previous, S);
1999 }
2000
2001 if (Previous.isAmbiguous())
2002 return true;
2003
2004 // Let the template parameter scope enter the lookup chain of the current
2005 // class template. For example, given
2006 //
2007 // namespace ns {
2008 // template <class> bool Param = false;
2009 // template <class T> struct N;
2010 // }
2011 //
2012 // template <class Param> struct ns::N { void foo(Param); };
2013 //
2014 // When we reference Param inside the function parameter list, our name lookup
2015 // chain for it should be like:
2016 // FunctionScope foo
2017 // -> RecordScope N
2018 // -> TemplateParamScope (where we will find Param)
2019 // -> NamespaceScope ns
2020 //
2021 // See also CppLookupName().
2022 if (S->isTemplateParamScope())
2023 EnterTemplatedContext(S, DC: SemanticContext);
2024
2025 NamedDecl *PrevDecl = nullptr;
2026 if (Previous.begin() != Previous.end())
2027 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2028
2029 if (PrevDecl && PrevDecl->isTemplateParameter()) {
2030 // Maybe we will complain about the shadowed template parameter.
2031 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl);
2032 // Just pretend that we didn't see the previous declaration.
2033 PrevDecl = nullptr;
2034 }
2035
2036 // If there is a previous declaration with the same name, check
2037 // whether this is a valid redeclaration.
2038 ClassTemplateDecl *PrevClassTemplate =
2039 dyn_cast_or_null<ClassTemplateDecl>(Val: PrevDecl);
2040
2041 // We may have found the injected-class-name of a class template,
2042 // class template partial specialization, or class template specialization.
2043 // In these cases, grab the template that is being defined or specialized.
2044 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(Val: PrevDecl) &&
2045 cast<CXXRecordDecl>(Val: PrevDecl)->isInjectedClassName()) {
2046 PrevDecl = cast<CXXRecordDecl>(Val: PrevDecl->getDeclContext());
2047 PrevClassTemplate
2048 = cast<CXXRecordDecl>(Val: PrevDecl)->getDescribedClassTemplate();
2049 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(Val: PrevDecl)) {
2050 PrevClassTemplate
2051 = cast<ClassTemplateSpecializationDecl>(Val: PrevDecl)
2052 ->getSpecializedTemplate();
2053 }
2054 }
2055
2056 if (TUK == TagUseKind::Friend) {
2057 // C++ [namespace.memdef]p3:
2058 // [...] When looking for a prior declaration of a class or a function
2059 // declared as a friend, and when the name of the friend class or
2060 // function is neither a qualified name nor a template-id, scopes outside
2061 // the innermost enclosing namespace scope are not considered.
2062 if (!SS.isSet()) {
2063 DeclContext *OutermostContext = CurContext;
2064 while (!OutermostContext->isFileContext())
2065 OutermostContext = OutermostContext->getLookupParent();
2066
2067 if (PrevDecl &&
2068 (OutermostContext->Equals(DC: PrevDecl->getDeclContext()) ||
2069 OutermostContext->Encloses(DC: PrevDecl->getDeclContext()))) {
2070 SemanticContext = PrevDecl->getDeclContext();
2071 } else {
2072 // Declarations in outer scopes don't matter. However, the outermost
2073 // context we computed is the semantic context for our new
2074 // declaration.
2075 PrevDecl = PrevClassTemplate = nullptr;
2076 SemanticContext = OutermostContext;
2077
2078 // Check that the chosen semantic context doesn't already contain a
2079 // declaration of this name as a non-tag type.
2080 Previous.clear(Kind: LookupOrdinaryName);
2081 DeclContext *LookupContext = SemanticContext;
2082 while (LookupContext->isTransparentContext())
2083 LookupContext = LookupContext->getLookupParent();
2084 LookupQualifiedName(R&: Previous, LookupCtx: LookupContext);
2085
2086 if (Previous.isAmbiguous())
2087 return true;
2088
2089 if (Previous.begin() != Previous.end())
2090 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2091 }
2092 }
2093 } else if (PrevDecl && !isDeclInScope(D: Previous.getRepresentativeDecl(),
2094 Ctx: SemanticContext, S, AllowInlineNamespace: SS.isValid()))
2095 PrevDecl = PrevClassTemplate = nullptr;
2096
2097 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2098 Val: PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2099 if (SS.isEmpty() &&
2100 !(PrevClassTemplate &&
2101 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2102 DC: SemanticContext->getRedeclContext()))) {
2103 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
2104 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
2105 DiagID: diag::note_using_decl_target);
2106 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
2107 // Recover by ignoring the old declaration.
2108 PrevDecl = PrevClassTemplate = nullptr;
2109 }
2110 }
2111
2112 if (PrevClassTemplate) {
2113 // Ensure that the template parameter lists are compatible. Skip this check
2114 // for a friend in a dependent context: the template parameter list itself
2115 // could be dependent.
2116 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2117 !TemplateParameterListsAreEqual(
2118 NewInstFrom: TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2119 : CurContext,
2120 CurContext, KWLoc),
2121 New: TemplateParams, OldInstFrom: PrevClassTemplate,
2122 Old: PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2123 Kind: TPL_TemplateMatch))
2124 return true;
2125
2126 // C++ [temp.class]p4:
2127 // In a redeclaration, partial specialization, explicit
2128 // specialization or explicit instantiation of a class template,
2129 // the class-key shall agree in kind with the original class
2130 // template declaration (7.1.5.3).
2131 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2132 if (!isAcceptableTagRedeclaration(
2133 Previous: PrevRecordDecl, NewTag: Kind, isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc, Name)) {
2134 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
2135 << Name
2136 << FixItHint::CreateReplacement(RemoveRange: KWLoc, Code: PrevRecordDecl->getKindName());
2137 Diag(Loc: PrevRecordDecl->getLocation(), DiagID: diag::note_previous_use);
2138 Kind = PrevRecordDecl->getTagKind();
2139 }
2140
2141 // Check for redefinition of this class template.
2142 if (TUK == TagUseKind::Definition) {
2143 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2144 // If we have a prior definition that is not visible, treat this as
2145 // simply making that previous definition visible.
2146 NamedDecl *Hidden = nullptr;
2147 bool HiddenDefVisible = false;
2148 if (SkipBody &&
2149 isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible)) {
2150 SkipBody->ShouldSkip = true;
2151 SkipBody->Previous = Def;
2152 if (!HiddenDefVisible && Hidden) {
2153 auto *Tmpl =
2154 cast<CXXRecordDecl>(Val: Hidden)->getDescribedClassTemplate();
2155 assert(Tmpl && "original definition of a class template is not a "
2156 "class template?");
2157 makeMergedDefinitionVisible(ND: Hidden);
2158 makeMergedDefinitionVisible(ND: Tmpl);
2159 }
2160 } else {
2161 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
2162 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
2163 // FIXME: Would it make sense to try to "forget" the previous
2164 // definition, as part of error recovery?
2165 return true;
2166 }
2167 }
2168 }
2169 } else if (PrevDecl) {
2170 // C++ [temp]p5:
2171 // A class template shall not have the same name as any other
2172 // template, class, function, object, enumeration, enumerator,
2173 // namespace, or type in the same scope (3.3), except as specified
2174 // in (14.5.4).
2175 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
2176 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
2177 return true;
2178 }
2179
2180 // Check the template parameter list of this declaration, possibly
2181 // merging in the template parameter list from the previous class
2182 // template declaration. Skip this check for a friend in a dependent
2183 // context, because the template parameter list might be dependent.
2184 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2185 CheckTemplateParameterList(
2186 NewParams: TemplateParams,
2187 OldParams: PrevClassTemplate ? GetTemplateParameterList(TD: PrevClassTemplate)
2188 : nullptr,
2189 TPC: (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2190 SemanticContext->isDependentContext())
2191 ? TPC_ClassTemplateMember
2192 : TUK == TagUseKind::Friend ? TPC_FriendClassTemplate
2193 : TPC_Other,
2194 SkipBody))
2195 Invalid = true;
2196
2197 if (SS.isSet()) {
2198 // If the name of the template was qualified, we must be defining the
2199 // template out-of-line.
2200 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2201 Diag(Loc: NameLoc, DiagID: TUK == TagUseKind::Friend
2202 ? diag::err_friend_decl_does_not_match
2203 : diag::err_member_decl_does_not_match)
2204 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2205 Invalid = true;
2206 }
2207 }
2208
2209 // If this is a templated friend in a dependent context we should not put it
2210 // on the redecl chain. In some cases, the templated friend can be the most
2211 // recent declaration tricking the template instantiator to make substitutions
2212 // there.
2213 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2214 bool ShouldAddRedecl =
2215 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2216
2217 CXXRecordDecl *NewClass = CXXRecordDecl::Create(
2218 C: Context, TK: Kind, DC: SemanticContext, StartLoc: KWLoc, IdLoc: NameLoc, Id: Name,
2219 PrevDecl: PrevClassTemplate && ShouldAddRedecl
2220 ? PrevClassTemplate->getTemplatedDecl()
2221 : nullptr);
2222 SetNestedNameSpecifier(S&: *this, T: NewClass, SS);
2223 if (NumOuterTemplateParamLists > 0)
2224 NewClass->setTemplateParameterListsInfo(
2225 Context,
2226 TPLists: llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2227
2228 // Add alignment attributes if necessary; these attributes are checked when
2229 // the ASTContext lays out the structure.
2230 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2231 if (LangOpts.HLSL)
2232 NewClass->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
2233 AddAlignmentAttributesForRecord(RD: NewClass);
2234 AddMsStructLayoutForRecord(RD: NewClass);
2235 }
2236
2237 ClassTemplateDecl *NewTemplate
2238 = ClassTemplateDecl::Create(C&: Context, DC: SemanticContext, L: NameLoc,
2239 Name: DeclarationName(Name), Params: TemplateParams,
2240 Decl: NewClass);
2241
2242 if (ShouldAddRedecl)
2243 NewTemplate->setPreviousDecl(PrevClassTemplate);
2244
2245 NewClass->setDescribedClassTemplate(NewTemplate);
2246
2247 if (ModulePrivateLoc.isValid())
2248 NewTemplate->setModulePrivate();
2249
2250 // If we are providing an explicit specialization of a member that is a
2251 // class template, make a note of that.
2252 if (PrevClassTemplate &&
2253 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2254 PrevClassTemplate->setMemberSpecialization();
2255
2256 // Set the access specifier.
2257 if (!Invalid && TUK != TagUseKind::Friend &&
2258 NewTemplate->getDeclContext()->isRecord())
2259 SetMemberAccessSpecifier(MemberDecl: NewTemplate, PrevMemberDecl: PrevClassTemplate, LexicalAS: AS);
2260
2261 // Set the lexical context of these templates
2262 NewClass->setLexicalDeclContext(CurContext);
2263 NewTemplate->setLexicalDeclContext(CurContext);
2264
2265 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2266 NewClass->startDefinition();
2267
2268 ProcessDeclAttributeList(S, D: NewClass, AttrList: Attr);
2269
2270 if (PrevClassTemplate)
2271 mergeDeclAttributes(New: NewClass, Old: PrevClassTemplate->getTemplatedDecl());
2272
2273 AddPushedVisibilityAttribute(RD: NewClass);
2274 inferGslOwnerPointerAttribute(Record: NewClass);
2275 inferNullableClassAttribute(CRD: NewClass);
2276
2277 if (TUK != TagUseKind::Friend) {
2278 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2279 Scope *Outer = S;
2280 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2281 Outer = Outer->getParent();
2282 PushOnScopeChains(D: NewTemplate, S: Outer);
2283 } else {
2284 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2285 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2286 NewClass->setAccess(PrevClassTemplate->getAccess());
2287 }
2288
2289 NewTemplate->setObjectOfFriendDecl();
2290
2291 // Friend templates are visible in fairly strange ways.
2292 if (!CurContext->isDependentContext()) {
2293 DeclContext *DC = SemanticContext->getRedeclContext();
2294 DC->makeDeclVisibleInContext(D: NewTemplate);
2295 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2296 PushOnScopeChains(D: NewTemplate, S: EnclosingScope,
2297 /* AddToContext = */ false);
2298 }
2299
2300 FriendDecl *Friend = FriendDecl::Create(
2301 C&: Context, DC: CurContext, L: NewClass->getLocation(), Friend_: NewTemplate, FriendL: FriendLoc);
2302 Friend->setAccess(AS_public);
2303 CurContext->addDecl(D: Friend);
2304 }
2305
2306 if (PrevClassTemplate)
2307 CheckRedeclarationInModule(New: NewTemplate, Old: PrevClassTemplate);
2308
2309 if (Invalid) {
2310 NewTemplate->setInvalidDecl();
2311 NewClass->setInvalidDecl();
2312 }
2313
2314 ActOnDocumentableDecl(D: NewTemplate);
2315
2316 if (SkipBody && SkipBody->ShouldSkip)
2317 return SkipBody->Previous;
2318
2319 return NewTemplate;
2320}
2321
2322/// Diagnose the presence of a default template argument on a
2323/// template parameter, which is ill-formed in certain contexts.
2324///
2325/// \returns true if the default template argument should be dropped.
2326static bool DiagnoseDefaultTemplateArgument(Sema &S,
2327 Sema::TemplateParamListContext TPC,
2328 SourceLocation ParamLoc,
2329 SourceRange DefArgRange) {
2330 switch (TPC) {
2331 case Sema::TPC_Other:
2332 case Sema::TPC_TemplateTemplateParameterPack:
2333 return false;
2334
2335 case Sema::TPC_FunctionTemplate:
2336 case Sema::TPC_FriendFunctionTemplateDefinition:
2337 // C++ [temp.param]p9:
2338 // A default template-argument shall not be specified in a
2339 // function template declaration or a function template
2340 // definition [...]
2341 // If a friend function template declaration specifies a default
2342 // template-argument, that declaration shall be a definition and shall be
2343 // the only declaration of the function template in the translation unit.
2344 // (C++98/03 doesn't have this wording; see DR226).
2345 S.DiagCompat(Loc: ParamLoc, CompatDiagId: diag_compat::templ_default_in_function_templ)
2346 << DefArgRange;
2347 return false;
2348
2349 case Sema::TPC_ClassTemplateMember:
2350 // C++0x [temp.param]p9:
2351 // A default template-argument shall not be specified in the
2352 // template-parameter-lists of the definition of a member of a
2353 // class template that appears outside of the member's class.
2354 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_template_member)
2355 << DefArgRange;
2356 return true;
2357
2358 case Sema::TPC_FriendClassTemplate:
2359 case Sema::TPC_FriendFunctionTemplate:
2360 // C++ [temp.param]p9:
2361 // A default template-argument shall not be specified in a
2362 // friend template declaration.
2363 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_friend_template)
2364 << DefArgRange;
2365 return true;
2366
2367 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2368 // for friend function templates if there is only a single
2369 // declaration (and it is a definition). Strange!
2370 }
2371
2372 llvm_unreachable("Invalid TemplateParamListContext!");
2373}
2374
2375/// Check for unexpanded parameter packs within the template parameters
2376/// of a template template parameter, recursively.
2377static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2378 TemplateTemplateParmDecl *TTP) {
2379 // A template template parameter which is a parameter pack is also a pack
2380 // expansion.
2381 if (TTP->isParameterPack())
2382 return false;
2383
2384 TemplateParameterList *Params = TTP->getTemplateParameters();
2385 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2386 NamedDecl *P = Params->getParam(Idx: I);
2387 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: P)) {
2388 if (!TTP->isParameterPack())
2389 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2390 if (TC->hasExplicitTemplateArgs())
2391 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2392 if (S.DiagnoseUnexpandedParameterPack(Arg: ArgLoc,
2393 UPPC: Sema::UPPC_TypeConstraint))
2394 return true;
2395 continue;
2396 }
2397
2398 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: P)) {
2399 if (!NTTP->isParameterPack() &&
2400 S.DiagnoseUnexpandedParameterPack(Loc: NTTP->getLocation(),
2401 T: NTTP->getTypeSourceInfo(),
2402 UPPC: Sema::UPPC_NonTypeTemplateParameterType))
2403 return true;
2404
2405 continue;
2406 }
2407
2408 if (TemplateTemplateParmDecl *InnerTTP
2409 = dyn_cast<TemplateTemplateParmDecl>(Val: P))
2410 if (DiagnoseUnexpandedParameterPacks(S, TTP: InnerTTP))
2411 return true;
2412 }
2413
2414 return false;
2415}
2416
2417bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2418 TemplateParameterList *OldParams,
2419 TemplateParamListContext TPC,
2420 SkipBodyInfo *SkipBody) {
2421 bool Invalid = false;
2422
2423 // C++ [temp.param]p10:
2424 // The set of default template-arguments available for use with a
2425 // template declaration or definition is obtained by merging the
2426 // default arguments from the definition (if in scope) and all
2427 // declarations in scope in the same way default function
2428 // arguments are (8.3.6).
2429 bool SawDefaultArgument = false;
2430 SourceLocation PreviousDefaultArgLoc;
2431
2432 // Dummy initialization to avoid warnings.
2433 TemplateParameterList::iterator OldParam = NewParams->end();
2434 if (OldParams)
2435 OldParam = OldParams->begin();
2436
2437 bool RemoveDefaultArguments = false;
2438 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2439 NewParamEnd = NewParams->end();
2440 NewParam != NewParamEnd; ++NewParam) {
2441 // Whether we've seen a duplicate default argument in the same translation
2442 // unit.
2443 bool RedundantDefaultArg = false;
2444 // Whether we've found inconsis inconsitent default arguments in different
2445 // translation unit.
2446 bool InconsistentDefaultArg = false;
2447 // The name of the module which contains the inconsistent default argument.
2448 std::string PrevModuleName;
2449
2450 SourceLocation OldDefaultLoc;
2451 SourceLocation NewDefaultLoc;
2452
2453 // Variable used to diagnose missing default arguments
2454 bool MissingDefaultArg = false;
2455
2456 // Variable used to diagnose non-final parameter packs
2457 bool SawParameterPack = false;
2458
2459 if (TemplateTypeParmDecl *NewTypeParm
2460 = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam)) {
2461 // Check the presence of a default argument here.
2462 if (NewTypeParm->hasDefaultArgument() &&
2463 DiagnoseDefaultTemplateArgument(
2464 S&: *this, TPC, ParamLoc: NewTypeParm->getLocation(),
2465 DefArgRange: NewTypeParm->getDefaultArgument().getSourceRange()))
2466 NewTypeParm->removeDefaultArgument();
2467
2468 // Merge default arguments for template type parameters.
2469 TemplateTypeParmDecl *OldTypeParm
2470 = OldParams? cast<TemplateTypeParmDecl>(Val: *OldParam) : nullptr;
2471 if (NewTypeParm->isParameterPack()) {
2472 assert(!NewTypeParm->hasDefaultArgument() &&
2473 "Parameter packs can't have a default argument!");
2474 SawParameterPack = true;
2475 } else if (OldTypeParm && hasVisibleDefaultArgument(D: OldTypeParm) &&
2476 NewTypeParm->hasDefaultArgument() &&
2477 (!SkipBody || !SkipBody->ShouldSkip)) {
2478 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2479 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2480 SawDefaultArgument = true;
2481
2482 if (!OldTypeParm->getOwningModule())
2483 RedundantDefaultArg = true;
2484 else if (!getASTContext().isSameDefaultTemplateArgument(X: OldTypeParm,
2485 Y: NewTypeParm)) {
2486 InconsistentDefaultArg = true;
2487 PrevModuleName =
2488 OldTypeParm->getImportedOwningModule()->getFullModuleName();
2489 }
2490 PreviousDefaultArgLoc = NewDefaultLoc;
2491 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2492 // Merge the default argument from the old declaration to the
2493 // new declaration.
2494 NewTypeParm->setInheritedDefaultArgument(C: Context, Prev: OldTypeParm);
2495 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2496 } else if (NewTypeParm->hasDefaultArgument()) {
2497 SawDefaultArgument = true;
2498 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2499 } else if (SawDefaultArgument)
2500 MissingDefaultArg = true;
2501 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2502 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam)) {
2503 // Check for unexpanded parameter packs, except in a template template
2504 // parameter pack, as in those any unexpanded packs should be expanded
2505 // along with the parameter itself.
2506 if (TPC != TPC_TemplateTemplateParameterPack &&
2507 !NewNonTypeParm->isParameterPack() &&
2508 DiagnoseUnexpandedParameterPack(Loc: NewNonTypeParm->getLocation(),
2509 T: NewNonTypeParm->getTypeSourceInfo(),
2510 UPPC: UPPC_NonTypeTemplateParameterType)) {
2511 Invalid = true;
2512 continue;
2513 }
2514
2515 // Check the presence of a default argument here.
2516 if (NewNonTypeParm->hasDefaultArgument() &&
2517 DiagnoseDefaultTemplateArgument(
2518 S&: *this, TPC, ParamLoc: NewNonTypeParm->getLocation(),
2519 DefArgRange: NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2520 NewNonTypeParm->removeDefaultArgument();
2521 }
2522
2523 // Merge default arguments for non-type template parameters
2524 NonTypeTemplateParmDecl *OldNonTypeParm
2525 = OldParams? cast<NonTypeTemplateParmDecl>(Val: *OldParam) : nullptr;
2526 if (NewNonTypeParm->isParameterPack()) {
2527 assert(!NewNonTypeParm->hasDefaultArgument() &&
2528 "Parameter packs can't have a default argument!");
2529 if (!NewNonTypeParm->isPackExpansion())
2530 SawParameterPack = true;
2531 } else if (OldNonTypeParm && hasVisibleDefaultArgument(D: OldNonTypeParm) &&
2532 NewNonTypeParm->hasDefaultArgument() &&
2533 (!SkipBody || !SkipBody->ShouldSkip)) {
2534 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2535 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2536 SawDefaultArgument = true;
2537 if (!OldNonTypeParm->getOwningModule())
2538 RedundantDefaultArg = true;
2539 else if (!getASTContext().isSameDefaultTemplateArgument(
2540 X: OldNonTypeParm, Y: NewNonTypeParm)) {
2541 InconsistentDefaultArg = true;
2542 PrevModuleName =
2543 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2544 }
2545 PreviousDefaultArgLoc = NewDefaultLoc;
2546 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2547 // Merge the default argument from the old declaration to the
2548 // new declaration.
2549 NewNonTypeParm->setInheritedDefaultArgument(C: Context, Parm: OldNonTypeParm);
2550 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2551 } else if (NewNonTypeParm->hasDefaultArgument()) {
2552 SawDefaultArgument = true;
2553 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2554 } else if (SawDefaultArgument)
2555 MissingDefaultArg = true;
2556 } else {
2557 TemplateTemplateParmDecl *NewTemplateParm
2558 = cast<TemplateTemplateParmDecl>(Val: *NewParam);
2559
2560 // Check for unexpanded parameter packs, recursively.
2561 if (::DiagnoseUnexpandedParameterPacks(S&: *this, TTP: NewTemplateParm)) {
2562 Invalid = true;
2563 continue;
2564 }
2565
2566 // Check the presence of a default argument here.
2567 if (NewTemplateParm->hasDefaultArgument() &&
2568 DiagnoseDefaultTemplateArgument(S&: *this, TPC,
2569 ParamLoc: NewTemplateParm->getLocation(),
2570 DefArgRange: NewTemplateParm->getDefaultArgument().getSourceRange()))
2571 NewTemplateParm->removeDefaultArgument();
2572
2573 // Merge default arguments for template template parameters
2574 TemplateTemplateParmDecl *OldTemplateParm
2575 = OldParams? cast<TemplateTemplateParmDecl>(Val: *OldParam) : nullptr;
2576 if (NewTemplateParm->isParameterPack()) {
2577 assert(!NewTemplateParm->hasDefaultArgument() &&
2578 "Parameter packs can't have a default argument!");
2579 if (!NewTemplateParm->isPackExpansion())
2580 SawParameterPack = true;
2581 } else if (OldTemplateParm &&
2582 hasVisibleDefaultArgument(D: OldTemplateParm) &&
2583 NewTemplateParm->hasDefaultArgument() &&
2584 (!SkipBody || !SkipBody->ShouldSkip)) {
2585 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2586 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2587 SawDefaultArgument = true;
2588 if (!OldTemplateParm->getOwningModule())
2589 RedundantDefaultArg = true;
2590 else if (!getASTContext().isSameDefaultTemplateArgument(
2591 X: OldTemplateParm, Y: NewTemplateParm)) {
2592 InconsistentDefaultArg = true;
2593 PrevModuleName =
2594 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2595 }
2596 PreviousDefaultArgLoc = NewDefaultLoc;
2597 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2598 // Merge the default argument from the old declaration to the
2599 // new declaration.
2600 NewTemplateParm->setInheritedDefaultArgument(C: Context, Prev: OldTemplateParm);
2601 PreviousDefaultArgLoc
2602 = OldTemplateParm->getDefaultArgument().getLocation();
2603 } else if (NewTemplateParm->hasDefaultArgument()) {
2604 SawDefaultArgument = true;
2605 PreviousDefaultArgLoc
2606 = NewTemplateParm->getDefaultArgument().getLocation();
2607 } else if (SawDefaultArgument)
2608 MissingDefaultArg = true;
2609 }
2610
2611 // C++11 [temp.param]p11:
2612 // If a template parameter of a primary class template or alias template
2613 // is a template parameter pack, it shall be the last template parameter.
2614 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2615 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2616 Diag(Loc: (*NewParam)->getLocation(),
2617 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
2618 Invalid = true;
2619 }
2620
2621 // [basic.def.odr]/13:
2622 // There can be more than one definition of a
2623 // ...
2624 // default template argument
2625 // ...
2626 // in a program provided that each definition appears in a different
2627 // translation unit and the definitions satisfy the [same-meaning
2628 // criteria of the ODR].
2629 //
2630 // Simply, the design of modules allows the definition of template default
2631 // argument to be repeated across translation unit. Note that the ODR is
2632 // checked elsewhere. But it is still not allowed to repeat template default
2633 // argument in the same translation unit.
2634 if (RedundantDefaultArg) {
2635 Diag(Loc: NewDefaultLoc, DiagID: diag::err_template_param_default_arg_redefinition);
2636 Diag(Loc: OldDefaultLoc, DiagID: diag::note_template_param_prev_default_arg);
2637 Invalid = true;
2638 } else if (InconsistentDefaultArg) {
2639 // We could only diagnose about the case that the OldParam is imported.
2640 // The case NewParam is imported should be handled in ASTReader.
2641 Diag(Loc: NewDefaultLoc,
2642 DiagID: diag::err_template_param_default_arg_inconsistent_redefinition);
2643 Diag(Loc: OldDefaultLoc,
2644 DiagID: diag::note_template_param_prev_default_arg_in_other_module)
2645 << PrevModuleName;
2646 Invalid = true;
2647 } else if (MissingDefaultArg &&
2648 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2649 TPC == TPC_FriendClassTemplate)) {
2650 // C++ 23[temp.param]p14:
2651 // If a template-parameter of a class template, variable template, or
2652 // alias template has a default template argument, each subsequent
2653 // template-parameter shall either have a default template argument
2654 // supplied or be a template parameter pack.
2655 Diag(Loc: (*NewParam)->getLocation(),
2656 DiagID: diag::err_template_param_default_arg_missing);
2657 Diag(Loc: PreviousDefaultArgLoc, DiagID: diag::note_template_param_prev_default_arg);
2658 Invalid = true;
2659 RemoveDefaultArguments = true;
2660 }
2661
2662 // If we have an old template parameter list that we're merging
2663 // in, move on to the next parameter.
2664 if (OldParams)
2665 ++OldParam;
2666 }
2667
2668 // We were missing some default arguments at the end of the list, so remove
2669 // all of the default arguments.
2670 if (RemoveDefaultArguments) {
2671 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2672 NewParamEnd = NewParams->end();
2673 NewParam != NewParamEnd; ++NewParam) {
2674 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam))
2675 TTP->removeDefaultArgument();
2676 else if (NonTypeTemplateParmDecl *NTTP
2677 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam))
2678 NTTP->removeDefaultArgument();
2679 else
2680 cast<TemplateTemplateParmDecl>(Val: *NewParam)->removeDefaultArgument();
2681 }
2682 }
2683
2684 return Invalid;
2685}
2686
2687namespace {
2688
2689/// A class which looks for a use of a certain level of template
2690/// parameter.
2691struct DependencyChecker : DynamicRecursiveASTVisitor {
2692 unsigned Depth;
2693
2694 // Whether we're looking for a use of a template parameter that makes the
2695 // overall construct type-dependent / a dependent type. This is strictly
2696 // best-effort for now; we may fail to match at all for a dependent type
2697 // in some cases if this is set.
2698 bool IgnoreNonTypeDependent;
2699
2700 bool Match;
2701 SourceLocation MatchLoc;
2702
2703 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2704 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2705 Match(false) {}
2706
2707 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2708 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2709 NamedDecl *ND = Params->getParam(Idx: 0);
2710 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(Val: ND)) {
2711 Depth = PD->getDepth();
2712 } else if (NonTypeTemplateParmDecl *PD =
2713 dyn_cast<NonTypeTemplateParmDecl>(Val: ND)) {
2714 Depth = PD->getDepth();
2715 } else {
2716 Depth = cast<TemplateTemplateParmDecl>(Val: ND)->getDepth();
2717 }
2718 }
2719
2720 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2721 if (ParmDepth >= Depth) {
2722 Match = true;
2723 MatchLoc = Loc;
2724 return true;
2725 }
2726 return false;
2727 }
2728
2729 bool TraverseStmt(Stmt *S) override {
2730 // Prune out non-type-dependent expressions if requested. This can
2731 // sometimes result in us failing to find a template parameter reference
2732 // (if a value-dependent expression creates a dependent type), but this
2733 // mode is best-effort only.
2734 if (auto *E = dyn_cast_or_null<Expr>(Val: S))
2735 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2736 return true;
2737 return DynamicRecursiveASTVisitor::TraverseStmt(S);
2738 }
2739
2740 bool TraverseTypeLoc(TypeLoc TL, bool TraverseQualifier = true) override {
2741 if (IgnoreNonTypeDependent && !TL.isNull() &&
2742 !TL.getType()->isDependentType())
2743 return true;
2744 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL, TraverseQualifier);
2745 }
2746
2747 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2748 return !Matches(ParmDepth: TL.getTypePtr()->getDepth(), Loc: TL.getNameLoc());
2749 }
2750
2751 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2752 // For a best-effort search, keep looking until we find a location.
2753 return IgnoreNonTypeDependent || !Matches(ParmDepth: T->getDepth());
2754 }
2755
2756 bool TraverseTemplateName(TemplateName N) override {
2757 if (TemplateTemplateParmDecl *PD =
2758 dyn_cast_or_null<TemplateTemplateParmDecl>(Val: N.getAsTemplateDecl()))
2759 if (Matches(ParmDepth: PD->getDepth()))
2760 return false;
2761 return DynamicRecursiveASTVisitor::TraverseTemplateName(Template: N);
2762 }
2763
2764 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2765 if (NonTypeTemplateParmDecl *PD =
2766 dyn_cast<NonTypeTemplateParmDecl>(Val: E->getDecl()))
2767 if (Matches(ParmDepth: PD->getDepth(), Loc: E->getExprLoc()))
2768 return false;
2769 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(S: E);
2770 }
2771
2772 bool VisitUnresolvedLookupExpr(UnresolvedLookupExpr *ULE) override {
2773 if (ULE->isConceptReference() || ULE->isVarDeclReference()) {
2774 if (auto *TTP = ULE->getTemplateTemplateDecl()) {
2775 if (Matches(ParmDepth: TTP->getDepth(), Loc: ULE->getExprLoc()))
2776 return false;
2777 }
2778 for (auto &TLoc : ULE->template_arguments())
2779 DynamicRecursiveASTVisitor::TraverseTemplateArgumentLoc(ArgLoc: TLoc);
2780 }
2781 return DynamicRecursiveASTVisitor::VisitUnresolvedLookupExpr(S: ULE);
2782 }
2783
2784 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2785 return TraverseType(T: T->getReplacementType());
2786 }
2787
2788 bool VisitSubstTemplateTypeParmPackType(
2789 SubstTemplateTypeParmPackType *T) override {
2790 return TraverseTemplateArgument(Arg: T->getArgumentPack());
2791 }
2792
2793 bool TraverseInjectedClassNameType(InjectedClassNameType *T,
2794 bool TraverseQualifier) override {
2795 // An InjectedClassNameType will never have a dependent template name,
2796 // so no need to traverse it.
2797 return TraverseTemplateArguments(
2798 Args: T->getTemplateArgs(Ctx: T->getDecl()->getASTContext()));
2799 }
2800};
2801} // end anonymous namespace
2802
2803/// Determines whether a given type depends on the given parameter
2804/// list.
2805static bool
2806DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2807 if (!Params->size())
2808 return false;
2809
2810 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2811 Checker.TraverseType(T);
2812 return Checker.Match;
2813}
2814
2815// Find the source range corresponding to the named type in the given
2816// nested-name-specifier, if any.
2817static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2818 QualType T,
2819 const CXXScopeSpec &SS) {
2820 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2821 for (;;) {
2822 NestedNameSpecifier NNS = NNSLoc.getNestedNameSpecifier();
2823 if (NNS.getKind() != NestedNameSpecifier::Kind::Type)
2824 break;
2825 if (Context.hasSameUnqualifiedType(T1: T, T2: QualType(NNS.getAsType(), 0)))
2826 return NNSLoc.castAsTypeLoc().getSourceRange();
2827 // FIXME: This will always be empty.
2828 NNSLoc = NNSLoc.getAsNamespaceAndPrefix().Prefix;
2829 }
2830
2831 return SourceRange();
2832}
2833
2834TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2835 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2836 TemplateIdAnnotation *TemplateId,
2837 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2838 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2839 IsMemberSpecialization = false;
2840 Invalid = false;
2841
2842 // The sequence of nested types to which we will match up the template
2843 // parameter lists. We first build this list by starting with the type named
2844 // by the nested-name-specifier and walking out until we run out of types.
2845 SmallVector<QualType, 4> NestedTypes;
2846 QualType T;
2847 if (NestedNameSpecifier Qualifier = SS.getScopeRep();
2848 Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
2849 if (CXXRecordDecl *Record =
2850 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: true)))
2851 T = Context.getCanonicalTagType(TD: Record);
2852 else
2853 T = QualType(Qualifier.getAsType(), 0);
2854 }
2855
2856 // If we found an explicit specialization that prevents us from needing
2857 // 'template<>' headers, this will be set to the location of that
2858 // explicit specialization.
2859 SourceLocation ExplicitSpecLoc;
2860
2861 while (!T.isNull()) {
2862 NestedTypes.push_back(Elt: T);
2863
2864 // Retrieve the parent of a record type.
2865 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2866 // If this type is an explicit specialization, we're done.
2867 if (ClassTemplateSpecializationDecl *Spec
2868 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
2869 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Spec) &&
2870 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2871 ExplicitSpecLoc = Spec->getLocation();
2872 break;
2873 }
2874 } else if (Record->getTemplateSpecializationKind()
2875 == TSK_ExplicitSpecialization) {
2876 ExplicitSpecLoc = Record->getLocation();
2877 break;
2878 }
2879
2880 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Record->getParent()))
2881 T = Context.getTypeDeclType(Decl: Parent);
2882 else
2883 T = QualType();
2884 continue;
2885 }
2886
2887 if (const TemplateSpecializationType *TST
2888 = T->getAs<TemplateSpecializationType>()) {
2889 TemplateName Name = TST->getTemplateName();
2890 if (const auto *DTS = Name.getAsDependentTemplateName()) {
2891 // Look one step prior in a dependent template specialization type.
2892 if (NestedNameSpecifier NNS = DTS->getQualifier();
2893 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2894 T = QualType(NNS.getAsType(), 0);
2895 else
2896 T = QualType();
2897 continue;
2898 }
2899 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2900 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Template->getDeclContext()))
2901 T = Context.getTypeDeclType(Decl: Parent);
2902 else
2903 T = QualType();
2904 continue;
2905 }
2906 }
2907
2908 // Look one step prior in a dependent name type.
2909 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2910 if (NestedNameSpecifier NNS = DependentName->getQualifier();
2911 NNS.getKind() == NestedNameSpecifier::Kind::Type)
2912 T = QualType(NNS.getAsType(), 0);
2913 else
2914 T = QualType();
2915 continue;
2916 }
2917
2918 // Retrieve the parent of an enumeration type.
2919 if (const EnumType *EnumT = T->getAsCanonical<EnumType>()) {
2920 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2921 // check here.
2922 EnumDecl *Enum = EnumT->getDecl();
2923
2924 // Get to the parent type.
2925 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Enum->getParent()))
2926 T = Context.getCanonicalTypeDeclType(TD: Parent);
2927 else
2928 T = QualType();
2929 continue;
2930 }
2931
2932 T = QualType();
2933 }
2934 // Reverse the nested types list, since we want to traverse from the outermost
2935 // to the innermost while checking template-parameter-lists.
2936 std::reverse(first: NestedTypes.begin(), last: NestedTypes.end());
2937
2938 // C++0x [temp.expl.spec]p17:
2939 // A member or a member template may be nested within many
2940 // enclosing class templates. In an explicit specialization for
2941 // such a member, the member declaration shall be preceded by a
2942 // template<> for each enclosing class template that is
2943 // explicitly specialized.
2944 bool SawNonEmptyTemplateParameterList = false;
2945
2946 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2947 if (SawNonEmptyTemplateParameterList) {
2948 if (!SuppressDiagnostic)
2949 Diag(Loc: DeclLoc, DiagID: diag::err_specialize_member_of_template)
2950 << !Recovery << Range;
2951 Invalid = true;
2952 IsMemberSpecialization = false;
2953 return true;
2954 }
2955
2956 return false;
2957 };
2958
2959 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2960 // Check that we can have an explicit specialization here.
2961 if (CheckExplicitSpecialization(Range, true))
2962 return true;
2963
2964 // We don't have a template header, but we should.
2965 SourceLocation ExpectedTemplateLoc;
2966 if (!ParamLists.empty())
2967 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2968 else
2969 ExpectedTemplateLoc = DeclStartLoc;
2970
2971 if (!SuppressDiagnostic)
2972 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_header)
2973 << Range
2974 << FixItHint::CreateInsertion(InsertionLoc: ExpectedTemplateLoc, Code: "template<> ");
2975 return false;
2976 };
2977
2978 unsigned ParamIdx = 0;
2979 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2980 ++TypeIdx) {
2981 T = NestedTypes[TypeIdx];
2982
2983 // Whether we expect a 'template<>' header.
2984 bool NeedEmptyTemplateHeader = false;
2985
2986 // Whether we expect a template header with parameters.
2987 bool NeedNonemptyTemplateHeader = false;
2988
2989 // For a dependent type, the set of template parameters that we
2990 // expect to see.
2991 TemplateParameterList *ExpectedTemplateParams = nullptr;
2992
2993 // C++0x [temp.expl.spec]p15:
2994 // A member or a member template may be nested within many enclosing
2995 // class templates. In an explicit specialization for such a member, the
2996 // member declaration shall be preceded by a template<> for each
2997 // enclosing class template that is explicitly specialized.
2998 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2999 if (ClassTemplatePartialSpecializationDecl *Partial
3000 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Record)) {
3001 ExpectedTemplateParams = Partial->getTemplateParameters();
3002 NeedNonemptyTemplateHeader = true;
3003 } else if (Record->isDependentType()) {
3004 if (Record->getDescribedClassTemplate()) {
3005 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3006 ->getTemplateParameters();
3007 NeedNonemptyTemplateHeader = true;
3008 }
3009 } else if (ClassTemplateSpecializationDecl *Spec
3010 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
3011 // C++0x [temp.expl.spec]p4:
3012 // Members of an explicitly specialized class template are defined
3013 // in the same manner as members of normal classes, and not using
3014 // the template<> syntax.
3015 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3016 NeedEmptyTemplateHeader = true;
3017 else
3018 continue;
3019 } else if (Record->getTemplateSpecializationKind()) {
3020 if (Record->getTemplateSpecializationKind()
3021 != TSK_ExplicitSpecialization &&
3022 TypeIdx == NumTypes - 1)
3023 IsMemberSpecialization = true;
3024
3025 continue;
3026 }
3027 } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
3028 TemplateName Name = TST->getTemplateName();
3029 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3030 ExpectedTemplateParams = Template->getTemplateParameters();
3031 NeedNonemptyTemplateHeader = true;
3032 } else if (Name.getAsDeducedTemplateName()) {
3033 // FIXME: We actually could/should check the template arguments here
3034 // against the corresponding template parameter list.
3035 NeedNonemptyTemplateHeader = false;
3036 }
3037 }
3038
3039 // C++ [temp.expl.spec]p16:
3040 // In an explicit specialization declaration for a member of a class
3041 // template or a member template that appears in namespace scope, the
3042 // member template and some of its enclosing class templates may remain
3043 // unspecialized, except that the declaration shall not explicitly
3044 // specialize a class member template if its enclosing class templates
3045 // are not explicitly specialized as well.
3046 if (ParamIdx < ParamLists.size()) {
3047 if (ParamLists[ParamIdx]->size() == 0) {
3048 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3049 false))
3050 return nullptr;
3051 } else
3052 SawNonEmptyTemplateParameterList = true;
3053 }
3054
3055 if (NeedEmptyTemplateHeader) {
3056 // If we're on the last of the types, and we need a 'template<>' header
3057 // here, then it's a member specialization.
3058 if (TypeIdx == NumTypes - 1)
3059 IsMemberSpecialization = true;
3060
3061 if (ParamIdx < ParamLists.size()) {
3062 if (ParamLists[ParamIdx]->size() > 0) {
3063 // The header has template parameters when it shouldn't. Complain.
3064 if (!SuppressDiagnostic)
3065 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3066 DiagID: diag::err_template_param_list_matches_nontemplate)
3067 << T
3068 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3069 ParamLists[ParamIdx]->getRAngleLoc())
3070 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3071 Invalid = true;
3072 return nullptr;
3073 }
3074
3075 // Consume this template header.
3076 ++ParamIdx;
3077 continue;
3078 }
3079
3080 if (!IsFriend)
3081 if (DiagnoseMissingExplicitSpecialization(
3082 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3083 return nullptr;
3084
3085 continue;
3086 }
3087
3088 if (NeedNonemptyTemplateHeader) {
3089 // In friend declarations we can have template-ids which don't
3090 // depend on the corresponding template parameter lists. But
3091 // assume that empty parameter lists are supposed to match this
3092 // template-id.
3093 if (IsFriend && T->isDependentType()) {
3094 if (ParamIdx < ParamLists.size() &&
3095 DependsOnTemplateParameters(T, Params: ParamLists[ParamIdx]))
3096 ExpectedTemplateParams = nullptr;
3097 else
3098 continue;
3099 }
3100
3101 if (ParamIdx < ParamLists.size()) {
3102 // Check the template parameter list, if we can.
3103 if (ExpectedTemplateParams &&
3104 !TemplateParameterListsAreEqual(New: ParamLists[ParamIdx],
3105 Old: ExpectedTemplateParams,
3106 Complain: !SuppressDiagnostic, Kind: TPL_TemplateMatch))
3107 Invalid = true;
3108
3109 if (!Invalid &&
3110 CheckTemplateParameterList(NewParams: ParamLists[ParamIdx], OldParams: nullptr,
3111 TPC: TPC_ClassTemplateMember))
3112 Invalid = true;
3113
3114 ++ParamIdx;
3115 continue;
3116 }
3117
3118 if (!SuppressDiagnostic)
3119 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_template_parameters)
3120 << T
3121 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3122 Invalid = true;
3123 continue;
3124 }
3125 }
3126
3127 // If there were at least as many template-ids as there were template
3128 // parameter lists, then there are no template parameter lists remaining for
3129 // the declaration itself.
3130 if (ParamIdx >= ParamLists.size()) {
3131 if (TemplateId && !IsFriend) {
3132 // We don't have a template header for the declaration itself, but we
3133 // should.
3134 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3135 TemplateId->RAngleLoc));
3136
3137 // Fabricate an empty template parameter list for the invented header.
3138 return TemplateParameterList::Create(C: Context, TemplateLoc: SourceLocation(),
3139 LAngleLoc: SourceLocation(), Params: {},
3140 RAngleLoc: SourceLocation(), RequiresClause: nullptr);
3141 }
3142
3143 return nullptr;
3144 }
3145
3146 // If there were too many template parameter lists, complain about that now.
3147 if (ParamIdx < ParamLists.size() - 1) {
3148 bool HasAnyExplicitSpecHeader = false;
3149 bool AllExplicitSpecHeaders = true;
3150 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3151 if (ParamLists[I]->size() == 0)
3152 HasAnyExplicitSpecHeader = true;
3153 else
3154 AllExplicitSpecHeaders = false;
3155 }
3156
3157 if (!SuppressDiagnostic)
3158 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3159 DiagID: AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3160 : diag::err_template_spec_extra_headers)
3161 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3162 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3163
3164 // If there was a specialization somewhere, such that 'template<>' is
3165 // not required, and there were any 'template<>' headers, note where the
3166 // specialization occurred.
3167 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3168 !SuppressDiagnostic)
3169 Diag(Loc: ExplicitSpecLoc,
3170 DiagID: diag::note_explicit_template_spec_does_not_need_header)
3171 << NestedTypes.back();
3172
3173 // We have a template parameter list with no corresponding scope, which
3174 // means that the resulting template declaration can't be instantiated
3175 // properly (we'll end up with dependent nodes when we shouldn't).
3176 if (!AllExplicitSpecHeaders)
3177 Invalid = true;
3178 }
3179
3180 // C++ [temp.expl.spec]p16:
3181 // In an explicit specialization declaration for a member of a class
3182 // template or a member template that ap- pears in namespace scope, the
3183 // member template and some of its enclosing class templates may remain
3184 // unspecialized, except that the declaration shall not explicitly
3185 // specialize a class member template if its en- closing class templates
3186 // are not explicitly specialized as well.
3187 if (ParamLists.back()->size() == 0 &&
3188 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3189 false))
3190 return nullptr;
3191
3192 // Return the last template parameter list, which corresponds to the
3193 // entity being declared.
3194 return ParamLists.back();
3195}
3196
3197void Sema::NoteAllFoundTemplates(TemplateName Name) {
3198 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3199 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_declared_here)
3200 << (isa<FunctionTemplateDecl>(Val: Template)
3201 ? 0
3202 : isa<ClassTemplateDecl>(Val: Template)
3203 ? 1
3204 : isa<VarTemplateDecl>(Val: Template)
3205 ? 2
3206 : isa<TypeAliasTemplateDecl>(Val: Template) ? 3 : 4)
3207 << Template->getDeclName();
3208 return;
3209 }
3210
3211 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3212 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3213 IEnd = OST->end();
3214 I != IEnd; ++I)
3215 Diag(Loc: (*I)->getLocation(), DiagID: diag::note_template_declared_here)
3216 << 0 << (*I)->getDeclName();
3217
3218 return;
3219 }
3220}
3221
3222static QualType builtinCommonTypeImpl(Sema &S, ElaboratedTypeKeyword Keyword,
3223 TemplateName BaseTemplate,
3224 SourceLocation TemplateLoc,
3225 ArrayRef<TemplateArgument> Ts) {
3226 auto lookUpCommonType = [&](TemplateArgument T1,
3227 TemplateArgument T2) -> QualType {
3228 // Don't bother looking for other specializations if both types are
3229 // builtins - users aren't allowed to specialize for them
3230 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3231 return builtinCommonTypeImpl(S, Keyword, BaseTemplate, TemplateLoc,
3232 Ts: {T1, T2});
3233
3234 TemplateArgumentListInfo Args;
3235 Args.addArgument(Loc: TemplateArgumentLoc(
3236 T1, S.Context.getTrivialTypeSourceInfo(T: T1.getAsType())));
3237 Args.addArgument(Loc: TemplateArgumentLoc(
3238 T2, S.Context.getTrivialTypeSourceInfo(T: T2.getAsType())));
3239
3240 EnterExpressionEvaluationContext UnevaluatedContext(
3241 S, Sema::ExpressionEvaluationContext::Unevaluated);
3242 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3243 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3244
3245 QualType BaseTemplateInst = S.CheckTemplateIdType(
3246 Keyword, Template: BaseTemplate, TemplateLoc, TemplateArgs&: Args,
3247 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
3248
3249 if (SFINAE.hasErrorOccurred())
3250 return QualType();
3251
3252 return BaseTemplateInst;
3253 };
3254
3255 // Note A: For the common_type trait applied to a template parameter pack T of
3256 // types, the member type shall be either defined or not present as follows:
3257 switch (Ts.size()) {
3258
3259 // If sizeof...(T) is zero, there shall be no member type.
3260 case 0:
3261 return QualType();
3262
3263 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3264 // pack T. The member typedef-name type shall denote the same type, if any, as
3265 // common_type_t<T0, T0>; otherwise there shall be no member type.
3266 case 1:
3267 return lookUpCommonType(Ts[0], Ts[0]);
3268
3269 // If sizeof...(T) is two, let the first and second types constituting T be
3270 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3271 // as decay_t<T1> and decay_t<T2>, respectively.
3272 case 2: {
3273 QualType T1 = Ts[0].getAsType();
3274 QualType T2 = Ts[1].getAsType();
3275 QualType D1 = S.BuiltinDecay(BaseType: T1, Loc: {});
3276 QualType D2 = S.BuiltinDecay(BaseType: T2, Loc: {});
3277
3278 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3279 // the same type, if any, as common_type_t<D1, D2>.
3280 if (!S.Context.hasSameType(T1, T2: D1) || !S.Context.hasSameType(T1: T2, T2: D2))
3281 return lookUpCommonType(D1, D2);
3282
3283 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3284 // denotes a valid type, let C denote that type.
3285 {
3286 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3287 EnterExpressionEvaluationContext UnevaluatedContext(
3288 S, Sema::ExpressionEvaluationContext::Unevaluated);
3289 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3290 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3291
3292 // false
3293 OpaqueValueExpr CondExpr(SourceLocation(), S.Context.BoolTy,
3294 VK_PRValue);
3295 ExprResult Cond = &CondExpr;
3296
3297 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3298 if (ConstRefQual) {
3299 D1.addConst();
3300 D2.addConst();
3301 }
3302
3303 // declval<D1>()
3304 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3305 ExprResult LHS = &LHSExpr;
3306
3307 // declval<D2>()
3308 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3309 ExprResult RHS = &RHSExpr;
3310
3311 ExprValueKind VK = VK_PRValue;
3312 ExprObjectKind OK = OK_Ordinary;
3313
3314 // decltype(false ? declval<D1>() : declval<D2>())
3315 QualType Result =
3316 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc: TemplateLoc);
3317
3318 if (Result.isNull() || SFINAE.hasErrorOccurred())
3319 return QualType();
3320
3321 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3322 return S.BuiltinDecay(BaseType: Result, Loc: TemplateLoc);
3323 };
3324
3325 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3326 return Res;
3327
3328 // Let:
3329 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3330 // COND-RES(X, Y) be
3331 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3332
3333 // C++20 only
3334 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3335 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3336 if (!S.Context.getLangOpts().CPlusPlus20)
3337 return QualType();
3338 return CheckConditionalOperands(true);
3339 }
3340 }
3341
3342 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3343 // denote the first, second, and (pack of) remaining types constituting T. Let
3344 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3345 // a type C, the member typedef-name type shall denote the same type, if any,
3346 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3347 default: {
3348 QualType Result = Ts.front().getAsType();
3349 for (auto T : llvm::drop_begin(RangeOrContainer&: Ts)) {
3350 Result = lookUpCommonType(Result, T.getAsType());
3351 if (Result.isNull())
3352 return QualType();
3353 }
3354 return Result;
3355 }
3356 }
3357}
3358
3359static bool isInVkNamespace(const RecordType *RT) {
3360 DeclContext *DC = RT->getDecl()->getDeclContext();
3361 if (!DC)
3362 return false;
3363
3364 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Val: DC);
3365 if (!ND)
3366 return false;
3367
3368 return ND->getQualifiedNameAsString() == "hlsl::vk";
3369}
3370
3371static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3372 QualType OperandArg,
3373 SourceLocation Loc) {
3374 if (auto *RT = OperandArg->getAsCanonical<RecordType>()) {
3375 bool Literal = false;
3376 SourceLocation LiteralLoc;
3377 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3378 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3379 assert(SpecDecl);
3380
3381 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3382 QualType ConstantType = LiteralArgs[0].getAsType();
3383 RT = ConstantType->getAsCanonical<RecordType>();
3384 Literal = true;
3385 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3386 }
3387
3388 if (RT && isInVkNamespace(RT) &&
3389 RT->getDecl()->getName() == "integral_constant") {
3390 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3391 assert(SpecDecl);
3392
3393 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3394
3395 QualType ConstantType = ConstantArgs[0].getAsType();
3396 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3397
3398 if (Literal)
3399 return SpirvOperand::createLiteral(Val: Value);
3400 return SpirvOperand::createConstant(ResultType: ConstantType, Val: Value);
3401 } else if (Literal) {
3402 SemaRef.Diag(Loc: LiteralLoc, DiagID: diag::err_hlsl_vk_literal_must_contain_constant);
3403 return SpirvOperand();
3404 }
3405 }
3406 if (SemaRef.RequireCompleteType(Loc, T: OperandArg,
3407 DiagID: diag::err_call_incomplete_argument))
3408 return SpirvOperand();
3409 return SpirvOperand::createType(T: OperandArg);
3410}
3411
3412static QualType checkBuiltinTemplateIdType(
3413 Sema &SemaRef, ElaboratedTypeKeyword Keyword, BuiltinTemplateDecl *BTD,
3414 ArrayRef<TemplateArgument> Converted, SourceLocation TemplateLoc,
3415 TemplateArgumentListInfo &TemplateArgs) {
3416 ASTContext &Context = SemaRef.getASTContext();
3417
3418 assert(Converted.size() == BTD->getTemplateParameters()->size() &&
3419 "Builtin template arguments do not match its parameters");
3420
3421 switch (BTD->getBuiltinTemplateKind()) {
3422 case BTK__make_integer_seq: {
3423 // Specializations of __make_integer_seq<S, T, N> are treated like
3424 // S<T, 0, ..., N-1>.
3425
3426 QualType OrigType = Converted[1].getAsType();
3427 // C++14 [inteseq.intseq]p1:
3428 // T shall be an integer type.
3429 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Ctx: Context)) {
3430 SemaRef.Diag(Loc: TemplateArgs[1].getLocation(),
3431 DiagID: diag::err_integer_sequence_integral_element_type);
3432 return QualType();
3433 }
3434
3435 TemplateArgument NumArgsArg = Converted[2];
3436 if (NumArgsArg.isDependent())
3437 return QualType();
3438
3439 TemplateArgumentListInfo SyntheticTemplateArgs;
3440 // The type argument, wrapped in substitution sugar, gets reused as the
3441 // first template argument in the synthetic template argument list.
3442 SyntheticTemplateArgs.addArgument(
3443 Loc: TemplateArgumentLoc(TemplateArgument(OrigType),
3444 SemaRef.Context.getTrivialTypeSourceInfo(
3445 T: OrigType, Loc: TemplateArgs[1].getLocation())));
3446
3447 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3448 // Expand N into 0 ... N-1.
3449 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3450 I < NumArgs; ++I) {
3451 TemplateArgument TA(Context, I, OrigType);
3452 SyntheticTemplateArgs.addArgument(Loc: SemaRef.getTrivialTemplateArgumentLoc(
3453 Arg: TA, NTTPType: OrigType, Loc: TemplateArgs[2].getLocation()));
3454 }
3455 } else {
3456 // C++14 [inteseq.make]p1:
3457 // If N is negative the program is ill-formed.
3458 SemaRef.Diag(Loc: TemplateArgs[2].getLocation(),
3459 DiagID: diag::err_integer_sequence_negative_length);
3460 return QualType();
3461 }
3462
3463 // The first template argument will be reused as the template decl that
3464 // our synthetic template arguments will be applied to.
3465 return SemaRef.CheckTemplateIdType(Keyword, Template: Converted[0].getAsTemplate(),
3466 TemplateLoc, TemplateArgs&: SyntheticTemplateArgs,
3467 /*Scope=*/nullptr,
3468 /*ForNestedNameSpecifier=*/false);
3469 }
3470
3471 case BTK__type_pack_element: {
3472 // Specializations of
3473 // __type_pack_element<Index, T_1, ..., T_N>
3474 // are treated like T_Index.
3475 assert(Converted.size() == 2 &&
3476 "__type_pack_element should be given an index and a parameter pack");
3477
3478 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3479 if (IndexArg.isDependent() || Ts.isDependent())
3480 return QualType();
3481
3482 llvm::APSInt Index = IndexArg.getAsIntegral();
3483 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3484 "type std::size_t, and hence be non-negative");
3485 // If the Index is out of bounds, the program is ill-formed.
3486 if (Index >= Ts.pack_size()) {
3487 SemaRef.Diag(Loc: TemplateArgs[0].getLocation(),
3488 DiagID: diag::err_type_pack_element_out_of_bounds);
3489 return QualType();
3490 }
3491
3492 // We simply return the type at index `Index`.
3493 int64_t N = Index.getExtValue();
3494 return Ts.getPackAsArray()[N].getAsType();
3495 }
3496
3497 case BTK__builtin_common_type: {
3498 assert(Converted.size() == 4);
3499 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3500 return QualType();
3501
3502 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3503 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3504 if (auto CT = builtinCommonTypeImpl(S&: SemaRef, Keyword, BaseTemplate,
3505 TemplateLoc, Ts);
3506 !CT.isNull()) {
3507 TemplateArgumentListInfo TAs;
3508 TAs.addArgument(Loc: TemplateArgumentLoc(
3509 TemplateArgument(CT), SemaRef.Context.getTrivialTypeSourceInfo(
3510 T: CT, Loc: TemplateArgs[1].getLocation())));
3511 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3512 return SemaRef.CheckTemplateIdType(Keyword, Template: HasTypeMember, TemplateLoc,
3513 TemplateArgs&: TAs, /*Scope=*/nullptr,
3514 /*ForNestedNameSpecifier=*/false);
3515 }
3516 QualType HasNoTypeMember = Converted[2].getAsType();
3517 return HasNoTypeMember;
3518 }
3519
3520 case BTK__hlsl_spirv_type: {
3521 assert(Converted.size() == 4);
3522
3523 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3524 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_hlsl_spirv_only) << BTD;
3525 }
3526
3527 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3528 return QualType();
3529
3530 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3531 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3532 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3533
3534 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3535
3536 llvm::SmallVector<SpirvOperand> Operands;
3537
3538 for (auto &OperandTA : OperandArgs) {
3539 QualType OperandArg = OperandTA.getAsType();
3540 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3541 Loc: TemplateArgs[3].getLocation());
3542 if (!Operand.isValid())
3543 return QualType();
3544 Operands.push_back(Elt: Operand);
3545 }
3546
3547 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3548 }
3549 case BTK__builtin_dedup_pack: {
3550 assert(Converted.size() == 1 && "__builtin_dedup_pack should be given "
3551 "a parameter pack");
3552 TemplateArgument Ts = Converted[0];
3553 // Delay the computation until we can compute the final result. We choose
3554 // not to remove the duplicates upfront before substitution to keep the code
3555 // simple.
3556 if (Ts.isDependent())
3557 return QualType();
3558 assert(Ts.getKind() == clang::TemplateArgument::Pack);
3559 llvm::SmallVector<TemplateArgument> OutArgs;
3560 llvm::SmallDenseSet<QualType> Seen;
3561 // Synthesize a new template argument list, removing duplicates.
3562 for (auto T : Ts.getPackAsArray()) {
3563 assert(T.getKind() == clang::TemplateArgument::Type);
3564 if (!Seen.insert(V: T.getAsType().getCanonicalType()).second)
3565 continue;
3566 OutArgs.push_back(Elt: T);
3567 }
3568 return Context.getSubstBuiltinTemplatePack(
3569 ArgPack: TemplateArgument::CreatePackCopy(Context, Args: OutArgs));
3570 }
3571 }
3572 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3573}
3574
3575/// Determine whether this alias template is "enable_if_t".
3576/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3577static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3578 return AliasTemplate->getName() == "enable_if_t" ||
3579 AliasTemplate->getName() == "__enable_if_t";
3580}
3581
3582/// Collect all of the separable terms in the given condition, which
3583/// might be a conjunction.
3584///
3585/// FIXME: The right answer is to convert the logical expression into
3586/// disjunctive normal form, so we can find the first failed term
3587/// within each possible clause.
3588static void collectConjunctionTerms(Expr *Clause,
3589 SmallVectorImpl<Expr *> &Terms) {
3590 if (auto BinOp = dyn_cast<BinaryOperator>(Val: Clause->IgnoreParenImpCasts())) {
3591 if (BinOp->getOpcode() == BO_LAnd) {
3592 collectConjunctionTerms(Clause: BinOp->getLHS(), Terms);
3593 collectConjunctionTerms(Clause: BinOp->getRHS(), Terms);
3594 return;
3595 }
3596 }
3597
3598 Terms.push_back(Elt: Clause);
3599}
3600
3601// The ranges-v3 library uses an odd pattern of a top-level "||" with
3602// a left-hand side that is value-dependent but never true. Identify
3603// the idiom and ignore that term.
3604static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3605 // Top-level '||'.
3606 auto *BinOp = dyn_cast<BinaryOperator>(Val: Cond->IgnoreParenImpCasts());
3607 if (!BinOp) return Cond;
3608
3609 if (BinOp->getOpcode() != BO_LOr) return Cond;
3610
3611 // With an inner '==' that has a literal on the right-hand side.
3612 Expr *LHS = BinOp->getLHS();
3613 auto *InnerBinOp = dyn_cast<BinaryOperator>(Val: LHS->IgnoreParenImpCasts());
3614 if (!InnerBinOp) return Cond;
3615
3616 if (InnerBinOp->getOpcode() != BO_EQ ||
3617 !isa<IntegerLiteral>(Val: InnerBinOp->getRHS()))
3618 return Cond;
3619
3620 // If the inner binary operation came from a macro expansion named
3621 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3622 // of the '||', which is the real, user-provided condition.
3623 SourceLocation Loc = InnerBinOp->getExprLoc();
3624 if (!Loc.isMacroID()) return Cond;
3625
3626 StringRef MacroName = PP.getImmediateMacroName(Loc);
3627 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3628 return BinOp->getRHS();
3629
3630 return Cond;
3631}
3632
3633namespace {
3634
3635// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3636// within failing boolean expression, such as substituting template parameters
3637// for actual types.
3638class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3639public:
3640 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3641 : Policy(P) {}
3642
3643 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3644 const auto *DR = dyn_cast<DeclRefExpr>(Val: E);
3645 if (DR && DR->getQualifier()) {
3646 // If this is a qualified name, expand the template arguments in nested
3647 // qualifiers.
3648 DR->getQualifier().print(OS, Policy, ResolveTemplateArguments: true);
3649 // Then print the decl itself.
3650 const ValueDecl *VD = DR->getDecl();
3651 OS << VD->getName();
3652 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) {
3653 // This is a template variable, print the expanded template arguments.
3654 printTemplateArgumentList(
3655 OS, Args: IV->getTemplateArgs().asArray(), Policy,
3656 TPL: IV->getSpecializedTemplate()->getTemplateParameters());
3657 }
3658 return true;
3659 }
3660 return false;
3661 }
3662
3663private:
3664 const PrintingPolicy Policy;
3665};
3666
3667} // end anonymous namespace
3668
3669std::pair<Expr *, std::string>
3670Sema::findFailedBooleanCondition(Expr *Cond) {
3671 Cond = lookThroughRangesV3Condition(PP, Cond);
3672
3673 // Separate out all of the terms in a conjunction.
3674 SmallVector<Expr *, 4> Terms;
3675 collectConjunctionTerms(Clause: Cond, Terms);
3676
3677 // Determine which term failed.
3678 Expr *FailedCond = nullptr;
3679 for (Expr *Term : Terms) {
3680 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3681
3682 // Literals are uninteresting.
3683 if (isa<CXXBoolLiteralExpr>(Val: TermAsWritten) ||
3684 isa<IntegerLiteral>(Val: TermAsWritten))
3685 continue;
3686
3687 // The initialization of the parameter from the argument is
3688 // a constant-evaluated context.
3689 EnterExpressionEvaluationContext ConstantEvaluated(
3690 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3691
3692 bool Succeeded;
3693 if (Term->EvaluateAsBooleanCondition(Result&: Succeeded, Ctx: Context) &&
3694 !Succeeded) {
3695 FailedCond = TermAsWritten;
3696 break;
3697 }
3698 }
3699 if (!FailedCond)
3700 FailedCond = Cond->IgnoreParenImpCasts();
3701
3702 std::string Description;
3703 {
3704 llvm::raw_string_ostream Out(Description);
3705 PrintingPolicy Policy = getPrintingPolicy();
3706 Policy.PrintAsCanonical = true;
3707 FailedBooleanConditionPrinterHelper Helper(Policy);
3708 FailedCond->printPretty(OS&: Out, Helper: &Helper, Policy, Indentation: 0, NewlineSymbol: "\n", Context: nullptr);
3709 }
3710 return { FailedCond, Description };
3711}
3712
3713static TemplateName
3714resolveAssumedTemplateNameAsType(Sema &S, Scope *Scope,
3715 const AssumedTemplateStorage *ATN,
3716 SourceLocation NameLoc) {
3717 // We assumed this undeclared identifier to be an (ADL-only) function
3718 // template name, but it was used in a context where a type was required.
3719 // Try to typo-correct it now.
3720 LookupResult R(S, ATN->getDeclName(), NameLoc, S.LookupOrdinaryName);
3721 struct CandidateCallback : CorrectionCandidateCallback {
3722 bool ValidateCandidate(const TypoCorrection &TC) override {
3723 return TC.getCorrectionDecl() &&
3724 getAsTypeTemplateDecl(D: TC.getCorrectionDecl());
3725 }
3726 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3727 return std::make_unique<CandidateCallback>(args&: *this);
3728 }
3729 } FilterCCC;
3730
3731 TypoCorrection Corrected =
3732 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Scope,
3733 /*SS=*/nullptr, CCC&: FilterCCC, Mode: CorrectTypoKind::ErrorRecovery);
3734 if (Corrected && Corrected.getFoundDecl()) {
3735 S.diagnoseTypo(Correction: Corrected, TypoDiag: S.PDiag(DiagID: diag::err_no_template_suggest)
3736 << ATN->getDeclName());
3737 return S.Context.getQualifiedTemplateName(
3738 /*Qualifier=*/std::nullopt, /*TemplateKeyword=*/false,
3739 Template: TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()));
3740 }
3741
3742 return TemplateName();
3743}
3744
3745QualType Sema::CheckTemplateIdType(ElaboratedTypeKeyword Keyword,
3746 TemplateName Name,
3747 SourceLocation TemplateLoc,
3748 TemplateArgumentListInfo &TemplateArgs,
3749 Scope *Scope, bool ForNestedNameSpecifier) {
3750 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
3751
3752 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
3753 if (!Template) {
3754 if (const auto *S = UnderlyingName.getAsSubstTemplateTemplateParmPack()) {
3755 Template = S->getParameterPack();
3756 } else if (const auto *DTN = UnderlyingName.getAsDependentTemplateName()) {
3757 if (DTN->getName().getIdentifier())
3758 // When building a template-id where the template-name is dependent,
3759 // assume the template is a type template. Either our assumption is
3760 // correct, or the code is ill-formed and will be diagnosed when the
3761 // dependent name is substituted.
3762 return Context.getTemplateSpecializationType(Keyword, T: Name,
3763 SpecifiedArgs: TemplateArgs.arguments(),
3764 /*CanonicalArgs=*/{});
3765 } else if (const auto *ATN = UnderlyingName.getAsAssumedTemplateName()) {
3766 if (TemplateName CorrectedName = ::resolveAssumedTemplateNameAsType(
3767 S&: *this, Scope, ATN, NameLoc: TemplateLoc);
3768 CorrectedName.isNull()) {
3769 Diag(Loc: TemplateLoc, DiagID: diag::err_no_template) << ATN->getDeclName();
3770 return QualType();
3771 } else {
3772 Name = CorrectedName;
3773 Template = Name.getAsTemplateDecl();
3774 }
3775 }
3776 }
3777 if (!Template ||
3778 isa<FunctionTemplateDecl, VarTemplateDecl, ConceptDecl>(Val: Template)) {
3779 SourceRange R(TemplateLoc, TemplateArgs.getRAngleLoc());
3780 if (ForNestedNameSpecifier)
3781 Diag(Loc: TemplateLoc, DiagID: diag::err_non_type_template_in_nested_name_specifier)
3782 << isa_and_nonnull<VarTemplateDecl>(Val: Template) << Name << R;
3783 else
3784 Diag(Loc: TemplateLoc, DiagID: diag::err_template_id_not_a_type) << Name << R;
3785 NoteAllFoundTemplates(Name);
3786 return QualType();
3787 }
3788
3789 // Check that the template argument list is well-formed for this
3790 // template.
3791 CheckTemplateArgumentInfo CTAI;
3792 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3793 DefaultArgs, /*PartialTemplateArgs=*/false,
3794 CTAI,
3795 /*UpdateArgsWithConversions=*/true))
3796 return QualType();
3797
3798 QualType CanonType;
3799
3800 if (isa<TemplateTemplateParmDecl>(Val: Template)) {
3801 // We might have a substituted template template parameter pack. If so,
3802 // build a template specialization type for it.
3803 } else if (TypeAliasTemplateDecl *AliasTemplate =
3804 dyn_cast<TypeAliasTemplateDecl>(Val: Template)) {
3805
3806 // C++0x [dcl.type.elab]p2:
3807 // If the identifier resolves to a typedef-name or the simple-template-id
3808 // resolves to an alias template specialization, the
3809 // elaborated-type-specifier is ill-formed.
3810 if (Keyword != ElaboratedTypeKeyword::None &&
3811 Keyword != ElaboratedTypeKeyword::Typename) {
3812 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_tag_reference_non_tag)
3813 << AliasTemplate << NonTagKind::TypeAliasTemplate
3814 << KeywordHelpers::getTagTypeKindForKeyword(Keyword);
3815 SemaRef.Diag(Loc: AliasTemplate->getLocation(), DiagID: diag::note_declared_at);
3816 }
3817
3818 // Find the canonical type for this type alias template specialization.
3819 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3820 if (Pattern->isInvalidDecl())
3821 return QualType();
3822
3823 // Only substitute for the innermost template argument list.
3824 MultiLevelTemplateArgumentList TemplateArgLists;
3825 TemplateArgLists.addOuterTemplateArguments(AssociatedDecl: Template, Args: CTAI.SugaredConverted,
3826 /*Final=*/true);
3827 TemplateArgLists.addOuterRetainedLevels(
3828 Num: AliasTemplate->getTemplateParameters()->getDepth());
3829
3830 LocalInstantiationScope Scope(*this);
3831
3832 // Diagnose uses of this alias.
3833 (void)DiagnoseUseOfDecl(D: AliasTemplate, Locs: TemplateLoc);
3834
3835 // FIXME: The TemplateArgs passed here are not used for the context note,
3836 // nor they should, because this note will be pointing to the specialization
3837 // anyway. These arguments are needed for a hack for instantiating lambdas
3838 // in the pattern of the alias. In getTemplateInstantiationArgs, these
3839 // arguments will be used for collating the template arguments needed to
3840 // instantiate the lambda.
3841 InstantiatingTemplate Inst(*this, /*PointOfInstantiation=*/TemplateLoc,
3842 /*Entity=*/AliasTemplate,
3843 /*TemplateArgs=*/CTAI.SugaredConverted);
3844 if (Inst.isInvalid())
3845 return QualType();
3846
3847 std::optional<ContextRAII> SavedContext;
3848 if (!AliasTemplate->getDeclContext()->isFileContext())
3849 SavedContext.emplace(args&: *this, args: AliasTemplate->getDeclContext());
3850
3851 CanonType =
3852 SubstType(T: Pattern->getUnderlyingType(), TemplateArgs: TemplateArgLists,
3853 Loc: AliasTemplate->getLocation(), Entity: AliasTemplate->getDeclName());
3854 if (CanonType.isNull()) {
3855 // If this was enable_if and we failed to find the nested type
3856 // within enable_if in a SFINAE context, dig out the specific
3857 // enable_if condition that failed and present that instead.
3858 if (isEnableIfAliasTemplate(AliasTemplate)) {
3859 if (SFINAETrap *Trap = getSFINAEContext();
3860 TemplateDeductionInfo *DeductionInfo =
3861 Trap ? Trap->getDeductionInfo() : nullptr) {
3862 if (DeductionInfo->hasSFINAEDiagnostic() &&
3863 DeductionInfo->peekSFINAEDiagnostic().second.getDiagID() ==
3864 diag::err_typename_nested_not_found_enable_if &&
3865 TemplateArgs[0].getArgument().getKind() ==
3866 TemplateArgument::Expression) {
3867 Expr *FailedCond;
3868 std::string FailedDescription;
3869 std::tie(args&: FailedCond, args&: FailedDescription) =
3870 findFailedBooleanCondition(Cond: TemplateArgs[0].getSourceExpression());
3871
3872 // Remove the old SFINAE diagnostic.
3873 PartialDiagnosticAt OldDiag =
3874 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3875 DeductionInfo->takeSFINAEDiagnostic(PD&: OldDiag);
3876
3877 // Add a new SFINAE diagnostic specifying which condition
3878 // failed.
3879 DeductionInfo->addSFINAEDiagnostic(
3880 Loc: OldDiag.first,
3881 PD: PDiag(DiagID: diag::err_typename_nested_not_found_requirement)
3882 << FailedDescription << FailedCond->getSourceRange());
3883 }
3884 }
3885 }
3886
3887 return QualType();
3888 }
3889 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Val: Template)) {
3890 CanonType = checkBuiltinTemplateIdType(
3891 SemaRef&: *this, Keyword, BTD, Converted: CTAI.SugaredConverted, TemplateLoc, TemplateArgs);
3892 } else if (Name.isDependent() ||
3893 TemplateSpecializationType::anyDependentTemplateArguments(
3894 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
3895 // This class template specialization is a dependent
3896 // type. Therefore, its canonical type is another class template
3897 // specialization type that contains all of the converted
3898 // arguments in canonical form. This ensures that, e.g., A<T> and
3899 // A<T, T> have identical types when A is declared as:
3900 //
3901 // template<typename T, typename U = T> struct A;
3902 CanonType = Context.getCanonicalTemplateSpecializationType(
3903 Keyword: ElaboratedTypeKeyword::None,
3904 T: Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3905 CanonicalArgs: CTAI.CanonicalConverted);
3906 assert(CanonType->isCanonicalUnqualified());
3907
3908 // This might work out to be a current instantiation, in which
3909 // case the canonical type needs to be the InjectedClassNameType.
3910 //
3911 // TODO: in theory this could be a simple hashtable lookup; most
3912 // changes to CurContext don't change the set of current
3913 // instantiations.
3914 if (isa<ClassTemplateDecl>(Val: Template)) {
3915 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3916 // If we get out to a namespace, we're done.
3917 if (Ctx->isFileContext()) break;
3918
3919 // If this isn't a record, keep looking.
3920 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Ctx);
3921 if (!Record) continue;
3922
3923 // Look for one of the two cases with InjectedClassNameTypes
3924 // and check whether it's the same template.
3925 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Record) &&
3926 !Record->getDescribedClassTemplate())
3927 continue;
3928
3929 // Fetch the injected class name type and check whether its
3930 // injected type is equal to the type we just built.
3931 CanQualType ICNT = Context.getCanonicalTagType(TD: Record);
3932 CanQualType Injected =
3933 Record->getCanonicalTemplateSpecializationType(Ctx: Context);
3934
3935 if (CanonType != Injected)
3936 continue;
3937
3938 // If so, the canonical type of this TST is the injected
3939 // class name type of the record we just found.
3940 CanonType = ICNT;
3941 break;
3942 }
3943 }
3944 } else if (ClassTemplateDecl *ClassTemplate =
3945 dyn_cast<ClassTemplateDecl>(Val: Template)) {
3946 // Find the class template specialization declaration that
3947 // corresponds to these arguments.
3948 void *InsertPos = nullptr;
3949 ClassTemplateSpecializationDecl *Decl =
3950 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
3951 if (!Decl) {
3952 // This is the first time we have referenced this class template
3953 // specialization. Create the canonical declaration and add it to
3954 // the set of specializations.
3955 Decl = ClassTemplateSpecializationDecl::Create(
3956 Context, TK: ClassTemplate->getTemplatedDecl()->getTagKind(),
3957 DC: ClassTemplate->getDeclContext(),
3958 StartLoc: ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3959 IdLoc: ClassTemplate->getLocation(), SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted,
3960 StrictPackMatch: CTAI.StrictPackMatch, PrevDecl: nullptr);
3961 ClassTemplate->AddSpecialization(D: Decl, InsertPos);
3962 if (ClassTemplate->isOutOfLine())
3963 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3964 }
3965
3966 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3967 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3968 NonSFINAEContext _(*this);
3969 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3970 if (!Inst.isInvalid()) {
3971 MultiLevelTemplateArgumentList TemplateArgLists(Template,
3972 CTAI.CanonicalConverted,
3973 /*Final=*/false);
3974 InstantiateAttrsForDecl(TemplateArgs: TemplateArgLists,
3975 Pattern: ClassTemplate->getTemplatedDecl(), Inst: Decl);
3976 }
3977 }
3978
3979 // Diagnose uses of this specialization.
3980 (void)DiagnoseUseOfDecl(D: Decl, Locs: TemplateLoc);
3981
3982 CanonType = Context.getCanonicalTagType(TD: Decl);
3983 assert(isa<RecordType>(CanonType) &&
3984 "type of non-dependent specialization is not a RecordType");
3985 } else {
3986 llvm_unreachable("Unhandled template kind");
3987 }
3988
3989 // Build the fully-sugared type for this class template
3990 // specialization, which refers back to the class template
3991 // specialization we created or found.
3992 return Context.getTemplateSpecializationType(
3993 Keyword, T: Name, SpecifiedArgs: TemplateArgs.arguments(), CanonicalArgs: CTAI.CanonicalConverted,
3994 Canon: CanonType);
3995}
3996
3997void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3998 TemplateNameKind &TNK,
3999 SourceLocation NameLoc,
4000 IdentifierInfo *&II) {
4001 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4002
4003 auto *ATN = ParsedName.get().getAsAssumedTemplateName();
4004 assert(ATN && "not an assumed template name");
4005 II = ATN->getDeclName().getAsIdentifierInfo();
4006
4007 if (TemplateName Name =
4008 ::resolveAssumedTemplateNameAsType(S&: *this, Scope: S, ATN, NameLoc);
4009 !Name.isNull()) {
4010 // Resolved to a type template name.
4011 ParsedName = TemplateTy::make(P: Name);
4012 TNK = TNK_Type_template;
4013 }
4014}
4015
4016TypeResult Sema::ActOnTemplateIdType(
4017 Scope *S, ElaboratedTypeKeyword ElaboratedKeyword,
4018 SourceLocation ElaboratedKeywordLoc, CXXScopeSpec &SS,
4019 SourceLocation TemplateKWLoc, TemplateTy TemplateD,
4020 const IdentifierInfo *TemplateII, SourceLocation TemplateIILoc,
4021 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
4022 SourceLocation RAngleLoc, bool IsCtorOrDtorName, bool IsClassName,
4023 ImplicitTypenameContext AllowImplicitTypename) {
4024 if (SS.isInvalid())
4025 return true;
4026
4027 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4028 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4029
4030 // C++ [temp.res]p3:
4031 // A qualified-id that refers to a type and in which the
4032 // nested-name-specifier depends on a template-parameter (14.6.2)
4033 // shall be prefixed by the keyword typename to indicate that the
4034 // qualified-id denotes a type, forming an
4035 // elaborated-type-specifier (7.1.5.3).
4036 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4037 // C++2a relaxes some of those restrictions in [temp.res]p5.
4038 QualType DNT = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
4039 NNS: SS.getScopeRep(), Name: TemplateII);
4040 NestedNameSpecifier NNS(DNT.getTypePtr());
4041 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4042 auto DB = DiagCompat(Loc: SS.getBeginLoc(), CompatDiagId: diag_compat::implicit_typename)
4043 << NNS;
4044 if (!getLangOpts().CPlusPlus20)
4045 DB << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "typename ");
4046 } else
4047 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_typename_missing_template) << NNS;
4048
4049 // FIXME: This is not quite correct recovery as we don't transform SS
4050 // into the corresponding dependent form (and we don't diagnose missing
4051 // 'template' keywords within SS as a result).
4052 return ActOnTypenameType(S: nullptr, TypenameLoc: SourceLocation(), SS, TemplateLoc: TemplateKWLoc,
4053 TemplateName: TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4054 TemplateArgs: TemplateArgsIn, RAngleLoc);
4055 }
4056
4057 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4058 // it's not actually allowed to be used as a type in most cases. Because
4059 // we annotate it before we know whether it's valid, we have to check for
4060 // this case here.
4061 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
4062 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4063 Diag(Loc: TemplateIILoc,
4064 DiagID: TemplateKWLoc.isInvalid()
4065 ? diag::err_out_of_line_qualified_id_type_names_constructor
4066 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4067 << TemplateII << 0 /*injected-class-name used as template name*/
4068 << 1 /*if any keyword was present, it was 'template'*/;
4069 }
4070 }
4071
4072 // Translate the parser's template argument list in our AST format.
4073 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4074 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4075
4076 QualType SpecTy = CheckTemplateIdType(
4077 Keyword: ElaboratedKeyword, Name: TemplateD.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
4078 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
4079 if (SpecTy.isNull())
4080 return true;
4081
4082 // Build type-source information.
4083 TypeLocBuilder TLB;
4084 TLB.push<TemplateSpecializationTypeLoc>(T: SpecTy).set(
4085 ElaboratedKeywordLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
4086 NameLoc: TemplateIILoc, TAL: TemplateArgs);
4087 return CreateParsedType(T: SpecTy, TInfo: TLB.getTypeSourceInfo(Context, T: SpecTy));
4088}
4089
4090TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
4091 TypeSpecifierType TagSpec,
4092 SourceLocation TagLoc,
4093 CXXScopeSpec &SS,
4094 SourceLocation TemplateKWLoc,
4095 TemplateTy TemplateD,
4096 SourceLocation TemplateLoc,
4097 SourceLocation LAngleLoc,
4098 ASTTemplateArgsPtr TemplateArgsIn,
4099 SourceLocation RAngleLoc) {
4100 if (SS.isInvalid())
4101 return TypeResult(true);
4102
4103 // Translate the parser's template argument list in our AST format.
4104 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4105 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4106
4107 // Determine the tag kind
4108 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
4109 ElaboratedTypeKeyword Keyword
4110 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
4111
4112 QualType Result =
4113 CheckTemplateIdType(Keyword, Name: TemplateD.get(), TemplateLoc, TemplateArgs,
4114 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
4115 if (Result.isNull())
4116 return TypeResult(true);
4117
4118 // Check the tag kind
4119 if (const RecordType *RT = Result->getAs<RecordType>()) {
4120 RecordDecl *D = RT->getDecl();
4121
4122 IdentifierInfo *Id = D->getIdentifier();
4123 assert(Id && "templated class must have an identifier");
4124
4125 if (!isAcceptableTagRedeclaration(Previous: D, NewTag: TagKind, isDefinition: TUK == TagUseKind::Definition,
4126 NewTagLoc: TagLoc, Name: Id)) {
4127 Diag(Loc: TagLoc, DiagID: diag::err_use_with_wrong_tag)
4128 << Result
4129 << FixItHint::CreateReplacement(RemoveRange: SourceRange(TagLoc), Code: D->getKindName());
4130 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_use);
4131 }
4132 }
4133
4134 // Provide source-location information for the template specialization.
4135 TypeLocBuilder TLB;
4136 TLB.push<TemplateSpecializationTypeLoc>(T: Result).set(
4137 ElaboratedKeywordLoc: TagLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc, NameLoc: TemplateLoc,
4138 TAL: TemplateArgs);
4139 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
4140}
4141
4142static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4143 NamedDecl *PrevDecl,
4144 SourceLocation Loc,
4145 bool IsPartialSpecialization);
4146
4147static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4148
4149static bool isTemplateArgumentTemplateParameter(const TemplateArgument &Arg,
4150 unsigned Depth,
4151 unsigned Index) {
4152 switch (Arg.getKind()) {
4153 case TemplateArgument::Null:
4154 case TemplateArgument::NullPtr:
4155 case TemplateArgument::Integral:
4156 case TemplateArgument::Declaration:
4157 case TemplateArgument::StructuralValue:
4158 case TemplateArgument::Pack:
4159 case TemplateArgument::TemplateExpansion:
4160 return false;
4161
4162 case TemplateArgument::Type: {
4163 QualType Type = Arg.getAsType();
4164 const TemplateTypeParmType *TPT =
4165 Arg.getAsType()->getAsCanonical<TemplateTypeParmType>();
4166 return TPT && !Type.hasQualifiers() &&
4167 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4168 }
4169
4170 case TemplateArgument::Expression: {
4171 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg.getAsExpr());
4172 if (!DRE || !DRE->getDecl())
4173 return false;
4174 const NonTypeTemplateParmDecl *NTTP =
4175 dyn_cast<NonTypeTemplateParmDecl>(Val: DRE->getDecl());
4176 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4177 }
4178
4179 case TemplateArgument::Template:
4180 const TemplateTemplateParmDecl *TTP =
4181 dyn_cast_or_null<TemplateTemplateParmDecl>(
4182 Val: Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4183 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4184 }
4185 llvm_unreachable("unexpected kind of template argument");
4186}
4187
4188static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4189 TemplateParameterList *SpecParams,
4190 ArrayRef<TemplateArgument> Args) {
4191 if (Params->size() != Args.size() || Params->size() != SpecParams->size())
4192 return false;
4193
4194 unsigned Depth = Params->getDepth();
4195
4196 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4197 TemplateArgument Arg = Args[I];
4198
4199 // If the parameter is a pack expansion, the argument must be a pack
4200 // whose only element is a pack expansion.
4201 if (Params->getParam(Idx: I)->isParameterPack()) {
4202 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4203 !Arg.pack_begin()->isPackExpansion())
4204 return false;
4205 Arg = Arg.pack_begin()->getPackExpansionPattern();
4206 }
4207
4208 if (!isTemplateArgumentTemplateParameter(Arg, Depth, Index: I))
4209 return false;
4210
4211 // For NTTPs further specialization is allowed via deduced types, so
4212 // we need to make sure to only reject here if primary template and
4213 // specialization use the same type for the NTTP.
4214 if (auto *SpecNTTP =
4215 dyn_cast<NonTypeTemplateParmDecl>(Val: SpecParams->getParam(Idx: I))) {
4216 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: I));
4217 if (!NTTP || NTTP->getType().getCanonicalType() !=
4218 SpecNTTP->getType().getCanonicalType())
4219 return false;
4220 }
4221 }
4222
4223 return true;
4224}
4225
4226template<typename PartialSpecDecl>
4227static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4228 if (Partial->getDeclContext()->isDependentContext())
4229 return;
4230
4231 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4232 // for non-substitution-failure issues?
4233 TemplateDeductionInfo Info(Partial->getLocation());
4234 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4235 return;
4236
4237 auto *Template = Partial->getSpecializedTemplate();
4238 S.Diag(Partial->getLocation(),
4239 diag::ext_partial_spec_not_more_specialized_than_primary)
4240 << isa<VarTemplateDecl>(Template);
4241
4242 if (Info.hasSFINAEDiagnostic()) {
4243 PartialDiagnosticAt Diag = {SourceLocation(),
4244 PartialDiagnostic::NullDiagnostic()};
4245 Info.takeSFINAEDiagnostic(PD&: Diag);
4246 SmallString<128> SFINAEArgString;
4247 Diag.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
4248 S.Diag(Loc: Diag.first,
4249 DiagID: diag::note_partial_spec_not_more_specialized_than_primary)
4250 << SFINAEArgString;
4251 }
4252
4253 S.NoteTemplateLocation(Decl: *Template);
4254 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4255 Template->getAssociatedConstraints(TemplateAC);
4256 Partial->getAssociatedConstraints(PartialAC);
4257 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Partial, AC1: PartialAC, D2: Template,
4258 AC2: TemplateAC);
4259}
4260
4261static void
4262noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4263 const llvm::SmallBitVector &DeducibleParams) {
4264 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4265 if (!DeducibleParams[I]) {
4266 NamedDecl *Param = TemplateParams->getParam(Idx: I);
4267 if (Param->getDeclName())
4268 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4269 << Param->getDeclName();
4270 else
4271 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4272 << "(anonymous)";
4273 }
4274 }
4275}
4276
4277
4278template<typename PartialSpecDecl>
4279static void checkTemplatePartialSpecialization(Sema &S,
4280 PartialSpecDecl *Partial) {
4281 // C++1z [temp.class.spec]p8: (DR1495)
4282 // - The specialization shall be more specialized than the primary
4283 // template (14.5.5.2).
4284 checkMoreSpecializedThanPrimary(S, Partial);
4285
4286 // C++ [temp.class.spec]p8: (DR1315)
4287 // - Each template-parameter shall appear at least once in the
4288 // template-id outside a non-deduced context.
4289 // C++1z [temp.class.spec.match]p3 (P0127R2)
4290 // If the template arguments of a partial specialization cannot be
4291 // deduced because of the structure of its template-parameter-list
4292 // and the template-id, the program is ill-formed.
4293 auto *TemplateParams = Partial->getTemplateParameters();
4294 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4295 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4296 TemplateParams->getDepth(), DeducibleParams);
4297
4298 if (!DeducibleParams.all()) {
4299 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4300 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4301 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4302 << (NumNonDeducible > 1)
4303 << SourceRange(Partial->getLocation(),
4304 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4305 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4306 }
4307}
4308
4309void Sema::CheckTemplatePartialSpecialization(
4310 ClassTemplatePartialSpecializationDecl *Partial) {
4311 checkTemplatePartialSpecialization(S&: *this, Partial);
4312}
4313
4314void Sema::CheckTemplatePartialSpecialization(
4315 VarTemplatePartialSpecializationDecl *Partial) {
4316 checkTemplatePartialSpecialization(S&: *this, Partial);
4317}
4318
4319void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4320 // C++1z [temp.param]p11:
4321 // A template parameter of a deduction guide template that does not have a
4322 // default-argument shall be deducible from the parameter-type-list of the
4323 // deduction guide template.
4324 auto *TemplateParams = TD->getTemplateParameters();
4325 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4326 MarkDeducedTemplateParameters(FunctionTemplate: TD, Deduced&: DeducibleParams);
4327 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4328 // A parameter pack is deducible (to an empty pack).
4329 auto *Param = TemplateParams->getParam(Idx: I);
4330 if (Param->isParameterPack() || hasVisibleDefaultArgument(D: Param))
4331 DeducibleParams[I] = true;
4332 }
4333
4334 if (!DeducibleParams.all()) {
4335 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4336 Diag(Loc: TD->getLocation(), DiagID: diag::err_deduction_guide_template_not_deducible)
4337 << (NumNonDeducible > 1);
4338 noteNonDeducibleParameters(S&: *this, TemplateParams, DeducibleParams);
4339 }
4340}
4341
4342DeclResult Sema::ActOnVarTemplateSpecialization(
4343 Scope *S, Declarator &D, TypeSourceInfo *TSI, LookupResult &Previous,
4344 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4345 StorageClass SC, bool IsPartialSpecialization) {
4346 // D must be variable template id.
4347 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4348 "Variable template specialization is declared with a template id.");
4349
4350 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4351 TemplateArgumentListInfo TemplateArgs =
4352 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TemplateId);
4353 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4354 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4355 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4356
4357 TemplateName Name = TemplateId->Template.get();
4358
4359 // The template-id must name a variable template.
4360 VarTemplateDecl *VarTemplate =
4361 dyn_cast_or_null<VarTemplateDecl>(Val: Name.getAsTemplateDecl());
4362 if (!VarTemplate) {
4363 NamedDecl *FnTemplate;
4364 if (auto *OTS = Name.getAsOverloadedTemplate())
4365 FnTemplate = *OTS->begin();
4366 else
4367 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Val: Name.getAsTemplateDecl());
4368 if (FnTemplate)
4369 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template_but_method)
4370 << FnTemplate->getDeclName();
4371 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template)
4372 << IsPartialSpecialization;
4373 }
4374
4375 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4376 auto Message = DSA->getMessage();
4377 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
4378 << VarTemplate << !Message.empty() << Message;
4379 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
4380 }
4381
4382 // Check for unexpanded parameter packs in any of the template arguments.
4383 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4384 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
4385 UPPC: IsPartialSpecialization
4386 ? UPPC_PartialSpecialization
4387 : UPPC_ExplicitSpecialization))
4388 return true;
4389
4390 // Check that the template argument list is well-formed for this
4391 // template.
4392 CheckTemplateArgumentInfo CTAI;
4393 if (CheckTemplateArgumentList(Template: VarTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
4394 /*DefaultArgs=*/{},
4395 /*PartialTemplateArgs=*/false, CTAI,
4396 /*UpdateArgsWithConversions=*/true))
4397 return true;
4398
4399 // Find the variable template (partial) specialization declaration that
4400 // corresponds to these arguments.
4401 if (IsPartialSpecialization) {
4402 if (CheckTemplatePartialSpecializationArgs(Loc: TemplateNameLoc, PrimaryTemplate: VarTemplate,
4403 NumExplicitArgs: TemplateArgs.size(),
4404 Args: CTAI.CanonicalConverted))
4405 return true;
4406
4407 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4408 // we also do them during instantiation.
4409 if (!Name.isDependent() &&
4410 !TemplateSpecializationType::anyDependentTemplateArguments(
4411 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4412 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
4413 << VarTemplate->getDeclName();
4414 IsPartialSpecialization = false;
4415 }
4416
4417 if (isSameAsPrimaryTemplate(Params: VarTemplate->getTemplateParameters(),
4418 SpecParams: TemplateParams, Args: CTAI.CanonicalConverted) &&
4419 (!Context.getLangOpts().CPlusPlus20 ||
4420 !TemplateParams->hasAssociatedConstraints())) {
4421 // C++ [temp.class.spec]p9b3:
4422 //
4423 // -- The argument list of the specialization shall not be identical
4424 // to the implicit argument list of the primary template.
4425 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
4426 << /*variable template*/ 1
4427 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4428 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
4429 // FIXME: Recover from this by treating the declaration as a
4430 // redeclaration of the primary template.
4431 return true;
4432 }
4433 }
4434
4435 void *InsertPos = nullptr;
4436 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4437
4438 if (IsPartialSpecialization)
4439 PrevDecl = VarTemplate->findPartialSpecialization(
4440 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertPos);
4441 else
4442 PrevDecl =
4443 VarTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
4444
4445 VarTemplateSpecializationDecl *Specialization = nullptr;
4446
4447 // Check whether we can declare a variable template specialization in
4448 // the current scope.
4449 if (CheckTemplateSpecializationScope(S&: *this, Specialized: VarTemplate, PrevDecl,
4450 Loc: TemplateNameLoc,
4451 IsPartialSpecialization))
4452 return true;
4453
4454 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4455 // Since the only prior variable template specialization with these
4456 // arguments was referenced but not declared, reuse that
4457 // declaration node as our own, updating its source location and
4458 // the list of outer template parameters to reflect our new declaration.
4459 Specialization = PrevDecl;
4460 Specialization->setLocation(TemplateNameLoc);
4461 PrevDecl = nullptr;
4462 } else if (IsPartialSpecialization) {
4463 // Create a new class template partial specialization declaration node.
4464 VarTemplatePartialSpecializationDecl *PrevPartial =
4465 cast_or_null<VarTemplatePartialSpecializationDecl>(Val: PrevDecl);
4466 VarTemplatePartialSpecializationDecl *Partial =
4467 VarTemplatePartialSpecializationDecl::Create(
4468 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc,
4469 IdLoc: TemplateNameLoc, Params: TemplateParams, SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI,
4470 S: SC, Args: CTAI.CanonicalConverted);
4471 Partial->setTemplateArgsAsWritten(TemplateArgs);
4472
4473 if (!PrevPartial)
4474 VarTemplate->AddPartialSpecialization(D: Partial, InsertPos);
4475 Specialization = Partial;
4476
4477 // If we are providing an explicit specialization of a member variable
4478 // template specialization, make a note of that.
4479 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4480 PrevPartial->setMemberSpecialization();
4481
4482 CheckTemplatePartialSpecialization(Partial);
4483 } else {
4484 // Create a new class template specialization declaration node for
4485 // this explicit specialization or friend declaration.
4486 Specialization = VarTemplateSpecializationDecl::Create(
4487 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc, IdLoc: TemplateNameLoc,
4488 SpecializedTemplate: VarTemplate, T: TSI->getType(), TInfo: TSI, S: SC, Args: CTAI.CanonicalConverted);
4489 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4490
4491 if (!PrevDecl)
4492 VarTemplate->AddSpecialization(D: Specialization, InsertPos);
4493 }
4494
4495 // C++ [temp.expl.spec]p6:
4496 // If a template, a member template or the member of a class template is
4497 // explicitly specialized then that specialization shall be declared
4498 // before the first use of that specialization that would cause an implicit
4499 // instantiation to take place, in every translation unit in which such a
4500 // use occurs; no diagnostic is required.
4501 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4502 bool Okay = false;
4503 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4504 // Is there any previous explicit specialization declaration?
4505 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
4506 Okay = true;
4507 break;
4508 }
4509 }
4510
4511 if (!Okay) {
4512 SourceRange Range(TemplateNameLoc, RAngleLoc);
4513 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
4514 << Name << Range;
4515
4516 Diag(Loc: PrevDecl->getPointOfInstantiation(),
4517 DiagID: diag::note_instantiation_required_here)
4518 << (PrevDecl->getTemplateSpecializationKind() !=
4519 TSK_ImplicitInstantiation);
4520 return true;
4521 }
4522 }
4523
4524 Specialization->setLexicalDeclContext(CurContext);
4525
4526 // Add the specialization into its lexical context, so that it can
4527 // be seen when iterating through the list of declarations in that
4528 // context. However, specializations are not found by name lookup.
4529 CurContext->addDecl(D: Specialization);
4530
4531 // Note that this is an explicit specialization.
4532 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4533
4534 Previous.clear();
4535 if (PrevDecl)
4536 Previous.addDecl(D: PrevDecl);
4537 else if (Specialization->isStaticDataMember() &&
4538 Specialization->isOutOfLine())
4539 Specialization->setAccess(VarTemplate->getAccess());
4540
4541 return Specialization;
4542}
4543
4544namespace {
4545/// A partial specialization whose template arguments have matched
4546/// a given template-id.
4547struct PartialSpecMatchResult {
4548 VarTemplatePartialSpecializationDecl *Partial;
4549 TemplateArgumentList *Args;
4550};
4551
4552// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4553// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4554static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4555 if (Var->getName() != "format_kind" ||
4556 !Var->getDeclContext()->isStdNamespace())
4557 return false;
4558
4559 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4560 // release in which users can access std::format_kind.
4561 // We can use 20250520 as the final date, see the following commits.
4562 // GCC releases/gcc-15 branch:
4563 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4564 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4565 // GCC master branch:
4566 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4567 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4568 return PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2025'05'20);
4569}
4570} // end anonymous namespace
4571
4572DeclResult
4573Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4574 SourceLocation TemplateNameLoc,
4575 const TemplateArgumentListInfo &TemplateArgs,
4576 bool SetWrittenArgs) {
4577 assert(Template && "A variable template id without template?");
4578
4579 // Check that the template argument list is well-formed for this template.
4580 CheckTemplateArgumentInfo CTAI;
4581 if (CheckTemplateArgumentList(
4582 Template, TemplateLoc: TemplateNameLoc,
4583 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4584 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4585 /*UpdateArgsWithConversions=*/true))
4586 return true;
4587
4588 // Produce a placeholder value if the specialization is dependent.
4589 if (Template->getDeclContext()->isDependentContext() ||
4590 TemplateSpecializationType::anyDependentTemplateArguments(
4591 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4592 if (ParsingInitForAutoVars.empty())
4593 return DeclResult();
4594
4595 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4596 const TemplateArgument &Arg2) {
4597 return Context.isSameTemplateArgument(Arg1, Arg2);
4598 };
4599
4600 if (VarDecl *Var = Template->getTemplatedDecl();
4601 ParsingInitForAutoVars.count(Ptr: Var) &&
4602 // See comments on this function definition
4603 !IsLibstdcxxStdFormatKind(PP, Var) &&
4604 llvm::equal(
4605 LRange&: CTAI.CanonicalConverted,
4606 RRange: Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4607 P: IsSameTemplateArg)) {
4608 Diag(Loc: TemplateNameLoc,
4609 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4610 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4611 return true;
4612 }
4613
4614 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4615 Template->getPartialSpecializations(PS&: PartialSpecs);
4616 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4617 if (ParsingInitForAutoVars.count(Ptr: Partial) &&
4618 llvm::equal(LRange&: CTAI.CanonicalConverted,
4619 RRange: Partial->getTemplateArgs().asArray(),
4620 P: IsSameTemplateArg)) {
4621 Diag(Loc: TemplateNameLoc,
4622 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4623 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4624 << Partial->getType();
4625 return true;
4626 }
4627
4628 return DeclResult();
4629 }
4630
4631 // Find the variable template specialization declaration that
4632 // corresponds to these arguments.
4633 void *InsertPos = nullptr;
4634 if (VarTemplateSpecializationDecl *Spec =
4635 Template->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos)) {
4636 checkSpecializationReachability(Loc: TemplateNameLoc, Spec);
4637 if (Spec->getType()->isUndeducedType()) {
4638 if (ParsingInitForAutoVars.count(Ptr: Spec))
4639 Diag(Loc: TemplateNameLoc,
4640 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4641 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4642 << Spec->getType();
4643 else
4644 // We are substituting the initializer of this variable template
4645 // specialization.
4646 Diag(Loc: TemplateNameLoc, DiagID: diag::err_var_template_spec_type_depends_on_self)
4647 << Spec << Spec->getType();
4648
4649 return true;
4650 }
4651 // If we already have a variable template specialization, return it.
4652 return Spec;
4653 }
4654
4655 // This is the first time we have referenced this variable template
4656 // specialization. Create the canonical declaration and add it to
4657 // the set of specializations, based on the closest partial specialization
4658 // that it represents. That is,
4659 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4660 const TemplateArgumentList *PartialSpecArgs = nullptr;
4661 bool AmbiguousPartialSpec = false;
4662 typedef PartialSpecMatchResult MatchResult;
4663 SmallVector<MatchResult, 4> Matched;
4664 SourceLocation PointOfInstantiation = TemplateNameLoc;
4665 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4666 /*ForTakingAddress=*/false);
4667
4668 // 1. Attempt to find the closest partial specialization that this
4669 // specializes, if any.
4670 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4671 // Perhaps better after unification of DeduceTemplateArguments() and
4672 // getMoreSpecializedPartialSpecialization().
4673 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4674 Template->getPartialSpecializations(PS&: PartialSpecs);
4675
4676 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4677 // C++ [temp.spec.partial.member]p2:
4678 // If the primary member template is explicitly specialized for a given
4679 // (implicit) specialization of the enclosing class template, the partial
4680 // specializations of the member template are ignored for this
4681 // specialization of the enclosing class template. If a partial
4682 // specialization of the member template is explicitly specialized for a
4683 // given (implicit) specialization of the enclosing class template, the
4684 // primary member template and its other partial specializations are still
4685 // considered for this specialization of the enclosing class template.
4686 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4687 !Partial->getMostRecentDecl()->isMemberSpecialization())
4688 continue;
4689
4690 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4691
4692 if (TemplateDeductionResult Result =
4693 DeduceTemplateArguments(Partial, TemplateArgs: CTAI.SugaredConverted, Info);
4694 Result != TemplateDeductionResult::Success) {
4695 // Store the failed-deduction information for use in diagnostics, later.
4696 // TODO: Actually use the failed-deduction info?
4697 FailedCandidates.addCandidate().set(
4698 Found: DeclAccessPair::make(D: Template, AS: AS_public), Spec: Partial,
4699 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
4700 (void)Result;
4701 } else {
4702 Matched.push_back(Elt: PartialSpecMatchResult());
4703 Matched.back().Partial = Partial;
4704 Matched.back().Args = Info.takeSugared();
4705 }
4706 }
4707
4708 if (Matched.size() >= 1) {
4709 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4710 if (Matched.size() == 1) {
4711 // -- If exactly one matching specialization is found, the
4712 // instantiation is generated from that specialization.
4713 // We don't need to do anything for this.
4714 } else {
4715 // -- If more than one matching specialization is found, the
4716 // partial order rules (14.5.4.2) are used to determine
4717 // whether one of the specializations is more specialized
4718 // than the others. If none of the specializations is more
4719 // specialized than all of the other matching
4720 // specializations, then the use of the variable template is
4721 // ambiguous and the program is ill-formed.
4722 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4723 PEnd = Matched.end();
4724 P != PEnd; ++P) {
4725 if (getMoreSpecializedPartialSpecialization(PS1: P->Partial, PS2: Best->Partial,
4726 Loc: PointOfInstantiation) ==
4727 P->Partial)
4728 Best = P;
4729 }
4730
4731 // Determine if the best partial specialization is more specialized than
4732 // the others.
4733 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4734 PEnd = Matched.end();
4735 P != PEnd; ++P) {
4736 if (P != Best && getMoreSpecializedPartialSpecialization(
4737 PS1: P->Partial, PS2: Best->Partial,
4738 Loc: PointOfInstantiation) != Best->Partial) {
4739 AmbiguousPartialSpec = true;
4740 break;
4741 }
4742 }
4743 }
4744
4745 // Instantiate using the best variable template partial specialization.
4746 InstantiationPattern = Best->Partial;
4747 PartialSpecArgs = Best->Args;
4748 } else {
4749 // -- If no match is found, the instantiation is generated
4750 // from the primary template.
4751 // InstantiationPattern = Template->getTemplatedDecl();
4752 }
4753
4754 // 2. Create the canonical declaration.
4755 // Note that we do not instantiate a definition until we see an odr-use
4756 // in DoMarkVarDeclReferenced().
4757 // FIXME: LateAttrs et al.?
4758 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4759 VarTemplate: Template, FromVar: InstantiationPattern, PartialSpecArgs, Converted&: CTAI.CanonicalConverted,
4760 PointOfInstantiation: TemplateNameLoc /*, LateAttrs, StartingScope*/);
4761 if (!Decl)
4762 return true;
4763 if (SetWrittenArgs)
4764 Decl->setTemplateArgsAsWritten(TemplateArgs);
4765
4766 if (AmbiguousPartialSpec) {
4767 // Partial ordering did not produce a clear winner. Complain.
4768 Decl->setInvalidDecl();
4769 Diag(Loc: PointOfInstantiation, DiagID: diag::err_partial_spec_ordering_ambiguous)
4770 << Decl;
4771
4772 // Print the matching partial specializations.
4773 for (MatchResult P : Matched)
4774 Diag(Loc: P.Partial->getLocation(), DiagID: diag::note_partial_spec_match)
4775 << getTemplateArgumentBindingsText(Params: P.Partial->getTemplateParameters(),
4776 Args: *P.Args);
4777 return true;
4778 }
4779
4780 if (VarTemplatePartialSpecializationDecl *D =
4781 dyn_cast<VarTemplatePartialSpecializationDecl>(Val: InstantiationPattern))
4782 Decl->setInstantiationOf(PartialSpec: D, TemplateArgs: PartialSpecArgs);
4783
4784 checkSpecializationReachability(Loc: TemplateNameLoc, Spec: Decl);
4785
4786 assert(Decl && "No variable template specialization?");
4787 return Decl;
4788}
4789
4790ExprResult Sema::CheckVarTemplateId(
4791 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4792 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4793 const TemplateArgumentListInfo *TemplateArgs) {
4794
4795 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, TemplateNameLoc: NameInfo.getLoc(),
4796 TemplateArgs: *TemplateArgs, /*SetWrittenArgs=*/false);
4797 if (Decl.isInvalid())
4798 return ExprError();
4799
4800 if (!Decl.get())
4801 return ExprResult();
4802
4803 VarDecl *Var = cast<VarDecl>(Val: Decl.get());
4804 if (!Var->getTemplateSpecializationKind())
4805 Var->setTemplateSpecializationKind(TSK: TSK_ImplicitInstantiation,
4806 PointOfInstantiation: NameInfo.getLoc());
4807
4808 // Build an ordinary singleton decl ref.
4809 return BuildDeclarationNameExpr(SS, NameInfo, D: Var, FoundD, TemplateArgs);
4810}
4811
4812ExprResult Sema::CheckVarOrConceptTemplateTemplateId(
4813 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4814 TemplateTemplateParmDecl *Template, SourceLocation TemplateLoc,
4815 const TemplateArgumentListInfo *TemplateArgs) {
4816 assert(Template && "A variable template id without template?");
4817
4818 if (Template->templateParameterKind() != TemplateNameKind::TNK_Var_template &&
4819 Template->templateParameterKind() !=
4820 TemplateNameKind::TNK_Concept_template)
4821 return ExprResult();
4822
4823 // Check that the template argument list is well-formed for this template.
4824 CheckTemplateArgumentInfo CTAI;
4825 if (CheckTemplateArgumentList(
4826 Template, TemplateLoc,
4827 // FIXME: TemplateArgs will not be modified because
4828 // UpdateArgsWithConversions is false, however, we should
4829 // CheckTemplateArgumentList to be const-correct.
4830 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4831 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4832 /*UpdateArgsWithConversions=*/false))
4833 return true;
4834
4835 UnresolvedSet<1> R;
4836 R.addDecl(D: Template);
4837
4838 // FIXME: We model references to variable template and concept parameters
4839 // as an UnresolvedLookupExpr. This is because they encapsulate the same
4840 // data, can generally be used in the same places and work the same way.
4841 // However, it might be cleaner to use a dedicated AST node in the long run.
4842 return UnresolvedLookupExpr::Create(
4843 Context: getASTContext(), NamingClass: nullptr, QualifierLoc: SS.getWithLocInContext(Context&: getASTContext()),
4844 TemplateKWLoc: SourceLocation(), NameInfo, RequiresADL: false, Args: TemplateArgs, Begin: R.begin(), End: R.end(),
4845 /*KnownDependent=*/false,
4846 /*KnownInstantiationDependent=*/false);
4847}
4848
4849void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4850 SourceLocation Loc) {
4851 Diag(Loc, DiagID: diag::err_template_missing_args)
4852 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4853 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4854 NoteTemplateLocation(Decl: *TD, ParamRange: TD->getTemplateParameters()->getSourceRange());
4855 }
4856}
4857
4858void Sema::diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
4859 bool TemplateKeyword,
4860 TemplateDecl *TD,
4861 SourceLocation Loc) {
4862 TemplateName Name = Context.getQualifiedTemplateName(
4863 Qualifier: SS.getScopeRep(), TemplateKeyword, Template: TemplateName(TD));
4864 diagnoseMissingTemplateArguments(Name, Loc);
4865}
4866
4867ExprResult Sema::CheckConceptTemplateId(
4868 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4869 const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl,
4870 TemplateDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs,
4871 bool DoCheckConstraintSatisfaction) {
4872 assert(NamedConcept && "A concept template id without a template?");
4873
4874 if (NamedConcept->isInvalidDecl())
4875 return ExprError();
4876
4877 CheckTemplateArgumentInfo CTAI;
4878 if (CheckTemplateArgumentList(
4879 Template: NamedConcept, TemplateLoc: ConceptNameInfo.getLoc(),
4880 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4881 /*DefaultArgs=*/{},
4882 /*PartialTemplateArgs=*/false, CTAI,
4883 /*UpdateArgsWithConversions=*/false))
4884 return ExprError();
4885
4886 DiagnoseUseOfDecl(D: NamedConcept, Locs: ConceptNameInfo.getLoc());
4887
4888 // There's a bug with CTAI.CanonicalConverted.
4889 // If the template argument contains a DependentDecltypeType that includes a
4890 // TypeAliasType, and the same written type had occurred previously in the
4891 // source, then the DependentDecltypeType would be canonicalized to that
4892 // previous type which would mess up the substitution.
4893 // FIXME: Reland https://github.com/llvm/llvm-project/pull/101782 properly!
4894 auto *CSD = ImplicitConceptSpecializationDecl::Create(
4895 C: Context, DC: NamedConcept->getDeclContext(), SL: NamedConcept->getLocation(),
4896 ConvertedArgs: CTAI.SugaredConverted);
4897 ConstraintSatisfaction Satisfaction;
4898 bool AreArgsDependent =
4899 TemplateSpecializationType::anyDependentTemplateArguments(
4900 *TemplateArgs, Converted: CTAI.SugaredConverted);
4901 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.SugaredConverted,
4902 /*Final=*/false);
4903 auto *CL = ConceptReference::Create(
4904 C: Context,
4905 NNS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4906 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4907 ArgsAsWritten: ASTTemplateArgumentListInfo::Create(C: Context, List: *TemplateArgs));
4908
4909 bool Error = false;
4910 if (const auto *Concept = dyn_cast<ConceptDecl>(Val: NamedConcept);
4911 Concept && Concept->getConstraintExpr() && !AreArgsDependent &&
4912 DoCheckConstraintSatisfaction) {
4913
4914 LocalInstantiationScope Scope(*this);
4915
4916 EnterExpressionEvaluationContext EECtx{
4917 *this, ExpressionEvaluationContext::Unevaluated, CSD};
4918
4919 Error = CheckConstraintSatisfaction(
4920 Entity: NamedConcept, AssociatedConstraints: AssociatedConstraint(Concept->getConstraintExpr()), TemplateArgLists: MLTAL,
4921 TemplateIDRange: SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4922 TemplateArgs->getRAngleLoc()),
4923 Satisfaction, TopLevelConceptId: CL);
4924 Satisfaction.ContainsErrors = Error;
4925 }
4926
4927 if (Error)
4928 return ExprError();
4929
4930 return ConceptSpecializationExpr::Create(
4931 C: Context, ConceptRef: CL, SpecDecl: CSD, Satisfaction: AreArgsDependent ? nullptr : &Satisfaction);
4932}
4933
4934ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4935 SourceLocation TemplateKWLoc,
4936 LookupResult &R,
4937 bool RequiresADL,
4938 const TemplateArgumentListInfo *TemplateArgs) {
4939 // FIXME: Can we do any checking at this point? I guess we could check the
4940 // template arguments that we have against the template name, if the template
4941 // name refers to a single template. That's not a terribly common case,
4942 // though.
4943 // foo<int> could identify a single function unambiguously
4944 // This approach does NOT work, since f<int>(1);
4945 // gets resolved prior to resorting to overload resolution
4946 // i.e., template<class T> void f(double);
4947 // vs template<class T, class U> void f(U);
4948
4949 // These should be filtered out by our callers.
4950 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4951
4952 // Non-function templates require a template argument list.
4953 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4954 if (!TemplateArgs && !isa<FunctionTemplateDecl>(Val: TD)) {
4955 diagnoseMissingTemplateArguments(
4956 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, Loc: R.getNameLoc());
4957 return ExprError();
4958 }
4959 }
4960 bool KnownDependent = false;
4961 // In C++1y, check variable template ids.
4962 if (R.getAsSingle<VarTemplateDecl>()) {
4963 ExprResult Res = CheckVarTemplateId(
4964 SS, NameInfo: R.getLookupNameInfo(), Template: R.getAsSingle<VarTemplateDecl>(),
4965 FoundD: R.getRepresentativeDecl(), TemplateLoc: TemplateKWLoc, TemplateArgs);
4966 if (Res.isInvalid() || Res.isUsable())
4967 return Res;
4968 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4969 KnownDependent = true;
4970 }
4971
4972 // We don't want lookup warnings at this point.
4973 R.suppressDiagnostics();
4974
4975 if (R.getAsSingle<ConceptDecl>()) {
4976 return CheckConceptTemplateId(SS, TemplateKWLoc, ConceptNameInfo: R.getLookupNameInfo(),
4977 FoundDecl: R.getRepresentativeDecl(),
4978 NamedConcept: R.getAsSingle<ConceptDecl>(), TemplateArgs);
4979 }
4980
4981 // Check variable template ids (C++17) and concept template parameters
4982 // (C++26).
4983 UnresolvedLookupExpr *ULE;
4984 if (R.getAsSingle<TemplateTemplateParmDecl>())
4985 return CheckVarOrConceptTemplateTemplateId(
4986 SS, NameInfo: R.getLookupNameInfo(), Template: R.getAsSingle<TemplateTemplateParmDecl>(),
4987 TemplateLoc: TemplateKWLoc, TemplateArgs);
4988
4989 // Function templates
4990 ULE = UnresolvedLookupExpr::Create(
4991 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
4992 TemplateKWLoc, NameInfo: R.getLookupNameInfo(), RequiresADL, Args: TemplateArgs,
4993 Begin: R.begin(), End: R.end(), KnownDependent,
4994 /*KnownInstantiationDependent=*/false);
4995 // Model the templates with UnresolvedTemplateTy. The expression should then
4996 // either be transformed in an instantiation or be diagnosed in
4997 // CheckPlaceholderExpr.
4998 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4999 !R.getFoundDecl()->getAsFunction())
5000 ULE->setType(Context.UnresolvedTemplateTy);
5001
5002 return ULE;
5003}
5004
5005ExprResult Sema::BuildQualifiedTemplateIdExpr(
5006 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5007 const DeclarationNameInfo &NameInfo,
5008 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
5009 assert(TemplateArgs || TemplateKWLoc.isValid());
5010
5011 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5012 if (LookupTemplateName(Found&: R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
5013 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc))
5014 return ExprError();
5015
5016 if (R.isAmbiguous())
5017 return ExprError();
5018
5019 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
5020 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5021
5022 if (R.empty()) {
5023 DeclContext *DC = computeDeclContext(SS);
5024 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
5025 << NameInfo.getName() << DC << SS.getRange();
5026 return ExprError();
5027 }
5028
5029 // If necessary, build an implicit class member access.
5030 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
5031 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
5032 /*S=*/nullptr);
5033
5034 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/RequiresADL: false, TemplateArgs);
5035}
5036
5037TemplateNameKind Sema::ActOnTemplateName(Scope *S,
5038 CXXScopeSpec &SS,
5039 SourceLocation TemplateKWLoc,
5040 const UnqualifiedId &Name,
5041 ParsedType ObjectType,
5042 bool EnteringContext,
5043 TemplateTy &Result,
5044 bool AllowInjectedClassName) {
5045 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5046 Diag(Loc: TemplateKWLoc,
5047 DiagID: getLangOpts().CPlusPlus11 ?
5048 diag::warn_cxx98_compat_template_outside_of_template :
5049 diag::ext_template_outside_of_template)
5050 << FixItHint::CreateRemoval(RemoveRange: TemplateKWLoc);
5051
5052 if (SS.isInvalid())
5053 return TNK_Non_template;
5054
5055 // Figure out where isTemplateName is going to look.
5056 DeclContext *LookupCtx = nullptr;
5057 if (SS.isNotEmpty())
5058 LookupCtx = computeDeclContext(SS, EnteringContext);
5059 else if (ObjectType)
5060 LookupCtx = computeDeclContext(T: GetTypeFromParser(Ty: ObjectType));
5061
5062 // C++0x [temp.names]p5:
5063 // If a name prefixed by the keyword template is not the name of
5064 // a template, the program is ill-formed. [Note: the keyword
5065 // template may not be applied to non-template members of class
5066 // templates. -end note ] [ Note: as is the case with the
5067 // typename prefix, the template prefix is allowed in cases
5068 // where it is not strictly necessary; i.e., when the
5069 // nested-name-specifier or the expression on the left of the ->
5070 // or . is not dependent on a template-parameter, or the use
5071 // does not appear in the scope of a template. -end note]
5072 //
5073 // Note: C++03 was more strict here, because it banned the use of
5074 // the "template" keyword prior to a template-name that was not a
5075 // dependent name. C++ DR468 relaxed this requirement (the
5076 // "template" keyword is now permitted). We follow the C++0x
5077 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5078 bool MemberOfUnknownSpecialization;
5079 TemplateNameKind TNK = isTemplateName(S, SS, hasTemplateKeyword: TemplateKWLoc.isValid(), Name,
5080 ObjectTypePtr: ObjectType, EnteringContext, TemplateResult&: Result,
5081 MemberOfUnknownSpecialization);
5082 if (TNK != TNK_Non_template) {
5083 // We resolved this to a (non-dependent) template name. Return it.
5084 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
5085 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5086 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5087 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5088 // C++14 [class.qual]p2:
5089 // In a lookup in which function names are not ignored and the
5090 // nested-name-specifier nominates a class C, if the name specified
5091 // [...] is the injected-class-name of C, [...] the name is instead
5092 // considered to name the constructor
5093 //
5094 // We don't get here if naming the constructor would be valid, so we
5095 // just reject immediately and recover by treating the
5096 // injected-class-name as naming the template.
5097 Diag(Loc: Name.getBeginLoc(),
5098 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
5099 << Name.Identifier
5100 << 0 /*injected-class-name used as template name*/
5101 << TemplateKWLoc.isValid();
5102 }
5103 return TNK;
5104 }
5105
5106 if (!MemberOfUnknownSpecialization) {
5107 // Didn't find a template name, and the lookup wasn't dependent.
5108 // Do the lookup again to determine if this is a "nothing found" case or
5109 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5110 // need to do this.
5111 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
5112 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5113 LookupOrdinaryName);
5114 // Tell LookupTemplateName that we require a template so that it diagnoses
5115 // cases where it finds a non-template.
5116 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5117 ? RequiredTemplateKind(TemplateKWLoc)
5118 : TemplateNameIsRequired;
5119 if (!LookupTemplateName(Found&: R, S, SS, ObjectType: ObjectType.get(), EnteringContext, RequiredTemplate: RTK,
5120 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
5121 !R.isAmbiguous()) {
5122 if (LookupCtx)
5123 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_no_member)
5124 << DNI.getName() << LookupCtx << SS.getRange();
5125 else
5126 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_undeclared_use)
5127 << DNI.getName() << SS.getRange();
5128 }
5129 return TNK_Non_template;
5130 }
5131
5132 NestedNameSpecifier Qualifier = SS.getScopeRep();
5133
5134 switch (Name.getKind()) {
5135 case UnqualifiedIdKind::IK_Identifier:
5136 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5137 Name: {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
5138 return TNK_Dependent_template_name;
5139
5140 case UnqualifiedIdKind::IK_OperatorFunctionId:
5141 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5142 Name: {Qualifier, Name.OperatorFunctionId.Operator,
5143 TemplateKWLoc.isValid()}));
5144 return TNK_Function_template;
5145
5146 case UnqualifiedIdKind::IK_LiteralOperatorId:
5147 // This is a kind of template name, but can never occur in a dependent
5148 // scope (literal operators can only be declared at namespace scope).
5149 break;
5150
5151 default:
5152 break;
5153 }
5154
5155 // This name cannot possibly name a dependent template. Diagnose this now
5156 // rather than building a dependent template name that can never be valid.
5157 Diag(Loc: Name.getBeginLoc(),
5158 DiagID: diag::err_template_kw_refers_to_dependent_non_template)
5159 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5160 << TemplateKWLoc.isValid() << TemplateKWLoc;
5161 return TNK_Non_template;
5162}
5163
5164bool Sema::CheckTemplateTypeArgument(
5165 TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
5166 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5167 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5168 const TemplateArgument &Arg = AL.getArgument();
5169 QualType ArgType;
5170 TypeSourceInfo *TSI = nullptr;
5171
5172 // Check template type parameter.
5173 switch(Arg.getKind()) {
5174 case TemplateArgument::Type:
5175 // C++ [temp.arg.type]p1:
5176 // A template-argument for a template-parameter which is a
5177 // type shall be a type-id.
5178 ArgType = Arg.getAsType();
5179 TSI = AL.getTypeSourceInfo();
5180 break;
5181 case TemplateArgument::Template:
5182 case TemplateArgument::TemplateExpansion: {
5183 // We have a template type parameter but the template argument
5184 // is a template without any arguments.
5185 SourceRange SR = AL.getSourceRange();
5186 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
5187 diagnoseMissingTemplateArguments(Name, Loc: SR.getEnd());
5188 return true;
5189 }
5190 case TemplateArgument::Expression: {
5191 // We have a template type parameter but the template argument is an
5192 // expression; see if maybe it is missing the "typename" keyword.
5193 CXXScopeSpec SS;
5194 DeclarationNameInfo NameInfo;
5195
5196 if (DependentScopeDeclRefExpr *ArgExpr =
5197 dyn_cast<DependentScopeDeclRefExpr>(Val: Arg.getAsExpr())) {
5198 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5199 NameInfo = ArgExpr->getNameInfo();
5200 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5201 dyn_cast<CXXDependentScopeMemberExpr>(Val: Arg.getAsExpr())) {
5202 if (ArgExpr->isImplicitAccess()) {
5203 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5204 NameInfo = ArgExpr->getMemberNameInfo();
5205 }
5206 }
5207
5208 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5209 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5210 LookupParsedName(R&: Result, S: CurScope, SS: &SS, /*ObjectType=*/QualType());
5211
5212 if (Result.getAsSingle<TypeDecl>() ||
5213 Result.wasNotFoundInCurrentInstantiation()) {
5214 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5215 // Suggest that the user add 'typename' before the NNS.
5216 SourceLocation Loc = AL.getSourceRange().getBegin();
5217 Diag(Loc, DiagID: getLangOpts().MSVCCompat
5218 ? diag::ext_ms_template_type_arg_missing_typename
5219 : diag::err_template_arg_must_be_type_suggest)
5220 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
5221 NoteTemplateParameterLocation(Decl: *Param);
5222
5223 // Recover by synthesizing a type using the location information that we
5224 // already have.
5225 ArgType = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
5226 NNS: SS.getScopeRep(), Name: II);
5227 TypeLocBuilder TLB;
5228 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: ArgType);
5229 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5230 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5231 TL.setNameLoc(NameInfo.getLoc());
5232 TSI = TLB.getTypeSourceInfo(Context, T: ArgType);
5233
5234 // Overwrite our input TemplateArgumentLoc so that we can recover
5235 // properly.
5236 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5237 TemplateArgumentLocInfo(TSI));
5238
5239 break;
5240 }
5241 }
5242 // fallthrough
5243 [[fallthrough]];
5244 }
5245 default: {
5246 // We allow instantiating a template with template argument packs when
5247 // building deduction guides or mapping constraint template parameters.
5248 if (Arg.getKind() == TemplateArgument::Pack &&
5249 (CodeSynthesisContexts.back().Kind ==
5250 Sema::CodeSynthesisContext::BuildingDeductionGuides ||
5251 inParameterMappingSubstitution())) {
5252 SugaredConverted.push_back(Elt: Arg);
5253 CanonicalConverted.push_back(Elt: Arg);
5254 return false;
5255 }
5256 // We have a template type parameter but the template argument
5257 // is not a type.
5258 SourceRange SR = AL.getSourceRange();
5259 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_type) << SR;
5260 NoteTemplateParameterLocation(Decl: *Param);
5261
5262 return true;
5263 }
5264 }
5265
5266 if (CheckTemplateArgument(Arg: TSI))
5267 return true;
5268
5269 // Objective-C ARC:
5270 // If an explicitly-specified template argument type is a lifetime type
5271 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5272 if (getLangOpts().ObjCAutoRefCount &&
5273 ArgType->isObjCLifetimeType() &&
5274 !ArgType.getObjCLifetime()) {
5275 Qualifiers Qs;
5276 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5277 ArgType = Context.getQualifiedType(T: ArgType, Qs);
5278 }
5279
5280 SugaredConverted.push_back(Elt: TemplateArgument(ArgType));
5281 CanonicalConverted.push_back(
5282 Elt: TemplateArgument(Context.getCanonicalType(T: ArgType)));
5283 return false;
5284}
5285
5286/// Substitute template arguments into the default template argument for
5287/// the given template type parameter.
5288///
5289/// \param SemaRef the semantic analysis object for which we are performing
5290/// the substitution.
5291///
5292/// \param Template the template that we are synthesizing template arguments
5293/// for.
5294///
5295/// \param TemplateLoc the location of the template name that started the
5296/// template-id we are checking.
5297///
5298/// \param RAngleLoc the location of the right angle bracket ('>') that
5299/// terminates the template-id.
5300///
5301/// \param Param the template template parameter whose default we are
5302/// substituting into.
5303///
5304/// \param Converted the list of template arguments provided for template
5305/// parameters that precede \p Param in the template parameter list.
5306///
5307/// \param Output the resulting substituted template argument.
5308///
5309/// \returns true if an error occurred.
5310static bool SubstDefaultTemplateArgument(
5311 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5312 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5313 ArrayRef<TemplateArgument> SugaredConverted,
5314 ArrayRef<TemplateArgument> CanonicalConverted,
5315 TemplateArgumentLoc &Output) {
5316 Output = Param->getDefaultArgument();
5317
5318 // If the argument type is dependent, instantiate it now based
5319 // on the previously-computed template arguments.
5320 if (Output.getArgument().isInstantiationDependent()) {
5321 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5322 SugaredConverted,
5323 SourceRange(TemplateLoc, RAngleLoc));
5324 if (Inst.isInvalid())
5325 return true;
5326
5327 // Only substitute for the innermost template argument list.
5328 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5329 /*Final=*/true);
5330 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5331 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5332
5333 bool ForLambdaCallOperator = false;
5334 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Val: Template->getDeclContext()))
5335 ForLambdaCallOperator = Rec->isLambda();
5336 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5337 !ForLambdaCallOperator);
5338
5339 if (SemaRef.SubstTemplateArgument(Input: Output, TemplateArgs: TemplateArgLists, Output,
5340 Loc: Param->getDefaultArgumentLoc(),
5341 Entity: Param->getDeclName()))
5342 return true;
5343 }
5344
5345 return false;
5346}
5347
5348/// Substitute template arguments into the default template argument for
5349/// the given non-type template parameter.
5350///
5351/// \param SemaRef the semantic analysis object for which we are performing
5352/// the substitution.
5353///
5354/// \param Template the template that we are synthesizing template arguments
5355/// for.
5356///
5357/// \param TemplateLoc the location of the template name that started the
5358/// template-id we are checking.
5359///
5360/// \param RAngleLoc the location of the right angle bracket ('>') that
5361/// terminates the template-id.
5362///
5363/// \param Param the non-type template parameter whose default we are
5364/// substituting into.
5365///
5366/// \param Converted the list of template arguments provided for template
5367/// parameters that precede \p Param in the template parameter list.
5368///
5369/// \returns the substituted template argument, or NULL if an error occurred.
5370static bool SubstDefaultTemplateArgument(
5371 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5372 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5373 ArrayRef<TemplateArgument> SugaredConverted,
5374 ArrayRef<TemplateArgument> CanonicalConverted,
5375 TemplateArgumentLoc &Output) {
5376 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5377 SugaredConverted,
5378 SourceRange(TemplateLoc, RAngleLoc));
5379 if (Inst.isInvalid())
5380 return true;
5381
5382 // Only substitute for the innermost template argument list.
5383 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5384 /*Final=*/true);
5385 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5386 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5387
5388 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5389 EnterExpressionEvaluationContext ConstantEvaluated(
5390 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5391 return SemaRef.SubstTemplateArgument(Input: Param->getDefaultArgument(),
5392 TemplateArgs: TemplateArgLists, Output);
5393}
5394
5395/// Substitute template arguments into the default template argument for
5396/// the given template template parameter.
5397///
5398/// \param SemaRef the semantic analysis object for which we are performing
5399/// the substitution.
5400///
5401/// \param Template the template that we are synthesizing template arguments
5402/// for.
5403///
5404/// \param TemplateLoc the location of the template name that started the
5405/// template-id we are checking.
5406///
5407/// \param RAngleLoc the location of the right angle bracket ('>') that
5408/// terminates the template-id.
5409///
5410/// \param Param the template template parameter whose default we are
5411/// substituting into.
5412///
5413/// \param Converted the list of template arguments provided for template
5414/// parameters that precede \p Param in the template parameter list.
5415///
5416/// \param QualifierLoc Will be set to the nested-name-specifier (with
5417/// source-location information) that precedes the template name.
5418///
5419/// \returns the substituted template argument, or NULL if an error occurred.
5420static TemplateName SubstDefaultTemplateArgument(
5421 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateKWLoc,
5422 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
5423 TemplateTemplateParmDecl *Param,
5424 ArrayRef<TemplateArgument> SugaredConverted,
5425 ArrayRef<TemplateArgument> CanonicalConverted,
5426 NestedNameSpecifierLoc &QualifierLoc) {
5427 Sema::InstantiatingTemplate Inst(
5428 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5429 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5430 if (Inst.isInvalid())
5431 return TemplateName();
5432
5433 // Only substitute for the innermost template argument list.
5434 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5435 /*Final=*/true);
5436 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5437 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5438
5439 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5440
5441 const TemplateArgumentLoc &A = Param->getDefaultArgument();
5442 QualifierLoc = A.getTemplateQualifierLoc();
5443 return SemaRef.SubstTemplateName(TemplateKWLoc, QualifierLoc,
5444 Name: A.getArgument().getAsTemplate(),
5445 NameLoc: A.getTemplateNameLoc(), TemplateArgs: TemplateArgLists);
5446}
5447
5448TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
5449 TemplateDecl *Template, SourceLocation TemplateKWLoc,
5450 SourceLocation TemplateNameLoc, SourceLocation RAngleLoc, Decl *Param,
5451 ArrayRef<TemplateArgument> SugaredConverted,
5452 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5453 HasDefaultArg = false;
5454
5455 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
5456 if (!hasReachableDefaultArgument(D: TypeParm))
5457 return TemplateArgumentLoc();
5458
5459 HasDefaultArg = true;
5460 TemplateArgumentLoc Output;
5461 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5462 RAngleLoc, Param: TypeParm, SugaredConverted,
5463 CanonicalConverted, Output))
5464 return TemplateArgumentLoc();
5465 return Output;
5466 }
5467
5468 if (NonTypeTemplateParmDecl *NonTypeParm
5469 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5470 if (!hasReachableDefaultArgument(D: NonTypeParm))
5471 return TemplateArgumentLoc();
5472
5473 HasDefaultArg = true;
5474 TemplateArgumentLoc Output;
5475 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc: TemplateNameLoc,
5476 RAngleLoc, Param: NonTypeParm, SugaredConverted,
5477 CanonicalConverted, Output))
5478 return TemplateArgumentLoc();
5479 return Output;
5480 }
5481
5482 TemplateTemplateParmDecl *TempTempParm
5483 = cast<TemplateTemplateParmDecl>(Val: Param);
5484 if (!hasReachableDefaultArgument(D: TempTempParm))
5485 return TemplateArgumentLoc();
5486
5487 HasDefaultArg = true;
5488 const TemplateArgumentLoc &A = TempTempParm->getDefaultArgument();
5489 NestedNameSpecifierLoc QualifierLoc;
5490 TemplateName TName = SubstDefaultTemplateArgument(
5491 SemaRef&: *this, Template, TemplateKWLoc, TemplateLoc: TemplateNameLoc, RAngleLoc, Param: TempTempParm,
5492 SugaredConverted, CanonicalConverted, QualifierLoc);
5493 if (TName.isNull())
5494 return TemplateArgumentLoc();
5495
5496 return TemplateArgumentLoc(Context, TemplateArgument(TName), TemplateKWLoc,
5497 QualifierLoc, A.getTemplateNameLoc());
5498}
5499
5500/// Convert a template-argument that we parsed as a type into a template, if
5501/// possible. C++ permits injected-class-names to perform dual service as
5502/// template template arguments and as template type arguments.
5503static TemplateArgumentLoc
5504convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5505 auto TagLoc = TLoc.getAs<TagTypeLoc>();
5506 if (!TagLoc)
5507 return TemplateArgumentLoc();
5508
5509 // If this type was written as an injected-class-name, it can be used as a
5510 // template template argument.
5511 // If this type was written as an injected-class-name, it may have been
5512 // converted to a RecordType during instantiation. If the RecordType is
5513 // *not* wrapped in a TemplateSpecializationType and denotes a class
5514 // template specialization, it must have come from an injected-class-name.
5515
5516 TemplateName Name = TagLoc.getTypePtr()->getTemplateName(Ctx: Context);
5517 if (Name.isNull())
5518 return TemplateArgumentLoc();
5519
5520 return TemplateArgumentLoc(Context, Name,
5521 /*TemplateKWLoc=*/SourceLocation(),
5522 TagLoc.getQualifierLoc(), TagLoc.getNameLoc());
5523}
5524
5525bool Sema::CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &ArgLoc,
5526 NamedDecl *Template,
5527 SourceLocation TemplateLoc,
5528 SourceLocation RAngleLoc,
5529 unsigned ArgumentPackIndex,
5530 CheckTemplateArgumentInfo &CTAI,
5531 CheckTemplateArgumentKind CTAK) {
5532 // Check template type parameters.
5533 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param))
5534 return CheckTemplateTypeArgument(Param: TTP, AL&: ArgLoc, SugaredConverted&: CTAI.SugaredConverted,
5535 CanonicalConverted&: CTAI.CanonicalConverted);
5536
5537 const TemplateArgument &Arg = ArgLoc.getArgument();
5538 // Check non-type template parameters.
5539 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5540 // Do substitution on the type of the non-type template parameter
5541 // with the template arguments we've seen thus far. But if the
5542 // template has a dependent context then we cannot substitute yet.
5543 QualType NTTPType = NTTP->getType();
5544 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5545 NTTPType = NTTP->getExpansionType(I: ArgumentPackIndex);
5546
5547 if (NTTPType->isInstantiationDependentType()) {
5548 // Do substitution on the type of the non-type template parameter.
5549 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5550 CTAI.SugaredConverted,
5551 SourceRange(TemplateLoc, RAngleLoc));
5552 if (Inst.isInvalid())
5553 return true;
5554
5555 MultiLevelTemplateArgumentList MLTAL(Template, CTAI.SugaredConverted,
5556 /*Final=*/true);
5557 MLTAL.addOuterRetainedLevels(Num: NTTP->getDepth());
5558 // If the parameter is a pack expansion, expand this slice of the pack.
5559 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5560 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5561 NTTPType = SubstType(T: PET->getPattern(), TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5562 Entity: NTTP->getDeclName());
5563 } else {
5564 NTTPType = SubstType(T: NTTPType, TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5565 Entity: NTTP->getDeclName());
5566 }
5567
5568 // If that worked, check the non-type template parameter type
5569 // for validity.
5570 if (!NTTPType.isNull())
5571 NTTPType = CheckNonTypeTemplateParameterType(T: NTTPType,
5572 Loc: NTTP->getLocation());
5573 if (NTTPType.isNull())
5574 return true;
5575 }
5576
5577 auto checkExpr = [&](Expr *E) -> Expr * {
5578 TemplateArgument SugaredResult, CanonicalResult;
5579 ExprResult Res = CheckTemplateArgument(
5580 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E, SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5581 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5582 // If the current template argument causes an error, give up now.
5583 if (Res.isInvalid())
5584 return nullptr;
5585 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5586 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5587 return Res.get();
5588 };
5589
5590 switch (Arg.getKind()) {
5591 case TemplateArgument::Null:
5592 llvm_unreachable("Should never see a NULL template argument here");
5593
5594 case TemplateArgument::Expression: {
5595 Expr *E = Arg.getAsExpr();
5596 Expr *R = checkExpr(E);
5597 if (!R)
5598 return true;
5599 // If the resulting expression is new, then use it in place of the
5600 // old expression in the template argument.
5601 if (R != E) {
5602 TemplateArgument TA(R, /*IsCanonical=*/false);
5603 ArgLoc = TemplateArgumentLoc(TA, R);
5604 }
5605 break;
5606 }
5607
5608 // As for the converted NTTP kinds, they still might need another
5609 // conversion, as the new corresponding parameter might be different.
5610 // Ideally, we would always perform substitution starting with sugared types
5611 // and never need these, as we would still have expressions. Since these are
5612 // needed so rarely, it's probably a better tradeoff to just convert them
5613 // back to expressions.
5614 case TemplateArgument::Integral:
5615 case TemplateArgument::Declaration:
5616 case TemplateArgument::NullPtr:
5617 case TemplateArgument::StructuralValue: {
5618 // FIXME: StructuralValue is untested here.
5619 ExprResult R =
5620 BuildExpressionFromNonTypeTemplateArgument(Arg, Loc: SourceLocation());
5621 assert(R.isUsable());
5622 if (!checkExpr(R.get()))
5623 return true;
5624 break;
5625 }
5626
5627 case TemplateArgument::Template:
5628 case TemplateArgument::TemplateExpansion:
5629 // We were given a template template argument. It may not be ill-formed;
5630 // see below.
5631 if (DependentTemplateName *DTN = Arg.getAsTemplateOrTemplatePattern()
5632 .getAsDependentTemplateName()) {
5633 // We have a template argument such as \c T::template X, which we
5634 // parsed as a template template argument. However, since we now
5635 // know that we need a non-type template argument, convert this
5636 // template name into an expression.
5637
5638 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5639 ArgLoc.getTemplateNameLoc());
5640
5641 CXXScopeSpec SS;
5642 SS.Adopt(Other: ArgLoc.getTemplateQualifierLoc());
5643 // FIXME: the template-template arg was a DependentTemplateName,
5644 // so it was provided with a template keyword. However, its source
5645 // location is not stored in the template argument structure.
5646 SourceLocation TemplateKWLoc;
5647 ExprResult E = DependentScopeDeclRefExpr::Create(
5648 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5649 TemplateArgs: nullptr);
5650
5651 // If we parsed the template argument as a pack expansion, create a
5652 // pack expansion expression.
5653 if (Arg.getKind() == TemplateArgument::TemplateExpansion) {
5654 E = ActOnPackExpansion(Pattern: E.get(), EllipsisLoc: ArgLoc.getTemplateEllipsisLoc());
5655 if (E.isInvalid())
5656 return true;
5657 }
5658
5659 TemplateArgument SugaredResult, CanonicalResult;
5660 E = CheckTemplateArgument(
5661 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E.get(), SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5662 /*StrictCheck=*/CTAI.PartialOrdering, CTAK: CTAK_Specified);
5663 if (E.isInvalid())
5664 return true;
5665
5666 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5667 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5668 break;
5669 }
5670
5671 // We have a template argument that actually does refer to a class
5672 // template, alias template, or template template parameter, and
5673 // therefore cannot be a non-type template argument.
5674 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_expr)
5675 << ArgLoc.getSourceRange();
5676 NoteTemplateParameterLocation(Decl: *Param);
5677
5678 return true;
5679
5680 case TemplateArgument::Type: {
5681 // We have a non-type template parameter but the template
5682 // argument is a type.
5683
5684 // C++ [temp.arg]p2:
5685 // In a template-argument, an ambiguity between a type-id and
5686 // an expression is resolved to a type-id, regardless of the
5687 // form of the corresponding template-parameter.
5688 //
5689 // We warn specifically about this case, since it can be rather
5690 // confusing for users.
5691 QualType T = Arg.getAsType();
5692 SourceRange SR = ArgLoc.getSourceRange();
5693 if (T->isFunctionType())
5694 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_nontype_ambig) << SR << T;
5695 else
5696 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_expr) << SR;
5697 NoteTemplateParameterLocation(Decl: *Param);
5698 return true;
5699 }
5700
5701 case TemplateArgument::Pack:
5702 llvm_unreachable("Caller must expand template argument packs");
5703 }
5704
5705 return false;
5706 }
5707
5708
5709 // Check template template parameters.
5710 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Val: Param);
5711
5712 TemplateParameterList *Params = TempParm->getTemplateParameters();
5713 if (TempParm->isExpandedParameterPack())
5714 Params = TempParm->getExpansionTemplateParameters(I: ArgumentPackIndex);
5715
5716 // Substitute into the template parameter list of the template
5717 // template parameter, since previously-supplied template arguments
5718 // may appear within the template template parameter.
5719 //
5720 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5721 {
5722 // Set up a template instantiation context.
5723 LocalInstantiationScope Scope(*this);
5724 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5725 CTAI.SugaredConverted,
5726 SourceRange(TemplateLoc, RAngleLoc));
5727 if (Inst.isInvalid())
5728 return true;
5729
5730 Params = SubstTemplateParams(
5731 Params, Owner: CurContext,
5732 TemplateArgs: MultiLevelTemplateArgumentList(Template, CTAI.SugaredConverted,
5733 /*Final=*/true),
5734 /*EvaluateConstraints=*/false);
5735 if (!Params)
5736 return true;
5737 }
5738
5739 // C++1z [temp.local]p1: (DR1004)
5740 // When [the injected-class-name] is used [...] as a template-argument for
5741 // a template template-parameter [...] it refers to the class template
5742 // itself.
5743 if (Arg.getKind() == TemplateArgument::Type) {
5744 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5745 Context, TLoc: ArgLoc.getTypeSourceInfo()->getTypeLoc());
5746 if (!ConvertedArg.getArgument().isNull())
5747 ArgLoc = ConvertedArg;
5748 }
5749
5750 switch (Arg.getKind()) {
5751 case TemplateArgument::Null:
5752 llvm_unreachable("Should never see a NULL template argument here");
5753
5754 case TemplateArgument::Template:
5755 case TemplateArgument::TemplateExpansion:
5756 if (CheckTemplateTemplateArgument(Param: TempParm, Params, Arg&: ArgLoc,
5757 PartialOrdering: CTAI.PartialOrdering,
5758 StrictPackMatch: &CTAI.StrictPackMatch))
5759 return true;
5760
5761 CTAI.SugaredConverted.push_back(Elt: Arg);
5762 CTAI.CanonicalConverted.push_back(
5763 Elt: Context.getCanonicalTemplateArgument(Arg));
5764 break;
5765
5766 case TemplateArgument::Expression:
5767 case TemplateArgument::Type: {
5768 auto Kind = 0;
5769 switch (TempParm->templateParameterKind()) {
5770 case TemplateNameKind::TNK_Var_template:
5771 Kind = 1;
5772 break;
5773 case TemplateNameKind::TNK_Concept_template:
5774 Kind = 2;
5775 break;
5776 default:
5777 break;
5778 }
5779
5780 // We have a template template parameter but the template
5781 // argument does not refer to a template.
5782 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_template)
5783 << Kind << getLangOpts().CPlusPlus11;
5784 return true;
5785 }
5786
5787 case TemplateArgument::Declaration:
5788 case TemplateArgument::Integral:
5789 case TemplateArgument::StructuralValue:
5790 case TemplateArgument::NullPtr:
5791 llvm_unreachable("non-type argument with template template parameter");
5792
5793 case TemplateArgument::Pack:
5794 llvm_unreachable("Caller must expand template argument packs");
5795 }
5796
5797 return false;
5798}
5799
5800/// Diagnose a missing template argument.
5801template<typename TemplateParmDecl>
5802static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5803 TemplateDecl *TD,
5804 const TemplateParmDecl *D,
5805 TemplateArgumentListInfo &Args) {
5806 // Dig out the most recent declaration of the template parameter; there may be
5807 // declarations of the template that are more recent than TD.
5808 D = cast<TemplateParmDecl>(cast<TemplateDecl>(Val: TD->getMostRecentDecl())
5809 ->getTemplateParameters()
5810 ->getParam(D->getIndex()));
5811
5812 // If there's a default argument that's not reachable, diagnose that we're
5813 // missing a module import.
5814 llvm::SmallVector<Module*, 8> Modules;
5815 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, Modules: &Modules)) {
5816 S.diagnoseMissingImport(Loc, cast<NamedDecl>(Val: TD),
5817 D->getDefaultArgumentLoc(), Modules,
5818 Sema::MissingImportKind::DefaultArgument,
5819 /*Recover*/true);
5820 return true;
5821 }
5822
5823 // FIXME: If there's a more recent default argument that *is* visible,
5824 // diagnose that it was declared too late.
5825
5826 TemplateParameterList *Params = TD->getTemplateParameters();
5827
5828 S.Diag(Loc, DiagID: diag::err_template_arg_list_different_arity)
5829 << /*not enough args*/0
5830 << (int)S.getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
5831 << TD;
5832 S.NoteTemplateLocation(Decl: *TD, ParamRange: Params->getSourceRange());
5833 return true;
5834}
5835
5836/// Check that the given template argument list is well-formed
5837/// for specializing the given template.
5838bool Sema::CheckTemplateArgumentList(
5839 TemplateDecl *Template, SourceLocation TemplateLoc,
5840 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5841 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5842 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5843 return CheckTemplateArgumentList(
5844 Template, Params: GetTemplateParameterList(TD: Template), TemplateLoc, TemplateArgs,
5845 DefaultArgs, PartialTemplateArgs, CTAI, UpdateArgsWithConversions,
5846 ConstraintsNotSatisfied);
5847}
5848
5849/// Check that the given template argument list is well-formed
5850/// for specializing the given template.
5851bool Sema::CheckTemplateArgumentList(
5852 TemplateDecl *Template, TemplateParameterList *Params,
5853 SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs,
5854 const DefaultArguments &DefaultArgs, bool PartialTemplateArgs,
5855 CheckTemplateArgumentInfo &CTAI, bool UpdateArgsWithConversions,
5856 bool *ConstraintsNotSatisfied) {
5857
5858 if (ConstraintsNotSatisfied)
5859 *ConstraintsNotSatisfied = false;
5860
5861 // Make a copy of the template arguments for processing. Only make the
5862 // changes at the end when successful in matching the arguments to the
5863 // template.
5864 TemplateArgumentListInfo NewArgs = TemplateArgs;
5865
5866 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5867
5868 // C++23 [temp.arg.general]p1:
5869 // [...] The type and form of each template-argument specified in
5870 // a template-id shall match the type and form specified for the
5871 // corresponding parameter declared by the template in its
5872 // template-parameter-list.
5873 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Val: Template);
5874 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5875 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5876 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5877 LocalInstantiationScope InstScope(*this, true);
5878 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5879 ParamEnd = Params->end(),
5880 Param = ParamBegin;
5881 Param != ParamEnd;
5882 /* increment in loop */) {
5883 if (size_t ParamIdx = Param - ParamBegin;
5884 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5885 // All written arguments should have been consumed by this point.
5886 assert(ArgIdx == NumArgs && "bad default argument deduction");
5887 if (ParamIdx == DefaultArgs.StartPos) {
5888 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5889 // Default arguments from a DeducedTemplateName are already converted.
5890 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5891 CTAI.SugaredConverted.push_back(Elt: DefArg);
5892 CTAI.CanonicalConverted.push_back(
5893 Elt: Context.getCanonicalTemplateArgument(Arg: DefArg));
5894 ++Param;
5895 }
5896 continue;
5897 }
5898 }
5899
5900 // If we have an expanded parameter pack, make sure we don't have too
5901 // many arguments.
5902 if (UnsignedOrNone Expansions = getExpandedPackSize(Param: *Param)) {
5903 if (*Expansions == SugaredArgumentPack.size()) {
5904 // We're done with this parameter pack. Pack up its arguments and add
5905 // them to the list.
5906 CTAI.SugaredConverted.push_back(
5907 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
5908 SugaredArgumentPack.clear();
5909
5910 CTAI.CanonicalConverted.push_back(
5911 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
5912 CanonicalArgumentPack.clear();
5913
5914 // This argument is assigned to the next parameter.
5915 ++Param;
5916 continue;
5917 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5918 // Not enough arguments for this parameter pack.
5919 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
5920 << /*not enough args*/0
5921 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
5922 << Template;
5923 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
5924 return true;
5925 }
5926 }
5927
5928 // Check for builtins producing template packs in this context, we do not
5929 // support them yet.
5930 if (const NonTypeTemplateParmDecl *NTTP =
5931 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param);
5932 NTTP && NTTP->isPackExpansion()) {
5933 auto TL = NTTP->getTypeSourceInfo()
5934 ->getTypeLoc()
5935 .castAs<PackExpansionTypeLoc>();
5936 llvm::SmallVector<UnexpandedParameterPack> Unexpanded;
5937 collectUnexpandedParameterPacks(TL: TL.getPatternLoc(), Unexpanded);
5938 for (const auto &UPP : Unexpanded) {
5939 auto *TST = UPP.first.dyn_cast<const TemplateSpecializationType *>();
5940 if (!TST)
5941 continue;
5942 assert(isPackProducingBuiltinTemplateName(TST->getTemplateName()));
5943 // Expanding a built-in pack in this context is not yet supported.
5944 Diag(Loc: TL.getEllipsisLoc(),
5945 DiagID: diag::err_unsupported_builtin_template_pack_expansion)
5946 << TST->getTemplateName();
5947 return true;
5948 }
5949 }
5950
5951 if (ArgIdx < NumArgs) {
5952 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5953 bool NonPackParameter =
5954 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(Param: *Param);
5955 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5956
5957 if (ArgIsExpansion && CTAI.MatchingTTP) {
5958 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5959 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5960 ++Param) {
5961 TemplateArgument &Arg = Args[Param - First];
5962 Arg = ArgLoc.getArgument();
5963 if (!(*Param)->isTemplateParameterPack() ||
5964 getExpandedPackSize(Param: *Param))
5965 Arg = Arg.getPackExpansionPattern();
5966 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5967 SaveAndRestore _1(CTAI.PartialOrdering, false);
5968 SaveAndRestore _2(CTAI.MatchingTTP, true);
5969 if (CheckTemplateArgument(Param: *Param, ArgLoc&: NewArgLoc, Template, TemplateLoc,
5970 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
5971 CTAK: CTAK_Specified))
5972 return true;
5973 Arg = NewArgLoc.getArgument();
5974 CTAI.CanonicalConverted.back().setIsDefaulted(
5975 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg, Param: *Param,
5976 Args: CTAI.CanonicalConverted,
5977 Depth: Params->getDepth()));
5978 }
5979 ArgLoc = TemplateArgumentLoc(
5980 TemplateArgument::CreatePackCopy(Context, Args),
5981 TemplateArgumentLocInfo(Context, ArgLoc.getLocation()));
5982 } else {
5983 SaveAndRestore _1(CTAI.PartialOrdering, false);
5984 if (CheckTemplateArgument(Param: *Param, ArgLoc, Template, TemplateLoc,
5985 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
5986 CTAK: CTAK_Specified))
5987 return true;
5988 CTAI.CanonicalConverted.back().setIsDefaulted(
5989 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg: ArgLoc.getArgument(),
5990 Param: *Param, Args: CTAI.CanonicalConverted,
5991 Depth: Params->getDepth()));
5992 if (ArgIsExpansion && NonPackParameter) {
5993 // CWG1430/CWG2686: we have a pack expansion as an argument to an
5994 // alias template, builtin template, or concept, and it's not part of
5995 // a parameter pack. This can't be canonicalized, so reject it now.
5996 if (isa<TypeAliasTemplateDecl, ConceptDecl, BuiltinTemplateDecl>(
5997 Val: Template)) {
5998 unsigned DiagSelect = isa<ConceptDecl>(Val: Template) ? 1
5999 : isa<BuiltinTemplateDecl>(Val: Template) ? 2
6000 : 0;
6001 Diag(Loc: ArgLoc.getLocation(),
6002 DiagID: diag::err_template_expansion_into_fixed_list)
6003 << DiagSelect << ArgLoc.getSourceRange();
6004 NoteTemplateParameterLocation(Decl: **Param);
6005 return true;
6006 }
6007 }
6008 }
6009
6010 // We're now done with this argument.
6011 ++ArgIdx;
6012
6013 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
6014 // Directly convert the remaining arguments, because we don't know what
6015 // parameters they'll match up with.
6016
6017 if (!SugaredArgumentPack.empty()) {
6018 // If we were part way through filling in an expanded parameter pack,
6019 // fall back to just producing individual arguments.
6020 CTAI.SugaredConverted.insert(I: CTAI.SugaredConverted.end(),
6021 From: SugaredArgumentPack.begin(),
6022 To: SugaredArgumentPack.end());
6023 SugaredArgumentPack.clear();
6024
6025 CTAI.CanonicalConverted.insert(I: CTAI.CanonicalConverted.end(),
6026 From: CanonicalArgumentPack.begin(),
6027 To: CanonicalArgumentPack.end());
6028 CanonicalArgumentPack.clear();
6029 }
6030
6031 while (ArgIdx < NumArgs) {
6032 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6033 CTAI.SugaredConverted.push_back(Elt: Arg);
6034 CTAI.CanonicalConverted.push_back(
6035 Elt: Context.getCanonicalTemplateArgument(Arg));
6036 ++ArgIdx;
6037 }
6038
6039 return false;
6040 }
6041
6042 if ((*Param)->isTemplateParameterPack()) {
6043 // The template parameter was a template parameter pack, so take the
6044 // deduced argument and place it on the argument pack. Note that we
6045 // stay on the same template parameter so that we can deduce more
6046 // arguments.
6047 SugaredArgumentPack.push_back(Elt: CTAI.SugaredConverted.pop_back_val());
6048 CanonicalArgumentPack.push_back(Elt: CTAI.CanonicalConverted.pop_back_val());
6049 } else {
6050 // Move to the next template parameter.
6051 ++Param;
6052 }
6053 continue;
6054 }
6055
6056 // If we're checking a partial template argument list, we're done.
6057 if (PartialTemplateArgs) {
6058 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6059 CTAI.SugaredConverted.push_back(
6060 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6061 CTAI.CanonicalConverted.push_back(
6062 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6063 }
6064 return false;
6065 }
6066
6067 // If we have a template parameter pack with no more corresponding
6068 // arguments, just break out now and we'll fill in the argument pack below.
6069 if ((*Param)->isTemplateParameterPack()) {
6070 assert(!getExpandedPackSize(*Param) &&
6071 "Should have dealt with this already");
6072
6073 // A non-expanded parameter pack before the end of the parameter list
6074 // only occurs for an ill-formed template parameter list, unless we've
6075 // got a partial argument list for a function template, so just bail out.
6076 if (Param + 1 != ParamEnd) {
6077 assert(
6078 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6079 "Concept templates must have parameter packs at the end.");
6080 return true;
6081 }
6082
6083 CTAI.SugaredConverted.push_back(
6084 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6085 SugaredArgumentPack.clear();
6086
6087 CTAI.CanonicalConverted.push_back(
6088 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6089 CanonicalArgumentPack.clear();
6090
6091 ++Param;
6092 continue;
6093 }
6094
6095 // Check whether we have a default argument.
6096 bool HasDefaultArg;
6097
6098 // Retrieve the default template argument from the template
6099 // parameter. For each kind of template parameter, we substitute the
6100 // template arguments provided thus far and any "outer" template arguments
6101 // (when the template parameter was part of a nested template) into
6102 // the default argument.
6103 TemplateArgumentLoc Arg = SubstDefaultTemplateArgumentIfAvailable(
6104 Template, /*TemplateKWLoc=*/SourceLocation(), TemplateNameLoc: TemplateLoc, RAngleLoc,
6105 Param: *Param, SugaredConverted: CTAI.SugaredConverted, CanonicalConverted: CTAI.CanonicalConverted, HasDefaultArg);
6106
6107 if (Arg.getArgument().isNull()) {
6108 if (!HasDefaultArg) {
6109 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *Param))
6110 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: TTP,
6111 Args&: NewArgs);
6112 if (NonTypeTemplateParmDecl *NTTP =
6113 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param))
6114 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: NTTP,
6115 Args&: NewArgs);
6116 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template,
6117 D: cast<TemplateTemplateParmDecl>(Val: *Param),
6118 Args&: NewArgs);
6119 }
6120 return true;
6121 }
6122
6123 // Introduce an instantiation record that describes where we are using
6124 // the default template argument. We're not actually instantiating a
6125 // template here, we just create this object to put a note into the
6126 // context stack.
6127 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6128 CTAI.SugaredConverted,
6129 SourceRange(TemplateLoc, RAngleLoc));
6130 if (Inst.isInvalid())
6131 return true;
6132
6133 SaveAndRestore _1(CTAI.PartialOrdering, false);
6134 SaveAndRestore _2(CTAI.MatchingTTP, false);
6135 SaveAndRestore _3(CTAI.StrictPackMatch, {});
6136 // Check the default template argument.
6137 if (CheckTemplateArgument(Param: *Param, ArgLoc&: Arg, Template, TemplateLoc, RAngleLoc, ArgumentPackIndex: 0,
6138 CTAI, CTAK: CTAK_Specified))
6139 return true;
6140
6141 CTAI.SugaredConverted.back().setIsDefaulted(true);
6142 CTAI.CanonicalConverted.back().setIsDefaulted(true);
6143
6144 // Core issue 150 (assumed resolution): if this is a template template
6145 // parameter, keep track of the default template arguments from the
6146 // template definition.
6147 if (isTemplateTemplateParameter)
6148 NewArgs.addArgument(Loc: Arg);
6149
6150 // Move to the next template parameter and argument.
6151 ++Param;
6152 ++ArgIdx;
6153 }
6154
6155 // If we're performing a partial argument substitution, allow any trailing
6156 // pack expansions; they might be empty. This can happen even if
6157 // PartialTemplateArgs is false (the list of arguments is complete but
6158 // still dependent).
6159 if (CTAI.MatchingTTP ||
6160 (CurrentInstantiationScope &&
6161 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
6162 while (ArgIdx < NumArgs &&
6163 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6164 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6165 CTAI.SugaredConverted.push_back(Elt: Arg);
6166 CTAI.CanonicalConverted.push_back(
6167 Elt: Context.getCanonicalTemplateArgument(Arg));
6168 }
6169 }
6170
6171 // If we have any leftover arguments, then there were too many arguments.
6172 // Complain and fail.
6173 if (ArgIdx < NumArgs) {
6174 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
6175 << /*too many args*/1
6176 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
6177 << Template
6178 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6179 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
6180 return true;
6181 }
6182
6183 // No problems found with the new argument list, propagate changes back
6184 // to caller.
6185 if (UpdateArgsWithConversions)
6186 TemplateArgs = std::move(NewArgs);
6187
6188 if (!PartialTemplateArgs) {
6189 // Setup the context/ThisScope for the case where we are needing to
6190 // re-instantiate constraints outside of normal instantiation.
6191 DeclContext *NewContext = Template->getDeclContext();
6192
6193 // If this template is in a template, make sure we extract the templated
6194 // decl.
6195 if (auto *TD = dyn_cast<TemplateDecl>(Val: NewContext))
6196 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6197 auto *RD = dyn_cast<CXXRecordDecl>(Val: NewContext);
6198
6199 Qualifiers ThisQuals;
6200 if (const auto *Method =
6201 dyn_cast_or_null<CXXMethodDecl>(Val: Template->getTemplatedDecl()))
6202 ThisQuals = Method->getMethodQualifiers();
6203
6204 ContextRAII Context(*this, NewContext);
6205 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6206
6207 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
6208 D: Template, DC: NewContext, /*Final=*/true, Innermost: CTAI.SugaredConverted,
6209 /*RelativeToPrimary=*/true,
6210 /*Pattern=*/nullptr,
6211 /*ForConceptInstantiation=*/ForConstraintInstantiation: true);
6212 if (!isa<ConceptDecl>(Val: Template) &&
6213 EnsureTemplateArgumentListConstraints(
6214 Template, TemplateArgs: MLTAL,
6215 TemplateIDRange: SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6216 if (ConstraintsNotSatisfied)
6217 *ConstraintsNotSatisfied = true;
6218 return true;
6219 }
6220 }
6221
6222 return false;
6223}
6224
6225namespace {
6226 class UnnamedLocalNoLinkageFinder
6227 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6228 {
6229 Sema &S;
6230 SourceRange SR;
6231
6232 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
6233
6234 public:
6235 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6236
6237 bool Visit(QualType T) {
6238 return T.isNull() ? false : inherited::Visit(T: T.getTypePtr());
6239 }
6240
6241#define TYPE(Class, Parent) \
6242 bool Visit##Class##Type(const Class##Type *);
6243#define ABSTRACT_TYPE(Class, Parent) \
6244 bool Visit##Class##Type(const Class##Type *) { return false; }
6245#define NON_CANONICAL_TYPE(Class, Parent) \
6246 bool Visit##Class##Type(const Class##Type *) { return false; }
6247#include "clang/AST/TypeNodes.inc"
6248
6249 bool VisitTagDecl(const TagDecl *Tag);
6250 bool VisitNestedNameSpecifier(NestedNameSpecifier NNS);
6251 };
6252} // end anonymous namespace
6253
6254bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6255 return false;
6256}
6257
6258bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6259 return Visit(T: T->getElementType());
6260}
6261
6262bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6263 return Visit(T: T->getPointeeType());
6264}
6265
6266bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6267 const BlockPointerType* T) {
6268 return Visit(T: T->getPointeeType());
6269}
6270
6271bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6272 const LValueReferenceType* T) {
6273 return Visit(T: T->getPointeeType());
6274}
6275
6276bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6277 const RValueReferenceType* T) {
6278 return Visit(T: T->getPointeeType());
6279}
6280
6281bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6282 const MemberPointerType *T) {
6283 if (Visit(T: T->getPointeeType()))
6284 return true;
6285 if (auto *RD = T->getMostRecentCXXRecordDecl())
6286 return VisitTagDecl(Tag: RD);
6287 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6288}
6289
6290bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6291 const ConstantArrayType* T) {
6292 return Visit(T: T->getElementType());
6293}
6294
6295bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6296 const IncompleteArrayType* T) {
6297 return Visit(T: T->getElementType());
6298}
6299
6300bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6301 const VariableArrayType* T) {
6302 return Visit(T: T->getElementType());
6303}
6304
6305bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6306 const DependentSizedArrayType* T) {
6307 return Visit(T: T->getElementType());
6308}
6309
6310bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6311 const DependentSizedExtVectorType* T) {
6312 return Visit(T: T->getElementType());
6313}
6314
6315bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6316 const DependentSizedMatrixType *T) {
6317 return Visit(T: T->getElementType());
6318}
6319
6320bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6321 const DependentAddressSpaceType *T) {
6322 return Visit(T: T->getPointeeType());
6323}
6324
6325bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6326 return Visit(T: T->getElementType());
6327}
6328
6329bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6330 const DependentVectorType *T) {
6331 return Visit(T: T->getElementType());
6332}
6333
6334bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6335 return Visit(T: T->getElementType());
6336}
6337
6338bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6339 const ConstantMatrixType *T) {
6340 return Visit(T: T->getElementType());
6341}
6342
6343bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6344 const FunctionProtoType* T) {
6345 for (const auto &A : T->param_types()) {
6346 if (Visit(T: A))
6347 return true;
6348 }
6349
6350 return Visit(T: T->getReturnType());
6351}
6352
6353bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6354 const FunctionNoProtoType* T) {
6355 return Visit(T: T->getReturnType());
6356}
6357
6358bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6359 const UnresolvedUsingType*) {
6360 return false;
6361}
6362
6363bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6364 return false;
6365}
6366
6367bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6368 return Visit(T: T->getUnmodifiedType());
6369}
6370
6371bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6372 return false;
6373}
6374
6375bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6376 const PackIndexingType *) {
6377 return false;
6378}
6379
6380bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6381 const UnaryTransformType*) {
6382 return false;
6383}
6384
6385bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6386 return Visit(T: T->getDeducedType());
6387}
6388
6389bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6390 const DeducedTemplateSpecializationType *T) {
6391 return Visit(T: T->getDeducedType());
6392}
6393
6394bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6395 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6396}
6397
6398bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6399 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6400}
6401
6402bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6403 const TemplateTypeParmType*) {
6404 return false;
6405}
6406
6407bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6408 const SubstTemplateTypeParmPackType *) {
6409 return false;
6410}
6411
6412bool UnnamedLocalNoLinkageFinder::VisitSubstBuiltinTemplatePackType(
6413 const SubstBuiltinTemplatePackType *) {
6414 return false;
6415}
6416
6417bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6418 const TemplateSpecializationType*) {
6419 return false;
6420}
6421
6422bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6423 const InjectedClassNameType* T) {
6424 return VisitTagDecl(Tag: T->getDecl()->getDefinitionOrSelf());
6425}
6426
6427bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6428 const DependentNameType* T) {
6429 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6430}
6431
6432bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6433 const PackExpansionType* T) {
6434 return Visit(T: T->getPattern());
6435}
6436
6437bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6438 return false;
6439}
6440
6441bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6442 const ObjCInterfaceType *) {
6443 return false;
6444}
6445
6446bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6447 const ObjCObjectPointerType *) {
6448 return false;
6449}
6450
6451bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6452 return Visit(T: T->getValueType());
6453}
6454
6455bool UnnamedLocalNoLinkageFinder::VisitOverflowBehaviorType(
6456 const OverflowBehaviorType *T) {
6457 return Visit(T: T->getUnderlyingType());
6458}
6459
6460bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6461 return false;
6462}
6463
6464bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6465 return false;
6466}
6467
6468bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6469 const ArrayParameterType *T) {
6470 return VisitConstantArrayType(T);
6471}
6472
6473bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6474 const DependentBitIntType *T) {
6475 return false;
6476}
6477
6478bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6479 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6480 S.Diag(Loc: SR.getBegin(), DiagID: S.getLangOpts().CPlusPlus11
6481 ? diag::warn_cxx98_compat_template_arg_local_type
6482 : diag::ext_template_arg_local_type)
6483 << S.Context.getCanonicalTagType(TD: Tag) << SR;
6484 return true;
6485 }
6486
6487 if (!Tag->hasNameForLinkage()) {
6488 S.Diag(Loc: SR.getBegin(),
6489 DiagID: S.getLangOpts().CPlusPlus11 ?
6490 diag::warn_cxx98_compat_template_arg_unnamed_type :
6491 diag::ext_template_arg_unnamed_type) << SR;
6492 S.Diag(Loc: Tag->getLocation(), DiagID: diag::note_template_unnamed_type_here);
6493 return true;
6494 }
6495
6496 return false;
6497}
6498
6499bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6500 NestedNameSpecifier NNS) {
6501 switch (NNS.getKind()) {
6502 case NestedNameSpecifier::Kind::Null:
6503 case NestedNameSpecifier::Kind::Namespace:
6504 case NestedNameSpecifier::Kind::Global:
6505 case NestedNameSpecifier::Kind::MicrosoftSuper:
6506 return false;
6507 case NestedNameSpecifier::Kind::Type:
6508 return Visit(T: QualType(NNS.getAsType(), 0));
6509 }
6510 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6511}
6512
6513bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6514 const HLSLAttributedResourceType *T) {
6515 if (T->hasContainedType() && Visit(T: T->getContainedType()))
6516 return true;
6517 return Visit(T: T->getWrappedType());
6518}
6519
6520bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6521 const HLSLInlineSpirvType *T) {
6522 for (auto &Operand : T->getOperands())
6523 if (Operand.isConstant() && Operand.isLiteral())
6524 if (Visit(T: Operand.getResultType()))
6525 return true;
6526 return false;
6527}
6528
6529bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6530 assert(ArgInfo && "invalid TypeSourceInfo");
6531 QualType Arg = ArgInfo->getType();
6532 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6533 QualType CanonArg = Context.getCanonicalType(T: Arg);
6534
6535 if (CanonArg->isVariablyModifiedType()) {
6536 return Diag(Loc: SR.getBegin(), DiagID: diag::err_variably_modified_template_arg) << Arg;
6537 } else if (Context.hasSameUnqualifiedType(T1: Arg, T2: Context.OverloadTy)) {
6538 return Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_overload_type) << SR;
6539 }
6540
6541 // C++03 [temp.arg.type]p2:
6542 // A local type, a type with no linkage, an unnamed type or a type
6543 // compounded from any of these types shall not be used as a
6544 // template-argument for a template type-parameter.
6545 //
6546 // C++11 allows these, and even in C++03 we allow them as an extension with
6547 // a warning.
6548 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6549 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6550 (void)Finder.Visit(T: CanonArg);
6551 }
6552
6553 return false;
6554}
6555
6556enum NullPointerValueKind {
6557 NPV_NotNullPointer,
6558 NPV_NullPointer,
6559 NPV_Error
6560};
6561
6562/// Determine whether the given template argument is a null pointer
6563/// value of the appropriate type.
6564static NullPointerValueKind
6565isNullPointerValueTemplateArgument(Sema &S, NamedDecl *Param,
6566 QualType ParamType, Expr *Arg,
6567 Decl *Entity = nullptr) {
6568 if (Arg->isValueDependent() || Arg->isTypeDependent())
6569 return NPV_NotNullPointer;
6570
6571 // dllimport'd entities aren't constant but are available inside of template
6572 // arguments.
6573 if (Entity && Entity->hasAttr<DLLImportAttr>())
6574 return NPV_NotNullPointer;
6575
6576 if (!S.isCompleteType(Loc: Arg->getExprLoc(), T: ParamType))
6577 llvm_unreachable(
6578 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6579
6580 if (!S.getLangOpts().CPlusPlus11)
6581 return NPV_NotNullPointer;
6582
6583 // Determine whether we have a constant expression.
6584 ExprResult ArgRV = S.DefaultFunctionArrayConversion(E: Arg);
6585 if (ArgRV.isInvalid())
6586 return NPV_Error;
6587 Arg = ArgRV.get();
6588
6589 Expr::EvalResult EvalResult;
6590 SmallVector<PartialDiagnosticAt, 8> Notes;
6591 EvalResult.Diag = &Notes;
6592 if (!Arg->EvaluateAsRValue(Result&: EvalResult, Ctx: S.Context) ||
6593 EvalResult.HasSideEffects) {
6594 SourceLocation DiagLoc = Arg->getExprLoc();
6595
6596 // If our only note is the usual "invalid subexpression" note, just point
6597 // the caret at its location rather than producing an essentially
6598 // redundant note.
6599 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6600 diag::note_invalid_subexpr_in_const_expr) {
6601 DiagLoc = Notes[0].first;
6602 Notes.clear();
6603 }
6604
6605 S.Diag(Loc: DiagLoc, DiagID: diag::err_template_arg_not_address_constant)
6606 << Arg->getType() << Arg->getSourceRange();
6607 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6608 S.Diag(Loc: Notes[I].first, PD: Notes[I].second);
6609
6610 S.NoteTemplateParameterLocation(Decl: *Param);
6611 return NPV_Error;
6612 }
6613
6614 // C++11 [temp.arg.nontype]p1:
6615 // - an address constant expression of type std::nullptr_t
6616 if (Arg->getType()->isNullPtrType())
6617 return NPV_NullPointer;
6618
6619 // - a constant expression that evaluates to a null pointer value (4.10); or
6620 // - a constant expression that evaluates to a null member pointer value
6621 // (4.11); or
6622 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6623 (EvalResult.Val.isMemberPointer() &&
6624 !EvalResult.Val.getMemberPointerDecl())) {
6625 // If our expression has an appropriate type, we've succeeded.
6626 bool ObjCLifetimeConversion;
6627 if (S.Context.hasSameUnqualifiedType(T1: Arg->getType(), T2: ParamType) ||
6628 S.IsQualificationConversion(FromType: Arg->getType(), ToType: ParamType, CStyle: false,
6629 ObjCLifetimeConversion))
6630 return NPV_NullPointer;
6631
6632 // The types didn't match, but we know we got a null pointer; complain,
6633 // then recover as if the types were correct.
6634 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_wrongtype_null_constant)
6635 << Arg->getType() << ParamType << Arg->getSourceRange();
6636 S.NoteTemplateParameterLocation(Decl: *Param);
6637 return NPV_NullPointer;
6638 }
6639
6640 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6641 // We found a pointer that isn't null, but doesn't refer to an object.
6642 // We could just return NPV_NotNullPointer, but we can print a better
6643 // message with the information we have here.
6644 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_invalid)
6645 << EvalResult.Val.getAsString(Ctx: S.Context, Ty: ParamType);
6646 S.NoteTemplateParameterLocation(Decl: *Param);
6647 return NPV_Error;
6648 }
6649
6650 // If we don't have a null pointer value, but we do have a NULL pointer
6651 // constant, suggest a cast to the appropriate type.
6652 if (Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_NeverValueDependent)) {
6653 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6654 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_untyped_null_constant)
6655 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code)
6656 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: Arg->getEndLoc()),
6657 Code: ")");
6658 S.NoteTemplateParameterLocation(Decl: *Param);
6659 return NPV_NullPointer;
6660 }
6661
6662 // FIXME: If we ever want to support general, address-constant expressions
6663 // as non-type template arguments, we should return the ExprResult here to
6664 // be interpreted by the caller.
6665 return NPV_NotNullPointer;
6666}
6667
6668/// Checks whether the given template argument is compatible with its
6669/// template parameter.
6670static bool
6671CheckTemplateArgumentIsCompatibleWithParameter(Sema &S, NamedDecl *Param,
6672 QualType ParamType, Expr *ArgIn,
6673 Expr *Arg, QualType ArgType) {
6674 bool ObjCLifetimeConversion;
6675 if (ParamType->isPointerType() &&
6676 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6677 S.IsQualificationConversion(FromType: ArgType, ToType: ParamType, CStyle: false,
6678 ObjCLifetimeConversion)) {
6679 // For pointer-to-object types, qualification conversions are
6680 // permitted.
6681 } else {
6682 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6683 if (!ParamRef->getPointeeType()->isFunctionType()) {
6684 // C++ [temp.arg.nontype]p5b3:
6685 // For a non-type template-parameter of type reference to
6686 // object, no conversions apply. The type referred to by the
6687 // reference may be more cv-qualified than the (otherwise
6688 // identical) type of the template- argument. The
6689 // template-parameter is bound directly to the
6690 // template-argument, which shall be an lvalue.
6691
6692 // FIXME: Other qualifiers?
6693 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6694 unsigned ArgQuals = ArgType.getCVRQualifiers();
6695
6696 if ((ParamQuals | ArgQuals) != ParamQuals) {
6697 S.Diag(Loc: Arg->getBeginLoc(),
6698 DiagID: diag::err_template_arg_ref_bind_ignores_quals)
6699 << ParamType << Arg->getType() << Arg->getSourceRange();
6700 S.NoteTemplateParameterLocation(Decl: *Param);
6701 return true;
6702 }
6703 }
6704 }
6705
6706 // At this point, the template argument refers to an object or
6707 // function with external linkage. We now need to check whether the
6708 // argument and parameter types are compatible.
6709 if (!S.Context.hasSameUnqualifiedType(T1: ArgType,
6710 T2: ParamType.getNonReferenceType())) {
6711 // We can't perform this conversion or binding.
6712 if (ParamType->isReferenceType())
6713 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_no_ref_bind)
6714 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6715 else
6716 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
6717 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6718 S.NoteTemplateParameterLocation(Decl: *Param);
6719 return true;
6720 }
6721 }
6722
6723 return false;
6724}
6725
6726/// Checks whether the given template argument is the address
6727/// of an object or function according to C++ [temp.arg.nontype]p1.
6728static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6729 Sema &S, NamedDecl *Param, QualType ParamType, Expr *ArgIn,
6730 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6731 bool Invalid = false;
6732 Expr *Arg = ArgIn;
6733 QualType ArgType = Arg->getType();
6734
6735 bool AddressTaken = false;
6736 SourceLocation AddrOpLoc;
6737 if (S.getLangOpts().MicrosoftExt) {
6738 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6739 // dereference and address-of operators.
6740 Arg = Arg->IgnoreParenCasts();
6741
6742 bool ExtWarnMSTemplateArg = false;
6743 UnaryOperatorKind FirstOpKind;
6744 SourceLocation FirstOpLoc;
6745 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6746 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6747 if (UnOpKind == UO_Deref)
6748 ExtWarnMSTemplateArg = true;
6749 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6750 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6751 if (!AddrOpLoc.isValid()) {
6752 FirstOpKind = UnOpKind;
6753 FirstOpLoc = UnOp->getOperatorLoc();
6754 }
6755 } else
6756 break;
6757 }
6758 if (FirstOpLoc.isValid()) {
6759 if (ExtWarnMSTemplateArg)
6760 S.Diag(Loc: ArgIn->getBeginLoc(), DiagID: diag::ext_ms_deref_template_argument)
6761 << ArgIn->getSourceRange();
6762
6763 if (FirstOpKind == UO_AddrOf)
6764 AddressTaken = true;
6765 else if (Arg->getType()->isPointerType()) {
6766 // We cannot let pointers get dereferenced here, that is obviously not a
6767 // constant expression.
6768 assert(FirstOpKind == UO_Deref);
6769 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6770 << Arg->getSourceRange();
6771 }
6772 }
6773 } else {
6774 // See through any implicit casts we added to fix the type.
6775 Arg = Arg->IgnoreImpCasts();
6776
6777 // C++ [temp.arg.nontype]p1:
6778 //
6779 // A template-argument for a non-type, non-template
6780 // template-parameter shall be one of: [...]
6781 //
6782 // -- the address of an object or function with external
6783 // linkage, including function templates and function
6784 // template-ids but excluding non-static class members,
6785 // expressed as & id-expression where the & is optional if
6786 // the name refers to a function or array, or if the
6787 // corresponding template-parameter is a reference; or
6788
6789 // In C++98/03 mode, give an extension warning on any extra parentheses.
6790 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6791 bool ExtraParens = false;
6792 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
6793 if (!Invalid && !ExtraParens) {
6794 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_extra_parens)
6795 << Arg->getSourceRange();
6796 ExtraParens = true;
6797 }
6798
6799 Arg = Parens->getSubExpr();
6800 }
6801
6802 while (SubstNonTypeTemplateParmExpr *subst =
6803 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6804 Arg = subst->getReplacement()->IgnoreImpCasts();
6805
6806 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6807 if (UnOp->getOpcode() == UO_AddrOf) {
6808 Arg = UnOp->getSubExpr();
6809 AddressTaken = true;
6810 AddrOpLoc = UnOp->getOperatorLoc();
6811 }
6812 }
6813
6814 while (SubstNonTypeTemplateParmExpr *subst =
6815 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6816 Arg = subst->getReplacement()->IgnoreImpCasts();
6817 }
6818
6819 ValueDecl *Entity = nullptr;
6820 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg))
6821 Entity = DRE->getDecl();
6822 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Val: Arg))
6823 Entity = CUE->getGuidDecl();
6824
6825 // If our parameter has pointer type, check for a null template value.
6826 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6827 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ArgIn,
6828 Entity)) {
6829 case NPV_NullPointer:
6830 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
6831 SugaredConverted = TemplateArgument(ParamType,
6832 /*isNullPtr=*/true);
6833 CanonicalConverted =
6834 TemplateArgument(S.Context.getCanonicalType(T: ParamType),
6835 /*isNullPtr=*/true);
6836 return false;
6837
6838 case NPV_Error:
6839 return true;
6840
6841 case NPV_NotNullPointer:
6842 break;
6843 }
6844 }
6845
6846 // Stop checking the precise nature of the argument if it is value dependent,
6847 // it should be checked when instantiated.
6848 if (Arg->isValueDependent()) {
6849 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6850 CanonicalConverted =
6851 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
6852 return false;
6853 }
6854
6855 if (!Entity) {
6856 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6857 << Arg->getSourceRange();
6858 S.NoteTemplateParameterLocation(Decl: *Param);
6859 return true;
6860 }
6861
6862 // Cannot refer to non-static data members
6863 if (isa<FieldDecl>(Val: Entity) || isa<IndirectFieldDecl>(Val: Entity)) {
6864 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_field)
6865 << Entity << Arg->getSourceRange();
6866 S.NoteTemplateParameterLocation(Decl: *Param);
6867 return true;
6868 }
6869
6870 // Cannot refer to non-static member functions
6871 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Entity)) {
6872 if (!Method->isStatic()) {
6873 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_method)
6874 << Method << Arg->getSourceRange();
6875 S.NoteTemplateParameterLocation(Decl: *Param);
6876 return true;
6877 }
6878 }
6879
6880 FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Entity);
6881 VarDecl *Var = dyn_cast<VarDecl>(Val: Entity);
6882 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Val: Entity);
6883
6884 // A non-type template argument must refer to an object or function.
6885 if (!Func && !Var && !Guid) {
6886 // We found something, but we don't know specifically what it is.
6887 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_object_or_func)
6888 << Arg->getSourceRange();
6889 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_refers_here);
6890 return true;
6891 }
6892
6893 // Address / reference template args must have external linkage in C++98.
6894 if (Entity->getFormalLinkage() == Linkage::Internal) {
6895 S.Diag(Loc: Arg->getBeginLoc(),
6896 DiagID: S.getLangOpts().CPlusPlus11
6897 ? diag::warn_cxx98_compat_template_arg_object_internal
6898 : diag::ext_template_arg_object_internal)
6899 << !Func << Entity << Arg->getSourceRange();
6900 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6901 << !Func;
6902 } else if (!Entity->hasLinkage()) {
6903 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_object_no_linkage)
6904 << !Func << Entity << Arg->getSourceRange();
6905 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6906 << !Func;
6907 return true;
6908 }
6909
6910 if (Var) {
6911 // A value of reference type is not an object.
6912 if (Var->getType()->isReferenceType()) {
6913 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_reference_var)
6914 << Var->getType() << Arg->getSourceRange();
6915 S.NoteTemplateParameterLocation(Decl: *Param);
6916 return true;
6917 }
6918
6919 // A template argument must have static storage duration.
6920 if (Var->getTLSKind()) {
6921 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_thread_local)
6922 << Arg->getSourceRange();
6923 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_template_arg_refers_here);
6924 return true;
6925 }
6926 }
6927
6928 if (AddressTaken && ParamType->isReferenceType()) {
6929 // If we originally had an address-of operator, but the
6930 // parameter has reference type, complain and (if things look
6931 // like they will work) drop the address-of operator.
6932 if (!S.Context.hasSameUnqualifiedType(T1: Entity->getType(),
6933 T2: ParamType.getNonReferenceType())) {
6934 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6935 << ParamType;
6936 S.NoteTemplateParameterLocation(Decl: *Param);
6937 return true;
6938 }
6939
6940 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6941 << ParamType
6942 << FixItHint::CreateRemoval(RemoveRange: AddrOpLoc);
6943 S.NoteTemplateParameterLocation(Decl: *Param);
6944
6945 ArgType = Entity->getType();
6946 }
6947
6948 // If the template parameter has pointer type, either we must have taken the
6949 // address or the argument must decay to a pointer.
6950 if (!AddressTaken && ParamType->isPointerType()) {
6951 if (Func) {
6952 // Function-to-pointer decay.
6953 ArgType = S.Context.getPointerType(T: Func->getType());
6954 } else if (Entity->getType()->isArrayType()) {
6955 // Array-to-pointer decay.
6956 ArgType = S.Context.getArrayDecayedType(T: Entity->getType());
6957 } else {
6958 // If the template parameter has pointer type but the address of
6959 // this object was not taken, complain and (possibly) recover by
6960 // taking the address of the entity.
6961 ArgType = S.Context.getPointerType(T: Entity->getType());
6962 if (!S.Context.hasSameUnqualifiedType(T1: ArgType, T2: ParamType)) {
6963 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
6964 << ParamType;
6965 S.NoteTemplateParameterLocation(Decl: *Param);
6966 return true;
6967 }
6968
6969 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
6970 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code: "&");
6971
6972 S.NoteTemplateParameterLocation(Decl: *Param);
6973 }
6974 }
6975
6976 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6977 Arg, ArgType))
6978 return true;
6979
6980 // Create the template argument.
6981 SugaredConverted = TemplateArgument(Entity, ParamType);
6982 CanonicalConverted =
6983 TemplateArgument(cast<ValueDecl>(Val: Entity->getCanonicalDecl()),
6984 S.Context.getCanonicalType(T: ParamType));
6985 S.MarkAnyDeclReferenced(Loc: Arg->getBeginLoc(), D: Entity, MightBeOdrUse: false);
6986 return false;
6987}
6988
6989/// Checks whether the given template argument is a pointer to
6990/// member constant according to C++ [temp.arg.nontype]p1.
6991static bool CheckTemplateArgumentPointerToMember(
6992 Sema &S, NamedDecl *Param, QualType ParamType, Expr *&ResultArg,
6993 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6994 bool Invalid = false;
6995
6996 Expr *Arg = ResultArg;
6997 bool ObjCLifetimeConversion;
6998
6999 // C++ [temp.arg.nontype]p1:
7000 //
7001 // A template-argument for a non-type, non-template
7002 // template-parameter shall be one of: [...]
7003 //
7004 // -- a pointer to member expressed as described in 5.3.1.
7005 DeclRefExpr *DRE = nullptr;
7006
7007 // In C++98/03 mode, give an extension warning on any extra parentheses.
7008 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7009 bool ExtraParens = false;
7010 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
7011 if (!Invalid && !ExtraParens) {
7012 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_extra_parens)
7013 << Arg->getSourceRange();
7014 ExtraParens = true;
7015 }
7016
7017 Arg = Parens->getSubExpr();
7018 }
7019
7020 while (SubstNonTypeTemplateParmExpr *subst =
7021 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
7022 Arg = subst->getReplacement()->IgnoreImpCasts();
7023
7024 // A pointer-to-member constant written &Class::member.
7025 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
7026 if (UnOp->getOpcode() == UO_AddrOf) {
7027 DRE = dyn_cast<DeclRefExpr>(Val: UnOp->getSubExpr());
7028 if (DRE && !DRE->getQualifier())
7029 DRE = nullptr;
7030 }
7031 }
7032 // A constant of pointer-to-member type.
7033 else if ((DRE = dyn_cast<DeclRefExpr>(Val: Arg))) {
7034 ValueDecl *VD = DRE->getDecl();
7035 if (VD->getType()->isMemberPointerType()) {
7036 if (isa<NonTypeTemplateParmDecl>(Val: VD)) {
7037 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7038 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7039 CanonicalConverted =
7040 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7041 } else {
7042 SugaredConverted = TemplateArgument(VD, ParamType);
7043 CanonicalConverted =
7044 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7045 S.Context.getCanonicalType(T: ParamType));
7046 }
7047 return Invalid;
7048 }
7049 }
7050
7051 DRE = nullptr;
7052 }
7053
7054 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7055
7056 // Check for a null pointer value.
7057 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ResultArg,
7058 Entity)) {
7059 case NPV_Error:
7060 return true;
7061 case NPV_NullPointer:
7062 S.Diag(Loc: ResultArg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7063 SugaredConverted = TemplateArgument(ParamType,
7064 /*isNullPtr*/ true);
7065 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(T: ParamType),
7066 /*isNullPtr*/ true);
7067 return false;
7068 case NPV_NotNullPointer:
7069 break;
7070 }
7071
7072 if (S.IsQualificationConversion(FromType: ResultArg->getType(),
7073 ToType: ParamType.getNonReferenceType(), CStyle: false,
7074 ObjCLifetimeConversion)) {
7075 ResultArg = S.ImpCastExprToType(E: ResultArg, Type: ParamType, CK: CK_NoOp,
7076 VK: ResultArg->getValueKind())
7077 .get();
7078 } else if (!S.Context.hasSameUnqualifiedType(
7079 T1: ResultArg->getType(), T2: ParamType.getNonReferenceType())) {
7080 // We can't perform this conversion.
7081 S.Diag(Loc: ResultArg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
7082 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7083 S.NoteTemplateParameterLocation(Decl: *Param);
7084 return true;
7085 }
7086
7087 if (!DRE)
7088 return S.Diag(Loc: Arg->getBeginLoc(),
7089 DiagID: diag::err_template_arg_not_pointer_to_member_form)
7090 << Arg->getSourceRange();
7091
7092 if (isa<FieldDecl>(Val: DRE->getDecl()) ||
7093 isa<IndirectFieldDecl>(Val: DRE->getDecl()) ||
7094 isa<CXXMethodDecl>(Val: DRE->getDecl())) {
7095 assert((isa<FieldDecl>(DRE->getDecl()) ||
7096 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7097 cast<CXXMethodDecl>(DRE->getDecl())
7098 ->isImplicitObjectMemberFunction()) &&
7099 "Only non-static member pointers can make it here");
7100
7101 // Okay: this is the address of a non-static member, and therefore
7102 // a member pointer constant.
7103 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7104 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7105 CanonicalConverted =
7106 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7107 } else {
7108 ValueDecl *D = DRE->getDecl();
7109 SugaredConverted = TemplateArgument(D, ParamType);
7110 CanonicalConverted =
7111 TemplateArgument(cast<ValueDecl>(Val: D->getCanonicalDecl()),
7112 S.Context.getCanonicalType(T: ParamType));
7113 }
7114 return Invalid;
7115 }
7116
7117 // We found something else, but we don't know specifically what it is.
7118 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_pointer_to_member_form)
7119 << Arg->getSourceRange();
7120 S.Diag(Loc: DRE->getDecl()->getLocation(), DiagID: diag::note_template_arg_refers_here);
7121 return true;
7122}
7123
7124/// Check a template argument against its corresponding
7125/// non-type template parameter.
7126///
7127/// This routine implements the semantics of C++ [temp.arg.nontype].
7128/// If an error occurred, it returns ExprError(); otherwise, it
7129/// returns the converted template argument. \p ParamType is the
7130/// type of the non-type template parameter after it has been instantiated.
7131ExprResult Sema::CheckTemplateArgument(NamedDecl *Param, QualType ParamType,
7132 Expr *Arg,
7133 TemplateArgument &SugaredConverted,
7134 TemplateArgument &CanonicalConverted,
7135 bool StrictCheck,
7136 CheckTemplateArgumentKind CTAK) {
7137 SourceLocation StartLoc = Arg->getBeginLoc();
7138 auto *ArgPE = dyn_cast<PackExpansionExpr>(Val: Arg);
7139 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
7140 auto setDeductionArg = [&](Expr *NewDeductionArg) {
7141 DeductionArg = NewDeductionArg;
7142 if (ArgPE) {
7143 // Recreate a pack expansion if we unwrapped one.
7144 Arg = new (Context) PackExpansionExpr(
7145 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
7146 } else {
7147 Arg = DeductionArg;
7148 }
7149 };
7150
7151 // If the parameter type somehow involves auto, deduce the type now.
7152 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7153 bool IsDeduced = DeducedT && DeducedT->getDeducedType().isNull();
7154 if (IsDeduced) {
7155 // When checking a deduced template argument, deduce from its type even if
7156 // the type is dependent, in order to check the types of non-type template
7157 // arguments line up properly in partial ordering.
7158 TypeSourceInfo *TSI =
7159 Context.getTrivialTypeSourceInfo(T: ParamType, Loc: Param->getLocation());
7160 if (isa<DeducedTemplateSpecializationType>(Val: DeducedT)) {
7161 InitializedEntity Entity =
7162 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7163 InitializationKind Kind = InitializationKind::CreateForInit(
7164 Loc: DeductionArg->getBeginLoc(), /*DirectInit*/false, Init: DeductionArg);
7165 Expr *Inits[1] = {DeductionArg};
7166 ParamType =
7167 DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind, Init: Inits);
7168 if (ParamType.isNull())
7169 return ExprError();
7170 } else {
7171 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7172 Param->getTemplateDepth() + 1);
7173 ParamType = QualType();
7174 TemplateDeductionResult Result =
7175 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeductionArg, Result&: ParamType, Info,
7176 /*DependentDeduction=*/true,
7177 // We do not check constraints right now because the
7178 // immediately-declared constraint of the auto type is
7179 // also an associated constraint, and will be checked
7180 // along with the other associated constraints after
7181 // checking the template argument list.
7182 /*IgnoreConstraints=*/true);
7183 if (Result != TemplateDeductionResult::Success) {
7184 ParamType = TSI->getType();
7185 if (StrictCheck || !DeductionArg->isTypeDependent()) {
7186 if (Result == TemplateDeductionResult::AlreadyDiagnosed)
7187 return ExprError();
7188 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Param))
7189 Diag(Loc: Arg->getExprLoc(),
7190 DiagID: diag::err_non_type_template_parm_type_deduction_failure)
7191 << Param->getDeclName() << NTTP->getType() << Arg->getType()
7192 << Arg->getSourceRange();
7193 NoteTemplateParameterLocation(Decl: *Param);
7194 return ExprError();
7195 }
7196 ParamType = SubstAutoTypeDependent(TypeWithAuto: ParamType);
7197 assert(!ParamType.isNull() && "substituting DependentTy can't fail");
7198 }
7199 }
7200 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7201 // an error. The error message normally references the parameter
7202 // declaration, but here we'll pass the argument location because that's
7203 // where the parameter type is deduced.
7204 ParamType = CheckNonTypeTemplateParameterType(T: ParamType, Loc: Arg->getExprLoc());
7205 if (ParamType.isNull()) {
7206 NoteTemplateParameterLocation(Decl: *Param);
7207 return ExprError();
7208 }
7209 }
7210
7211 // We should have already dropped all cv-qualifiers by now.
7212 assert(!ParamType.hasQualifiers() &&
7213 "non-type template parameter type cannot be qualified");
7214
7215 // If either the parameter has a dependent type or the argument is
7216 // type-dependent, there's nothing we can check now.
7217 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7218 // Force the argument to the type of the parameter to maintain invariants.
7219 if (!IsDeduced) {
7220 ExprResult E = ImpCastExprToType(
7221 E: DeductionArg, Type: ParamType.getNonLValueExprType(Context), CK: CK_Dependent,
7222 VK: ParamType->isLValueReferenceType() ? VK_LValue
7223 : ParamType->isRValueReferenceType() ? VK_XValue
7224 : VK_PRValue);
7225 if (E.isInvalid())
7226 return ExprError();
7227 setDeductionArg(E.get());
7228 }
7229 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7230 CanonicalConverted = TemplateArgument(
7231 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7232 return Arg;
7233 }
7234
7235 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7236 if (CTAK == CTAK_Deduced && !StrictCheck &&
7237 (ParamType->isReferenceType()
7238 ? !Context.hasSameType(T1: ParamType.getNonReferenceType(),
7239 T2: DeductionArg->getType())
7240 : !Context.hasSameUnqualifiedType(T1: ParamType,
7241 T2: DeductionArg->getType()))) {
7242 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7243 // we should actually be checking the type of the template argument in P,
7244 // not the type of the template argument deduced from A, against the
7245 // template parameter type.
7246 Diag(Loc: StartLoc, DiagID: diag::err_deduced_non_type_template_arg_type_mismatch)
7247 << Arg->getType() << ParamType.getUnqualifiedType();
7248 NoteTemplateParameterLocation(Decl: *Param);
7249 return ExprError();
7250 }
7251
7252 // If the argument is a pack expansion, we don't know how many times it would
7253 // expand. If we continue checking the argument, this will make the template
7254 // definition ill-formed if it would be ill-formed for any number of
7255 // expansions during instantiation time. When partial ordering or matching
7256 // template template parameters, this is exactly what we want. Otherwise, the
7257 // normal template rules apply: we accept the template if it would be valid
7258 // for any number of expansions (i.e. none).
7259 if (ArgPE && !StrictCheck) {
7260 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7261 CanonicalConverted = TemplateArgument(
7262 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7263 return Arg;
7264 }
7265
7266 // Avoid making a copy when initializing a template parameter of class type
7267 // from a template parameter object of the same type. This is going beyond
7268 // the standard, but is required for soundness: in
7269 // template<A a> struct X { X *p; X<a> *q; };
7270 // ... we need p and q to have the same type.
7271 //
7272 // Similarly, don't inject a call to a copy constructor when initializing
7273 // from a template parameter of the same type.
7274 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7275 if (ParamType->isRecordType() && isa<DeclRefExpr>(Val: InnerArg) &&
7276 Context.hasSameUnqualifiedType(T1: ParamType, T2: InnerArg->getType())) {
7277 NamedDecl *ND = cast<DeclRefExpr>(Val: InnerArg)->getDecl();
7278 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(Val: ND)) {
7279
7280 SugaredConverted = TemplateArgument(TPO, ParamType);
7281 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7282 ParamType.getCanonicalType());
7283 return Arg;
7284 }
7285 if (isa<NonTypeTemplateParmDecl>(Val: ND)) {
7286 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7287 CanonicalConverted =
7288 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7289 return Arg;
7290 }
7291 }
7292
7293 // The initialization of the parameter from the argument is
7294 // a constant-evaluated context.
7295 EnterExpressionEvaluationContext ConstantEvaluated(
7296 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7297
7298 bool IsConvertedConstantExpression = true;
7299 if (isa<InitListExpr>(Val: DeductionArg) || ParamType->isRecordType()) {
7300 InitializationKind Kind = InitializationKind::CreateForInit(
7301 Loc: StartLoc, /*DirectInit=*/false, Init: DeductionArg);
7302 Expr *Inits[1] = {DeductionArg};
7303 InitializedEntity Entity =
7304 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7305 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7306 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Inits);
7307 if (Result.isInvalid() || !Result.get())
7308 return ExprError();
7309 Result = ActOnConstantExpression(Res: Result.get());
7310 if (Result.isInvalid() || !Result.get())
7311 return ExprError();
7312 setDeductionArg(ActOnFinishFullExpr(Expr: Result.get(), CC: Arg->getBeginLoc(),
7313 /*DiscardedValue=*/false,
7314 /*IsConstexpr=*/true,
7315 /*IsTemplateArgument=*/true)
7316 .get());
7317 IsConvertedConstantExpression = false;
7318 }
7319
7320 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7321 // C++17 [temp.arg.nontype]p1:
7322 // A template-argument for a non-type template parameter shall be
7323 // a converted constant expression of the type of the template-parameter.
7324 APValue Value;
7325 ExprResult ArgResult;
7326 if (IsConvertedConstantExpression) {
7327 ArgResult = BuildConvertedConstantExpression(
7328 From: DeductionArg, T: ParamType,
7329 CCE: StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Dest: Param);
7330 assert(!ArgResult.isUnset());
7331 if (ArgResult.isInvalid()) {
7332 NoteTemplateParameterLocation(Decl: *Param);
7333 return ExprError();
7334 }
7335 } else {
7336 ArgResult = DeductionArg;
7337 }
7338
7339 // For a value-dependent argument, CheckConvertedConstantExpression is
7340 // permitted (and expected) to be unable to determine a value.
7341 if (ArgResult.get()->isValueDependent()) {
7342 setDeductionArg(ArgResult.get());
7343 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7344 CanonicalConverted =
7345 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7346 return Arg;
7347 }
7348
7349 APValue PreNarrowingValue;
7350 ArgResult = EvaluateConvertedConstantExpression(
7351 E: ArgResult.get(), T: ParamType, Value, CCE: CCEKind::TemplateArg, /*RequireInt=*/
7352 false, PreNarrowingValue);
7353 if (ArgResult.isInvalid())
7354 return ExprError();
7355 setDeductionArg(ArgResult.get());
7356
7357 if (Value.isLValue()) {
7358 APValue::LValueBase Base = Value.getLValueBase();
7359 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7360 // For a non-type template-parameter of pointer or reference type,
7361 // the value of the constant expression shall not refer to
7362 assert(ParamType->isPointerOrReferenceType() ||
7363 ParamType->isNullPtrType());
7364 // -- a temporary object
7365 // -- a string literal
7366 // -- the result of a typeid expression, or
7367 // -- a predefined __func__ variable
7368 if (Base &&
7369 (!VD ||
7370 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(Val: VD))) {
7371 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
7372 << Arg->getSourceRange();
7373 return ExprError();
7374 }
7375
7376 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7377 VD->getType()->isArrayType() &&
7378 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7379 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7380 if (ArgPE) {
7381 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7382 CanonicalConverted =
7383 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7384 } else {
7385 SugaredConverted = TemplateArgument(VD, ParamType);
7386 CanonicalConverted =
7387 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7388 ParamType.getCanonicalType());
7389 }
7390 return Arg;
7391 }
7392
7393 // -- a subobject [until C++20]
7394 if (!getLangOpts().CPlusPlus20) {
7395 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7396 Value.isLValueOnePastTheEnd()) {
7397 Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_subobject)
7398 << Value.getAsString(Ctx: Context, Ty: ParamType);
7399 return ExprError();
7400 }
7401 assert((VD || !ParamType->isReferenceType()) &&
7402 "null reference should not be a constant expression");
7403 assert((!VD || !ParamType->isNullPtrType()) &&
7404 "non-null value of type nullptr_t?");
7405 }
7406 }
7407
7408 if (Value.isAddrLabelDiff())
7409 return Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_addr_label_diff);
7410
7411 if (ArgPE) {
7412 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7413 CanonicalConverted =
7414 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7415 } else {
7416 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7417 CanonicalConverted =
7418 TemplateArgument(Context, ParamType.getCanonicalType(), Value);
7419 }
7420 return Arg;
7421 }
7422
7423 // These should have all been handled above using the C++17 rules.
7424 assert(!ArgPE && !StrictCheck);
7425
7426 // C++ [temp.arg.nontype]p5:
7427 // The following conversions are performed on each expression used
7428 // as a non-type template-argument. If a non-type
7429 // template-argument cannot be converted to the type of the
7430 // corresponding template-parameter then the program is
7431 // ill-formed.
7432 if (ParamType->isIntegralOrEnumerationType()) {
7433 // C++11:
7434 // -- for a non-type template-parameter of integral or
7435 // enumeration type, conversions permitted in a converted
7436 // constant expression are applied.
7437 //
7438 // C++98:
7439 // -- for a non-type template-parameter of integral or
7440 // enumeration type, integral promotions (4.5) and integral
7441 // conversions (4.7) are applied.
7442
7443 if (getLangOpts().CPlusPlus11) {
7444 // C++ [temp.arg.nontype]p1:
7445 // A template-argument for a non-type, non-template template-parameter
7446 // shall be one of:
7447 //
7448 // -- for a non-type template-parameter of integral or enumeration
7449 // type, a converted constant expression of the type of the
7450 // template-parameter; or
7451 llvm::APSInt Value;
7452 ExprResult ArgResult = CheckConvertedConstantExpression(
7453 From: Arg, T: ParamType, Value, CCE: CCEKind::TemplateArg);
7454 if (ArgResult.isInvalid())
7455 return ExprError();
7456 Arg = ArgResult.get();
7457
7458 // We can't check arbitrary value-dependent arguments.
7459 if (Arg->isValueDependent()) {
7460 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7461 CanonicalConverted =
7462 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7463 return Arg;
7464 }
7465
7466 // Widen the argument value to sizeof(parameter type). This is almost
7467 // always a no-op, except when the parameter type is bool. In
7468 // that case, this may extend the argument from 1 bit to 8 bits.
7469 QualType IntegerType = ParamType;
7470 if (const auto *ED = IntegerType->getAsEnumDecl())
7471 IntegerType = ED->getIntegerType();
7472 Value = Value.extOrTrunc(width: IntegerType->isBitIntType()
7473 ? Context.getIntWidth(T: IntegerType)
7474 : Context.getTypeSize(T: IntegerType));
7475
7476 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7477 CanonicalConverted =
7478 TemplateArgument(Context, Value, Context.getCanonicalType(T: ParamType));
7479 return Arg;
7480 }
7481
7482 ExprResult ArgResult = DefaultLvalueConversion(E: Arg);
7483 if (ArgResult.isInvalid())
7484 return ExprError();
7485 Arg = ArgResult.get();
7486
7487 QualType ArgType = Arg->getType();
7488
7489 // C++ [temp.arg.nontype]p1:
7490 // A template-argument for a non-type, non-template
7491 // template-parameter shall be one of:
7492 //
7493 // -- an integral constant-expression of integral or enumeration
7494 // type; or
7495 // -- the name of a non-type template-parameter; or
7496 llvm::APSInt Value;
7497 if (!ArgType->isIntegralOrEnumerationType()) {
7498 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_integral_or_enumeral)
7499 << ArgType << Arg->getSourceRange();
7500 NoteTemplateParameterLocation(Decl: *Param);
7501 return ExprError();
7502 }
7503 if (!Arg->isValueDependent()) {
7504 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7505 QualType T;
7506
7507 public:
7508 TmplArgICEDiagnoser(QualType T) : T(T) { }
7509
7510 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7511 SourceLocation Loc) override {
7512 return S.Diag(Loc, DiagID: diag::err_template_arg_not_ice) << T;
7513 }
7514 } Diagnoser(ArgType);
7515
7516 Arg = VerifyIntegerConstantExpression(E: Arg, Result: &Value, Diagnoser).get();
7517 if (!Arg)
7518 return ExprError();
7519 }
7520
7521 // From here on out, all we care about is the unqualified form
7522 // of the argument type.
7523 ArgType = ArgType.getUnqualifiedType();
7524
7525 // Try to convert the argument to the parameter's type.
7526 if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
7527 // Okay: no conversion necessary
7528 } else if (ParamType->isBooleanType()) {
7529 // This is an integral-to-boolean conversion.
7530 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralToBoolean).get();
7531 } else if (IsIntegralPromotion(From: Arg, FromType: ArgType, ToType: ParamType) ||
7532 !ParamType->isEnumeralType()) {
7533 // This is an integral promotion or conversion.
7534 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralCast).get();
7535 } else {
7536 // We can't perform this conversion.
7537 Diag(Loc: StartLoc, DiagID: diag::err_template_arg_not_convertible)
7538 << Arg->getType() << ParamType << Arg->getSourceRange();
7539 NoteTemplateParameterLocation(Decl: *Param);
7540 return ExprError();
7541 }
7542
7543 // Add the value of this argument to the list of converted
7544 // arguments. We use the bitwidth and signedness of the template
7545 // parameter.
7546 if (Arg->isValueDependent()) {
7547 // The argument is value-dependent. Create a new
7548 // TemplateArgument with the converted expression.
7549 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7550 CanonicalConverted =
7551 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7552 return Arg;
7553 }
7554
7555 QualType IntegerType = ParamType;
7556 if (const auto *ED = IntegerType->getAsEnumDecl()) {
7557 IntegerType = ED->getIntegerType();
7558 }
7559
7560 if (ParamType->isBooleanType()) {
7561 // Value must be zero or one.
7562 Value = Value != 0;
7563 unsigned AllowedBits = Context.getTypeSize(T: IntegerType);
7564 if (Value.getBitWidth() != AllowedBits)
7565 Value = Value.extOrTrunc(width: AllowedBits);
7566 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7567 } else {
7568 llvm::APSInt OldValue = Value;
7569
7570 // Coerce the template argument's value to the value it will have
7571 // based on the template parameter's type.
7572 unsigned AllowedBits = IntegerType->isBitIntType()
7573 ? Context.getIntWidth(T: IntegerType)
7574 : Context.getTypeSize(T: IntegerType);
7575 if (Value.getBitWidth() != AllowedBits)
7576 Value = Value.extOrTrunc(width: AllowedBits);
7577 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7578
7579 // Complain if an unsigned parameter received a negative value.
7580 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7581 (OldValue.isSigned() && OldValue.isNegative())) {
7582 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_negative)
7583 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7584 << Arg->getSourceRange();
7585 NoteTemplateParameterLocation(Decl: *Param);
7586 }
7587
7588 // Complain if we overflowed the template parameter's type.
7589 unsigned RequiredBits;
7590 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7591 RequiredBits = OldValue.getActiveBits();
7592 else if (OldValue.isUnsigned())
7593 RequiredBits = OldValue.getActiveBits() + 1;
7594 else
7595 RequiredBits = OldValue.getSignificantBits();
7596 if (RequiredBits > AllowedBits) {
7597 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_too_large)
7598 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << ParamType
7599 << Arg->getSourceRange();
7600 NoteTemplateParameterLocation(Decl: *Param);
7601 }
7602 }
7603
7604 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7605 SugaredConverted = TemplateArgument(Context, Value, T);
7606 CanonicalConverted =
7607 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7608 return Arg;
7609 }
7610
7611 QualType ArgType = Arg->getType();
7612 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7613
7614 // Handle pointer-to-function, reference-to-function, and
7615 // pointer-to-member-function all in (roughly) the same way.
7616 if (// -- For a non-type template-parameter of type pointer to
7617 // function, only the function-to-pointer conversion (4.3) is
7618 // applied. If the template-argument represents a set of
7619 // overloaded functions (or a pointer to such), the matching
7620 // function is selected from the set (13.4).
7621 (ParamType->isPointerType() &&
7622 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7623 // -- For a non-type template-parameter of type reference to
7624 // function, no conversions apply. If the template-argument
7625 // represents a set of overloaded functions, the matching
7626 // function is selected from the set (13.4).
7627 (ParamType->isReferenceType() &&
7628 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7629 // -- For a non-type template-parameter of type pointer to
7630 // member function, no conversions apply. If the
7631 // template-argument represents a set of overloaded member
7632 // functions, the matching member function is selected from
7633 // the set (13.4).
7634 (ParamType->isMemberPointerType() &&
7635 ParamType->castAs<MemberPointerType>()->getPointeeType()
7636 ->isFunctionType())) {
7637
7638 if (Arg->getType() == Context.OverloadTy) {
7639 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg, TargetType: ParamType,
7640 Complain: true,
7641 Found&: FoundResult)) {
7642 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7643 return ExprError();
7644
7645 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7646 if (Res.isInvalid())
7647 return ExprError();
7648 Arg = Res.get();
7649 ArgType = Arg->getType();
7650 } else
7651 return ExprError();
7652 }
7653
7654 if (!ParamType->isMemberPointerType()) {
7655 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7656 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted,
7657 CanonicalConverted))
7658 return ExprError();
7659 return Arg;
7660 }
7661
7662 if (CheckTemplateArgumentPointerToMember(
7663 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7664 return ExprError();
7665 return Arg;
7666 }
7667
7668 if (ParamType->isPointerType()) {
7669 // -- for a non-type template-parameter of type pointer to
7670 // object, qualification conversions (4.4) and the
7671 // array-to-pointer conversion (4.2) are applied.
7672 // C++0x also allows a value of std::nullptr_t.
7673 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7674 "Only object pointers allowed here");
7675
7676 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7677 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted, CanonicalConverted))
7678 return ExprError();
7679 return Arg;
7680 }
7681
7682 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7683 // -- For a non-type template-parameter of type reference to
7684 // object, no conversions apply. The type referred to by the
7685 // reference may be more cv-qualified than the (otherwise
7686 // identical) type of the template-argument. The
7687 // template-parameter is bound directly to the
7688 // template-argument, which must be an lvalue.
7689 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7690 "Only object references allowed here");
7691
7692 if (Arg->getType() == Context.OverloadTy) {
7693 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg,
7694 TargetType: ParamRefType->getPointeeType(),
7695 Complain: true,
7696 Found&: FoundResult)) {
7697 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7698 return ExprError();
7699 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7700 if (Res.isInvalid())
7701 return ExprError();
7702 Arg = Res.get();
7703 ArgType = Arg->getType();
7704 } else
7705 return ExprError();
7706 }
7707
7708 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7709 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted, CanonicalConverted))
7710 return ExprError();
7711 return Arg;
7712 }
7713
7714 // Deal with parameters of type std::nullptr_t.
7715 if (ParamType->isNullPtrType()) {
7716 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7717 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7718 CanonicalConverted =
7719 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7720 return Arg;
7721 }
7722
7723 switch (isNullPointerValueTemplateArgument(S&: *this, Param, ParamType, Arg)) {
7724 case NPV_NotNullPointer:
7725 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_not_convertible)
7726 << Arg->getType() << ParamType;
7727 NoteTemplateParameterLocation(Decl: *Param);
7728 return ExprError();
7729
7730 case NPV_Error:
7731 return ExprError();
7732
7733 case NPV_NullPointer:
7734 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7735 SugaredConverted = TemplateArgument(ParamType,
7736 /*isNullPtr=*/true);
7737 CanonicalConverted = TemplateArgument(Context.getCanonicalType(T: ParamType),
7738 /*isNullPtr=*/true);
7739 return Arg;
7740 }
7741 }
7742
7743 // -- For a non-type template-parameter of type pointer to data
7744 // member, qualification conversions (4.4) are applied.
7745 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7746
7747 if (CheckTemplateArgumentPointerToMember(
7748 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7749 return ExprError();
7750 return Arg;
7751}
7752
7753static void DiagnoseTemplateParameterListArityMismatch(
7754 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7755 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7756
7757bool Sema::CheckDeclCompatibleWithTemplateTemplate(
7758 TemplateDecl *Template, TemplateTemplateParmDecl *Param,
7759 const TemplateArgumentLoc &Arg) {
7760 // C++0x [temp.arg.template]p1:
7761 // A template-argument for a template template-parameter shall be
7762 // the name of a class template or an alias template, expressed as an
7763 // id-expression. When the template-argument names a class template, only
7764 // primary class templates are considered when matching the
7765 // template template argument with the corresponding parameter;
7766 // partial specializations are not considered even if their
7767 // parameter lists match that of the template template parameter.
7768 //
7769
7770 TemplateNameKind Kind = TNK_Non_template;
7771 unsigned DiagFoundKind = 0;
7772
7773 if (auto *TTP = llvm::dyn_cast<TemplateTemplateParmDecl>(Val: Template)) {
7774 switch (TTP->templateParameterKind()) {
7775 case TemplateNameKind::TNK_Concept_template:
7776 DiagFoundKind = 3;
7777 break;
7778 case TemplateNameKind::TNK_Var_template:
7779 DiagFoundKind = 2;
7780 break;
7781 default:
7782 DiagFoundKind = 1;
7783 break;
7784 }
7785 Kind = TTP->templateParameterKind();
7786 } else if (isa<ConceptDecl>(Val: Template)) {
7787 Kind = TemplateNameKind::TNK_Concept_template;
7788 DiagFoundKind = 3;
7789 } else if (isa<FunctionTemplateDecl>(Val: Template)) {
7790 Kind = TemplateNameKind::TNK_Function_template;
7791 DiagFoundKind = 0;
7792 } else if (isa<VarTemplateDecl>(Val: Template)) {
7793 Kind = TemplateNameKind::TNK_Var_template;
7794 DiagFoundKind = 2;
7795 } else if (isa<ClassTemplateDecl>(Val: Template) ||
7796 isa<TypeAliasTemplateDecl>(Val: Template) ||
7797 isa<BuiltinTemplateDecl>(Val: Template)) {
7798 Kind = TemplateNameKind::TNK_Type_template;
7799 DiagFoundKind = 1;
7800 } else {
7801 assert(false && "Unexpected Decl");
7802 }
7803
7804 if (Kind == Param->templateParameterKind()) {
7805 return true;
7806 }
7807
7808 unsigned DiagKind = 0;
7809 switch (Param->templateParameterKind()) {
7810 case TemplateNameKind::TNK_Concept_template:
7811 DiagKind = 2;
7812 break;
7813 case TemplateNameKind::TNK_Var_template:
7814 DiagKind = 1;
7815 break;
7816 default:
7817 DiagKind = 0;
7818 break;
7819 }
7820 Diag(Loc: Arg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
7821 << DiagKind;
7822 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_arg_refers_to_template_here)
7823 << DiagFoundKind << Template;
7824 return false;
7825}
7826
7827/// Check a template argument against its corresponding
7828/// template template parameter.
7829///
7830/// This routine implements the semantics of C++ [temp.arg.template].
7831/// It returns true if an error occurred, and false otherwise.
7832bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7833 TemplateParameterList *Params,
7834 TemplateArgumentLoc &Arg,
7835 bool PartialOrdering,
7836 bool *StrictPackMatch) {
7837 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7838 auto [UnderlyingName, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7839 TemplateDecl *Template = UnderlyingName.getAsTemplateDecl();
7840 if (!Template) {
7841 // FIXME: Handle AssumedTemplateNames
7842 // Any dependent template name is fine.
7843 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7844 return false;
7845 }
7846
7847 if (Template->isInvalidDecl())
7848 return true;
7849
7850 if (!CheckDeclCompatibleWithTemplateTemplate(Template, Param, Arg)) {
7851 return true;
7852 }
7853
7854 // C++1z [temp.arg.template]p3: (DR 150)
7855 // A template-argument matches a template template-parameter P when P
7856 // is at least as specialized as the template-argument A.
7857 if (!isTemplateTemplateParameterAtLeastAsSpecializedAs(
7858 PParam: Params, PArg: Param, AArg: Template, DefaultArgs, ArgLoc: Arg.getLocation(),
7859 PartialOrdering, StrictPackMatch))
7860 return true;
7861 // P2113
7862 // C++20[temp.func.order]p2
7863 // [...] If both deductions succeed, the partial ordering selects the
7864 // more constrained template (if one exists) as determined below.
7865 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7866 Params->getAssociatedConstraints(AC&: ParamsAC);
7867 // C++20[temp.arg.template]p3
7868 // [...] In this comparison, if P is unconstrained, the constraints on A
7869 // are not considered.
7870 if (ParamsAC.empty())
7871 return false;
7872
7873 Template->getAssociatedConstraints(AC&: TemplateAC);
7874
7875 bool IsParamAtLeastAsConstrained;
7876 if (IsAtLeastAsConstrained(D1: Param, AC1: ParamsAC, D2: Template, AC2: TemplateAC,
7877 Result&: IsParamAtLeastAsConstrained))
7878 return true;
7879 if (!IsParamAtLeastAsConstrained) {
7880 Diag(Loc: Arg.getLocation(),
7881 DiagID: diag::err_template_template_parameter_not_at_least_as_constrained)
7882 << Template << Param << Arg.getSourceRange();
7883 Diag(Loc: Param->getLocation(), DiagID: diag::note_entity_declared_at) << Param;
7884 Diag(Loc: Template->getLocation(), DiagID: diag::note_entity_declared_at) << Template;
7885 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Param, AC1: ParamsAC, D2: Template,
7886 AC2: TemplateAC);
7887 return true;
7888 }
7889 return false;
7890}
7891
7892static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7893 unsigned HereDiagID,
7894 unsigned ExternalDiagID) {
7895 if (Decl.getLocation().isValid())
7896 return S.Diag(Loc: Decl.getLocation(), DiagID: HereDiagID);
7897
7898 SmallString<128> Str;
7899 llvm::raw_svector_ostream Out(Str);
7900 PrintingPolicy PP = S.getPrintingPolicy();
7901 PP.TerseOutput = 1;
7902 Decl.print(Out, Policy: PP);
7903 return S.Diag(Loc: Decl.getLocation(), DiagID: ExternalDiagID) << Out.str();
7904}
7905
7906void Sema::NoteTemplateLocation(const NamedDecl &Decl,
7907 std::optional<SourceRange> ParamRange) {
7908 SemaDiagnosticBuilder DB =
7909 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_decl_here,
7910 ExternalDiagID: diag::note_template_decl_external);
7911 if (ParamRange && ParamRange->isValid()) {
7912 assert(Decl.getLocation().isValid() &&
7913 "Parameter range has location when Decl does not");
7914 DB << *ParamRange;
7915 }
7916}
7917
7918void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
7919 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_param_here,
7920 ExternalDiagID: diag::note_template_param_external);
7921}
7922
7923/// Given a non-type template argument that refers to a
7924/// declaration and the type of its corresponding non-type template
7925/// parameter, produce an expression that properly refers to that
7926/// declaration.
7927ExprResult Sema::BuildExpressionFromDeclTemplateArgument(
7928 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7929 NamedDecl *TemplateParam) {
7930 // C++ [temp.param]p8:
7931 //
7932 // A non-type template-parameter of type "array of T" or
7933 // "function returning T" is adjusted to be of type "pointer to
7934 // T" or "pointer to function returning T", respectively.
7935 if (ParamType->isArrayType())
7936 ParamType = Context.getArrayDecayedType(T: ParamType);
7937 else if (ParamType->isFunctionType())
7938 ParamType = Context.getPointerType(T: ParamType);
7939
7940 // For a NULL non-type template argument, return nullptr casted to the
7941 // parameter's type.
7942 if (Arg.getKind() == TemplateArgument::NullPtr) {
7943 return ImpCastExprToType(
7944 E: new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7945 Type: ParamType,
7946 CK: ParamType->getAs<MemberPointerType>()
7947 ? CK_NullToMemberPointer
7948 : CK_NullToPointer);
7949 }
7950 assert(Arg.getKind() == TemplateArgument::Declaration &&
7951 "Only declaration template arguments permitted here");
7952
7953 ValueDecl *VD = Arg.getAsDecl();
7954
7955 CXXScopeSpec SS;
7956 if (ParamType->isMemberPointerType()) {
7957 // If this is a pointer to member, we need to use a qualified name to
7958 // form a suitable pointer-to-member constant.
7959 assert(VD->getDeclContext()->isRecord() &&
7960 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7961 isa<IndirectFieldDecl>(VD)));
7962 CanQualType ClassType =
7963 Context.getCanonicalTagType(TD: cast<RecordDecl>(Val: VD->getDeclContext()));
7964 NestedNameSpecifier Qualifier(ClassType.getTypePtr());
7965 SS.MakeTrivial(Context, Qualifier, R: Loc);
7966 }
7967
7968 ExprResult RefExpr = BuildDeclarationNameExpr(
7969 SS, NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
7970 if (RefExpr.isInvalid())
7971 return ExprError();
7972
7973 // For a pointer, the argument declaration is the pointee. Take its address.
7974 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7975 if (ParamType->isPointerType() && !ElemT.isNull() &&
7976 Context.hasSimilarType(T1: ElemT, T2: ParamType->getPointeeType())) {
7977 // Decay an array argument if we want a pointer to its first element.
7978 RefExpr = DefaultFunctionArrayConversion(E: RefExpr.get());
7979 if (RefExpr.isInvalid())
7980 return ExprError();
7981 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7982 // For any other pointer, take the address (or form a pointer-to-member).
7983 RefExpr = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_AddrOf, InputExpr: RefExpr.get());
7984 if (RefExpr.isInvalid())
7985 return ExprError();
7986 } else if (ParamType->isRecordType()) {
7987 assert(isa<TemplateParamObjectDecl>(VD) &&
7988 "arg for class template param not a template parameter object");
7989 // No conversions apply in this case.
7990 return RefExpr;
7991 } else {
7992 assert(ParamType->isReferenceType() &&
7993 "unexpected type for decl template argument");
7994 if (NonTypeTemplateParmDecl *NTTP =
7995 dyn_cast_if_present<NonTypeTemplateParmDecl>(Val: TemplateParam)) {
7996 QualType TemplateParamType = NTTP->getType();
7997 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7998 if (AT && AT->isDecltypeAuto()) {
7999 RefExpr = new (getASTContext()) SubstNonTypeTemplateParmExpr(
8000 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
8001 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
8002 /*PackIndex=*/std::nullopt,
8003 /*RefParam=*/true, /*Final=*/true);
8004 }
8005 }
8006 }
8007
8008 // At this point we should have the right value category.
8009 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8010 "value kind mismatch for non-type template argument");
8011
8012 // The type of the template parameter can differ from the type of the
8013 // argument in various ways; convert it now if necessary.
8014 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8015 if (!Context.hasSameType(T1: RefExpr.get()->getType(), T2: DestExprType)) {
8016 CastKind CK;
8017 if (Context.hasSimilarType(T1: RefExpr.get()->getType(), T2: DestExprType) ||
8018 IsFunctionConversion(FromType: RefExpr.get()->getType(), ToType: DestExprType)) {
8019 CK = CK_NoOp;
8020 } else if (ParamType->isVoidPointerType() &&
8021 RefExpr.get()->getType()->isPointerType()) {
8022 CK = CK_BitCast;
8023 } else {
8024 // FIXME: Pointers to members can need conversion derived-to-base or
8025 // base-to-derived conversions. We currently don't retain enough
8026 // information to convert properly (we need to track a cast path or
8027 // subobject number in the template argument).
8028 llvm_unreachable(
8029 "unexpected conversion required for non-type template argument");
8030 }
8031 RefExpr = ImpCastExprToType(E: RefExpr.get(), Type: DestExprType, CK,
8032 VK: RefExpr.get()->getValueKind());
8033 }
8034
8035 return RefExpr;
8036}
8037
8038/// Construct a new expression that refers to the given
8039/// integral template argument with the given source-location
8040/// information.
8041///
8042/// This routine takes care of the mapping from an integral template
8043/// argument (which may have any integral type) to the appropriate
8044/// literal value.
8045static Expr *BuildExpressionFromIntegralTemplateArgumentValue(
8046 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8047 assert(OrigT->isIntegralOrEnumerationType());
8048
8049 // If this is an enum type that we're instantiating, we need to use an integer
8050 // type the same size as the enumerator. We don't want to build an
8051 // IntegerLiteral with enum type. The integer type of an enum type can be of
8052 // any integral type with C++11 enum classes, make sure we create the right
8053 // type of literal for it.
8054 QualType T = OrigT;
8055 if (const auto *ED = OrigT->getAsEnumDecl())
8056 T = ED->getIntegerType();
8057
8058 Expr *E;
8059 if (T->isAnyCharacterType()) {
8060 CharacterLiteralKind Kind;
8061 if (T->isWideCharType())
8062 Kind = CharacterLiteralKind::Wide;
8063 else if (T->isChar8Type() && S.getLangOpts().Char8)
8064 Kind = CharacterLiteralKind::UTF8;
8065 else if (T->isChar16Type())
8066 Kind = CharacterLiteralKind::UTF16;
8067 else if (T->isChar32Type())
8068 Kind = CharacterLiteralKind::UTF32;
8069 else
8070 Kind = CharacterLiteralKind::Ascii;
8071
8072 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8073 } else if (T->isBooleanType()) {
8074 E = CXXBoolLiteralExpr::Create(C: S.Context, Val: Int.getBoolValue(), Ty: T, Loc);
8075 } else {
8076 E = IntegerLiteral::Create(C: S.Context, V: Int, type: T, l: Loc);
8077 }
8078
8079 if (OrigT->isEnumeralType()) {
8080 // FIXME: This is a hack. We need a better way to handle substituted
8081 // non-type template parameters.
8082 E = CStyleCastExpr::Create(Context: S.Context, T: OrigT, VK: VK_PRValue, K: CK_IntegralCast, Op: E,
8083 BasePath: nullptr, FPO: S.CurFPFeatureOverrides(),
8084 WrittenTy: S.Context.getTrivialTypeSourceInfo(T: OrigT, Loc),
8085 L: Loc, R: Loc);
8086 }
8087
8088 return E;
8089}
8090
8091static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(
8092 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8093 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8094 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
8095 ILE->setType(T);
8096 return ILE;
8097 };
8098
8099 switch (Val.getKind()) {
8100 case APValue::AddrLabelDiff:
8101 // This cannot occur in a template argument at all.
8102 case APValue::Array:
8103 case APValue::Struct:
8104 case APValue::Union:
8105 // These can only occur within a template parameter object, which is
8106 // represented as a TemplateArgument::Declaration.
8107 llvm_unreachable("unexpected template argument value");
8108
8109 case APValue::Int:
8110 return BuildExpressionFromIntegralTemplateArgumentValue(S, OrigT: T, Int: Val.getInt(),
8111 Loc);
8112
8113 case APValue::Float:
8114 return FloatingLiteral::Create(C: S.Context, V: Val.getFloat(), /*IsExact=*/isexact: true,
8115 Type: T, L: Loc);
8116
8117 case APValue::FixedPoint:
8118 return FixedPointLiteral::CreateFromRawInt(
8119 C: S.Context, V: Val.getFixedPoint().getValue(), type: T, l: Loc,
8120 Scale: Val.getFixedPoint().getScale());
8121
8122 case APValue::ComplexInt: {
8123 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8124 return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(
8125 S, OrigT: ElemT, Int: Val.getComplexIntReal(), Loc),
8126 BuildExpressionFromIntegralTemplateArgumentValue(
8127 S, OrigT: ElemT, Int: Val.getComplexIntImag(), Loc)});
8128 }
8129
8130 case APValue::ComplexFloat: {
8131 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8132 return MakeInitList(
8133 {FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatReal(), isexact: true,
8134 Type: ElemT, L: Loc),
8135 FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatImag(), isexact: true,
8136 Type: ElemT, L: Loc)});
8137 }
8138
8139 case APValue::Vector: {
8140 QualType ElemT = T->castAs<VectorType>()->getElementType();
8141 llvm::SmallVector<Expr *, 8> Elts;
8142 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8143 Elts.push_back(Elt: BuildExpressionFromNonTypeTemplateArgumentValue(
8144 S, T: ElemT, Val: Val.getVectorElt(I), Loc));
8145 return MakeInitList(Elts);
8146 }
8147
8148 case APValue::Matrix:
8149 llvm_unreachable("Matrix template argument expression not yet supported");
8150
8151 case APValue::None:
8152 case APValue::Indeterminate:
8153 llvm_unreachable("Unexpected APValue kind.");
8154 case APValue::LValue:
8155 case APValue::MemberPointer:
8156 // There isn't necessarily a valid equivalent source-level syntax for
8157 // these; in particular, a naive lowering might violate access control.
8158 // So for now we lower to a ConstantExpr holding the value, wrapped around
8159 // an OpaqueValueExpr.
8160 // FIXME: We should have a better representation for this.
8161 ExprValueKind VK = VK_PRValue;
8162 if (T->isReferenceType()) {
8163 T = T->getPointeeType();
8164 VK = VK_LValue;
8165 }
8166 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8167 return ConstantExpr::Create(Context: S.Context, E: OVE, Result: Val);
8168 }
8169 llvm_unreachable("Unhandled APValue::ValueKind enum");
8170}
8171
8172ExprResult
8173Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
8174 SourceLocation Loc) {
8175 switch (Arg.getKind()) {
8176 case TemplateArgument::Null:
8177 case TemplateArgument::Type:
8178 case TemplateArgument::Template:
8179 case TemplateArgument::TemplateExpansion:
8180 case TemplateArgument::Pack:
8181 llvm_unreachable("not a non-type template argument");
8182
8183 case TemplateArgument::Expression:
8184 return Arg.getAsExpr();
8185
8186 case TemplateArgument::NullPtr:
8187 case TemplateArgument::Declaration:
8188 return BuildExpressionFromDeclTemplateArgument(
8189 Arg, ParamType: Arg.getNonTypeTemplateArgumentType(), Loc);
8190
8191 case TemplateArgument::Integral:
8192 return BuildExpressionFromIntegralTemplateArgumentValue(
8193 S&: *this, OrigT: Arg.getIntegralType(), Int: Arg.getAsIntegral(), Loc);
8194
8195 case TemplateArgument::StructuralValue:
8196 return BuildExpressionFromNonTypeTemplateArgumentValue(
8197 S&: *this, T: Arg.getStructuralValueType(), Val: Arg.getAsStructuralValue(), Loc);
8198 }
8199 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8200}
8201
8202/// Match two template parameters within template parameter lists.
8203static bool MatchTemplateParameterKind(
8204 Sema &S, NamedDecl *New,
8205 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8206 const NamedDecl *OldInstFrom, bool Complain,
8207 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8208 // Check the actual kind (type, non-type, template).
8209 if (Old->getKind() != New->getKind()) {
8210 if (Complain) {
8211 unsigned NextDiag = diag::err_template_param_different_kind;
8212 if (TemplateArgLoc.isValid()) {
8213 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8214 NextDiag = diag::note_template_param_different_kind;
8215 }
8216 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8217 << (Kind != Sema::TPL_TemplateMatch);
8218 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_prev_declaration)
8219 << (Kind != Sema::TPL_TemplateMatch);
8220 }
8221
8222 return false;
8223 }
8224
8225 // Check that both are parameter packs or neither are parameter packs.
8226 // However, if we are matching a template template argument to a
8227 // template template parameter, the template template parameter can have
8228 // a parameter pack where the template template argument does not.
8229 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
8230 if (Complain) {
8231 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8232 if (TemplateArgLoc.isValid()) {
8233 S.Diag(Loc: TemplateArgLoc,
8234 DiagID: diag::err_template_arg_template_params_mismatch);
8235 NextDiag = diag::note_template_parameter_pack_non_pack;
8236 }
8237
8238 unsigned ParamKind = isa<TemplateTypeParmDecl>(Val: New)? 0
8239 : isa<NonTypeTemplateParmDecl>(Val: New)? 1
8240 : 2;
8241 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8242 << ParamKind << New->isParameterPack();
8243 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_parameter_pack_here)
8244 << ParamKind << Old->isParameterPack();
8245 }
8246
8247 return false;
8248 }
8249 // For non-type template parameters, check the type of the parameter.
8250 if (NonTypeTemplateParmDecl *OldNTTP =
8251 dyn_cast<NonTypeTemplateParmDecl>(Val: Old)) {
8252 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(Val: New);
8253
8254 // If we are matching a template template argument to a template
8255 // template parameter and one of the non-type template parameter types
8256 // is dependent, then we must wait until template instantiation time
8257 // to actually compare the arguments.
8258 if (Kind != Sema::TPL_TemplateTemplateParmMatch ||
8259 (!OldNTTP->getType()->isDependentType() &&
8260 !NewNTTP->getType()->isDependentType())) {
8261 // C++20 [temp.over.link]p6:
8262 // Two [non-type] template-parameters are equivalent [if] they have
8263 // equivalent types ignoring the use of type-constraints for
8264 // placeholder types
8265 QualType OldType = S.Context.getUnconstrainedType(T: OldNTTP->getType());
8266 QualType NewType = S.Context.getUnconstrainedType(T: NewNTTP->getType());
8267 if (!S.Context.hasSameType(T1: OldType, T2: NewType)) {
8268 if (Complain) {
8269 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8270 if (TemplateArgLoc.isValid()) {
8271 S.Diag(Loc: TemplateArgLoc,
8272 DiagID: diag::err_template_arg_template_params_mismatch);
8273 NextDiag = diag::note_template_nontype_parm_different_type;
8274 }
8275 S.Diag(Loc: NewNTTP->getLocation(), DiagID: NextDiag)
8276 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8277 S.Diag(Loc: OldNTTP->getLocation(),
8278 DiagID: diag::note_template_nontype_parm_prev_declaration)
8279 << OldNTTP->getType();
8280 }
8281 return false;
8282 }
8283 }
8284 }
8285 // For template template parameters, check the template parameter types.
8286 // The template parameter lists of template template
8287 // parameters must agree.
8288 else if (TemplateTemplateParmDecl *OldTTP =
8289 dyn_cast<TemplateTemplateParmDecl>(Val: Old)) {
8290 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(Val: New);
8291 if (OldTTP->templateParameterKind() != NewTTP->templateParameterKind())
8292 return false;
8293 if (!S.TemplateParameterListsAreEqual(
8294 NewInstFrom, New: NewTTP->getTemplateParameters(), OldInstFrom,
8295 Old: OldTTP->getTemplateParameters(), Complain,
8296 Kind: (Kind == Sema::TPL_TemplateMatch
8297 ? Sema::TPL_TemplateTemplateParmMatch
8298 : Kind),
8299 TemplateArgLoc))
8300 return false;
8301 }
8302
8303 if (Kind != Sema::TPL_TemplateParamsEquivalent &&
8304 Kind != Sema::TPL_TemplateTemplateParmMatch &&
8305 !isa<TemplateTemplateParmDecl>(Val: Old)) {
8306 const Expr *NewC = nullptr, *OldC = nullptr;
8307
8308 if (isa<TemplateTypeParmDecl>(Val: New)) {
8309 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: New)->getTypeConstraint())
8310 NewC = TC->getImmediatelyDeclaredConstraint();
8311 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: Old)->getTypeConstraint())
8312 OldC = TC->getImmediatelyDeclaredConstraint();
8313 } else if (isa<NonTypeTemplateParmDecl>(Val: New)) {
8314 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: New)
8315 ->getPlaceholderTypeConstraint())
8316 NewC = E;
8317 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: Old)
8318 ->getPlaceholderTypeConstraint())
8319 OldC = E;
8320 } else
8321 llvm_unreachable("unexpected template parameter type");
8322
8323 auto Diagnose = [&] {
8324 S.Diag(Loc: NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8325 DiagID: diag::err_template_different_type_constraint);
8326 S.Diag(Loc: OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8327 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8328 };
8329
8330 if (!NewC != !OldC) {
8331 if (Complain)
8332 Diagnose();
8333 return false;
8334 }
8335
8336 if (NewC) {
8337 if (!S.AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldC, New: NewInstFrom,
8338 NewConstr: NewC)) {
8339 if (Complain)
8340 Diagnose();
8341 return false;
8342 }
8343 }
8344 }
8345
8346 return true;
8347}
8348
8349/// Diagnose a known arity mismatch when comparing template argument
8350/// lists.
8351static
8352void DiagnoseTemplateParameterListArityMismatch(Sema &S,
8353 TemplateParameterList *New,
8354 TemplateParameterList *Old,
8355 Sema::TemplateParameterListEqualKind Kind,
8356 SourceLocation TemplateArgLoc) {
8357 unsigned NextDiag = diag::err_template_param_list_different_arity;
8358 if (TemplateArgLoc.isValid()) {
8359 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8360 NextDiag = diag::note_template_param_list_different_arity;
8361 }
8362 S.Diag(Loc: New->getTemplateLoc(), DiagID: NextDiag)
8363 << (New->size() > Old->size())
8364 << (Kind != Sema::TPL_TemplateMatch)
8365 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8366 S.Diag(Loc: Old->getTemplateLoc(), DiagID: diag::note_template_prev_declaration)
8367 << (Kind != Sema::TPL_TemplateMatch)
8368 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8369}
8370
8371bool Sema::TemplateParameterListsAreEqual(
8372 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8373 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8374 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8375 if (Old->size() != New->size()) {
8376 if (Complain)
8377 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8378 TemplateArgLoc);
8379
8380 return false;
8381 }
8382
8383 // C++0x [temp.arg.template]p3:
8384 // A template-argument matches a template template-parameter (call it P)
8385 // when each of the template parameters in the template-parameter-list of
8386 // the template-argument's corresponding class template or alias template
8387 // (call it A) matches the corresponding template parameter in the
8388 // template-parameter-list of P. [...]
8389 TemplateParameterList::iterator NewParm = New->begin();
8390 TemplateParameterList::iterator NewParmEnd = New->end();
8391 for (TemplateParameterList::iterator OldParm = Old->begin(),
8392 OldParmEnd = Old->end();
8393 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8394 if (NewParm == NewParmEnd) {
8395 if (Complain)
8396 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8397 TemplateArgLoc);
8398 return false;
8399 }
8400 if (!MatchTemplateParameterKind(S&: *this, New: *NewParm, NewInstFrom, Old: *OldParm,
8401 OldInstFrom, Complain, Kind,
8402 TemplateArgLoc))
8403 return false;
8404 }
8405
8406 // Make sure we exhausted all of the arguments.
8407 if (NewParm != NewParmEnd) {
8408 if (Complain)
8409 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8410 TemplateArgLoc);
8411
8412 return false;
8413 }
8414
8415 if (Kind != TPL_TemplateParamsEquivalent) {
8416 const Expr *NewRC = New->getRequiresClause();
8417 const Expr *OldRC = Old->getRequiresClause();
8418
8419 auto Diagnose = [&] {
8420 Diag(Loc: NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8421 DiagID: diag::err_template_different_requires_clause);
8422 Diag(Loc: OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8423 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8424 };
8425
8426 if (!NewRC != !OldRC) {
8427 if (Complain)
8428 Diagnose();
8429 return false;
8430 }
8431
8432 if (NewRC) {
8433 if (!AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldRC, New: NewInstFrom,
8434 NewConstr: NewRC)) {
8435 if (Complain)
8436 Diagnose();
8437 return false;
8438 }
8439 }
8440 }
8441
8442 return true;
8443}
8444
8445bool
8446Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
8447 if (!S)
8448 return false;
8449
8450 // Find the nearest enclosing declaration scope.
8451 S = S->getDeclParent();
8452
8453 // C++ [temp.pre]p6: [P2096]
8454 // A template, explicit specialization, or partial specialization shall not
8455 // have C linkage.
8456 DeclContext *Ctx = S->getEntity();
8457 if (Ctx && Ctx->isExternCContext()) {
8458 SourceRange Range =
8459 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8460 ? TemplateParams->getParam(Idx: 0)->getSourceRange()
8461 : TemplateParams->getSourceRange();
8462 Diag(Loc: Range.getBegin(), DiagID: diag::err_template_linkage) << Range;
8463 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8464 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
8465 return true;
8466 }
8467 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8468
8469 // C++ [temp]p2:
8470 // A template-declaration can appear only as a namespace scope or
8471 // class scope declaration.
8472 // C++ [temp.expl.spec]p3:
8473 // An explicit specialization may be declared in any scope in which the
8474 // corresponding primary template may be defined.
8475 // C++ [temp.class.spec]p6: [P2096]
8476 // A partial specialization may be declared in any scope in which the
8477 // corresponding primary template may be defined.
8478 if (Ctx) {
8479 if (Ctx->isFileContext())
8480 return false;
8481 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Ctx)) {
8482 // C++ [temp.mem]p2:
8483 // A local class shall not have member templates.
8484 if (RD->isLocalClass())
8485 return Diag(Loc: TemplateParams->getTemplateLoc(),
8486 DiagID: diag::err_template_inside_local_class)
8487 << TemplateParams->getSourceRange();
8488 else
8489 return false;
8490 }
8491 }
8492
8493 return Diag(Loc: TemplateParams->getTemplateLoc(),
8494 DiagID: diag::err_template_outside_namespace_or_class_scope)
8495 << TemplateParams->getSourceRange();
8496}
8497
8498/// Determine what kind of template specialization the given declaration
8499/// is.
8500static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8501 if (!D)
8502 return TSK_Undeclared;
8503
8504 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D))
8505 return Record->getTemplateSpecializationKind();
8506 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D))
8507 return Function->getTemplateSpecializationKind();
8508 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D))
8509 return Var->getTemplateSpecializationKind();
8510
8511 return TSK_Undeclared;
8512}
8513
8514/// Check whether a specialization is well-formed in the current
8515/// context.
8516///
8517/// This routine determines whether a template specialization can be declared
8518/// in the current context (C++ [temp.expl.spec]p2).
8519///
8520/// \param S the semantic analysis object for which this check is being
8521/// performed.
8522///
8523/// \param Specialized the entity being specialized or instantiated, which
8524/// may be a kind of template (class template, function template, etc.) or
8525/// a member of a class template (member function, static data member,
8526/// member class).
8527///
8528/// \param PrevDecl the previous declaration of this entity, if any.
8529///
8530/// \param Loc the location of the explicit specialization or instantiation of
8531/// this entity.
8532///
8533/// \param IsPartialSpecialization whether this is a partial specialization of
8534/// a class template.
8535///
8536/// \returns true if there was an error that we cannot recover from, false
8537/// otherwise.
8538static bool CheckTemplateSpecializationScope(Sema &S,
8539 NamedDecl *Specialized,
8540 NamedDecl *PrevDecl,
8541 SourceLocation Loc,
8542 bool IsPartialSpecialization) {
8543 // Keep these "kind" numbers in sync with the %select statements in the
8544 // various diagnostics emitted by this routine.
8545 int EntityKind = 0;
8546 if (isa<ClassTemplateDecl>(Val: Specialized))
8547 EntityKind = IsPartialSpecialization? 1 : 0;
8548 else if (isa<VarTemplateDecl>(Val: Specialized))
8549 EntityKind = IsPartialSpecialization ? 3 : 2;
8550 else if (isa<FunctionTemplateDecl>(Val: Specialized))
8551 EntityKind = 4;
8552 else if (isa<CXXMethodDecl>(Val: Specialized))
8553 EntityKind = 5;
8554 else if (isa<VarDecl>(Val: Specialized))
8555 EntityKind = 6;
8556 else if (isa<RecordDecl>(Val: Specialized))
8557 EntityKind = 7;
8558 else if (isa<EnumDecl>(Val: Specialized) && S.getLangOpts().CPlusPlus11)
8559 EntityKind = 8;
8560 else {
8561 S.Diag(Loc, DiagID: diag::err_template_spec_unknown_kind)
8562 << S.getLangOpts().CPlusPlus11;
8563 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8564 return true;
8565 }
8566
8567 // C++ [temp.expl.spec]p2:
8568 // An explicit specialization may be declared in any scope in which
8569 // the corresponding primary template may be defined.
8570 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8571 S.Diag(Loc, DiagID: diag::err_template_spec_decl_function_scope)
8572 << Specialized;
8573 return true;
8574 }
8575
8576 // C++ [temp.class.spec]p6:
8577 // A class template partial specialization may be declared in any
8578 // scope in which the primary template may be defined.
8579 DeclContext *SpecializedContext =
8580 Specialized->getDeclContext()->getRedeclContext();
8581 DeclContext *DC = S.CurContext->getRedeclContext();
8582
8583 // Make sure that this redeclaration (or definition) occurs in the same
8584 // scope or an enclosing namespace.
8585 if (!(DC->isFileContext() ? DC->Encloses(DC: SpecializedContext)
8586 : DC->Equals(DC: SpecializedContext))) {
8587 if (isa<TranslationUnitDecl>(Val: SpecializedContext))
8588 S.Diag(Loc, DiagID: diag::err_template_spec_redecl_global_scope)
8589 << EntityKind << Specialized;
8590 else {
8591 auto *ND = cast<NamedDecl>(Val: SpecializedContext);
8592 int Diag = diag::err_template_spec_redecl_out_of_scope;
8593 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8594 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8595 S.Diag(Loc, DiagID: Diag) << EntityKind << Specialized
8596 << ND << isa<CXXRecordDecl>(Val: ND);
8597 }
8598
8599 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8600
8601 // Don't allow specializing in the wrong class during error recovery.
8602 // Otherwise, things can go horribly wrong.
8603 if (DC->isRecord())
8604 return true;
8605 }
8606
8607 return false;
8608}
8609
8610static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8611 if (!E->isTypeDependent())
8612 return SourceLocation();
8613 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8614 Checker.TraverseStmt(S: E);
8615 if (Checker.MatchLoc.isInvalid())
8616 return E->getSourceRange();
8617 return Checker.MatchLoc;
8618}
8619
8620static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8621 if (!TL.getType()->isDependentType())
8622 return SourceLocation();
8623 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8624 Checker.TraverseTypeLoc(TL);
8625 if (Checker.MatchLoc.isInvalid())
8626 return TL.getSourceRange();
8627 return Checker.MatchLoc;
8628}
8629
8630/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8631/// that checks non-type template partial specialization arguments.
8632static bool CheckNonTypeTemplatePartialSpecializationArgs(
8633 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8634 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8635 bool HasError = false;
8636 for (unsigned I = 0; I != NumArgs; ++I) {
8637 if (Args[I].getKind() == TemplateArgument::Pack) {
8638 if (CheckNonTypeTemplatePartialSpecializationArgs(
8639 S, TemplateNameLoc, Param, Args: Args[I].pack_begin(),
8640 NumArgs: Args[I].pack_size(), IsDefaultArgument))
8641 return true;
8642
8643 continue;
8644 }
8645
8646 if (Args[I].getKind() != TemplateArgument::Expression)
8647 continue;
8648
8649 Expr *ArgExpr = Args[I].getAsExpr();
8650 if (ArgExpr->containsErrors()) {
8651 HasError = true;
8652 continue;
8653 }
8654
8655 // We can have a pack expansion of any of the bullets below.
8656 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Val: ArgExpr))
8657 ArgExpr = Expansion->getPattern();
8658
8659 // Strip off any implicit casts we added as part of type checking.
8660 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
8661 ArgExpr = ICE->getSubExpr();
8662
8663 // C++ [temp.class.spec]p8:
8664 // A non-type argument is non-specialized if it is the name of a
8665 // non-type parameter. All other non-type arguments are
8666 // specialized.
8667 //
8668 // Below, we check the two conditions that only apply to
8669 // specialized non-type arguments, so skip any non-specialized
8670 // arguments.
8671 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ArgExpr))
8672 if (isa<NonTypeTemplateParmDecl>(Val: DRE->getDecl()))
8673 continue;
8674
8675 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ArgExpr);
8676 ULE && (ULE->isConceptReference() || ULE->isVarDeclReference())) {
8677 continue;
8678 }
8679
8680 // C++ [temp.class.spec]p9:
8681 // Within the argument list of a class template partial
8682 // specialization, the following restrictions apply:
8683 // -- A partially specialized non-type argument expression
8684 // shall not involve a template parameter of the partial
8685 // specialization except when the argument expression is a
8686 // simple identifier.
8687 // -- The type of a template parameter corresponding to a
8688 // specialized non-type argument shall not be dependent on a
8689 // parameter of the specialization.
8690 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8691 // We implement a compromise between the original rules and DR1315:
8692 // -- A specialized non-type template argument shall not be
8693 // type-dependent and the corresponding template parameter
8694 // shall have a non-dependent type.
8695 SourceRange ParamUseRange =
8696 findTemplateParameterInType(Depth: Param->getDepth(), E: ArgExpr);
8697 if (ParamUseRange.isValid()) {
8698 if (IsDefaultArgument) {
8699 S.Diag(Loc: TemplateNameLoc,
8700 DiagID: diag::err_dependent_non_type_arg_in_partial_spec);
8701 S.Diag(Loc: ParamUseRange.getBegin(),
8702 DiagID: diag::note_dependent_non_type_default_arg_in_partial_spec)
8703 << ParamUseRange;
8704 } else {
8705 S.Diag(Loc: ParamUseRange.getBegin(),
8706 DiagID: diag::err_dependent_non_type_arg_in_partial_spec)
8707 << ParamUseRange;
8708 }
8709 return true;
8710 }
8711
8712 ParamUseRange = findTemplateParameter(
8713 Depth: Param->getDepth(), TL: Param->getTypeSourceInfo()->getTypeLoc());
8714 if (ParamUseRange.isValid()) {
8715 S.Diag(Loc: IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8716 DiagID: diag::err_dependent_typed_non_type_arg_in_partial_spec)
8717 << Param->getType();
8718 S.NoteTemplateParameterLocation(Decl: *Param);
8719 return true;
8720 }
8721 }
8722
8723 return HasError;
8724}
8725
8726bool Sema::CheckTemplatePartialSpecializationArgs(
8727 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8728 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8729 // We have to be conservative when checking a template in a dependent
8730 // context.
8731 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8732 return false;
8733
8734 TemplateParameterList *TemplateParams =
8735 PrimaryTemplate->getTemplateParameters();
8736 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8737 NonTypeTemplateParmDecl *Param
8738 = dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: I));
8739 if (!Param)
8740 continue;
8741
8742 if (CheckNonTypeTemplatePartialSpecializationArgs(S&: *this, TemplateNameLoc,
8743 Param, Args: &TemplateArgs[I],
8744 NumArgs: 1, IsDefaultArgument: I >= NumExplicit))
8745 return true;
8746 }
8747
8748 return false;
8749}
8750
8751DeclResult Sema::ActOnClassTemplateSpecialization(
8752 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8753 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8754 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8755 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8756 assert(TUK != TagUseKind::Reference && "References are not specializations");
8757
8758 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8759 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8760 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8761
8762 // Find the class template we're specializing
8763 TemplateName Name = TemplateId.Template.get();
8764 ClassTemplateDecl *ClassTemplate
8765 = dyn_cast_or_null<ClassTemplateDecl>(Val: Name.getAsTemplateDecl());
8766
8767 if (!ClassTemplate) {
8768 Diag(Loc: TemplateNameLoc, DiagID: diag::err_not_class_template_specialization)
8769 << (Name.getAsTemplateDecl() &&
8770 isa<TemplateTemplateParmDecl>(Val: Name.getAsTemplateDecl()));
8771 return true;
8772 }
8773
8774 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8775 auto Message = DSA->getMessage();
8776 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
8777 << ClassTemplate << !Message.empty() << Message;
8778 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
8779 }
8780
8781 if (S->isTemplateParamScope())
8782 EnterTemplatedContext(S, DC: ClassTemplate->getTemplatedDecl());
8783
8784 DeclContext *DC = ClassTemplate->getDeclContext();
8785
8786 bool isMemberSpecialization = false;
8787 bool isPartialSpecialization = false;
8788
8789 if (SS.isSet()) {
8790 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8791 diagnoseQualifiedDeclaration(SS, DC, Name: ClassTemplate->getDeclName(),
8792 Loc: TemplateNameLoc, TemplateId: &TemplateId,
8793 /*IsMemberSpecialization=*/false))
8794 return true;
8795 }
8796
8797 // Check the validity of the template headers that introduce this
8798 // template.
8799 // FIXME: We probably shouldn't complain about these headers for
8800 // friend declarations.
8801 bool Invalid = false;
8802 TemplateParameterList *TemplateParams =
8803 MatchTemplateParametersToScopeSpecifier(
8804 DeclStartLoc: KWLoc, DeclLoc: TemplateNameLoc, SS, TemplateId: &TemplateId, ParamLists: TemplateParameterLists,
8805 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
8806 if (Invalid)
8807 return true;
8808
8809 // Check that we can declare a template specialization here.
8810 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8811 return true;
8812
8813 if (TemplateParams && DC->isDependentContext()) {
8814 ContextRAII SavedContext(*this, DC);
8815 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
8816 return true;
8817 }
8818
8819 if (TemplateParams && TemplateParams->size() > 0) {
8820 isPartialSpecialization = true;
8821
8822 if (TUK == TagUseKind::Friend) {
8823 Diag(Loc: KWLoc, DiagID: diag::err_partial_specialization_friend)
8824 << SourceRange(LAngleLoc, RAngleLoc);
8825 return true;
8826 }
8827
8828 // C++ [temp.class.spec]p10:
8829 // The template parameter list of a specialization shall not
8830 // contain default template argument values.
8831 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8832 Decl *Param = TemplateParams->getParam(Idx: I);
8833 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
8834 if (TTP->hasDefaultArgument()) {
8835 Diag(Loc: TTP->getDefaultArgumentLoc(),
8836 DiagID: diag::err_default_arg_in_partial_spec);
8837 TTP->removeDefaultArgument();
8838 }
8839 } else if (NonTypeTemplateParmDecl *NTTP
8840 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
8841 if (NTTP->hasDefaultArgument()) {
8842 Diag(Loc: NTTP->getDefaultArgumentLoc(),
8843 DiagID: diag::err_default_arg_in_partial_spec)
8844 << NTTP->getDefaultArgument().getSourceRange();
8845 NTTP->removeDefaultArgument();
8846 }
8847 } else {
8848 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
8849 if (TTP->hasDefaultArgument()) {
8850 Diag(Loc: TTP->getDefaultArgument().getLocation(),
8851 DiagID: diag::err_default_arg_in_partial_spec)
8852 << TTP->getDefaultArgument().getSourceRange();
8853 TTP->removeDefaultArgument();
8854 }
8855 }
8856 }
8857 } else if (TemplateParams) {
8858 if (TUK == TagUseKind::Friend)
8859 Diag(Loc: KWLoc, DiagID: diag::err_template_spec_friend)
8860 << FixItHint::CreateRemoval(
8861 RemoveRange: SourceRange(TemplateParams->getTemplateLoc(),
8862 TemplateParams->getRAngleLoc()))
8863 << SourceRange(LAngleLoc, RAngleLoc);
8864 } else {
8865 assert(TUK == TagUseKind::Friend &&
8866 "should have a 'template<>' for this decl");
8867 }
8868
8869 // Check that the specialization uses the same tag kind as the
8870 // original template.
8871 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
8872 assert(Kind != TagTypeKind::Enum &&
8873 "Invalid enum tag in class template spec!");
8874 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(), NewTag: Kind,
8875 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
8876 Name: ClassTemplate->getIdentifier())) {
8877 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
8878 << ClassTemplate
8879 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
8880 Code: ClassTemplate->getTemplatedDecl()->getKindName());
8881 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
8882 DiagID: diag::note_previous_use);
8883 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8884 }
8885
8886 // Translate the parser's template argument list in our AST format.
8887 TemplateArgumentListInfo TemplateArgs =
8888 makeTemplateArgumentListInfo(S&: *this, TemplateId);
8889
8890 // Check for unexpanded parameter packs in any of the template arguments.
8891 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8892 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
8893 UPPC: isPartialSpecialization
8894 ? UPPC_PartialSpecialization
8895 : UPPC_ExplicitSpecialization))
8896 return true;
8897
8898 // Check that the template argument list is well-formed for this
8899 // template.
8900 CheckTemplateArgumentInfo CTAI;
8901 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
8902 /*DefaultArgs=*/{},
8903 /*PartialTemplateArgs=*/false, CTAI,
8904 /*UpdateArgsWithConversions=*/true))
8905 return true;
8906
8907 // Find the class template (partial) specialization declaration that
8908 // corresponds to these arguments.
8909 if (isPartialSpecialization) {
8910 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, PrimaryTemplate: ClassTemplate,
8911 NumExplicit: TemplateArgs.size(),
8912 TemplateArgs: CTAI.CanonicalConverted))
8913 return true;
8914
8915 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8916 // also do it during instantiation.
8917 if (!Name.isDependent() &&
8918 !TemplateSpecializationType::anyDependentTemplateArguments(
8919 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
8920 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
8921 << ClassTemplate->getDeclName();
8922 isPartialSpecialization = false;
8923 Invalid = true;
8924 }
8925 }
8926
8927 void *InsertPos = nullptr;
8928 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8929
8930 if (isPartialSpecialization)
8931 PrevDecl = ClassTemplate->findPartialSpecialization(
8932 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertPos);
8933 else
8934 PrevDecl =
8935 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
8936
8937 ClassTemplateSpecializationDecl *Specialization = nullptr;
8938
8939 // Check whether we can declare a class template specialization in
8940 // the current scope.
8941 if (TUK != TagUseKind::Friend &&
8942 CheckTemplateSpecializationScope(S&: *this, Specialized: ClassTemplate, PrevDecl,
8943 Loc: TemplateNameLoc,
8944 IsPartialSpecialization: isPartialSpecialization))
8945 return true;
8946
8947 if (!isPartialSpecialization) {
8948 // Create a new class template specialization declaration node for
8949 // this explicit specialization or friend declaration.
8950 Specialization = ClassTemplateSpecializationDecl::Create(
8951 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
8952 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
8953 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8954 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
8955 if (TemplateParameterLists.size() > 0) {
8956 Specialization->setTemplateParameterListsInfo(Context,
8957 TPLists: TemplateParameterLists);
8958 }
8959
8960 if (!PrevDecl)
8961 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
8962 } else {
8963 CanQualType CanonType = CanQualType::CreateUnsafe(
8964 Other: Context.getCanonicalTemplateSpecializationType(
8965 Keyword: ElaboratedTypeKeyword::None,
8966 T: TemplateName(ClassTemplate->getCanonicalDecl()),
8967 CanonicalArgs: CTAI.CanonicalConverted));
8968 if (Context.hasSameType(
8969 T1: CanonType,
8970 T2: ClassTemplate->getCanonicalInjectedSpecializationType(Ctx: Context)) &&
8971 (!Context.getLangOpts().CPlusPlus20 ||
8972 !TemplateParams->hasAssociatedConstraints())) {
8973 // C++ [temp.class.spec]p9b3:
8974 //
8975 // -- The argument list of the specialization shall not be identical
8976 // to the implicit argument list of the primary template.
8977 //
8978 // This rule has since been removed, because it's redundant given DR1495,
8979 // but we keep it because it produces better diagnostics and recovery.
8980 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
8981 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8982 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
8983 return CheckClassTemplate(
8984 S, TagSpec, TUK, KWLoc, SS, Name: ClassTemplate->getIdentifier(),
8985 NameLoc: TemplateNameLoc, Attr, TemplateParams, AS: AS_none,
8986 /*ModulePrivateLoc=*/SourceLocation(),
8987 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
8988 OuterTemplateParamLists: TemplateParameterLists.data());
8989 }
8990
8991 // Create a new class template partial specialization declaration node.
8992 ClassTemplatePartialSpecializationDecl *PrevPartial =
8993 cast_or_null<ClassTemplatePartialSpecializationDecl>(Val: PrevDecl);
8994 ClassTemplatePartialSpecializationDecl *Partial =
8995 ClassTemplatePartialSpecializationDecl::Create(
8996 Context, TK: Kind, DC, StartLoc: KWLoc, IdLoc: TemplateNameLoc, Params: TemplateParams,
8997 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, CanonInjectedTST: CanonType, PrevDecl: PrevPartial);
8998 Partial->setTemplateArgsAsWritten(TemplateArgs);
8999 SetNestedNameSpecifier(S&: *this, T: Partial, SS);
9000 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9001 Partial->setTemplateParameterListsInfo(
9002 Context, TPLists: TemplateParameterLists.drop_back(N: 1));
9003 }
9004
9005 if (!PrevPartial)
9006 ClassTemplate->AddPartialSpecialization(D: Partial, InsertPos);
9007 Specialization = Partial;
9008
9009 // If we are providing an explicit specialization of a member class
9010 // template specialization, make a note of that.
9011 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
9012 PrevPartial->setMemberSpecialization();
9013
9014 CheckTemplatePartialSpecialization(Partial);
9015 }
9016
9017 // C++ [temp.expl.spec]p6:
9018 // If a template, a member template or the member of a class template is
9019 // explicitly specialized then that specialization shall be declared
9020 // before the first use of that specialization that would cause an implicit
9021 // instantiation to take place, in every translation unit in which such a
9022 // use occurs; no diagnostic is required.
9023 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9024 bool Okay = false;
9025 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9026 // Is there any previous explicit specialization declaration?
9027 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9028 Okay = true;
9029 break;
9030 }
9031 }
9032
9033 if (!Okay) {
9034 SourceRange Range(TemplateNameLoc, RAngleLoc);
9035 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
9036 << Context.getCanonicalTagType(TD: Specialization) << Range;
9037
9038 Diag(Loc: PrevDecl->getPointOfInstantiation(),
9039 DiagID: diag::note_instantiation_required_here)
9040 << (PrevDecl->getTemplateSpecializationKind()
9041 != TSK_ImplicitInstantiation);
9042 return true;
9043 }
9044 }
9045
9046 // If this is not a friend, note that this is an explicit specialization.
9047 if (TUK != TagUseKind::Friend)
9048 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9049
9050 // Check that this isn't a redefinition of this specialization.
9051 if (TUK == TagUseKind::Definition) {
9052 RecordDecl *Def = Specialization->getDefinition();
9053 NamedDecl *Hidden = nullptr;
9054 bool HiddenDefVisible = false;
9055 if (Def && SkipBody &&
9056 isRedefinitionAllowedFor(D: Def, Suggested: &Hidden, Visible&: HiddenDefVisible)) {
9057 SkipBody->ShouldSkip = true;
9058 SkipBody->Previous = Def;
9059 if (!HiddenDefVisible && Hidden)
9060 makeMergedDefinitionVisible(ND: Hidden);
9061 } else if (Def) {
9062 SourceRange Range(TemplateNameLoc, RAngleLoc);
9063 Diag(Loc: TemplateNameLoc, DiagID: diag::err_redefinition) << Specialization << Range;
9064 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
9065 Specialization->setInvalidDecl();
9066 return true;
9067 }
9068 }
9069
9070 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
9071 ProcessAPINotes(D: Specialization);
9072
9073 // Add alignment attributes if necessary; these attributes are checked when
9074 // the ASTContext lays out the structure.
9075 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9076 if (LangOpts.HLSL)
9077 Specialization->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
9078 AddAlignmentAttributesForRecord(RD: Specialization);
9079 AddMsStructLayoutForRecord(RD: Specialization);
9080 }
9081
9082 if (ModulePrivateLoc.isValid())
9083 Diag(Loc: Specialization->getLocation(), DiagID: diag::err_module_private_specialization)
9084 << (isPartialSpecialization? 1 : 0)
9085 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
9086
9087 // C++ [temp.expl.spec]p9:
9088 // A template explicit specialization is in the scope of the
9089 // namespace in which the template was defined.
9090 //
9091 // We actually implement this paragraph where we set the semantic
9092 // context (in the creation of the ClassTemplateSpecializationDecl),
9093 // but we also maintain the lexical context where the actual
9094 // definition occurs.
9095 Specialization->setLexicalDeclContext(CurContext);
9096
9097 // We may be starting the definition of this specialization.
9098 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
9099 Specialization->startDefinition();
9100
9101 if (TUK == TagUseKind::Friend) {
9102 CanQualType CanonType = Context.getCanonicalTagType(TD: Specialization);
9103 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
9104 Keyword: ElaboratedTypeKeyword::None, /*ElaboratedKeywordLoc=*/SourceLocation(),
9105 QualifierLoc: SS.getWithLocInContext(Context),
9106 /*TemplateKeywordLoc=*/SourceLocation(), T: Name, TLoc: TemplateNameLoc,
9107 SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted, Canon: CanonType);
9108
9109 // Build the fully-sugared type for this class template
9110 // specialization as the user wrote in the specialization
9111 // itself. This means that we'll pretty-print the type retrieved
9112 // from the specialization's declaration the way that the user
9113 // actually wrote the specialization, rather than formatting the
9114 // name based on the "canonical" representation used to store the
9115 // template arguments in the specialization.
9116 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext,
9117 L: TemplateNameLoc,
9118 Friend_: WrittenTy,
9119 /*FIXME:*/FriendL: KWLoc);
9120 Friend->setAccess(AS_public);
9121 CurContext->addDecl(D: Friend);
9122 } else {
9123 // Add the specialization into its lexical context, so that it can
9124 // be seen when iterating through the list of declarations in that
9125 // context. However, specializations are not found by name lookup.
9126 CurContext->addDecl(D: Specialization);
9127 }
9128
9129 if (SkipBody && SkipBody->ShouldSkip)
9130 return SkipBody->Previous;
9131
9132 Specialization->setInvalidDecl(Invalid);
9133 inferGslOwnerPointerAttribute(Record: Specialization);
9134 return Specialization;
9135}
9136
9137Decl *Sema::ActOnTemplateDeclarator(Scope *S,
9138 MultiTemplateParamsArg TemplateParameterLists,
9139 Declarator &D) {
9140 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9141 ActOnDocumentableDecl(D: NewDecl);
9142 return NewDecl;
9143}
9144
9145ConceptDecl *Sema::ActOnStartConceptDefinition(
9146 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9147 const IdentifierInfo *Name, SourceLocation NameLoc) {
9148 DeclContext *DC = CurContext;
9149
9150 if (!DC->getRedeclContext()->isFileContext()) {
9151 Diag(Loc: NameLoc,
9152 DiagID: diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9153 return nullptr;
9154 }
9155
9156 if (TemplateParameterLists.size() > 1) {
9157 Diag(Loc: NameLoc, DiagID: diag::err_concept_extra_headers);
9158 return nullptr;
9159 }
9160
9161 TemplateParameterList *Params = TemplateParameterLists.front();
9162
9163 if (Params->size() == 0) {
9164 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_parameters);
9165 return nullptr;
9166 }
9167
9168 // Ensure that the parameter pack, if present, is the last parameter in the
9169 // template.
9170 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9171 ParamEnd = Params->end();
9172 ParamIt != ParamEnd; ++ParamIt) {
9173 Decl const *Param = *ParamIt;
9174 if (Param->isParameterPack()) {
9175 if (++ParamIt == ParamEnd)
9176 break;
9177 Diag(Loc: Param->getLocation(),
9178 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
9179 return nullptr;
9180 }
9181 }
9182
9183 ConceptDecl *NewDecl =
9184 ConceptDecl::Create(C&: Context, DC, L: NameLoc, Name, Params);
9185
9186 if (NewDecl->hasAssociatedConstraints()) {
9187 // C++2a [temp.concept]p4:
9188 // A concept shall not have associated constraints.
9189 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_associated_constraints);
9190 NewDecl->setInvalidDecl();
9191 }
9192
9193 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
9194 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9195 forRedeclarationInCurContext());
9196 LookupName(R&: Previous, S);
9197 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9198 /*AllowInlineNamespace*/ false);
9199
9200 // We cannot properly handle redeclarations until we parse the constraint
9201 // expression, so only inject the name if we are sure we are not redeclaring a
9202 // symbol
9203 if (Previous.empty())
9204 PushOnScopeChains(D: NewDecl, S, AddToContext: true);
9205
9206 return NewDecl;
9207}
9208
9209static bool RemoveLookupResult(LookupResult &R, NamedDecl *C) {
9210 bool Found = false;
9211 LookupResult::Filter F = R.makeFilter();
9212 while (F.hasNext()) {
9213 NamedDecl *D = F.next();
9214 if (D == C) {
9215 F.erase();
9216 Found = true;
9217 break;
9218 }
9219 }
9220 F.done();
9221 return Found;
9222}
9223
9224ConceptDecl *
9225Sema::ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
9226 Expr *ConstraintExpr,
9227 const ParsedAttributesView &Attrs) {
9228 assert(!C->hasDefinition() && "Concept already defined");
9229 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr)) {
9230 C->setInvalidDecl();
9231 return nullptr;
9232 }
9233 C->setDefinition(ConstraintExpr);
9234 ProcessDeclAttributeList(S, D: C, AttrList: Attrs);
9235
9236 // Check for conflicting previous declaration.
9237 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
9238 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9239 forRedeclarationInCurContext());
9240 LookupName(R&: Previous, S);
9241 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
9242 /*AllowInlineNamespace*/ false);
9243 bool WasAlreadyAdded = RemoveLookupResult(R&: Previous, C);
9244 bool AddToScope = true;
9245 CheckConceptRedefinition(NewDecl: C, Previous, AddToScope);
9246
9247 ActOnDocumentableDecl(D: C);
9248 if (!WasAlreadyAdded && AddToScope)
9249 PushOnScopeChains(D: C, S);
9250
9251 return C;
9252}
9253
9254void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
9255 LookupResult &Previous, bool &AddToScope) {
9256 AddToScope = true;
9257
9258 if (Previous.empty())
9259 return;
9260
9261 auto *OldConcept = dyn_cast<ConceptDecl>(Val: Previous.getRepresentativeDecl()->getUnderlyingDecl());
9262 if (!OldConcept) {
9263 auto *Old = Previous.getRepresentativeDecl();
9264 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_kind)
9265 << NewDecl->getDeclName();
9266 notePreviousDefinition(Old, New: NewDecl->getLocation());
9267 AddToScope = false;
9268 return;
9269 }
9270 // Check if we can merge with a concept declaration.
9271 bool IsSame = Context.isSameEntity(X: NewDecl, Y: OldConcept);
9272 if (!IsSame) {
9273 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_concept)
9274 << NewDecl->getDeclName();
9275 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9276 AddToScope = false;
9277 return;
9278 }
9279 if (hasReachableDefinition(D: OldConcept) &&
9280 IsRedefinitionInModule(New: NewDecl, Old: OldConcept)) {
9281 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition)
9282 << NewDecl->getDeclName();
9283 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9284 AddToScope = false;
9285 return;
9286 }
9287 if (!Previous.isSingleResult()) {
9288 // FIXME: we should produce an error in case of ambig and failed lookups.
9289 // Other decls (e.g. namespaces) also have this shortcoming.
9290 return;
9291 }
9292 // We unwrap canonical decl late to check for module visibility.
9293 Context.setPrimaryMergedDecl(D: NewDecl, Primary: OldConcept->getCanonicalDecl());
9294}
9295
9296bool Sema::CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc) {
9297 if (auto *CE = llvm::dyn_cast<ConceptDecl>(Val: Concept);
9298 CE && !CE->isInvalidDecl() && !CE->hasDefinition()) {
9299 Diag(Loc, DiagID: diag::err_recursive_concept) << CE;
9300 Diag(Loc: CE->getLocation(), DiagID: diag::note_declared_at);
9301 return true;
9302 }
9303 // Concept template parameters don't have a definition and can't
9304 // be defined recursively.
9305 return false;
9306}
9307
9308/// \brief Strips various properties off an implicit instantiation
9309/// that has just been explicitly specialized.
9310static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9311 if (MinGW || (isa<FunctionDecl>(Val: D) &&
9312 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization()))
9313 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9314
9315 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D))
9316 FD->setInlineSpecified(false);
9317}
9318
9319/// Compute the diagnostic location for an explicit instantiation
9320// declaration or definition.
9321static SourceLocation DiagLocForExplicitInstantiation(
9322 NamedDecl* D, SourceLocation PointOfInstantiation) {
9323 // Explicit instantiations following a specialization have no effect and
9324 // hence no PointOfInstantiation. In that case, walk decl backwards
9325 // until a valid name loc is found.
9326 SourceLocation PrevDiagLoc = PointOfInstantiation;
9327 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9328 Prev = Prev->getPreviousDecl()) {
9329 PrevDiagLoc = Prev->getLocation();
9330 }
9331 assert(PrevDiagLoc.isValid() &&
9332 "Explicit instantiation without point of instantiation?");
9333 return PrevDiagLoc;
9334}
9335
9336bool
9337Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
9338 TemplateSpecializationKind NewTSK,
9339 NamedDecl *PrevDecl,
9340 TemplateSpecializationKind PrevTSK,
9341 SourceLocation PrevPointOfInstantiation,
9342 bool &HasNoEffect) {
9343 HasNoEffect = false;
9344
9345 switch (NewTSK) {
9346 case TSK_Undeclared:
9347 case TSK_ImplicitInstantiation:
9348 assert(
9349 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9350 "previous declaration must be implicit!");
9351 return false;
9352
9353 case TSK_ExplicitSpecialization:
9354 switch (PrevTSK) {
9355 case TSK_Undeclared:
9356 case TSK_ExplicitSpecialization:
9357 // Okay, we're just specializing something that is either already
9358 // explicitly specialized or has merely been mentioned without any
9359 // instantiation.
9360 return false;
9361
9362 case TSK_ImplicitInstantiation:
9363 if (PrevPointOfInstantiation.isInvalid()) {
9364 // The declaration itself has not actually been instantiated, so it is
9365 // still okay to specialize it.
9366 StripImplicitInstantiation(
9367 D: PrevDecl, MinGW: Context.getTargetInfo().getTriple().isOSCygMing());
9368 return false;
9369 }
9370 // Fall through
9371 [[fallthrough]];
9372
9373 case TSK_ExplicitInstantiationDeclaration:
9374 case TSK_ExplicitInstantiationDefinition:
9375 assert((PrevTSK == TSK_ImplicitInstantiation ||
9376 PrevPointOfInstantiation.isValid()) &&
9377 "Explicit instantiation without point of instantiation?");
9378
9379 // C++ [temp.expl.spec]p6:
9380 // If a template, a member template or the member of a class template
9381 // is explicitly specialized then that specialization shall be declared
9382 // before the first use of that specialization that would cause an
9383 // implicit instantiation to take place, in every translation unit in
9384 // which such a use occurs; no diagnostic is required.
9385 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9386 // Is there any previous explicit specialization declaration?
9387 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization)
9388 return false;
9389 }
9390
9391 Diag(Loc: NewLoc, DiagID: diag::err_specialization_after_instantiation)
9392 << PrevDecl;
9393 Diag(Loc: PrevPointOfInstantiation, DiagID: diag::note_instantiation_required_here)
9394 << (PrevTSK != TSK_ImplicitInstantiation);
9395
9396 return true;
9397 }
9398 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9399
9400 case TSK_ExplicitInstantiationDeclaration:
9401 switch (PrevTSK) {
9402 case TSK_ExplicitInstantiationDeclaration:
9403 // This explicit instantiation declaration is redundant (that's okay).
9404 HasNoEffect = true;
9405 return false;
9406
9407 case TSK_Undeclared:
9408 case TSK_ImplicitInstantiation:
9409 // We're explicitly instantiating something that may have already been
9410 // implicitly instantiated; that's fine.
9411 return false;
9412
9413 case TSK_ExplicitSpecialization:
9414 // C++0x [temp.explicit]p4:
9415 // For a given set of template parameters, if an explicit instantiation
9416 // of a template appears after a declaration of an explicit
9417 // specialization for that template, the explicit instantiation has no
9418 // effect.
9419 HasNoEffect = true;
9420 return false;
9421
9422 case TSK_ExplicitInstantiationDefinition:
9423 // C++0x [temp.explicit]p10:
9424 // If an entity is the subject of both an explicit instantiation
9425 // declaration and an explicit instantiation definition in the same
9426 // translation unit, the definition shall follow the declaration.
9427 Diag(Loc: NewLoc,
9428 DiagID: diag::err_explicit_instantiation_declaration_after_definition);
9429
9430 // Explicit instantiations following a specialization have no effect and
9431 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9432 // until a valid name loc is found.
9433 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9434 DiagID: diag::note_explicit_instantiation_definition_here);
9435 HasNoEffect = true;
9436 return false;
9437 }
9438 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9439
9440 case TSK_ExplicitInstantiationDefinition:
9441 switch (PrevTSK) {
9442 case TSK_Undeclared:
9443 case TSK_ImplicitInstantiation:
9444 // We're explicitly instantiating something that may have already been
9445 // implicitly instantiated; that's fine.
9446 return false;
9447
9448 case TSK_ExplicitSpecialization:
9449 // C++ DR 259, C++0x [temp.explicit]p4:
9450 // For a given set of template parameters, if an explicit
9451 // instantiation of a template appears after a declaration of
9452 // an explicit specialization for that template, the explicit
9453 // instantiation has no effect.
9454 Diag(Loc: NewLoc, DiagID: diag::warn_explicit_instantiation_after_specialization)
9455 << PrevDecl;
9456 Diag(Loc: PrevDecl->getLocation(),
9457 DiagID: diag::note_previous_template_specialization);
9458 HasNoEffect = true;
9459 return false;
9460
9461 case TSK_ExplicitInstantiationDeclaration:
9462 // We're explicitly instantiating a definition for something for which we
9463 // were previously asked to suppress instantiations. That's fine.
9464
9465 // C++0x [temp.explicit]p4:
9466 // For a given set of template parameters, if an explicit instantiation
9467 // of a template appears after a declaration of an explicit
9468 // specialization for that template, the explicit instantiation has no
9469 // effect.
9470 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9471 // Is there any previous explicit specialization declaration?
9472 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9473 HasNoEffect = true;
9474 break;
9475 }
9476 }
9477
9478 return false;
9479
9480 case TSK_ExplicitInstantiationDefinition:
9481 // C++0x [temp.spec]p5:
9482 // For a given template and a given set of template-arguments,
9483 // - an explicit instantiation definition shall appear at most once
9484 // in a program,
9485
9486 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9487 Diag(Loc: NewLoc, DiagID: (getLangOpts().MSVCCompat)
9488 ? diag::ext_explicit_instantiation_duplicate
9489 : diag::err_explicit_instantiation_duplicate)
9490 << PrevDecl;
9491 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9492 DiagID: diag::note_previous_explicit_instantiation);
9493 HasNoEffect = true;
9494 return false;
9495 }
9496 }
9497
9498 llvm_unreachable("Missing specialization/instantiation case?");
9499}
9500
9501bool Sema::CheckDependentFunctionTemplateSpecialization(
9502 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9503 LookupResult &Previous) {
9504 // Remove anything from Previous that isn't a function template in
9505 // the correct context.
9506 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9507 LookupResult::Filter F = Previous.makeFilter();
9508 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9509 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9510 while (F.hasNext()) {
9511 NamedDecl *D = F.next()->getUnderlyingDecl();
9512 if (!isa<FunctionTemplateDecl>(Val: D)) {
9513 F.erase();
9514 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAFunctionTemplate, y&: D));
9515 continue;
9516 }
9517
9518 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9519 NS: D->getDeclContext()->getRedeclContext())) {
9520 F.erase();
9521 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAMemberOfEnclosing, y&: D));
9522 continue;
9523 }
9524 }
9525 F.done();
9526
9527 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9528 if (Previous.empty()) {
9529 Diag(Loc: FD->getLocation(), DiagID: diag::err_dependent_function_template_spec_no_match)
9530 << IsFriend;
9531 for (auto &P : DiscardedCandidates)
9532 Diag(Loc: P.second->getLocation(),
9533 DiagID: diag::note_dependent_function_template_spec_discard_reason)
9534 << P.first << IsFriend;
9535 return true;
9536 }
9537
9538 FD->setDependentTemplateSpecialization(Context, Templates: Previous.asUnresolvedSet(),
9539 TemplateArgs: ExplicitTemplateArgs);
9540 return false;
9541}
9542
9543bool Sema::CheckFunctionTemplateSpecialization(
9544 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9545 LookupResult &Previous, bool QualifiedFriend) {
9546 // The set of function template specializations that could match this
9547 // explicit function template specialization.
9548 UnresolvedSet<8> Candidates;
9549 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9550 /*ForTakingAddress=*/false);
9551
9552 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9553 ConvertedTemplateArgs;
9554
9555 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9556 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9557 I != E; ++I) {
9558 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9559 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Ovl)) {
9560 // Only consider templates found within the same semantic lookup scope as
9561 // FD.
9562 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9563 NS: Ovl->getDeclContext()->getRedeclContext()))
9564 continue;
9565
9566 QualType FT = FD->getType();
9567 // C++11 [dcl.constexpr]p8:
9568 // A constexpr specifier for a non-static member function that is not
9569 // a constructor declares that member function to be const.
9570 //
9571 // When matching a constexpr member function template specialization
9572 // against the primary template, we don't yet know whether the
9573 // specialization has an implicit 'const' (because we don't know whether
9574 // it will be a static member function until we know which template it
9575 // specializes). This rule was removed in C++14.
9576 if (auto *NewMD = dyn_cast<CXXMethodDecl>(Val: FD);
9577 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9578 !isa<CXXConstructorDecl, CXXDestructorDecl>(Val: NewMD)) {
9579 auto *OldMD = dyn_cast<CXXMethodDecl>(Val: FunTmpl->getTemplatedDecl());
9580 if (OldMD && OldMD->isConst()) {
9581 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9582 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9583 EPI.TypeQuals.addConst();
9584 FT = Context.getFunctionType(ResultTy: FPT->getReturnType(),
9585 Args: FPT->getParamTypes(), EPI);
9586 }
9587 }
9588
9589 TemplateArgumentListInfo Args;
9590 if (ExplicitTemplateArgs)
9591 Args = *ExplicitTemplateArgs;
9592
9593 // C++ [temp.expl.spec]p11:
9594 // A trailing template-argument can be left unspecified in the
9595 // template-id naming an explicit function template specialization
9596 // provided it can be deduced from the function argument type.
9597 // Perform template argument deduction to determine whether we may be
9598 // specializing this template.
9599 // FIXME: It is somewhat wasteful to build
9600 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9601 FunctionDecl *Specialization = nullptr;
9602 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9603 FunctionTemplate: cast<FunctionTemplateDecl>(Val: FunTmpl->getFirstDecl()),
9604 ExplicitTemplateArgs: ExplicitTemplateArgs ? &Args : nullptr, ArgFunctionType: FT, Specialization, Info);
9605 TDK != TemplateDeductionResult::Success) {
9606 // Template argument deduction failed; record why it failed, so
9607 // that we can provide nifty diagnostics.
9608 FailedCandidates.addCandidate().set(
9609 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9610 Info: MakeDeductionFailureInfo(Context, TDK, Info));
9611 (void)TDK;
9612 continue;
9613 }
9614
9615 // Target attributes are part of the cuda function signature, so
9616 // the deduced template's cuda target must match that of the
9617 // specialization. Given that C++ template deduction does not
9618 // take target attributes into account, we reject candidates
9619 // here that have a different target.
9620 if (LangOpts.CUDA &&
9621 CUDA().IdentifyTarget(D: Specialization,
9622 /* IgnoreImplicitHDAttr = */ true) !=
9623 CUDA().IdentifyTarget(D: FD, /* IgnoreImplicitHDAttr = */ true)) {
9624 FailedCandidates.addCandidate().set(
9625 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9626 Info: MakeDeductionFailureInfo(
9627 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
9628 continue;
9629 }
9630
9631 // Record this candidate.
9632 if (ExplicitTemplateArgs)
9633 ConvertedTemplateArgs[Specialization] = std::move(Args);
9634 Candidates.addDecl(D: Specialization, AS: I.getAccess());
9635 }
9636 }
9637
9638 // For a qualified friend declaration (with no explicit marker to indicate
9639 // that a template specialization was intended), note all (template and
9640 // non-template) candidates.
9641 if (QualifiedFriend && Candidates.empty()) {
9642 Diag(Loc: FD->getLocation(), DiagID: diag::err_qualified_friend_no_match)
9643 << FD->getDeclName() << FDLookupContext;
9644 // FIXME: We should form a single candidate list and diagnose all
9645 // candidates at once, to get proper sorting and limiting.
9646 for (auto *OldND : Previous) {
9647 if (auto *OldFD = dyn_cast<FunctionDecl>(Val: OldND->getUnderlyingDecl()))
9648 NoteOverloadCandidate(Found: OldND, Fn: OldFD, RewriteKind: CRK_None, DestType: FD->getType(), TakingAddress: false);
9649 }
9650 FailedCandidates.NoteCandidates(S&: *this, Loc: FD->getLocation());
9651 return true;
9652 }
9653
9654 // Find the most specialized function template.
9655 UnresolvedSetIterator Result = getMostSpecialized(
9656 SBegin: Candidates.begin(), SEnd: Candidates.end(), FailedCandidates, Loc: FD->getLocation(),
9657 NoneDiag: PDiag(DiagID: diag::err_function_template_spec_no_match) << FD->getDeclName(),
9658 AmbigDiag: PDiag(DiagID: diag::err_function_template_spec_ambiguous)
9659 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9660 CandidateDiag: PDiag(DiagID: diag::note_function_template_spec_matched));
9661
9662 if (Result == Candidates.end())
9663 return true;
9664
9665 // Ignore access information; it doesn't figure into redeclaration checking.
9666 FunctionDecl *Specialization = cast<FunctionDecl>(Val: *Result);
9667
9668 if (const auto *PT = Specialization->getPrimaryTemplate();
9669 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9670 auto Message = DSA->getMessage();
9671 Diag(Loc: FD->getLocation(), DiagID: diag::warn_invalid_specialization)
9672 << PT << !Message.empty() << Message;
9673 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
9674 }
9675
9676 // C++23 [except.spec]p13:
9677 // An exception specification is considered to be needed when:
9678 // - [...]
9679 // - the exception specification is compared to that of another declaration
9680 // (e.g., an explicit specialization or an overriding virtual function);
9681 // - [...]
9682 //
9683 // The exception specification of a defaulted function is evaluated as
9684 // described above only when needed; similarly, the noexcept-specifier of a
9685 // specialization of a function template or member function of a class
9686 // template is instantiated only when needed.
9687 //
9688 // The standard doesn't specify what the "comparison with another declaration"
9689 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9690 // not state which properties of an explicit specialization must match the
9691 // primary template.
9692 //
9693 // We assume that an explicit specialization must correspond with (per
9694 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9695 // the declaration produced by substitution into the function template.
9696 //
9697 // Since the determination whether two function declarations correspond does
9698 // not consider exception specification, we only need to instantiate it once
9699 // we determine the primary template when comparing types per
9700 // [basic.link]p11.1.
9701 auto *SpecializationFPT =
9702 Specialization->getType()->castAs<FunctionProtoType>();
9703 // If the function has a dependent exception specification, resolve it after
9704 // we have selected the primary template so we can check whether it matches.
9705 if (getLangOpts().CPlusPlus17 &&
9706 isUnresolvedExceptionSpec(ESpecType: SpecializationFPT->getExceptionSpecType()) &&
9707 !ResolveExceptionSpec(Loc: FD->getLocation(), FPT: SpecializationFPT))
9708 return true;
9709
9710 FunctionTemplateSpecializationInfo *SpecInfo
9711 = Specialization->getTemplateSpecializationInfo();
9712 assert(SpecInfo && "Function template specialization info missing?");
9713
9714 // Note: do not overwrite location info if previous template
9715 // specialization kind was explicit.
9716 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9717 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9718 Specialization->setLocation(FD->getLocation());
9719 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9720 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9721 // function can differ from the template declaration with respect to
9722 // the constexpr specifier.
9723 // FIXME: We need an update record for this AST mutation.
9724 // FIXME: What if there are multiple such prior declarations (for instance,
9725 // from different modules)?
9726 Specialization->setConstexprKind(FD->getConstexprKind());
9727 }
9728
9729 // FIXME: Check if the prior specialization has a point of instantiation.
9730 // If so, we have run afoul of .
9731
9732 // If this is a friend declaration, then we're not really declaring
9733 // an explicit specialization.
9734 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9735
9736 // Check the scope of this explicit specialization.
9737 if (!isFriend &&
9738 CheckTemplateSpecializationScope(S&: *this,
9739 Specialized: Specialization->getPrimaryTemplate(),
9740 PrevDecl: Specialization, Loc: FD->getLocation(),
9741 IsPartialSpecialization: false))
9742 return true;
9743
9744 // C++ [temp.expl.spec]p6:
9745 // If a template, a member template or the member of a class template is
9746 // explicitly specialized then that specialization shall be declared
9747 // before the first use of that specialization that would cause an implicit
9748 // instantiation to take place, in every translation unit in which such a
9749 // use occurs; no diagnostic is required.
9750 bool HasNoEffect = false;
9751 if (!isFriend &&
9752 CheckSpecializationInstantiationRedecl(NewLoc: FD->getLocation(),
9753 NewTSK: TSK_ExplicitSpecialization,
9754 PrevDecl: Specialization,
9755 PrevTSK: SpecInfo->getTemplateSpecializationKind(),
9756 PrevPointOfInstantiation: SpecInfo->getPointOfInstantiation(),
9757 HasNoEffect))
9758 return true;
9759
9760 // Mark the prior declaration as an explicit specialization, so that later
9761 // clients know that this is an explicit specialization.
9762 // A dependent friend specialization which has a definition should be treated
9763 // as explicit specialization, despite being invalid.
9764 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9765 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9766 // Since explicit specializations do not inherit '=delete' from their
9767 // primary function template - check if the 'specialization' that was
9768 // implicitly generated (during template argument deduction for partial
9769 // ordering) from the most specialized of all the function templates that
9770 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9771 // first check that it was implicitly generated during template argument
9772 // deduction by making sure it wasn't referenced, and then reset the deleted
9773 // flag to not-deleted, so that we can inherit that information from 'FD'.
9774 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9775 !Specialization->getCanonicalDecl()->isReferenced()) {
9776 // FIXME: This assert will not hold in the presence of modules.
9777 assert(
9778 Specialization->getCanonicalDecl() == Specialization &&
9779 "This must be the only existing declaration of this specialization");
9780 // FIXME: We need an update record for this AST mutation.
9781 Specialization->setDeletedAsWritten(D: false);
9782 }
9783 // FIXME: We need an update record for this AST mutation.
9784 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9785 MarkUnusedFileScopedDecl(D: Specialization);
9786 }
9787
9788 // Turn the given function declaration into a function template
9789 // specialization, with the template arguments from the previous
9790 // specialization.
9791 // Take copies of (semantic and syntactic) template argument lists.
9792 TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy(
9793 Context, Args: Specialization->getTemplateSpecializationArgs()->asArray());
9794 FD->setFunctionTemplateSpecialization(
9795 Template: Specialization->getPrimaryTemplate(), TemplateArgs: TemplArgs, /*InsertPos=*/nullptr,
9796 TSK: SpecInfo->getTemplateSpecializationKind(),
9797 TemplateArgsAsWritten: ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9798
9799 // A function template specialization inherits the target attributes
9800 // of its template. (We require the attributes explicitly in the
9801 // code to match, but a template may have implicit attributes by
9802 // virtue e.g. of being constexpr, and it passes these implicit
9803 // attributes on to its specializations.)
9804 if (LangOpts.CUDA)
9805 CUDA().inheritTargetAttrs(FD, TD: *Specialization->getPrimaryTemplate());
9806
9807 // The "previous declaration" for this function template specialization is
9808 // the prior function template specialization.
9809 Previous.clear();
9810 Previous.addDecl(D: Specialization);
9811 return false;
9812}
9813
9814bool
9815Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9816 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9817 "Only for non-template members");
9818
9819 // Try to find the member we are instantiating.
9820 NamedDecl *FoundInstantiation = nullptr;
9821 NamedDecl *Instantiation = nullptr;
9822 NamedDecl *InstantiatedFrom = nullptr;
9823 MemberSpecializationInfo *MSInfo = nullptr;
9824
9825 if (Previous.empty()) {
9826 // Nowhere to look anyway.
9827 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Member)) {
9828 UnresolvedSet<8> Candidates;
9829 for (NamedDecl *Candidate : Previous) {
9830 auto *Method = dyn_cast<CXXMethodDecl>(Val: Candidate->getUnderlyingDecl());
9831 // Ignore any candidates that aren't member functions.
9832 if (!Method)
9833 continue;
9834
9835 QualType Adjusted = Function->getType();
9836 if (!hasExplicitCallingConv(T: Adjusted))
9837 Adjusted = adjustCCAndNoReturn(ArgFunctionType: Adjusted, FunctionType: Method->getType());
9838 // Ignore any candidates with the wrong type.
9839 // This doesn't handle deduced return types, but both function
9840 // declarations should be undeduced at this point.
9841 // FIXME: The exception specification should probably be ignored when
9842 // comparing the types.
9843 if (!Context.hasSameType(T1: Adjusted, T2: Method->getType()))
9844 continue;
9845
9846 // Ignore any candidates with unsatisfied constraints.
9847 if (ConstraintSatisfaction Satisfaction;
9848 Method->getTrailingRequiresClause() &&
9849 (CheckFunctionConstraints(FD: Method, Satisfaction,
9850 /*UsageLoc=*/Member->getLocation(),
9851 /*ForOverloadResolution=*/true) ||
9852 !Satisfaction.IsSatisfied))
9853 continue;
9854
9855 Candidates.addDecl(D: Candidate);
9856 }
9857
9858 // If we have no viable candidates left after filtering, we are done.
9859 if (Candidates.empty())
9860 return false;
9861
9862 // Find the function that is more constrained than every other function it
9863 // has been compared to.
9864 UnresolvedSetIterator Best = Candidates.begin();
9865 CXXMethodDecl *BestMethod = nullptr;
9866 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9867 I != E; ++I) {
9868 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9869 if (I == Best ||
9870 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) == Method) {
9871 Best = I;
9872 BestMethod = Method;
9873 }
9874 }
9875
9876 FoundInstantiation = *Best;
9877 Instantiation = BestMethod;
9878 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9879 MSInfo = BestMethod->getMemberSpecializationInfo();
9880
9881 // Make sure the best candidate is more constrained than all of the others.
9882 bool Ambiguous = false;
9883 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9884 I != E; ++I) {
9885 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9886 if (I != Best &&
9887 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) != BestMethod) {
9888 Ambiguous = true;
9889 break;
9890 }
9891 }
9892
9893 if (Ambiguous) {
9894 Diag(Loc: Member->getLocation(), DiagID: diag::err_function_member_spec_ambiguous)
9895 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9896 for (NamedDecl *Candidate : Candidates) {
9897 Candidate = Candidate->getUnderlyingDecl();
9898 Diag(Loc: Candidate->getLocation(), DiagID: diag::note_function_member_spec_matched)
9899 << Candidate;
9900 }
9901 return true;
9902 }
9903 } else if (isa<VarDecl>(Val: Member)) {
9904 VarDecl *PrevVar;
9905 if (Previous.isSingleResult() &&
9906 (PrevVar = dyn_cast<VarDecl>(Val: Previous.getFoundDecl())))
9907 if (PrevVar->isStaticDataMember()) {
9908 FoundInstantiation = Previous.getRepresentativeDecl();
9909 Instantiation = PrevVar;
9910 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9911 MSInfo = PrevVar->getMemberSpecializationInfo();
9912 }
9913 } else if (isa<RecordDecl>(Val: Member)) {
9914 CXXRecordDecl *PrevRecord;
9915 if (Previous.isSingleResult() &&
9916 (PrevRecord = dyn_cast<CXXRecordDecl>(Val: Previous.getFoundDecl()))) {
9917 FoundInstantiation = Previous.getRepresentativeDecl();
9918 Instantiation = PrevRecord;
9919 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9920 MSInfo = PrevRecord->getMemberSpecializationInfo();
9921 }
9922 } else if (isa<EnumDecl>(Val: Member)) {
9923 EnumDecl *PrevEnum;
9924 if (Previous.isSingleResult() &&
9925 (PrevEnum = dyn_cast<EnumDecl>(Val: Previous.getFoundDecl()))) {
9926 FoundInstantiation = Previous.getRepresentativeDecl();
9927 Instantiation = PrevEnum;
9928 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9929 MSInfo = PrevEnum->getMemberSpecializationInfo();
9930 }
9931 }
9932
9933 if (!Instantiation) {
9934 // There is no previous declaration that matches. Since member
9935 // specializations are always out-of-line, the caller will complain about
9936 // this mismatch later.
9937 return false;
9938 }
9939
9940 // A member specialization in a friend declaration isn't really declaring
9941 // an explicit specialization, just identifying a specific (possibly implicit)
9942 // specialization. Don't change the template specialization kind.
9943 //
9944 // FIXME: Is this really valid? Other compilers reject.
9945 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9946 // Preserve instantiation information.
9947 if (InstantiatedFrom && isa<CXXMethodDecl>(Val: Member)) {
9948 cast<CXXMethodDecl>(Val: Member)->setInstantiationOfMemberFunction(
9949 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom),
9950 TSK: cast<CXXMethodDecl>(Val: Instantiation)->getTemplateSpecializationKind());
9951 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Val: Member)) {
9952 cast<CXXRecordDecl>(Val: Member)->setInstantiationOfMemberClass(
9953 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom),
9954 TSK: cast<CXXRecordDecl>(Val: Instantiation)->getTemplateSpecializationKind());
9955 }
9956
9957 Previous.clear();
9958 Previous.addDecl(D: FoundInstantiation);
9959 return false;
9960 }
9961
9962 // Make sure that this is a specialization of a member.
9963 if (!InstantiatedFrom) {
9964 Diag(Loc: Member->getLocation(), DiagID: diag::err_spec_member_not_instantiated)
9965 << Member;
9966 Diag(Loc: Instantiation->getLocation(), DiagID: diag::note_specialized_decl);
9967 return true;
9968 }
9969
9970 // C++ [temp.expl.spec]p6:
9971 // If a template, a member template or the member of a class template is
9972 // explicitly specialized then that specialization shall be declared
9973 // before the first use of that specialization that would cause an implicit
9974 // instantiation to take place, in every translation unit in which such a
9975 // use occurs; no diagnostic is required.
9976 assert(MSInfo && "Member specialization info missing?");
9977
9978 bool HasNoEffect = false;
9979 if (CheckSpecializationInstantiationRedecl(NewLoc: Member->getLocation(),
9980 NewTSK: TSK_ExplicitSpecialization,
9981 PrevDecl: Instantiation,
9982 PrevTSK: MSInfo->getTemplateSpecializationKind(),
9983 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
9984 HasNoEffect))
9985 return true;
9986
9987 // Check the scope of this explicit specialization.
9988 if (CheckTemplateSpecializationScope(S&: *this,
9989 Specialized: InstantiatedFrom,
9990 PrevDecl: Instantiation, Loc: Member->getLocation(),
9991 IsPartialSpecialization: false))
9992 return true;
9993
9994 // Note that this member specialization is an "instantiation of" the
9995 // corresponding member of the original template.
9996 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Val: Member)) {
9997 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Val: Instantiation);
9998 if (InstantiationFunction->getTemplateSpecializationKind() ==
9999 TSK_ImplicitInstantiation) {
10000 // Explicit specializations of member functions of class templates do not
10001 // inherit '=delete' from the member function they are specializing.
10002 if (InstantiationFunction->isDeleted()) {
10003 // FIXME: This assert will not hold in the presence of modules.
10004 assert(InstantiationFunction->getCanonicalDecl() ==
10005 InstantiationFunction);
10006 // FIXME: We need an update record for this AST mutation.
10007 InstantiationFunction->setDeletedAsWritten(D: false);
10008 }
10009 }
10010
10011 MemberFunction->setInstantiationOfMemberFunction(
10012 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10013 } else if (auto *MemberVar = dyn_cast<VarDecl>(Val: Member)) {
10014 MemberVar->setInstantiationOfStaticDataMember(
10015 VD: cast<VarDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10016 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Val: Member)) {
10017 MemberClass->setInstantiationOfMemberClass(
10018 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10019 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Val: Member)) {
10020 MemberEnum->setInstantiationOfMemberEnum(
10021 ED: cast<EnumDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10022 } else {
10023 llvm_unreachable("unknown member specialization kind");
10024 }
10025
10026 // Save the caller the trouble of having to figure out which declaration
10027 // this specialization matches.
10028 Previous.clear();
10029 Previous.addDecl(D: FoundInstantiation);
10030 return false;
10031}
10032
10033/// Complete the explicit specialization of a member of a class template by
10034/// updating the instantiated member to be marked as an explicit specialization.
10035///
10036/// \param OrigD The member declaration instantiated from the template.
10037/// \param Loc The location of the explicit specialization of the member.
10038template<typename DeclT>
10039static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10040 SourceLocation Loc) {
10041 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10042 return;
10043
10044 // FIXME: Inform AST mutation listeners of this AST mutation.
10045 // FIXME: If there are multiple in-class declarations of the member (from
10046 // multiple modules, or a declaration and later definition of a member type),
10047 // should we update all of them?
10048 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10049 OrigD->setLocation(Loc);
10050}
10051
10052void Sema::CompleteMemberSpecialization(NamedDecl *Member,
10053 LookupResult &Previous) {
10054 NamedDecl *Instantiation = cast<NamedDecl>(Val: Member->getCanonicalDecl());
10055 if (Instantiation == Member)
10056 return;
10057
10058 if (auto *Function = dyn_cast<CXXMethodDecl>(Val: Instantiation))
10059 completeMemberSpecializationImpl(S&: *this, OrigD: Function, Loc: Member->getLocation());
10060 else if (auto *Var = dyn_cast<VarDecl>(Val: Instantiation))
10061 completeMemberSpecializationImpl(S&: *this, OrigD: Var, Loc: Member->getLocation());
10062 else if (auto *Record = dyn_cast<CXXRecordDecl>(Val: Instantiation))
10063 completeMemberSpecializationImpl(S&: *this, OrigD: Record, Loc: Member->getLocation());
10064 else if (auto *Enum = dyn_cast<EnumDecl>(Val: Instantiation))
10065 completeMemberSpecializationImpl(S&: *this, OrigD: Enum, Loc: Member->getLocation());
10066 else
10067 llvm_unreachable("unknown member specialization kind");
10068}
10069
10070/// Check the scope of an explicit instantiation.
10071///
10072/// \returns true if a serious error occurs, false otherwise.
10073static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
10074 SourceLocation InstLoc,
10075 bool WasQualifiedName) {
10076 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
10077 DeclContext *CurContext = S.CurContext->getRedeclContext();
10078
10079 if (CurContext->isRecord()) {
10080 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_in_class)
10081 << D;
10082 return true;
10083 }
10084
10085 // C++11 [temp.explicit]p3:
10086 // An explicit instantiation shall appear in an enclosing namespace of its
10087 // template. If the name declared in the explicit instantiation is an
10088 // unqualified name, the explicit instantiation shall appear in the
10089 // namespace where its template is declared or, if that namespace is inline
10090 // (7.3.1), any namespace from its enclosing namespace set.
10091 //
10092 // This is DR275, which we do not retroactively apply to C++98/03.
10093 if (WasQualifiedName) {
10094 if (CurContext->Encloses(DC: OrigContext))
10095 return false;
10096 } else {
10097 if (CurContext->InEnclosingNamespaceSetOf(NS: OrigContext))
10098 return false;
10099 }
10100
10101 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: OrigContext)) {
10102 if (WasQualifiedName)
10103 S.Diag(Loc: InstLoc,
10104 DiagID: S.getLangOpts().CPlusPlus11?
10105 diag::err_explicit_instantiation_out_of_scope :
10106 diag::warn_explicit_instantiation_out_of_scope_0x)
10107 << D << NS;
10108 else
10109 S.Diag(Loc: InstLoc,
10110 DiagID: S.getLangOpts().CPlusPlus11?
10111 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10112 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10113 << D << NS;
10114 } else
10115 S.Diag(Loc: InstLoc,
10116 DiagID: S.getLangOpts().CPlusPlus11?
10117 diag::err_explicit_instantiation_must_be_global :
10118 diag::warn_explicit_instantiation_must_be_global_0x)
10119 << D;
10120 S.Diag(Loc: D->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10121 return false;
10122}
10123
10124/// Common checks for whether an explicit instantiation of \p D is valid.
10125static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
10126 SourceLocation InstLoc,
10127 bool WasQualifiedName,
10128 TemplateSpecializationKind TSK) {
10129 // C++ [temp.explicit]p13:
10130 // An explicit instantiation declaration shall not name a specialization of
10131 // a template with internal linkage.
10132 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10133 D->getFormalLinkage() == Linkage::Internal) {
10134 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_internal_linkage) << D;
10135 return true;
10136 }
10137
10138 // C++11 [temp.explicit]p3: [DR 275]
10139 // An explicit instantiation shall appear in an enclosing namespace of its
10140 // template.
10141 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10142 return true;
10143
10144 return false;
10145}
10146
10147/// Determine whether the given scope specifier has a template-id in it.
10148static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
10149 // C++11 [temp.explicit]p3:
10150 // If the explicit instantiation is for a member function, a member class
10151 // or a static data member of a class template specialization, the name of
10152 // the class template specialization in the qualified-id for the member
10153 // name shall be a simple-template-id.
10154 //
10155 // C++98 has the same restriction, just worded differently.
10156 for (NestedNameSpecifier NNS = SS.getScopeRep();
10157 NNS.getKind() == NestedNameSpecifier::Kind::Type;
10158 /**/) {
10159 const Type *T = NNS.getAsType();
10160 if (isa<TemplateSpecializationType>(Val: T))
10161 return true;
10162 NNS = T->getPrefix();
10163 }
10164 return false;
10165}
10166
10167/// Make a dllexport or dllimport attr on a class template specialization take
10168/// effect.
10169static void dllExportImportClassTemplateSpecialization(
10170 Sema &S, ClassTemplateSpecializationDecl *Def) {
10171 auto *A = cast_or_null<InheritableAttr>(Val: getDLLAttr(D: Def));
10172 assert(A && "dllExportImportClassTemplateSpecialization called "
10173 "on Def without dllexport or dllimport");
10174
10175 // We reject explicit instantiations in class scope, so there should
10176 // never be any delayed exported classes to worry about.
10177 assert(S.DelayedDllExportClasses.empty() &&
10178 "delayed exports present at explicit instantiation");
10179 S.checkClassLevelDLLAttribute(Class: Def);
10180
10181 // Propagate attribute to base class templates.
10182 for (auto &B : Def->bases()) {
10183 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10184 Val: B.getType()->getAsCXXRecordDecl()))
10185 S.propagateDLLAttrToBaseClassTemplate(Class: Def, ClassAttr: A, BaseTemplateSpec: BT, BaseLoc: B.getBeginLoc());
10186 }
10187
10188 S.referenceDLLExportedClassMethods();
10189}
10190
10191DeclResult Sema::ActOnExplicitInstantiation(
10192 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10193 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10194 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10195 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10196 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10197 // Find the class template we're specializing
10198 TemplateName Name = TemplateD.get();
10199 TemplateDecl *TD = Name.getAsTemplateDecl();
10200 // Check that the specialization uses the same tag kind as the
10201 // original template.
10202 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10203 assert(Kind != TagTypeKind::Enum &&
10204 "Invalid enum tag in class template explicit instantiation!");
10205
10206 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: TD);
10207
10208 if (!ClassTemplate) {
10209 NonTagKind NTK = getNonTagTypeDeclKind(D: TD, TTK: Kind);
10210 Diag(Loc: TemplateNameLoc, DiagID: diag::err_tag_reference_non_tag) << TD << NTK << Kind;
10211 Diag(Loc: TD->getLocation(), DiagID: diag::note_previous_use);
10212 return true;
10213 }
10214
10215 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(),
10216 NewTag: Kind, /*isDefinition*/false, NewTagLoc: KWLoc,
10217 Name: ClassTemplate->getIdentifier())) {
10218 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
10219 << ClassTemplate
10220 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
10221 Code: ClassTemplate->getTemplatedDecl()->getKindName());
10222 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
10223 DiagID: diag::note_previous_use);
10224 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10225 }
10226
10227 // C++0x [temp.explicit]p2:
10228 // There are two forms of explicit instantiation: an explicit instantiation
10229 // definition and an explicit instantiation declaration. An explicit
10230 // instantiation declaration begins with the extern keyword. [...]
10231 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10232 ? TSK_ExplicitInstantiationDefinition
10233 : TSK_ExplicitInstantiationDeclaration;
10234
10235 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10236 !Context.getTargetInfo().getTriple().isOSCygMing()) {
10237 // Check for dllexport class template instantiation declarations,
10238 // except for MinGW mode.
10239 for (const ParsedAttr &AL : Attr) {
10240 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10241 Diag(Loc: ExternLoc,
10242 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10243 Diag(Loc: AL.getLoc(), DiagID: diag::note_attribute);
10244 break;
10245 }
10246 }
10247
10248 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10249 Diag(Loc: ExternLoc,
10250 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
10251 Diag(Loc: A->getLocation(), DiagID: diag::note_attribute);
10252 }
10253 }
10254
10255 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10256 // instantiation declarations for most purposes.
10257 bool DLLImportExplicitInstantiationDef = false;
10258 if (TSK == TSK_ExplicitInstantiationDefinition &&
10259 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10260 // Check for dllimport class template instantiation definitions.
10261 bool DLLImport =
10262 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10263 for (const ParsedAttr &AL : Attr) {
10264 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10265 DLLImport = true;
10266 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10267 // dllexport trumps dllimport here.
10268 DLLImport = false;
10269 break;
10270 }
10271 }
10272 if (DLLImport) {
10273 TSK = TSK_ExplicitInstantiationDeclaration;
10274 DLLImportExplicitInstantiationDef = true;
10275 }
10276 }
10277
10278 // Translate the parser's template argument list in our AST format.
10279 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10280 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10281
10282 // Check that the template argument list is well-formed for this
10283 // template.
10284 CheckTemplateArgumentInfo CTAI;
10285 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
10286 /*DefaultArgs=*/{}, PartialTemplateArgs: false, CTAI,
10287 /*UpdateArgsWithConversions=*/true,
10288 /*ConstraintsNotSatisfied=*/nullptr))
10289 return true;
10290
10291 // Find the class template specialization declaration that
10292 // corresponds to these arguments.
10293 void *InsertPos = nullptr;
10294 ClassTemplateSpecializationDecl *PrevDecl =
10295 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
10296
10297 TemplateSpecializationKind PrevDecl_TSK
10298 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10299
10300 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10301 Context.getTargetInfo().getTriple().isOSCygMing()) {
10302 // Check for dllexport class template instantiation definitions in MinGW
10303 // mode, if a previous declaration of the instantiation was seen.
10304 for (const ParsedAttr &AL : Attr) {
10305 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10306 if (PrevDecl->hasAttr<DLLExportAttr>()) {
10307 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attr_dllexport_explicit_inst_def);
10308 } else {
10309 Diag(Loc: AL.getLoc(),
10310 DiagID: diag::warn_attr_dllexport_explicit_inst_def_mismatch);
10311 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_prev_decl_missing_dllexport);
10312 }
10313 break;
10314 }
10315 }
10316 }
10317
10318 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl &&
10319 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10320 llvm::none_of(Range: Attr, P: [](const ParsedAttr &AL) {
10321 return AL.getKind() == ParsedAttr::AT_DLLExport;
10322 })) {
10323 if (const auto *DEA = PrevDecl->getAttr<DLLExportOnDeclAttr>()) {
10324 Diag(Loc: TemplateLoc, DiagID: diag::warn_dllexport_on_decl_ignored);
10325 Diag(Loc: DEA->getLoc(), DiagID: diag::note_dllexport_on_decl);
10326 }
10327 }
10328
10329 if (CheckExplicitInstantiation(S&: *this, D: ClassTemplate, InstLoc: TemplateNameLoc,
10330 WasQualifiedName: SS.isSet(), TSK))
10331 return true;
10332
10333 ClassTemplateSpecializationDecl *Specialization = nullptr;
10334
10335 bool HasNoEffect = false;
10336 if (PrevDecl) {
10337 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateNameLoc, NewTSK: TSK,
10338 PrevDecl, PrevTSK: PrevDecl_TSK,
10339 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
10340 HasNoEffect))
10341 return PrevDecl;
10342
10343 // Even though HasNoEffect == true means that this explicit instantiation
10344 // has no effect on semantics, we go on to put its syntax in the AST.
10345
10346 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10347 PrevDecl_TSK == TSK_Undeclared) {
10348 // Since the only prior class template specialization with these
10349 // arguments was referenced but not declared, reuse that
10350 // declaration node as our own, updating the source location
10351 // for the template name to reflect our new declaration.
10352 // (Other source locations will be updated later.)
10353 Specialization = PrevDecl;
10354 Specialization->setLocation(TemplateNameLoc);
10355 PrevDecl = nullptr;
10356 }
10357
10358 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10359 DLLImportExplicitInstantiationDef) {
10360 // The new specialization might add a dllimport attribute.
10361 HasNoEffect = false;
10362 }
10363 }
10364
10365 if (!Specialization) {
10366 // Create a new class template specialization declaration node for
10367 // this explicit specialization.
10368 Specialization = ClassTemplateSpecializationDecl::Create(
10369 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
10370 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
10371 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
10372
10373 // A MSInheritanceAttr attached to the previous declaration must be
10374 // propagated to the new node prior to instantiation.
10375 if (PrevDecl) {
10376 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10377 auto *Clone = A->clone(C&: getASTContext());
10378 Clone->setInherited(true);
10379 Specialization->addAttr(A: Clone);
10380 Consumer.AssignInheritanceModel(RD: Specialization);
10381 }
10382 }
10383
10384 if (!HasNoEffect && !PrevDecl) {
10385 // Insert the new specialization.
10386 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
10387 }
10388 }
10389
10390 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10391
10392 // Set source locations for keywords.
10393 Specialization->setExternKeywordLoc(ExternLoc);
10394 Specialization->setTemplateKeywordLoc(TemplateLoc);
10395 Specialization->setBraceRange(SourceRange());
10396
10397 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10398 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
10399 ProcessAPINotes(D: Specialization);
10400
10401 // Add the explicit instantiation into its lexical context. However,
10402 // since explicit instantiations are never found by name lookup, we
10403 // just put it into the declaration context directly.
10404 Specialization->setLexicalDeclContext(CurContext);
10405 CurContext->addDecl(D: Specialization);
10406
10407 // Syntax is now OK, so return if it has no other effect on semantics.
10408 if (HasNoEffect) {
10409 // Set the template specialization kind.
10410 Specialization->setTemplateSpecializationKind(TSK);
10411 return Specialization;
10412 }
10413
10414 // C++ [temp.explicit]p3:
10415 // A definition of a class template or class member template
10416 // shall be in scope at the point of the explicit instantiation of
10417 // the class template or class member template.
10418 //
10419 // This check comes when we actually try to perform the
10420 // instantiation.
10421 ClassTemplateSpecializationDecl *Def
10422 = cast_or_null<ClassTemplateSpecializationDecl>(
10423 Val: Specialization->getDefinition());
10424 if (!Def)
10425 InstantiateClassTemplateSpecialization(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Specialization, TSK,
10426 /*Complain=*/true,
10427 PrimaryStrictPackMatch: CTAI.StrictPackMatch);
10428 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10429 MarkVTableUsed(Loc: TemplateNameLoc, Class: Specialization, DefinitionRequired: true);
10430 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10431 }
10432
10433 // Instantiate the members of this class template specialization.
10434 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10435 Val: Specialization->getDefinition());
10436 if (Def) {
10437 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
10438 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10439 // TSK_ExplicitInstantiationDefinition
10440 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10441 (TSK == TSK_ExplicitInstantiationDefinition ||
10442 DLLImportExplicitInstantiationDef)) {
10443 // FIXME: Need to notify the ASTMutationListener that we did this.
10444 Def->setTemplateSpecializationKind(TSK);
10445
10446 if (!getDLLAttr(D: Def) && getDLLAttr(D: Specialization) &&
10447 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10448 // An explicit instantiation definition can add a dll attribute to a
10449 // template with a previous instantiation declaration. MinGW doesn't
10450 // allow this.
10451 auto *A = cast<InheritableAttr>(
10452 Val: getDLLAttr(D: Specialization)->clone(C&: getASTContext()));
10453 A->setInherited(true);
10454 Def->addAttr(A);
10455 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10456 }
10457 }
10458
10459 // Fix a TSK_ImplicitInstantiation followed by a
10460 // TSK_ExplicitInstantiationDefinition
10461 bool NewlyDLLExported =
10462 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10463 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10464 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10465 // An explicit instantiation definition can add a dll attribute to a
10466 // template with a previous implicit instantiation. MinGW doesn't allow
10467 // this. We limit clang to only adding dllexport, to avoid potentially
10468 // strange codegen behavior. For example, if we extend this conditional
10469 // to dllimport, and we have a source file calling a method on an
10470 // implicitly instantiated template class instance and then declaring a
10471 // dllimport explicit instantiation definition for the same template
10472 // class, the codegen for the method call will not respect the dllimport,
10473 // while it will with cl. The Def will already have the DLL attribute,
10474 // since the Def and Specialization will be the same in the case of
10475 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10476 // attribute to the Specialization; we just need to make it take effect.
10477 assert(Def == Specialization &&
10478 "Def and Specialization should match for implicit instantiation");
10479 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10480 }
10481
10482 // In MinGW mode, export the template instantiation if the declaration
10483 // was marked dllexport.
10484 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10485 Context.getTargetInfo().getTriple().isOSCygMing() &&
10486 PrevDecl->hasAttr<DLLExportAttr>()) {
10487 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10488 }
10489
10490 // Set the template specialization kind. Make sure it is set before
10491 // instantiating the members which will trigger ASTConsumer callbacks.
10492 Specialization->setTemplateSpecializationKind(TSK);
10493 InstantiateClassTemplateSpecializationMembers(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Def, TSK);
10494 } else {
10495
10496 // Set the template specialization kind.
10497 Specialization->setTemplateSpecializationKind(TSK);
10498 }
10499
10500 return Specialization;
10501}
10502
10503DeclResult
10504Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10505 SourceLocation TemplateLoc, unsigned TagSpec,
10506 SourceLocation KWLoc, CXXScopeSpec &SS,
10507 IdentifierInfo *Name, SourceLocation NameLoc,
10508 const ParsedAttributesView &Attr) {
10509
10510 bool Owned = false;
10511 bool IsDependent = false;
10512 Decl *TagD =
10513 ActOnTag(S, TagSpec, TUK: TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10514 Attr, AS: AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10515 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent, ScopedEnumKWLoc: SourceLocation(),
10516 ScopedEnumUsesClassTag: false, UnderlyingType: TypeResult(), /*IsTypeSpecifier*/ false,
10517 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10518 .get();
10519 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10520
10521 if (!TagD)
10522 return true;
10523
10524 TagDecl *Tag = cast<TagDecl>(Val: TagD);
10525 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10526
10527 if (Tag->isInvalidDecl())
10528 return true;
10529
10530 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: Tag);
10531 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10532 if (!Pattern) {
10533 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_nontemplate_type)
10534 << Context.getCanonicalTagType(TD: Record);
10535 Diag(Loc: Record->getLocation(), DiagID: diag::note_nontemplate_decl_here);
10536 return true;
10537 }
10538
10539 // C++0x [temp.explicit]p2:
10540 // If the explicit instantiation is for a class or member class, the
10541 // elaborated-type-specifier in the declaration shall include a
10542 // simple-template-id.
10543 //
10544 // C++98 has the same restriction, just worded differently.
10545 if (!ScopeSpecifierHasTemplateId(SS))
10546 Diag(Loc: TemplateLoc, DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10547 << Record << SS.getRange();
10548
10549 // C++0x [temp.explicit]p2:
10550 // There are two forms of explicit instantiation: an explicit instantiation
10551 // definition and an explicit instantiation declaration. An explicit
10552 // instantiation declaration begins with the extern keyword. [...]
10553 TemplateSpecializationKind TSK
10554 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10555 : TSK_ExplicitInstantiationDeclaration;
10556
10557 CheckExplicitInstantiation(S&: *this, D: Record, InstLoc: NameLoc, WasQualifiedName: true, TSK);
10558
10559 // Verify that it is okay to explicitly instantiate here.
10560 CXXRecordDecl *PrevDecl
10561 = cast_or_null<CXXRecordDecl>(Val: Record->getPreviousDecl());
10562 if (!PrevDecl && Record->getDefinition())
10563 PrevDecl = Record;
10564 if (PrevDecl) {
10565 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10566 bool HasNoEffect = false;
10567 assert(MSInfo && "No member specialization information?");
10568 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateLoc, NewTSK: TSK,
10569 PrevDecl,
10570 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10571 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10572 HasNoEffect))
10573 return true;
10574 if (HasNoEffect)
10575 return TagD;
10576 }
10577
10578 CXXRecordDecl *RecordDef
10579 = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10580 if (!RecordDef) {
10581 // C++ [temp.explicit]p3:
10582 // A definition of a member class of a class template shall be in scope
10583 // at the point of an explicit instantiation of the member class.
10584 CXXRecordDecl *Def
10585 = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition());
10586 if (!Def) {
10587 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_undefined_member)
10588 << 0 << Record->getDeclName() << Record->getDeclContext();
10589 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_forward_declaration)
10590 << Pattern;
10591 return true;
10592 } else {
10593 if (InstantiateClass(PointOfInstantiation: NameLoc, Instantiation: Record, Pattern: Def,
10594 TemplateArgs: getTemplateInstantiationArgs(D: Record),
10595 TSK))
10596 return true;
10597
10598 RecordDef = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10599 if (!RecordDef)
10600 return true;
10601 }
10602 }
10603
10604 // Instantiate all of the members of the class.
10605 InstantiateClassMembers(PointOfInstantiation: NameLoc, Instantiation: RecordDef,
10606 TemplateArgs: getTemplateInstantiationArgs(D: Record), TSK);
10607
10608 if (TSK == TSK_ExplicitInstantiationDefinition)
10609 MarkVTableUsed(Loc: NameLoc, Class: RecordDef, DefinitionRequired: true);
10610
10611 // FIXME: We don't have any representation for explicit instantiations of
10612 // member classes. Such a representation is not needed for compilation, but it
10613 // should be available for clients that want to see all of the declarations in
10614 // the source code.
10615 return TagD;
10616}
10617
10618DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10619 SourceLocation ExternLoc,
10620 SourceLocation TemplateLoc,
10621 Declarator &D) {
10622 // Explicit instantiations always require a name.
10623 // TODO: check if/when DNInfo should replace Name.
10624 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10625 DeclarationName Name = NameInfo.getName();
10626 if (!Name) {
10627 if (!D.isInvalidType())
10628 Diag(Loc: D.getDeclSpec().getBeginLoc(),
10629 DiagID: diag::err_explicit_instantiation_requires_name)
10630 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10631
10632 return true;
10633 }
10634
10635 // Get the innermost enclosing declaration scope.
10636 S = S->getDeclParent();
10637
10638 // Determine the type of the declaration.
10639 TypeSourceInfo *T = GetTypeForDeclarator(D);
10640 QualType R = T->getType();
10641 if (R.isNull())
10642 return true;
10643
10644 // C++ [dcl.stc]p1:
10645 // A storage-class-specifier shall not be specified in [...] an explicit
10646 // instantiation (14.7.2) directive.
10647 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10648 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_of_typedef)
10649 << Name;
10650 return true;
10651 } else if (D.getDeclSpec().getStorageClassSpec()
10652 != DeclSpec::SCS_unspecified) {
10653 // Complain about then remove the storage class specifier.
10654 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_storage_class)
10655 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10656
10657 D.getMutableDeclSpec().ClearStorageClassSpecs();
10658 }
10659
10660 // C++0x [temp.explicit]p1:
10661 // [...] An explicit instantiation of a function template shall not use the
10662 // inline or constexpr specifiers.
10663 // Presumably, this also applies to member functions of class templates as
10664 // well.
10665 if (D.getDeclSpec().isInlineSpecified())
10666 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10667 DiagID: getLangOpts().CPlusPlus11 ?
10668 diag::err_explicit_instantiation_inline :
10669 diag::warn_explicit_instantiation_inline_0x)
10670 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10671 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10672 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10673 // not already specified.
10674 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10675 DiagID: diag::err_explicit_instantiation_constexpr);
10676
10677 // A deduction guide is not on the list of entities that can be explicitly
10678 // instantiated.
10679 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10680 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
10681 << /*explicit instantiation*/ 0;
10682 return true;
10683 }
10684
10685 // C++0x [temp.explicit]p2:
10686 // There are two forms of explicit instantiation: an explicit instantiation
10687 // definition and an explicit instantiation declaration. An explicit
10688 // instantiation declaration begins with the extern keyword. [...]
10689 TemplateSpecializationKind TSK
10690 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10691 : TSK_ExplicitInstantiationDeclaration;
10692
10693 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10694 LookupParsedName(R&: Previous, S, SS: &D.getCXXScopeSpec(),
10695 /*ObjectType=*/QualType());
10696
10697 if (!R->isFunctionType()) {
10698 // C++ [temp.explicit]p1:
10699 // A [...] static data member of a class template can be explicitly
10700 // instantiated from the member definition associated with its class
10701 // template.
10702 // C++1y [temp.explicit]p1:
10703 // A [...] variable [...] template specialization can be explicitly
10704 // instantiated from its template.
10705 if (Previous.isAmbiguous())
10706 return true;
10707
10708 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10709 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10710
10711 if (!PrevTemplate) {
10712 if (!Prev || !Prev->isStaticDataMember()) {
10713 // We expect to see a static data member here.
10714 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_not_known)
10715 << Name;
10716 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10717 P != PEnd; ++P)
10718 Diag(Loc: (*P)->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10719 return true;
10720 }
10721
10722 if (!Prev->getInstantiatedFromStaticDataMember()) {
10723 // FIXME: Check for explicit specialization?
10724 Diag(Loc: D.getIdentifierLoc(),
10725 DiagID: diag::err_explicit_instantiation_data_member_not_instantiated)
10726 << Prev;
10727 Diag(Loc: Prev->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10728 // FIXME: Can we provide a note showing where this was declared?
10729 return true;
10730 }
10731 } else {
10732 // Explicitly instantiate a variable template.
10733
10734 // C++1y [dcl.spec.auto]p6:
10735 // ... A program that uses auto or decltype(auto) in a context not
10736 // explicitly allowed in this section is ill-formed.
10737 //
10738 // This includes auto-typed variable template instantiations.
10739 if (R->isUndeducedType()) {
10740 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10741 DiagID: diag::err_auto_not_allowed_var_inst);
10742 return true;
10743 }
10744
10745 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10746 // C++1y [temp.explicit]p3:
10747 // If the explicit instantiation is for a variable, the unqualified-id
10748 // in the declaration shall be a template-id.
10749 Diag(Loc: D.getIdentifierLoc(),
10750 DiagID: diag::err_explicit_instantiation_without_template_id)
10751 << PrevTemplate;
10752 Diag(Loc: PrevTemplate->getLocation(),
10753 DiagID: diag::note_explicit_instantiation_here);
10754 return true;
10755 }
10756
10757 // Translate the parser's template argument list into our AST format.
10758 TemplateArgumentListInfo TemplateArgs =
10759 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10760
10761 DeclResult Res =
10762 CheckVarTemplateId(Template: PrevTemplate, TemplateLoc, TemplateNameLoc: D.getIdentifierLoc(),
10763 TemplateArgs, /*SetWrittenArgs=*/true);
10764 if (Res.isInvalid())
10765 return true;
10766
10767 if (!Res.isUsable()) {
10768 // We somehow specified dependent template arguments in an explicit
10769 // instantiation. This should probably only happen during error
10770 // recovery.
10771 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_dependent);
10772 return true;
10773 }
10774
10775 // Ignore access control bits, we don't need them for redeclaration
10776 // checking.
10777 Prev = cast<VarDecl>(Val: Res.get());
10778 }
10779
10780 // C++0x [temp.explicit]p2:
10781 // If the explicit instantiation is for a member function, a member class
10782 // or a static data member of a class template specialization, the name of
10783 // the class template specialization in the qualified-id for the member
10784 // name shall be a simple-template-id.
10785 //
10786 // C++98 has the same restriction, just worded differently.
10787 //
10788 // This does not apply to variable template specializations, where the
10789 // template-id is in the unqualified-id instead.
10790 if (!ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()) && !PrevTemplate)
10791 Diag(Loc: D.getIdentifierLoc(),
10792 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10793 << Prev << D.getCXXScopeSpec().getRange();
10794
10795 CheckExplicitInstantiation(S&: *this, D: Prev, InstLoc: D.getIdentifierLoc(), WasQualifiedName: true, TSK);
10796
10797 // Verify that it is okay to explicitly instantiate here.
10798 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10799 SourceLocation POI = Prev->getPointOfInstantiation();
10800 bool HasNoEffect = false;
10801 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK, PrevDecl: Prev,
10802 PrevTSK, PrevPointOfInstantiation: POI, HasNoEffect))
10803 return true;
10804
10805 if (!HasNoEffect) {
10806 // Instantiate static data member or variable template.
10807 Prev->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
10808 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: Prev)) {
10809 VTSD->setExternKeywordLoc(ExternLoc);
10810 VTSD->setTemplateKeywordLoc(TemplateLoc);
10811 }
10812
10813 // Merge attributes.
10814 ProcessDeclAttributeList(S, D: Prev, AttrList: D.getDeclSpec().getAttributes());
10815 if (PrevTemplate)
10816 ProcessAPINotes(D: Prev);
10817
10818 if (TSK == TSK_ExplicitInstantiationDefinition)
10819 InstantiateVariableDefinition(PointOfInstantiation: D.getIdentifierLoc(), Var: Prev);
10820 }
10821
10822 // Check the new variable specialization against the parsed input.
10823 if (PrevTemplate && !Context.hasSameType(T1: Prev->getType(), T2: R)) {
10824 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10825 DiagID: diag::err_invalid_var_template_spec_type)
10826 << 0 << PrevTemplate << R << Prev->getType();
10827 Diag(Loc: PrevTemplate->getLocation(), DiagID: diag::note_template_declared_here)
10828 << 2 << PrevTemplate->getDeclName();
10829 return true;
10830 }
10831
10832 // FIXME: Create an ExplicitInstantiation node?
10833 return (Decl*) nullptr;
10834 }
10835
10836 // If the declarator is a template-id, translate the parser's template
10837 // argument list into our AST format.
10838 bool HasExplicitTemplateArgs = false;
10839 TemplateArgumentListInfo TemplateArgs;
10840 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10841 TemplateArgs = makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10842 HasExplicitTemplateArgs = true;
10843 }
10844
10845 // C++ [temp.explicit]p1:
10846 // A [...] function [...] can be explicitly instantiated from its template.
10847 // A member function [...] of a class template can be explicitly
10848 // instantiated from the member definition associated with its class
10849 // template.
10850 UnresolvedSet<8> TemplateMatches;
10851 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10852 OverloadCandidateSet::CSK_Normal);
10853 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10854 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10855 P != PEnd; ++P) {
10856 NamedDecl *Prev = *P;
10857 if (!HasExplicitTemplateArgs) {
10858 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Prev)) {
10859 QualType Adjusted = adjustCCAndNoReturn(ArgFunctionType: R, FunctionType: Method->getType(),
10860 /*AdjustExceptionSpec*/true);
10861 if (Context.hasSameUnqualifiedType(T1: Method->getType(), T2: Adjusted)) {
10862 if (Method->getPrimaryTemplate()) {
10863 TemplateMatches.addDecl(D: Method, AS: P.getAccess());
10864 } else {
10865 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10866 C.FoundDecl = P.getPair();
10867 C.Function = Method;
10868 C.Viable = true;
10869 ConstraintSatisfaction S;
10870 if (Method->getTrailingRequiresClause() &&
10871 (CheckFunctionConstraints(FD: Method, Satisfaction&: S, UsageLoc: D.getIdentifierLoc(),
10872 /*ForOverloadResolution=*/true) ||
10873 !S.IsSatisfied)) {
10874 C.Viable = false;
10875 C.FailureKind = ovl_fail_constraints_not_satisfied;
10876 }
10877 }
10878 }
10879 }
10880 }
10881
10882 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Prev);
10883 if (!FunTmpl)
10884 continue;
10885
10886 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10887 FunctionDecl *Specialization = nullptr;
10888 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
10889 FunctionTemplate: FunTmpl, ExplicitTemplateArgs: (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), ArgFunctionType: R,
10890 Specialization, Info);
10891 TDK != TemplateDeductionResult::Success) {
10892 // Keep track of almost-matches.
10893 FailedTemplateCandidates.addCandidate().set(
10894 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
10895 Info: MakeDeductionFailureInfo(Context, TDK, Info));
10896 (void)TDK;
10897 continue;
10898 }
10899
10900 // Target attributes are part of the cuda function signature, so
10901 // the cuda target of the instantiated function must match that of its
10902 // template. Given that C++ template deduction does not take
10903 // target attributes into account, we reject candidates here that
10904 // have a different target.
10905 if (LangOpts.CUDA &&
10906 CUDA().IdentifyTarget(D: Specialization,
10907 /* IgnoreImplicitHDAttr = */ true) !=
10908 CUDA().IdentifyTarget(Attrs: D.getDeclSpec().getAttributes())) {
10909 FailedTemplateCandidates.addCandidate().set(
10910 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
10911 Info: MakeDeductionFailureInfo(
10912 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
10913 continue;
10914 }
10915
10916 TemplateMatches.addDecl(D: Specialization, AS: P.getAccess());
10917 }
10918
10919 FunctionDecl *Specialization = nullptr;
10920 if (!NonTemplateMatches.empty()) {
10921 unsigned Msg = 0;
10922 OverloadCandidateDisplayKind DisplayKind;
10923 OverloadCandidateSet::iterator Best;
10924 switch (NonTemplateMatches.BestViableFunction(S&: *this, Loc: D.getIdentifierLoc(),
10925 Best)) {
10926 case OR_Success:
10927 case OR_Deleted:
10928 Specialization = cast<FunctionDecl>(Val: Best->Function);
10929 break;
10930 case OR_Ambiguous:
10931 Msg = diag::err_explicit_instantiation_ambiguous;
10932 DisplayKind = OCD_AmbiguousCandidates;
10933 break;
10934 case OR_No_Viable_Function:
10935 Msg = diag::err_explicit_instantiation_no_candidate;
10936 DisplayKind = OCD_AllCandidates;
10937 break;
10938 }
10939 if (Msg) {
10940 PartialDiagnostic Diag = PDiag(DiagID: Msg) << Name;
10941 NonTemplateMatches.NoteCandidates(
10942 PA: PartialDiagnosticAt(D.getIdentifierLoc(), Diag), S&: *this, OCD: DisplayKind,
10943 Args: {});
10944 return true;
10945 }
10946 }
10947
10948 if (!Specialization) {
10949 // Find the most specialized function template specialization.
10950 UnresolvedSetIterator Result = getMostSpecialized(
10951 SBegin: TemplateMatches.begin(), SEnd: TemplateMatches.end(),
10952 FailedCandidates&: FailedTemplateCandidates, Loc: D.getIdentifierLoc(),
10953 NoneDiag: PDiag(DiagID: diag::err_explicit_instantiation_not_known) << Name,
10954 AmbigDiag: PDiag(DiagID: diag::err_explicit_instantiation_ambiguous) << Name,
10955 CandidateDiag: PDiag(DiagID: diag::note_explicit_instantiation_candidate));
10956
10957 if (Result == TemplateMatches.end())
10958 return true;
10959
10960 // Ignore access control bits, we don't need them for redeclaration checking.
10961 Specialization = cast<FunctionDecl>(Val: *Result);
10962 }
10963
10964 // C++11 [except.spec]p4
10965 // In an explicit instantiation an exception-specification may be specified,
10966 // but is not required.
10967 // If an exception-specification is specified in an explicit instantiation
10968 // directive, it shall be compatible with the exception-specifications of
10969 // other declarations of that function.
10970 if (auto *FPT = R->getAs<FunctionProtoType>())
10971 if (FPT->hasExceptionSpec()) {
10972 unsigned DiagID =
10973 diag::err_mismatched_exception_spec_explicit_instantiation;
10974 if (getLangOpts().MicrosoftExt)
10975 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10976 bool Result = CheckEquivalentExceptionSpec(
10977 DiagID: PDiag(DiagID) << Specialization->getType(),
10978 NoteID: PDiag(DiagID: diag::note_explicit_instantiation_here),
10979 Old: Specialization->getType()->getAs<FunctionProtoType>(),
10980 OldLoc: Specialization->getLocation(), New: FPT, NewLoc: D.getBeginLoc());
10981 // In Microsoft mode, mismatching exception specifications just cause a
10982 // warning.
10983 if (!getLangOpts().MicrosoftExt && Result)
10984 return true;
10985 }
10986
10987 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10988 Diag(Loc: D.getIdentifierLoc(),
10989 DiagID: diag::err_explicit_instantiation_member_function_not_instantiated)
10990 << Specialization
10991 << (Specialization->getTemplateSpecializationKind() ==
10992 TSK_ExplicitSpecialization);
10993 Diag(Loc: Specialization->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10994 return true;
10995 }
10996
10997 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10998 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10999 PrevDecl = Specialization;
11000
11001 if (PrevDecl) {
11002 bool HasNoEffect = false;
11003 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK,
11004 PrevDecl,
11005 PrevTSK: PrevDecl->getTemplateSpecializationKind(),
11006 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
11007 HasNoEffect))
11008 return true;
11009
11010 // FIXME: We may still want to build some representation of this
11011 // explicit specialization.
11012 if (HasNoEffect)
11013 return (Decl*) nullptr;
11014 }
11015
11016 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11017 // functions
11018 // valarray<size_t>::valarray(size_t) and
11019 // valarray<size_t>::~valarray()
11020 // that it declared to have internal linkage with the internal_linkage
11021 // attribute. Ignore the explicit instantiation declaration in this case.
11022 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11023 TSK == TSK_ExplicitInstantiationDeclaration) {
11024 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Specialization->getDeclContext()))
11025 if (RD->getIdentifier() && RD->getIdentifier()->isStr(Str: "valarray") &&
11026 RD->isInStdNamespace())
11027 return (Decl*) nullptr;
11028 }
11029
11030 ProcessDeclAttributeList(S, D: Specialization, AttrList: D.getDeclSpec().getAttributes());
11031 ProcessAPINotes(D: Specialization);
11032
11033 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11034 // instantiation declarations.
11035 if (TSK == TSK_ExplicitInstantiationDefinition &&
11036 Specialization->hasAttr<DLLImportAttr>() &&
11037 Context.getTargetInfo().getCXXABI().isMicrosoft())
11038 TSK = TSK_ExplicitInstantiationDeclaration;
11039
11040 Specialization->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
11041
11042 if (Specialization->isDefined()) {
11043 // Let the ASTConsumer know that this function has been explicitly
11044 // instantiated now, and its linkage might have changed.
11045 Consumer.HandleTopLevelDecl(D: DeclGroupRef(Specialization));
11046 } else if (TSK == TSK_ExplicitInstantiationDefinition)
11047 InstantiateFunctionDefinition(PointOfInstantiation: D.getIdentifierLoc(), Function: Specialization);
11048
11049 // C++0x [temp.explicit]p2:
11050 // If the explicit instantiation is for a member function, a member class
11051 // or a static data member of a class template specialization, the name of
11052 // the class template specialization in the qualified-id for the member
11053 // name shall be a simple-template-id.
11054 //
11055 // C++98 has the same restriction, just worded differently.
11056 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11057 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11058 D.getCXXScopeSpec().isSet() &&
11059 !ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()))
11060 Diag(Loc: D.getIdentifierLoc(),
11061 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
11062 << Specialization << D.getCXXScopeSpec().getRange();
11063
11064 CheckExplicitInstantiation(
11065 S&: *this,
11066 D: FunTmpl ? (NamedDecl *)FunTmpl
11067 : Specialization->getInstantiatedFromMemberFunction(),
11068 InstLoc: D.getIdentifierLoc(), WasQualifiedName: D.getCXXScopeSpec().isSet(), TSK);
11069
11070 // FIXME: Create some kind of ExplicitInstantiationDecl here.
11071 return (Decl*) nullptr;
11072}
11073
11074TypeResult Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11075 const CXXScopeSpec &SS,
11076 const IdentifierInfo *Name,
11077 SourceLocation TagLoc,
11078 SourceLocation NameLoc) {
11079 // This has to hold, because SS is expected to be defined.
11080 assert(Name && "Expected a name in a dependent tag");
11081
11082 NestedNameSpecifier NNS = SS.getScopeRep();
11083 if (!NNS)
11084 return true;
11085
11086 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
11087
11088 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
11089 Diag(Loc: NameLoc, DiagID: diag::err_dependent_tag_decl)
11090 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
11091 return true;
11092 }
11093
11094 // Create the resulting type.
11095 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
11096 QualType Result = Context.getDependentNameType(Keyword: Kwd, NNS, Name);
11097
11098 // Create type-source location information for this type.
11099 TypeLocBuilder TLB;
11100 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: Result);
11101 TL.setElaboratedKeywordLoc(TagLoc);
11102 TL.setQualifierLoc(SS.getWithLocInContext(Context));
11103 TL.setNameLoc(NameLoc);
11104 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
11105}
11106
11107TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11108 const CXXScopeSpec &SS,
11109 const IdentifierInfo &II,
11110 SourceLocation IdLoc,
11111 ImplicitTypenameContext IsImplicitTypename) {
11112 if (SS.isInvalid())
11113 return true;
11114
11115 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11116 DiagCompat(Loc: TypenameLoc, CompatDiagId: diag_compat::typename_outside_of_template)
11117 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11118
11119 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11120 TypeSourceInfo *TSI = nullptr;
11121 QualType T =
11122 CheckTypenameType(Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11123 : ElaboratedTypeKeyword::None,
11124 KeywordLoc: TypenameLoc, QualifierLoc, II, IILoc: IdLoc, TSI: &TSI,
11125 /*DeducedTSTContext=*/true);
11126 if (T.isNull())
11127 return true;
11128 return CreateParsedType(T, TInfo: TSI);
11129}
11130
11131TypeResult
11132Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11133 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11134 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11135 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11136 ASTTemplateArgsPtr TemplateArgsIn,
11137 SourceLocation RAngleLoc) {
11138 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11139 Diag(Loc: TypenameLoc, DiagID: getLangOpts().CPlusPlus11
11140 ? diag::compat_cxx11_typename_outside_of_template
11141 : diag::compat_pre_cxx11_typename_outside_of_template)
11142 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
11143
11144 // Strangely, non-type results are not ignored by this lookup, so the
11145 // program is ill-formed if it finds an injected-class-name.
11146 if (TypenameLoc.isValid()) {
11147 auto *LookupRD =
11148 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: false));
11149 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11150 Diag(Loc: TemplateIILoc,
11151 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
11152 << TemplateII << 0 /*injected-class-name used as template name*/
11153 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11154 }
11155 }
11156
11157 // Translate the parser's template argument list in our AST format.
11158 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11159 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11160
11161 QualType T = CheckTemplateIdType(
11162 Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
11163 : ElaboratedTypeKeyword::None,
11164 Name: TemplateIn.get(), TemplateLoc: TemplateIILoc, TemplateArgs,
11165 /*Scope=*/S, /*ForNestedNameSpecifier=*/false);
11166 if (T.isNull())
11167 return true;
11168
11169 // Provide source-location information for the template specialization type.
11170 TypeLocBuilder Builder;
11171 TemplateSpecializationTypeLoc SpecTL
11172 = Builder.push<TemplateSpecializationTypeLoc>(T);
11173 SpecTL.set(ElaboratedKeywordLoc: TypenameLoc, QualifierLoc: SS.getWithLocInContext(Context), TemplateKeywordLoc: TemplateKWLoc,
11174 NameLoc: TemplateIILoc, TAL: TemplateArgs);
11175 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11176 return CreateParsedType(T, TInfo: TSI);
11177}
11178
11179/// Determine whether this failed name lookup should be treated as being
11180/// disabled by a usage of std::enable_if.
11181static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
11182 SourceRange &CondRange, Expr *&Cond) {
11183 // We must be looking for a ::type...
11184 if (!II.isStr(Str: "type"))
11185 return false;
11186
11187 // ... within an explicitly-written template specialization...
11188 if (NNS.getNestedNameSpecifier().getKind() != NestedNameSpecifier::Kind::Type)
11189 return false;
11190
11191 // FIXME: Look through sugar.
11192 auto EnableIfTSTLoc =
11193 NNS.castAsTypeLoc().getAs<TemplateSpecializationTypeLoc>();
11194 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11195 return false;
11196 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11197
11198 // ... which names a complete class template declaration...
11199 const TemplateDecl *EnableIfDecl =
11200 EnableIfTST->getTemplateName().getAsTemplateDecl();
11201 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11202 return false;
11203
11204 // ... called "enable_if".
11205 const IdentifierInfo *EnableIfII =
11206 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11207 if (!EnableIfII || !EnableIfII->isStr(Str: "enable_if"))
11208 return false;
11209
11210 // Assume the first template argument is the condition.
11211 CondRange = EnableIfTSTLoc.getArgLoc(i: 0).getSourceRange();
11212
11213 // Dig out the condition.
11214 Cond = nullptr;
11215 if (EnableIfTSTLoc.getArgLoc(i: 0).getArgument().getKind()
11216 != TemplateArgument::Expression)
11217 return true;
11218
11219 Cond = EnableIfTSTLoc.getArgLoc(i: 0).getSourceExpression();
11220
11221 // Ignore Boolean literals; they add no value.
11222 if (isa<CXXBoolLiteralExpr>(Val: Cond->IgnoreParenCasts()))
11223 Cond = nullptr;
11224
11225 return true;
11226}
11227
11228QualType
11229Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11230 SourceLocation KeywordLoc,
11231 NestedNameSpecifierLoc QualifierLoc,
11232 const IdentifierInfo &II,
11233 SourceLocation IILoc,
11234 TypeSourceInfo **TSI,
11235 bool DeducedTSTContext) {
11236 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11237 DeducedTSTContext);
11238 if (T.isNull())
11239 return QualType();
11240
11241 TypeLocBuilder TLB;
11242 if (isa<DependentNameType>(Val: T)) {
11243 auto TL = TLB.push<DependentNameTypeLoc>(T);
11244 TL.setElaboratedKeywordLoc(KeywordLoc);
11245 TL.setQualifierLoc(QualifierLoc);
11246 TL.setNameLoc(IILoc);
11247 } else if (isa<DeducedTemplateSpecializationType>(Val: T)) {
11248 auto TL = TLB.push<DeducedTemplateSpecializationTypeLoc>(T);
11249 TL.setElaboratedKeywordLoc(KeywordLoc);
11250 TL.setQualifierLoc(QualifierLoc);
11251 TL.setNameLoc(IILoc);
11252 } else if (isa<TemplateTypeParmType>(Val: T)) {
11253 // FIXME: There might be a 'typename' keyword here, but we just drop it
11254 // as it can't be represented.
11255 assert(!QualifierLoc);
11256 TLB.pushTypeSpec(T).setNameLoc(IILoc);
11257 } else if (isa<TagType>(Val: T)) {
11258 auto TL = TLB.push<TagTypeLoc>(T);
11259 TL.setElaboratedKeywordLoc(KeywordLoc);
11260 TL.setQualifierLoc(QualifierLoc);
11261 TL.setNameLoc(IILoc);
11262 } else if (isa<TypedefType>(Val: T)) {
11263 TLB.push<TypedefTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11264 } else {
11265 TLB.push<UnresolvedUsingTypeLoc>(T).set(ElaboratedKeywordLoc: KeywordLoc, QualifierLoc, NameLoc: IILoc);
11266 }
11267 *TSI = TLB.getTypeSourceInfo(Context, T);
11268 return T;
11269}
11270
11271/// Build the type that describes a C++ typename specifier,
11272/// e.g., "typename T::type".
11273QualType
11274Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11275 SourceLocation KeywordLoc,
11276 NestedNameSpecifierLoc QualifierLoc,
11277 const IdentifierInfo &II,
11278 SourceLocation IILoc, bool DeducedTSTContext) {
11279 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11280
11281 CXXScopeSpec SS;
11282 SS.Adopt(Other: QualifierLoc);
11283
11284 DeclContext *Ctx = nullptr;
11285 if (QualifierLoc) {
11286 Ctx = computeDeclContext(SS);
11287 if (!Ctx) {
11288 // If the nested-name-specifier is dependent and couldn't be
11289 // resolved to a type, build a typename type.
11290 assert(QualifierLoc.getNestedNameSpecifier().isDependent());
11291 return Context.getDependentNameType(Keyword,
11292 NNS: QualifierLoc.getNestedNameSpecifier(),
11293 Name: &II);
11294 }
11295
11296 // If the nested-name-specifier refers to the current instantiation,
11297 // the "typename" keyword itself is superfluous. In C++03, the
11298 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11299 // allows such extraneous "typename" keywords, and we retroactively
11300 // apply this DR to C++03 code with only a warning. In any case we continue.
11301
11302 if (RequireCompleteDeclContext(SS, DC: Ctx))
11303 return QualType();
11304 }
11305
11306 DeclarationName Name(&II);
11307 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11308 if (Ctx)
11309 LookupQualifiedName(R&: Result, LookupCtx: Ctx, SS);
11310 else
11311 LookupName(R&: Result, S: CurScope);
11312 unsigned DiagID = 0;
11313 Decl *Referenced = nullptr;
11314 switch (Result.getResultKind()) {
11315 case LookupResultKind::NotFound: {
11316 // If we're looking up 'type' within a template named 'enable_if', produce
11317 // a more specific diagnostic.
11318 SourceRange CondRange;
11319 Expr *Cond = nullptr;
11320 if (Ctx && isEnableIf(NNS: QualifierLoc, II, CondRange, Cond)) {
11321 // If we have a condition, narrow it down to the specific failed
11322 // condition.
11323 if (Cond) {
11324 Expr *FailedCond;
11325 std::string FailedDescription;
11326 std::tie(args&: FailedCond, args&: FailedDescription) =
11327 findFailedBooleanCondition(Cond);
11328
11329 Diag(Loc: FailedCond->getExprLoc(),
11330 DiagID: diag::err_typename_nested_not_found_requirement)
11331 << FailedDescription
11332 << FailedCond->getSourceRange();
11333 return QualType();
11334 }
11335
11336 Diag(Loc: CondRange.getBegin(),
11337 DiagID: diag::err_typename_nested_not_found_enable_if)
11338 << Ctx << CondRange;
11339 return QualType();
11340 }
11341
11342 DiagID = Ctx ? diag::err_typename_nested_not_found
11343 : diag::err_unknown_typename;
11344 break;
11345 }
11346
11347 case LookupResultKind::FoundUnresolvedValue: {
11348 // We found a using declaration that is a value. Most likely, the using
11349 // declaration itself is meant to have the 'typename' keyword.
11350 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11351 IILoc);
11352 Diag(Loc: IILoc, DiagID: diag::err_typename_refers_to_using_value_decl)
11353 << Name << Ctx << FullRange;
11354 if (UnresolvedUsingValueDecl *Using
11355 = dyn_cast<UnresolvedUsingValueDecl>(Val: Result.getRepresentativeDecl())){
11356 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11357 Diag(Loc, DiagID: diag::note_using_value_decl_missing_typename)
11358 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
11359 }
11360 }
11361 // Fall through to create a dependent typename type, from which we can
11362 // recover better.
11363 [[fallthrough]];
11364
11365 case LookupResultKind::NotFoundInCurrentInstantiation:
11366 // Okay, it's a member of an unknown instantiation.
11367 return Context.getDependentNameType(Keyword,
11368 NNS: QualifierLoc.getNestedNameSpecifier(),
11369 Name: &II);
11370
11371 case LookupResultKind::Found:
11372 // FXIME: Missing support for UsingShadowDecl on this path?
11373 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: Result.getFoundDecl())) {
11374 // C++ [class.qual]p2:
11375 // In a lookup in which function names are not ignored and the
11376 // nested-name-specifier nominates a class C, if the name specified
11377 // after the nested-name-specifier, when looked up in C, is the
11378 // injected-class-name of C [...] then the name is instead considered
11379 // to name the constructor of class C.
11380 //
11381 // Unlike in an elaborated-type-specifier, function names are not ignored
11382 // in typename-specifier lookup. However, they are ignored in all the
11383 // contexts where we form a typename type with no keyword (that is, in
11384 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11385 //
11386 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11387 // ignore functions, but that appears to be an oversight.
11388 checkTypeDeclType(LookupCtx: Ctx,
11389 DCK: Keyword == ElaboratedTypeKeyword::Typename
11390 ? DiagCtorKind::Typename
11391 : DiagCtorKind::None,
11392 TD: Type, NameLoc: IILoc);
11393 // FIXME: This appears to be the only case where a template type parameter
11394 // can have an elaborated keyword. We should preserve it somehow.
11395 if (isa<TemplateTypeParmDecl>(Val: Type)) {
11396 assert(Keyword == ElaboratedTypeKeyword::Typename);
11397 assert(!QualifierLoc);
11398 Keyword = ElaboratedTypeKeyword::None;
11399 }
11400 return Context.getTypeDeclType(
11401 Keyword, Qualifier: QualifierLoc.getNestedNameSpecifier(), Decl: Type);
11402 }
11403
11404 // C++ [dcl.type.simple]p2:
11405 // A type-specifier of the form
11406 // typename[opt] nested-name-specifier[opt] template-name
11407 // is a placeholder for a deduced class type [...].
11408 if (getLangOpts().CPlusPlus17) {
11409 if (auto *TD = getAsTypeTemplateDecl(D: Result.getFoundDecl())) {
11410 if (!DeducedTSTContext) {
11411 NestedNameSpecifier Qualifier = QualifierLoc.getNestedNameSpecifier();
11412 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type)
11413 Diag(Loc: IILoc, DiagID: diag::err_dependent_deduced_tst)
11414 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
11415 << QualType(Qualifier.getAsType(), 0);
11416 else
11417 Diag(Loc: IILoc, DiagID: diag::err_deduced_tst)
11418 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD));
11419 NoteTemplateLocation(Decl: *TD);
11420 return QualType();
11421 }
11422 TemplateName Name = Context.getQualifiedTemplateName(
11423 Qualifier: QualifierLoc.getNestedNameSpecifier(), /*TemplateKeyword=*/false,
11424 Template: TemplateName(TD));
11425 return Context.getDeducedTemplateSpecializationType(
11426 DK: DeducedKind::Undeduced, /*DeducedAsType=*/QualType(), Keyword,
11427 Template: Name);
11428 }
11429 }
11430
11431 DiagID = Ctx ? diag::err_typename_nested_not_type
11432 : diag::err_typename_not_type;
11433 Referenced = Result.getFoundDecl();
11434 break;
11435
11436 case LookupResultKind::FoundOverloaded:
11437 DiagID = Ctx ? diag::err_typename_nested_not_type
11438 : diag::err_typename_not_type;
11439 Referenced = *Result.begin();
11440 break;
11441
11442 case LookupResultKind::Ambiguous:
11443 return QualType();
11444 }
11445
11446 // If we get here, it's because name lookup did not find a
11447 // type. Emit an appropriate diagnostic and return an error.
11448 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11449 IILoc);
11450 if (Ctx)
11451 Diag(Loc: IILoc, DiagID) << FullRange << Name << Ctx;
11452 else
11453 Diag(Loc: IILoc, DiagID) << FullRange << Name;
11454 if (Referenced)
11455 Diag(Loc: Referenced->getLocation(),
11456 DiagID: Ctx ? diag::note_typename_member_refers_here
11457 : diag::note_typename_refers_here)
11458 << Name;
11459 return QualType();
11460}
11461
11462namespace {
11463 // See Sema::RebuildTypeInCurrentInstantiation
11464 class CurrentInstantiationRebuilder
11465 : public TreeTransform<CurrentInstantiationRebuilder> {
11466 SourceLocation Loc;
11467 DeclarationName Entity;
11468
11469 public:
11470 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11471
11472 CurrentInstantiationRebuilder(Sema &SemaRef,
11473 SourceLocation Loc,
11474 DeclarationName Entity)
11475 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11476 Loc(Loc), Entity(Entity) { }
11477
11478 /// Determine whether the given type \p T has already been
11479 /// transformed.
11480 ///
11481 /// For the purposes of type reconstruction, a type has already been
11482 /// transformed if it is NULL or if it is not dependent.
11483 bool AlreadyTransformed(QualType T) {
11484 return T.isNull() || !T->isInstantiationDependentType();
11485 }
11486
11487 /// Returns the location of the entity whose type is being
11488 /// rebuilt.
11489 SourceLocation getBaseLocation() { return Loc; }
11490
11491 /// Returns the name of the entity whose type is being rebuilt.
11492 DeclarationName getBaseEntity() { return Entity; }
11493
11494 /// Sets the "base" location and entity when that
11495 /// information is known based on another transformation.
11496 void setBase(SourceLocation Loc, DeclarationName Entity) {
11497 this->Loc = Loc;
11498 this->Entity = Entity;
11499 }
11500
11501 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11502 // Lambdas never need to be transformed.
11503 return E;
11504 }
11505 };
11506} // end anonymous namespace
11507
11508TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11509 SourceLocation Loc,
11510 DeclarationName Name) {
11511 if (!T || !T->getType()->isInstantiationDependentType())
11512 return T;
11513
11514 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11515 return Rebuilder.TransformType(TSI: T);
11516}
11517
11518ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11519 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11520 DeclarationName());
11521 return Rebuilder.TransformExpr(E);
11522}
11523
11524bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11525 if (SS.isInvalid())
11526 return true;
11527
11528 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11529 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11530 DeclarationName());
11531 NestedNameSpecifierLoc Rebuilt
11532 = Rebuilder.TransformNestedNameSpecifierLoc(NNS: QualifierLoc);
11533 if (!Rebuilt)
11534 return true;
11535
11536 SS.Adopt(Other: Rebuilt);
11537 return false;
11538}
11539
11540bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11541 TemplateParameterList *Params) {
11542 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11543 Decl *Param = Params->getParam(Idx: I);
11544
11545 // There is nothing to rebuild in a type parameter.
11546 if (isa<TemplateTypeParmDecl>(Val: Param))
11547 continue;
11548
11549 // Rebuild the template parameter list of a template template parameter.
11550 if (TemplateTemplateParmDecl *TTP
11551 = dyn_cast<TemplateTemplateParmDecl>(Val: Param)) {
11552 if (RebuildTemplateParamsInCurrentInstantiation(
11553 Params: TTP->getTemplateParameters()))
11554 return true;
11555
11556 continue;
11557 }
11558
11559 // Rebuild the type of a non-type template parameter.
11560 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Val: Param);
11561 TypeSourceInfo *NewTSI
11562 = RebuildTypeInCurrentInstantiation(T: NTTP->getTypeSourceInfo(),
11563 Loc: NTTP->getLocation(),
11564 Name: NTTP->getDeclName());
11565 if (!NewTSI)
11566 return true;
11567
11568 if (NewTSI->getType()->isUndeducedType()) {
11569 // C++17 [temp.dep.expr]p3:
11570 // An id-expression is type-dependent if it contains
11571 // - an identifier associated by name lookup with a non-type
11572 // template-parameter declared with a type that contains a
11573 // placeholder type (7.1.7.4),
11574 NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: NewTSI);
11575 }
11576
11577 if (NewTSI != NTTP->getTypeSourceInfo()) {
11578 NTTP->setTypeSourceInfo(NewTSI);
11579 NTTP->setType(NewTSI->getType());
11580 }
11581 }
11582
11583 return false;
11584}
11585
11586std::string
11587Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11588 const TemplateArgumentList &Args) {
11589 return getTemplateArgumentBindingsText(Params, Args: Args.data(), NumArgs: Args.size());
11590}
11591
11592std::string
11593Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11594 const TemplateArgument *Args,
11595 unsigned NumArgs) {
11596 SmallString<128> Str;
11597 llvm::raw_svector_ostream Out(Str);
11598
11599 if (!Params || Params->size() == 0 || NumArgs == 0)
11600 return std::string();
11601
11602 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11603 if (I >= NumArgs)
11604 break;
11605
11606 if (I == 0)
11607 Out << "[with ";
11608 else
11609 Out << ", ";
11610
11611 if (const IdentifierInfo *Id = Params->getParam(Idx: I)->getIdentifier()) {
11612 Out << Id->getName();
11613 } else {
11614 Out << '$' << I;
11615 }
11616
11617 Out << " = ";
11618 Args[I].print(Policy: getPrintingPolicy(), Out,
11619 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
11620 Policy: getPrintingPolicy(), TPL: Params, Idx: I));
11621 }
11622
11623 Out << ']';
11624 return std::string(Out.str());
11625}
11626
11627void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11628 CachedTokens &Toks) {
11629 if (!FD)
11630 return;
11631
11632 auto LPT = std::make_unique<LateParsedTemplate>();
11633
11634 // Take tokens to avoid allocations
11635 LPT->Toks.swap(RHS&: Toks);
11636 LPT->D = FnD;
11637 LPT->FPO = getCurFPFeatures();
11638 LateParsedTemplateMap.insert(KV: std::make_pair(x&: FD, y: std::move(LPT)));
11639
11640 FD->setLateTemplateParsed(true);
11641}
11642
11643void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11644 if (!FD)
11645 return;
11646 FD->setLateTemplateParsed(false);
11647}
11648
11649bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11650 DeclContext *DC = CurContext;
11651
11652 while (DC) {
11653 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
11654 const FunctionDecl *FD = RD->isLocalClass();
11655 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11656 } else if (DC->isTranslationUnit() || DC->isNamespace())
11657 return false;
11658
11659 DC = DC->getParent();
11660 }
11661 return false;
11662}
11663
11664namespace {
11665/// Walk the path from which a declaration was instantiated, and check
11666/// that every explicit specialization along that path is visible. This enforces
11667/// C++ [temp.expl.spec]/6:
11668///
11669/// If a template, a member template or a member of a class template is
11670/// explicitly specialized then that specialization shall be declared before
11671/// the first use of that specialization that would cause an implicit
11672/// instantiation to take place, in every translation unit in which such a
11673/// use occurs; no diagnostic is required.
11674///
11675/// and also C++ [temp.class.spec]/1:
11676///
11677/// A partial specialization shall be declared before the first use of a
11678/// class template specialization that would make use of the partial
11679/// specialization as the result of an implicit or explicit instantiation
11680/// in every translation unit in which such a use occurs; no diagnostic is
11681/// required.
11682class ExplicitSpecializationVisibilityChecker {
11683 Sema &S;
11684 SourceLocation Loc;
11685 llvm::SmallVector<Module *, 8> Modules;
11686 Sema::AcceptableKind Kind;
11687
11688public:
11689 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11690 Sema::AcceptableKind Kind)
11691 : S(S), Loc(Loc), Kind(Kind) {}
11692
11693 void check(NamedDecl *ND) {
11694 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
11695 return checkImpl(Spec: FD);
11696 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
11697 return checkImpl(Spec: RD);
11698 if (auto *VD = dyn_cast<VarDecl>(Val: ND))
11699 return checkImpl(Spec: VD);
11700 if (auto *ED = dyn_cast<EnumDecl>(Val: ND))
11701 return checkImpl(Spec: ED);
11702 }
11703
11704private:
11705 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11706 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11707 : Sema::MissingImportKind::ExplicitSpecialization;
11708 const bool Recover = true;
11709
11710 // If we got a custom set of modules (because only a subset of the
11711 // declarations are interesting), use them, otherwise let
11712 // diagnoseMissingImport intelligently pick some.
11713 if (Modules.empty())
11714 S.diagnoseMissingImport(Loc, Decl: D, MIK: Kind, Recover);
11715 else
11716 S.diagnoseMissingImport(Loc, Decl: D, DeclLoc: D->getLocation(), Modules, MIK: Kind, Recover);
11717 }
11718
11719 bool CheckMemberSpecialization(const NamedDecl *D) {
11720 return Kind == Sema::AcceptableKind::Visible
11721 ? S.hasVisibleMemberSpecialization(D)
11722 : S.hasReachableMemberSpecialization(D);
11723 }
11724
11725 bool CheckExplicitSpecialization(const NamedDecl *D) {
11726 return Kind == Sema::AcceptableKind::Visible
11727 ? S.hasVisibleExplicitSpecialization(D)
11728 : S.hasReachableExplicitSpecialization(D);
11729 }
11730
11731 bool CheckDeclaration(const NamedDecl *D) {
11732 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11733 : S.hasReachableDeclaration(D);
11734 }
11735
11736 // Check a specific declaration. There are three problematic cases:
11737 //
11738 // 1) The declaration is an explicit specialization of a template
11739 // specialization.
11740 // 2) The declaration is an explicit specialization of a member of an
11741 // templated class.
11742 // 3) The declaration is an instantiation of a template, and that template
11743 // is an explicit specialization of a member of a templated class.
11744 //
11745 // We don't need to go any deeper than that, as the instantiation of the
11746 // surrounding class / etc is not triggered by whatever triggered this
11747 // instantiation, and thus should be checked elsewhere.
11748 template<typename SpecDecl>
11749 void checkImpl(SpecDecl *Spec) {
11750 bool IsHiddenExplicitSpecialization = false;
11751 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11752 // Some invalid friend declarations are written as specializations but are
11753 // instantiated implicitly.
11754 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11755 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11756 if (SpecKind == TSK_ExplicitSpecialization) {
11757 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11758 ? !CheckMemberSpecialization(D: Spec)
11759 : !CheckExplicitSpecialization(D: Spec);
11760 } else {
11761 checkInstantiated(Spec);
11762 }
11763
11764 if (IsHiddenExplicitSpecialization)
11765 diagnose(D: Spec->getMostRecentDecl(), IsPartialSpec: false);
11766 }
11767
11768 void checkInstantiated(FunctionDecl *FD) {
11769 if (auto *TD = FD->getPrimaryTemplate())
11770 checkTemplate(TD);
11771 }
11772
11773 void checkInstantiated(CXXRecordDecl *RD) {
11774 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD);
11775 if (!SD)
11776 return;
11777
11778 auto From = SD->getSpecializedTemplateOrPartial();
11779 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11780 checkTemplate(TD);
11781 else if (auto *TD =
11782 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11783 if (!CheckDeclaration(D: TD))
11784 diagnose(D: TD, IsPartialSpec: true);
11785 checkTemplate(TD);
11786 }
11787 }
11788
11789 void checkInstantiated(VarDecl *RD) {
11790 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(Val: RD);
11791 if (!SD)
11792 return;
11793
11794 auto From = SD->getSpecializedTemplateOrPartial();
11795 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11796 checkTemplate(TD);
11797 else if (auto *TD =
11798 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11799 if (!CheckDeclaration(D: TD))
11800 diagnose(D: TD, IsPartialSpec: true);
11801 checkTemplate(TD);
11802 }
11803 }
11804
11805 void checkInstantiated(EnumDecl *FD) {}
11806
11807 template<typename TemplDecl>
11808 void checkTemplate(TemplDecl *TD) {
11809 if (TD->isMemberSpecialization()) {
11810 if (!CheckMemberSpecialization(D: TD))
11811 diagnose(D: TD->getMostRecentDecl(), IsPartialSpec: false);
11812 }
11813 }
11814};
11815} // end anonymous namespace
11816
11817void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
11818 if (!getLangOpts().Modules)
11819 return;
11820
11821 ExplicitSpecializationVisibilityChecker(*this, Loc,
11822 Sema::AcceptableKind::Visible)
11823 .check(ND: Spec);
11824}
11825
11826void Sema::checkSpecializationReachability(SourceLocation Loc,
11827 NamedDecl *Spec) {
11828 if (!getLangOpts().CPlusPlusModules)
11829 return checkSpecializationVisibility(Loc, Spec);
11830
11831 ExplicitSpecializationVisibilityChecker(*this, Loc,
11832 Sema::AcceptableKind::Reachable)
11833 .check(ND: Spec);
11834}
11835
11836SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
11837 if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
11838 return N->getLocation();
11839 if (const auto *FD = dyn_cast<FunctionDecl>(Val: N)) {
11840 if (!FD->isFunctionTemplateSpecialization())
11841 return FD->getLocation();
11842 } else if (!isa<ClassTemplateSpecializationDecl,
11843 VarTemplateSpecializationDecl>(Val: N)) {
11844 return N->getLocation();
11845 }
11846 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11847 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11848 continue;
11849 return CSC.PointOfInstantiation;
11850 }
11851 return N->getLocation();
11852}
11853