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/ASTConsumer.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/Decl.h"
15#include "clang/AST/DeclFriend.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DynamicRecursiveASTVisitor.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/TemplateName.h"
21#include "clang/AST/TypeVisitor.h"
22#include "clang/Basic/Builtins.h"
23#include "clang/Basic/DiagnosticSema.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/PartialDiagnostic.h"
26#include "clang/Basic/SourceLocation.h"
27#include "clang/Basic/TargetInfo.h"
28#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/EnterExpressionEvaluationContext.h"
30#include "clang/Sema/Initialization.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
33#include "clang/Sema/ParsedTemplate.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/SemaCUDA.h"
36#include "clang/Sema/SemaInternal.h"
37#include "clang/Sema/Template.h"
38#include "clang/Sema/TemplateDeduction.h"
39#include "llvm/ADT/SmallBitVector.h"
40#include "llvm/ADT/StringExtras.h"
41#include "llvm/Support/SaveAndRestore.h"
42
43#include <optional>
44using namespace clang;
45using namespace sema;
46
47// Exported for use by Parser.
48SourceRange
49clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
50 unsigned N) {
51 if (!N) return SourceRange();
52 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
53}
54
55unsigned Sema::getTemplateDepth(Scope *S) const {
56 unsigned Depth = 0;
57
58 // Each template parameter scope represents one level of template parameter
59 // depth.
60 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
61 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
62 ++Depth;
63 }
64
65 // Note that there are template parameters with the given depth.
66 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(a: Depth, b: D + 1); };
67
68 // Look for parameters of an enclosing generic lambda. We don't create a
69 // template parameter scope for these.
70 for (FunctionScopeInfo *FSI : getFunctionScopes()) {
71 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FSI)) {
72 if (!LSI->TemplateParams.empty()) {
73 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
74 break;
75 }
76 if (LSI->GLTemplateParameterList) {
77 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
78 break;
79 }
80 }
81 }
82
83 // Look for parameters of an enclosing terse function template. We don't
84 // create a template parameter scope for these either.
85 for (const InventedTemplateParameterInfo &Info :
86 getInventedParameterInfos()) {
87 if (!Info.TemplateParams.empty()) {
88 ParamsAtDepth(Info.AutoTemplateParameterDepth);
89 break;
90 }
91 }
92
93 return Depth;
94}
95
96/// \brief Determine whether the declaration found is acceptable as the name
97/// of a template and, if so, return that template declaration. Otherwise,
98/// returns null.
99///
100/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
101/// is true. In all other cases it will return a TemplateDecl (or null).
102NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
103 bool AllowFunctionTemplates,
104 bool AllowDependent) {
105 D = D->getUnderlyingDecl();
106
107 if (isa<TemplateDecl>(Val: D)) {
108 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(Val: D))
109 return nullptr;
110
111 return D;
112 }
113
114 if (const auto *Record = dyn_cast<CXXRecordDecl>(Val: D)) {
115 // C++ [temp.local]p1:
116 // Like normal (non-template) classes, class templates have an
117 // injected-class-name (Clause 9). The injected-class-name
118 // can be used with or without a template-argument-list. When
119 // it is used without a template-argument-list, it is
120 // equivalent to the injected-class-name followed by the
121 // template-parameters of the class template enclosed in
122 // <>. When it is used with a template-argument-list, it
123 // refers to the specified class template specialization,
124 // which could be the current specialization or another
125 // specialization.
126 if (Record->isInjectedClassName()) {
127 Record = cast<CXXRecordDecl>(Val: Record->getDeclContext());
128 if (Record->getDescribedClassTemplate())
129 return Record->getDescribedClassTemplate();
130
131 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record))
132 return Spec->getSpecializedTemplate();
133 }
134
135 return nullptr;
136 }
137
138 // 'using Dependent::foo;' can resolve to a template name.
139 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
140 // injected-class-name).
141 if (AllowDependent && isa<UnresolvedUsingValueDecl>(Val: D))
142 return D;
143
144 return nullptr;
145}
146
147void Sema::FilterAcceptableTemplateNames(LookupResult &R,
148 bool AllowFunctionTemplates,
149 bool AllowDependent) {
150 LookupResult::Filter filter = R.makeFilter();
151 while (filter.hasNext()) {
152 NamedDecl *Orig = filter.next();
153 if (!getAsTemplateNameDecl(D: Orig, AllowFunctionTemplates, AllowDependent))
154 filter.erase();
155 }
156 filter.done();
157}
158
159bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
160 bool AllowFunctionTemplates,
161 bool AllowDependent,
162 bool AllowNonTemplateFunctions) {
163 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
164 if (getAsTemplateNameDecl(D: *I, AllowFunctionTemplates, AllowDependent))
165 return true;
166 if (AllowNonTemplateFunctions &&
167 isa<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
168 return true;
169 }
170
171 return false;
172}
173
174TemplateNameKind Sema::isTemplateName(Scope *S,
175 CXXScopeSpec &SS,
176 bool hasTemplateKeyword,
177 const UnqualifiedId &Name,
178 ParsedType ObjectTypePtr,
179 bool EnteringContext,
180 TemplateTy &TemplateResult,
181 bool &MemberOfUnknownSpecialization,
182 bool Disambiguation) {
183 assert(getLangOpts().CPlusPlus && "No template names in C!");
184
185 DeclarationName TName;
186 MemberOfUnknownSpecialization = false;
187
188 switch (Name.getKind()) {
189 case UnqualifiedIdKind::IK_Identifier:
190 TName = DeclarationName(Name.Identifier);
191 break;
192
193 case UnqualifiedIdKind::IK_OperatorFunctionId:
194 TName = Context.DeclarationNames.getCXXOperatorName(
195 Op: Name.OperatorFunctionId.Operator);
196 break;
197
198 case UnqualifiedIdKind::IK_LiteralOperatorId:
199 TName = Context.DeclarationNames.getCXXLiteralOperatorName(II: Name.Identifier);
200 break;
201
202 default:
203 return TNK_Non_template;
204 }
205
206 QualType ObjectType = ObjectTypePtr.get();
207
208 AssumedTemplateKind AssumedTemplate;
209 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
210 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
211 /*RequiredTemplate=*/SourceLocation(),
212 ATK: &AssumedTemplate,
213 /*AllowTypoCorrection=*/!Disambiguation))
214 return TNK_Non_template;
215 MemberOfUnknownSpecialization = R.wasNotFoundInCurrentInstantiation();
216
217 if (AssumedTemplate != AssumedTemplateKind::None) {
218 TemplateResult = TemplateTy::make(P: Context.getAssumedTemplateName(Name: TName));
219 // Let the parser know whether we found nothing or found functions; if we
220 // found nothing, we want to more carefully check whether this is actually
221 // a function template name versus some other kind of undeclared identifier.
222 return AssumedTemplate == AssumedTemplateKind::FoundNothing
223 ? TNK_Undeclared_template
224 : TNK_Function_template;
225 }
226
227 if (R.empty())
228 return TNK_Non_template;
229
230 NamedDecl *D = nullptr;
231 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *R.begin());
232 if (R.isAmbiguous()) {
233 // If we got an ambiguity involving a non-function template, treat this
234 // as a template name, and pick an arbitrary template for error recovery.
235 bool AnyFunctionTemplates = false;
236 for (NamedDecl *FoundD : R) {
237 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(D: FoundD)) {
238 if (isa<FunctionTemplateDecl>(Val: FoundTemplate))
239 AnyFunctionTemplates = true;
240 else {
241 D = FoundTemplate;
242 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: FoundD);
243 break;
244 }
245 }
246 }
247
248 // If we didn't find any templates at all, this isn't a template name.
249 // Leave the ambiguity for a later lookup to diagnose.
250 if (!D && !AnyFunctionTemplates) {
251 R.suppressDiagnostics();
252 return TNK_Non_template;
253 }
254
255 // If the only templates were function templates, filter out the rest.
256 // We'll diagnose the ambiguity later.
257 if (!D)
258 FilterAcceptableTemplateNames(R);
259 }
260
261 // At this point, we have either picked a single template name declaration D
262 // or we have a non-empty set of results R containing either one template name
263 // declaration or a set of function templates.
264
265 TemplateName Template;
266 TemplateNameKind TemplateKind;
267
268 unsigned ResultCount = R.end() - R.begin();
269 if (!D && ResultCount > 1) {
270 // We assume that we'll preserve the qualifier from a function
271 // template name in other ways.
272 Template = Context.getOverloadedTemplateName(Begin: R.begin(), End: R.end());
273 TemplateKind = TNK_Function_template;
274
275 // We'll do this lookup again later.
276 R.suppressDiagnostics();
277 } else {
278 if (!D) {
279 D = getAsTemplateNameDecl(D: *R.begin());
280 assert(D && "unambiguous result is not a template name");
281 }
282
283 if (isa<UnresolvedUsingValueDecl>(Val: D)) {
284 // We don't yet know whether this is a template-name or not.
285 MemberOfUnknownSpecialization = true;
286 return TNK_Non_template;
287 }
288
289 TemplateDecl *TD = cast<TemplateDecl>(Val: D);
290 Template =
291 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
292 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
293 if (!SS.isInvalid()) {
294 NestedNameSpecifier *Qualifier = SS.getScopeRep();
295 Template = Context.getQualifiedTemplateName(NNS: Qualifier, TemplateKeyword: hasTemplateKeyword,
296 Template);
297 }
298
299 if (isa<FunctionTemplateDecl>(Val: TD)) {
300 TemplateKind = TNK_Function_template;
301
302 // We'll do this lookup again later.
303 R.suppressDiagnostics();
304 } else {
305 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
306 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
307 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
308 TemplateKind =
309 isa<VarTemplateDecl>(Val: TD) ? TNK_Var_template :
310 isa<ConceptDecl>(Val: TD) ? TNK_Concept_template :
311 TNK_Type_template;
312 }
313 }
314
315 TemplateResult = TemplateTy::make(P: Template);
316 return TemplateKind;
317}
318
319bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
320 SourceLocation NameLoc, CXXScopeSpec &SS,
321 ParsedTemplateTy *Template /*=nullptr*/) {
322 // We could use redeclaration lookup here, but we don't need to: the
323 // syntactic form of a deduction guide is enough to identify it even
324 // if we can't look up the template name at all.
325 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
326 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
327 /*EnteringContext*/ false))
328 return false;
329
330 if (R.empty()) return false;
331 if (R.isAmbiguous()) {
332 // FIXME: Diagnose an ambiguity if we find at least one template.
333 R.suppressDiagnostics();
334 return false;
335 }
336
337 // We only treat template-names that name type templates as valid deduction
338 // guide names.
339 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
340 if (!TD || !getAsTypeTemplateDecl(D: TD))
341 return false;
342
343 if (Template) {
344 TemplateName Name = Context.getQualifiedTemplateName(
345 NNS: SS.getScopeRep(), /*TemplateKeyword=*/false, Template: TemplateName(TD));
346 *Template = TemplateTy::make(P: Name);
347 }
348 return true;
349}
350
351bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
352 SourceLocation IILoc,
353 Scope *S,
354 const CXXScopeSpec *SS,
355 TemplateTy &SuggestedTemplate,
356 TemplateNameKind &SuggestedKind) {
357 // We can't recover unless there's a dependent scope specifier preceding the
358 // template name.
359 // FIXME: Typo correction?
360 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(SS: *SS) ||
361 computeDeclContext(SS: *SS))
362 return false;
363
364 // The code is missing a 'template' keyword prior to the dependent template
365 // name.
366 NestedNameSpecifier *Qualifier = (NestedNameSpecifier *)SS->getScopeRep();
367 SuggestedTemplate = TemplateTy::make(P: Context.getDependentTemplateName(
368 Name: {Qualifier, &II, /*HasTemplateKeyword=*/false}));
369 Diag(Loc: IILoc, DiagID: diag::err_template_kw_missing)
370 << SuggestedTemplate.get()
371 << FixItHint::CreateInsertion(InsertionLoc: IILoc, Code: "template ");
372 SuggestedKind = TNK_Dependent_template_name;
373 return true;
374}
375
376bool Sema::LookupTemplateName(LookupResult &Found, Scope *S, CXXScopeSpec &SS,
377 QualType ObjectType, bool EnteringContext,
378 RequiredTemplateKind RequiredTemplate,
379 AssumedTemplateKind *ATK,
380 bool AllowTypoCorrection) {
381 if (ATK)
382 *ATK = AssumedTemplateKind::None;
383
384 if (SS.isInvalid())
385 return true;
386
387 Found.setTemplateNameLookup(true);
388
389 // Determine where to perform name lookup
390 DeclContext *LookupCtx = nullptr;
391 bool IsDependent = false;
392 if (!ObjectType.isNull()) {
393 // This nested-name-specifier occurs in a member access expression, e.g.,
394 // x->B::f, and we are looking into the type of the object.
395 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
396 LookupCtx = computeDeclContext(T: ObjectType);
397 IsDependent = !LookupCtx && ObjectType->isDependentType();
398 assert((IsDependent || !ObjectType->isIncompleteType() ||
399 !ObjectType->getAs<TagType>() ||
400 ObjectType->castAs<TagType>()->isBeingDefined()) &&
401 "Caller should have completed object type");
402
403 // Template names cannot appear inside an Objective-C class or object type
404 // or a vector type.
405 //
406 // FIXME: This is wrong. For example:
407 //
408 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
409 // Vec<int> vi;
410 // vi.Vec<int>::~Vec<int>();
411 //
412 // ... should be accepted but we will not treat 'Vec' as a template name
413 // here. The right thing to do would be to check if the name is a valid
414 // vector component name, and look up a template name if not. And similarly
415 // for lookups into Objective-C class and object types, where the same
416 // problem can arise.
417 if (ObjectType->isObjCObjectOrInterfaceType() ||
418 ObjectType->isVectorType()) {
419 Found.clear();
420 return false;
421 }
422 } else if (SS.isNotEmpty()) {
423 // This nested-name-specifier occurs after another nested-name-specifier,
424 // so long into the context associated with the prior nested-name-specifier.
425 LookupCtx = computeDeclContext(SS, EnteringContext);
426 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
427
428 // The declaration context must be complete.
429 if (LookupCtx && RequireCompleteDeclContext(SS, DC: LookupCtx))
430 return true;
431 }
432
433 bool ObjectTypeSearchedInScope = false;
434 bool AllowFunctionTemplatesInLookup = true;
435 if (LookupCtx) {
436 // Perform "qualified" name lookup into the declaration context we
437 // computed, which is either the type of the base of a member access
438 // expression or the declaration context associated with a prior
439 // nested-name-specifier.
440 LookupQualifiedName(R&: Found, LookupCtx);
441
442 // FIXME: The C++ standard does not clearly specify what happens in the
443 // case where the object type is dependent, and implementations vary. In
444 // Clang, we treat a name after a . or -> as a template-name if lookup
445 // finds a non-dependent member or member of the current instantiation that
446 // is a type template, or finds no such members and lookup in the context
447 // of the postfix-expression finds a type template. In the latter case, the
448 // name is nonetheless dependent, and we may resolve it to a member of an
449 // unknown specialization when we come to instantiate the template.
450 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
451 }
452
453 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
454 // C++ [basic.lookup.classref]p1:
455 // In a class member access expression (5.2.5), if the . or -> token is
456 // immediately followed by an identifier followed by a <, the
457 // identifier must be looked up to determine whether the < is the
458 // beginning of a template argument list (14.2) or a less-than operator.
459 // The identifier is first looked up in the class of the object
460 // expression. If the identifier is not found, it is then looked up in
461 // the context of the entire postfix-expression and shall name a class
462 // template.
463 if (S)
464 LookupName(R&: Found, S);
465
466 if (!ObjectType.isNull()) {
467 // FIXME: We should filter out all non-type templates here, particularly
468 // variable templates and concepts. But the exclusion of alias templates
469 // and template template parameters is a wording defect.
470 AllowFunctionTemplatesInLookup = false;
471 ObjectTypeSearchedInScope = true;
472 }
473
474 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
475 }
476
477 if (Found.isAmbiguous())
478 return false;
479
480 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
481 !RequiredTemplate.hasTemplateKeyword()) {
482 // C++2a [temp.names]p2:
483 // A name is also considered to refer to a template if it is an
484 // unqualified-id followed by a < and name lookup finds either one or more
485 // functions or finds nothing.
486 //
487 // To keep our behavior consistent, we apply the "finds nothing" part in
488 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
489 // successfully form a call to an undeclared template-id.
490 bool AllFunctions =
491 getLangOpts().CPlusPlus20 && llvm::all_of(Range&: Found, P: [](NamedDecl *ND) {
492 return isa<FunctionDecl>(Val: ND->getUnderlyingDecl());
493 });
494 if (AllFunctions || (Found.empty() && !IsDependent)) {
495 // If lookup found any functions, or if this is a name that can only be
496 // used for a function, then strongly assume this is a function
497 // template-id.
498 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
499 ? AssumedTemplateKind::FoundNothing
500 : AssumedTemplateKind::FoundFunctions;
501 Found.clear();
502 return false;
503 }
504 }
505
506 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
507 // If we did not find any names, and this is not a disambiguation, attempt
508 // to correct any typos.
509 DeclarationName Name = Found.getLookupName();
510 Found.clear();
511 // Simple filter callback that, for keywords, only accepts the C++ *_cast
512 DefaultFilterCCC FilterCCC{};
513 FilterCCC.WantTypeSpecifiers = false;
514 FilterCCC.WantExpressionKeywords = false;
515 FilterCCC.WantRemainingKeywords = false;
516 FilterCCC.WantCXXNamedCasts = true;
517 if (TypoCorrection Corrected = CorrectTypo(
518 Typo: Found.getLookupNameInfo(), LookupKind: Found.getLookupKind(), S, SS: &SS, CCC&: FilterCCC,
519 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
520 if (auto *ND = Corrected.getFoundDecl())
521 Found.addDecl(D: ND);
522 FilterAcceptableTemplateNames(R&: Found);
523 if (Found.isAmbiguous()) {
524 Found.clear();
525 } else if (!Found.empty()) {
526 // Do not erase the typo-corrected result to avoid duplicated
527 // diagnostics.
528 AllowFunctionTemplatesInLookup = true;
529 Found.setLookupName(Corrected.getCorrection());
530 if (LookupCtx) {
531 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
532 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
533 Name.getAsString() == CorrectedStr;
534 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_template_suggest)
535 << Name << LookupCtx << DroppedSpecifier
536 << SS.getRange());
537 } else {
538 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_template_suggest) << Name);
539 }
540 }
541 }
542 }
543
544 NamedDecl *ExampleLookupResult =
545 Found.empty() ? nullptr : Found.getRepresentativeDecl();
546 FilterAcceptableTemplateNames(R&: Found, AllowFunctionTemplates: AllowFunctionTemplatesInLookup);
547 if (Found.empty()) {
548 if (IsDependent) {
549 Found.setNotFoundInCurrentInstantiation();
550 return false;
551 }
552
553 // If a 'template' keyword was used, a lookup that finds only non-template
554 // names is an error.
555 if (ExampleLookupResult && RequiredTemplate) {
556 Diag(Loc: Found.getNameLoc(), DiagID: diag::err_template_kw_refers_to_non_template)
557 << Found.getLookupName() << SS.getRange()
558 << RequiredTemplate.hasTemplateKeyword()
559 << RequiredTemplate.getTemplateKeywordLoc();
560 Diag(Loc: ExampleLookupResult->getUnderlyingDecl()->getLocation(),
561 DiagID: diag::note_template_kw_refers_to_non_template)
562 << Found.getLookupName();
563 return true;
564 }
565
566 return false;
567 }
568
569 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
570 !getLangOpts().CPlusPlus11) {
571 // C++03 [basic.lookup.classref]p1:
572 // [...] If the lookup in the class of the object expression finds a
573 // template, the name is also looked up in the context of the entire
574 // postfix-expression and [...]
575 //
576 // Note: C++11 does not perform this second lookup.
577 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
578 LookupOrdinaryName);
579 FoundOuter.setTemplateNameLookup(true);
580 LookupName(R&: FoundOuter, S);
581 // FIXME: We silently accept an ambiguous lookup here, in violation of
582 // [basic.lookup]/1.
583 FilterAcceptableTemplateNames(R&: FoundOuter, /*AllowFunctionTemplates=*/false);
584
585 NamedDecl *OuterTemplate;
586 if (FoundOuter.empty()) {
587 // - if the name is not found, the name found in the class of the
588 // object expression is used, otherwise
589 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
590 !(OuterTemplate =
591 getAsTemplateNameDecl(D: FoundOuter.getFoundDecl()))) {
592 // - if the name is found in the context of the entire
593 // postfix-expression and does not name a class template, the name
594 // found in the class of the object expression is used, otherwise
595 FoundOuter.clear();
596 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
597 // - if the name found is a class template, it must refer to the same
598 // entity as the one found in the class of the object expression,
599 // otherwise the program is ill-formed.
600 if (!Found.isSingleResult() ||
601 getAsTemplateNameDecl(D: Found.getFoundDecl())->getCanonicalDecl() !=
602 OuterTemplate->getCanonicalDecl()) {
603 Diag(Loc: Found.getNameLoc(),
604 DiagID: diag::ext_nested_name_member_ref_lookup_ambiguous)
605 << Found.getLookupName()
606 << ObjectType;
607 Diag(Loc: Found.getRepresentativeDecl()->getLocation(),
608 DiagID: diag::note_ambig_member_ref_object_type)
609 << ObjectType;
610 Diag(Loc: FoundOuter.getFoundDecl()->getLocation(),
611 DiagID: diag::note_ambig_member_ref_scope);
612
613 // Recover by taking the template that we found in the object
614 // expression's type.
615 }
616 }
617 }
618
619 return false;
620}
621
622void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
623 SourceLocation Less,
624 SourceLocation Greater) {
625 if (TemplateName.isInvalid())
626 return;
627
628 DeclarationNameInfo NameInfo;
629 CXXScopeSpec SS;
630 LookupNameKind LookupKind;
631
632 DeclContext *LookupCtx = nullptr;
633 NamedDecl *Found = nullptr;
634 bool MissingTemplateKeyword = false;
635
636 // Figure out what name we looked up.
637 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: TemplateName.get())) {
638 NameInfo = DRE->getNameInfo();
639 SS.Adopt(Other: DRE->getQualifierLoc());
640 LookupKind = LookupOrdinaryName;
641 Found = DRE->getFoundDecl();
642 } else if (auto *ME = dyn_cast<MemberExpr>(Val: TemplateName.get())) {
643 NameInfo = ME->getMemberNameInfo();
644 SS.Adopt(Other: ME->getQualifierLoc());
645 LookupKind = LookupMemberName;
646 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
647 Found = ME->getMemberDecl();
648 } else if (auto *DSDRE =
649 dyn_cast<DependentScopeDeclRefExpr>(Val: TemplateName.get())) {
650 NameInfo = DSDRE->getNameInfo();
651 SS.Adopt(Other: DSDRE->getQualifierLoc());
652 MissingTemplateKeyword = true;
653 } else if (auto *DSME =
654 dyn_cast<CXXDependentScopeMemberExpr>(Val: TemplateName.get())) {
655 NameInfo = DSME->getMemberNameInfo();
656 SS.Adopt(Other: DSME->getQualifierLoc());
657 MissingTemplateKeyword = true;
658 } else {
659 llvm_unreachable("unexpected kind of potential template name");
660 }
661
662 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
663 // was missing.
664 if (MissingTemplateKeyword) {
665 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_template_kw_missing)
666 << NameInfo.getName() << SourceRange(Less, Greater);
667 return;
668 }
669
670 // Try to correct the name by looking for templates and C++ named casts.
671 struct TemplateCandidateFilter : CorrectionCandidateCallback {
672 Sema &S;
673 TemplateCandidateFilter(Sema &S) : S(S) {
674 WantTypeSpecifiers = false;
675 WantExpressionKeywords = false;
676 WantRemainingKeywords = false;
677 WantCXXNamedCasts = true;
678 };
679 bool ValidateCandidate(const TypoCorrection &Candidate) override {
680 if (auto *ND = Candidate.getCorrectionDecl())
681 return S.getAsTemplateNameDecl(D: ND);
682 return Candidate.isKeyword();
683 }
684
685 std::unique_ptr<CorrectionCandidateCallback> clone() override {
686 return std::make_unique<TemplateCandidateFilter>(args&: *this);
687 }
688 };
689
690 DeclarationName Name = NameInfo.getName();
691 TemplateCandidateFilter CCC(*this);
692 if (TypoCorrection Corrected =
693 CorrectTypo(Typo: NameInfo, LookupKind, S, SS: &SS, CCC,
694 Mode: CorrectTypoKind::ErrorRecovery, MemberContext: LookupCtx)) {
695 auto *ND = Corrected.getFoundDecl();
696 if (ND)
697 ND = getAsTemplateNameDecl(D: ND);
698 if (ND || Corrected.isKeyword()) {
699 if (LookupCtx) {
700 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
701 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
702 Name.getAsString() == CorrectedStr;
703 diagnoseTypo(Correction: Corrected,
704 TypoDiag: PDiag(DiagID: diag::err_non_template_in_member_template_id_suggest)
705 << Name << LookupCtx << DroppedSpecifier
706 << SS.getRange(), ErrorRecovery: false);
707 } else {
708 diagnoseTypo(Correction: Corrected,
709 TypoDiag: PDiag(DiagID: diag::err_non_template_in_template_id_suggest)
710 << Name, ErrorRecovery: false);
711 }
712 if (Found)
713 Diag(Loc: Found->getLocation(),
714 DiagID: diag::note_non_template_in_template_id_found);
715 return;
716 }
717 }
718
719 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_non_template_in_template_id)
720 << Name << SourceRange(Less, Greater);
721 if (Found)
722 Diag(Loc: Found->getLocation(), DiagID: diag::note_non_template_in_template_id_found);
723}
724
725ExprResult
726Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
727 SourceLocation TemplateKWLoc,
728 const DeclarationNameInfo &NameInfo,
729 bool isAddressOfOperand,
730 const TemplateArgumentListInfo *TemplateArgs) {
731 if (SS.isEmpty()) {
732 // FIXME: This codepath is only used by dependent unqualified names
733 // (e.g. a dependent conversion-function-id, or operator= once we support
734 // it). It doesn't quite do the right thing, and it will silently fail if
735 // getCurrentThisType() returns null.
736 QualType ThisType = getCurrentThisType();
737 if (ThisType.isNull())
738 return ExprError();
739
740 return CXXDependentScopeMemberExpr::Create(
741 Ctx: Context, /*Base=*/nullptr, BaseType: ThisType,
742 /*IsArrow=*/!Context.getLangOpts().HLSL,
743 /*OperatorLoc=*/SourceLocation(),
744 /*QualifierLoc=*/NestedNameSpecifierLoc(), TemplateKWLoc,
745 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, TemplateArgs);
746 }
747 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
748}
749
750ExprResult
751Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
752 SourceLocation TemplateKWLoc,
753 const DeclarationNameInfo &NameInfo,
754 const TemplateArgumentListInfo *TemplateArgs) {
755 // DependentScopeDeclRefExpr::Create requires a valid NestedNameSpecifierLoc
756 if (!SS.isValid())
757 return CreateRecoveryExpr(
758 Begin: SS.getBeginLoc(),
759 End: TemplateArgs ? TemplateArgs->getRAngleLoc() : NameInfo.getEndLoc(), SubExprs: {});
760
761 return DependentScopeDeclRefExpr::Create(
762 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
763 TemplateArgs);
764}
765
766bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
767 NamedDecl *Instantiation,
768 bool InstantiatedFromMember,
769 const NamedDecl *Pattern,
770 const NamedDecl *PatternDef,
771 TemplateSpecializationKind TSK,
772 bool Complain, bool *Unreachable) {
773 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
774 isa<VarDecl>(Instantiation));
775
776 bool IsEntityBeingDefined = false;
777 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(Val: PatternDef))
778 IsEntityBeingDefined = TD->isBeingDefined();
779
780 if (PatternDef && !IsEntityBeingDefined) {
781 NamedDecl *SuggestedDef = nullptr;
782 if (!hasReachableDefinition(D: const_cast<NamedDecl *>(PatternDef),
783 Suggested: &SuggestedDef,
784 /*OnlyNeedComplete*/ false)) {
785 if (Unreachable)
786 *Unreachable = true;
787 // If we're allowed to diagnose this and recover, do so.
788 bool Recover = Complain && !isSFINAEContext();
789 if (Complain)
790 diagnoseMissingImport(Loc: PointOfInstantiation, Decl: SuggestedDef,
791 MIK: Sema::MissingImportKind::Definition, Recover);
792 return !Recover;
793 }
794 return false;
795 }
796
797 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
798 return true;
799
800 QualType InstantiationTy;
801 if (TagDecl *TD = dyn_cast<TagDecl>(Val: Instantiation))
802 InstantiationTy = Context.getTypeDeclType(Decl: TD);
803 if (PatternDef) {
804 Diag(Loc: PointOfInstantiation,
805 DiagID: diag::err_template_instantiate_within_definition)
806 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
807 << InstantiationTy;
808 // Not much point in noting the template declaration here, since
809 // we're lexically inside it.
810 Instantiation->setInvalidDecl();
811 } else if (InstantiatedFromMember) {
812 if (isa<FunctionDecl>(Val: Instantiation)) {
813 Diag(Loc: PointOfInstantiation,
814 DiagID: diag::err_explicit_instantiation_undefined_member)
815 << /*member function*/ 1 << Instantiation->getDeclName()
816 << Instantiation->getDeclContext();
817 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
818 } else {
819 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
820 Diag(Loc: PointOfInstantiation,
821 DiagID: diag::err_implicit_instantiate_member_undefined)
822 << InstantiationTy;
823 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_member_declared_at);
824 }
825 } else {
826 if (isa<FunctionDecl>(Val: Instantiation)) {
827 Diag(Loc: PointOfInstantiation,
828 DiagID: diag::err_explicit_instantiation_undefined_func_template)
829 << Pattern;
830 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
831 } else if (isa<TagDecl>(Val: Instantiation)) {
832 Diag(Loc: PointOfInstantiation, DiagID: diag::err_template_instantiate_undefined)
833 << (TSK != TSK_ImplicitInstantiation)
834 << InstantiationTy;
835 NoteTemplateLocation(Decl: *Pattern);
836 } else {
837 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
838 if (isa<VarTemplateSpecializationDecl>(Val: Instantiation)) {
839 Diag(Loc: PointOfInstantiation,
840 DiagID: diag::err_explicit_instantiation_undefined_var_template)
841 << Instantiation;
842 Instantiation->setInvalidDecl();
843 } else
844 Diag(Loc: PointOfInstantiation,
845 DiagID: diag::err_explicit_instantiation_undefined_member)
846 << /*static data member*/ 2 << Instantiation->getDeclName()
847 << Instantiation->getDeclContext();
848 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_explicit_instantiation_here);
849 }
850 }
851
852 // In general, Instantiation isn't marked invalid to get more than one
853 // error for multiple undefined instantiations. But the code that does
854 // explicit declaration -> explicit definition conversion can't handle
855 // invalid declarations, so mark as invalid in that case.
856 if (TSK == TSK_ExplicitInstantiationDeclaration)
857 Instantiation->setInvalidDecl();
858 return true;
859}
860
861void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
862 bool SupportedForCompatibility) {
863 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
864
865 // C++23 [temp.local]p6:
866 // The name of a template-parameter shall not be bound to any following.
867 // declaration whose locus is contained by the scope to which the
868 // template-parameter belongs.
869 //
870 // When MSVC compatibility is enabled, the diagnostic is always a warning
871 // by default. Otherwise, it an error unless SupportedForCompatibility is
872 // true, in which case it is a default-to-error warning.
873 unsigned DiagId =
874 getLangOpts().MSVCCompat
875 ? diag::ext_template_param_shadow
876 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
877 : diag::err_template_param_shadow);
878 const auto *ND = cast<NamedDecl>(Val: PrevDecl);
879 Diag(Loc, DiagID: DiagId) << ND->getDeclName();
880 NoteTemplateParameterLocation(Decl: *ND);
881}
882
883TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
884 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(Val: D)) {
885 D = Temp->getTemplatedDecl();
886 return Temp;
887 }
888 return nullptr;
889}
890
891ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
892 SourceLocation EllipsisLoc) const {
893 assert(Kind == Template &&
894 "Only template template arguments can be pack expansions here");
895 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
896 "Template template argument pack expansion without packs");
897 ParsedTemplateArgument Result(*this);
898 Result.EllipsisLoc = EllipsisLoc;
899 return Result;
900}
901
902static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
903 const ParsedTemplateArgument &Arg) {
904
905 switch (Arg.getKind()) {
906 case ParsedTemplateArgument::Type: {
907 TypeSourceInfo *DI;
908 QualType T = SemaRef.GetTypeFromParser(Ty: Arg.getAsType(), TInfo: &DI);
909 if (!DI)
910 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc: Arg.getLocation());
911 return TemplateArgumentLoc(TemplateArgument(T), DI);
912 }
913
914 case ParsedTemplateArgument::NonType: {
915 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
916 return TemplateArgumentLoc(TemplateArgument(E, /*IsCanonical=*/false), E);
917 }
918
919 case ParsedTemplateArgument::Template: {
920 TemplateName Template = Arg.getAsTemplate().get();
921 TemplateArgument TArg;
922 if (Arg.getEllipsisLoc().isValid())
923 TArg = TemplateArgument(Template, /*NumExpansions=*/std::nullopt);
924 else
925 TArg = Template;
926 return TemplateArgumentLoc(
927 SemaRef.Context, TArg,
928 Arg.getScopeSpec().getWithLocInContext(Context&: SemaRef.Context),
929 Arg.getLocation(), Arg.getEllipsisLoc());
930 }
931 }
932
933 llvm_unreachable("Unhandled parsed template argument");
934}
935
936void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
937 TemplateArgumentListInfo &TemplateArgs) {
938 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
939 TemplateArgs.addArgument(Loc: translateTemplateArgument(SemaRef&: *this,
940 Arg: TemplateArgsIn[I]));
941}
942
943static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
944 SourceLocation Loc,
945 const IdentifierInfo *Name) {
946 NamedDecl *PrevDecl =
947 SemaRef.LookupSingleName(S, Name, Loc, NameKind: Sema::LookupOrdinaryName,
948 Redecl: RedeclarationKind::ForVisibleRedeclaration);
949 if (PrevDecl && PrevDecl->isTemplateParameter())
950 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
951}
952
953ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
954 TypeSourceInfo *TInfo;
955 QualType T = GetTypeFromParser(Ty: ParsedType.get(), TInfo: &TInfo);
956 if (T.isNull())
957 return ParsedTemplateArgument();
958 assert(TInfo && "template argument with no location");
959
960 // If we might have formed a deduced template specialization type, convert
961 // it to a template template argument.
962 if (getLangOpts().CPlusPlus17) {
963 TypeLoc TL = TInfo->getTypeLoc();
964 SourceLocation EllipsisLoc;
965 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
966 EllipsisLoc = PET.getEllipsisLoc();
967 TL = PET.getPatternLoc();
968 }
969
970 CXXScopeSpec SS;
971 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
972 SS.Adopt(Other: ET.getQualifierLoc());
973 TL = ET.getNamedTypeLoc();
974 }
975
976 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
977 TemplateName Name = DTST.getTypePtr()->getTemplateName();
978 ParsedTemplateArgument Result(SS, TemplateTy::make(P: Name),
979 DTST.getTemplateNameLoc());
980 if (EllipsisLoc.isValid())
981 Result = Result.getTemplatePackExpansion(EllipsisLoc);
982 return Result;
983 }
984 }
985
986 // This is a normal type template argument. Note, if the type template
987 // argument is an injected-class-name for a template, it has a dual nature
988 // and can be used as either a type or a template. We handle that in
989 // convertTypeTemplateArgumentToTemplate.
990 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
991 ParsedType.get().getAsOpaquePtr(),
992 TInfo->getTypeLoc().getBeginLoc());
993}
994
995NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
996 SourceLocation EllipsisLoc,
997 SourceLocation KeyLoc,
998 IdentifierInfo *ParamName,
999 SourceLocation ParamNameLoc,
1000 unsigned Depth, unsigned Position,
1001 SourceLocation EqualLoc,
1002 ParsedType DefaultArg,
1003 bool HasTypeConstraint) {
1004 assert(S->isTemplateParamScope() &&
1005 "Template type parameter not in template parameter scope!");
1006
1007 bool IsParameterPack = EllipsisLoc.isValid();
1008 TemplateTypeParmDecl *Param
1009 = TemplateTypeParmDecl::Create(C: Context, DC: Context.getTranslationUnitDecl(),
1010 KeyLoc, NameLoc: ParamNameLoc, D: Depth, P: Position,
1011 Id: ParamName, Typename, ParameterPack: IsParameterPack,
1012 HasTypeConstraint);
1013 Param->setAccess(AS_public);
1014
1015 if (Param->isParameterPack())
1016 if (auto *CSI = getEnclosingLambdaOrBlock())
1017 CSI->LocalPacks.push_back(Elt: Param);
1018
1019 if (ParamName) {
1020 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: ParamNameLoc, Name: ParamName);
1021
1022 // Add the template parameter into the current scope.
1023 S->AddDecl(D: Param);
1024 IdResolver.AddDecl(D: Param);
1025 }
1026
1027 // C++0x [temp.param]p9:
1028 // A default template-argument may be specified for any kind of
1029 // template-parameter that is not a template parameter pack.
1030 if (DefaultArg && IsParameterPack) {
1031 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1032 DefaultArg = nullptr;
1033 }
1034
1035 // Handle the default argument, if provided.
1036 if (DefaultArg) {
1037 TypeSourceInfo *DefaultTInfo;
1038 GetTypeFromParser(Ty: DefaultArg, TInfo: &DefaultTInfo);
1039
1040 assert(DefaultTInfo && "expected source information for type");
1041
1042 // Check for unexpanded parameter packs.
1043 if (DiagnoseUnexpandedParameterPack(Loc: ParamNameLoc, T: DefaultTInfo,
1044 UPPC: UPPC_DefaultArgument))
1045 return Param;
1046
1047 // Check the template argument itself.
1048 if (CheckTemplateArgument(Arg: DefaultTInfo)) {
1049 Param->setInvalidDecl();
1050 return Param;
1051 }
1052
1053 Param->setDefaultArgument(
1054 C: Context, DefArg: TemplateArgumentLoc(DefaultTInfo->getType(), DefaultTInfo));
1055 }
1056
1057 return Param;
1058}
1059
1060/// Convert the parser's template argument list representation into our form.
1061static TemplateArgumentListInfo
1062makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1063 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1064 TemplateId.RAngleLoc);
1065 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1066 TemplateId.NumArgs);
1067 S.translateTemplateArguments(TemplateArgsIn: TemplateArgsPtr, TemplateArgs);
1068 return TemplateArgs;
1069}
1070
1071bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {
1072
1073 TemplateName TN = TypeConstr->Template.get();
1074 ConceptDecl *CD = cast<ConceptDecl>(Val: TN.getAsTemplateDecl());
1075
1076 // C++2a [temp.param]p4:
1077 // [...] The concept designated by a type-constraint shall be a type
1078 // concept ([temp.concept]).
1079 if (!CD->isTypeConcept()) {
1080 Diag(Loc: TypeConstr->TemplateNameLoc,
1081 DiagID: diag::err_type_constraint_non_type_concept);
1082 return true;
1083 }
1084
1085 if (CheckConceptUseInDefinition(Concept: CD, Loc: TypeConstr->TemplateNameLoc))
1086 return true;
1087
1088 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1089
1090 if (!WereArgsSpecified &&
1091 CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
1092 Diag(Loc: TypeConstr->TemplateNameLoc,
1093 DiagID: diag::err_type_constraint_missing_arguments)
1094 << CD;
1095 return true;
1096 }
1097 return false;
1098}
1099
1100bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1101 TemplateIdAnnotation *TypeConstr,
1102 TemplateTypeParmDecl *ConstrainedParameter,
1103 SourceLocation EllipsisLoc) {
1104 return BuildTypeConstraint(SS, TypeConstraint: TypeConstr, ConstrainedParameter, EllipsisLoc,
1105 AllowUnexpandedPack: false);
1106}
1107
1108bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1109 TemplateIdAnnotation *TypeConstr,
1110 TemplateTypeParmDecl *ConstrainedParameter,
1111 SourceLocation EllipsisLoc,
1112 bool AllowUnexpandedPack) {
1113
1114 if (CheckTypeConstraint(TypeConstr))
1115 return true;
1116
1117 TemplateName TN = TypeConstr->Template.get();
1118 ConceptDecl *CD = cast<ConceptDecl>(Val: TN.getAsTemplateDecl());
1119 UsingShadowDecl *USD = TN.getAsUsingShadowDecl();
1120
1121 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1122 TypeConstr->TemplateNameLoc);
1123
1124 TemplateArgumentListInfo TemplateArgs;
1125 if (TypeConstr->LAngleLoc.isValid()) {
1126 TemplateArgs =
1127 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TypeConstr);
1128
1129 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1130 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1131 if (DiagnoseUnexpandedParameterPack(Arg, UPPC: UPPC_TypeConstraint))
1132 return true;
1133 }
1134 }
1135 }
1136 return AttachTypeConstraint(
1137 NS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1138 NameInfo: ConceptName, NamedConcept: CD, /*FoundDecl=*/USD ? cast<NamedDecl>(Val: USD) : CD,
1139 TemplateArgs: TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1140 ConstrainedParameter, EllipsisLoc);
1141}
1142
1143template <typename ArgumentLocAppender>
1144static ExprResult formImmediatelyDeclaredConstraint(
1145 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1146 ConceptDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1147 SourceLocation RAngleLoc, QualType ConstrainedType,
1148 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1149 SourceLocation EllipsisLoc) {
1150
1151 TemplateArgumentListInfo ConstraintArgs;
1152 ConstraintArgs.addArgument(
1153 Loc: S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(ConstrainedType),
1154 /*NTTPType=*/QualType(), Loc: ParamNameLoc));
1155
1156 ConstraintArgs.setRAngleLoc(RAngleLoc);
1157 ConstraintArgs.setLAngleLoc(LAngleLoc);
1158 Appender(ConstraintArgs);
1159
1160 // C++2a [temp.param]p4:
1161 // [...] This constraint-expression E is called the immediately-declared
1162 // constraint of T. [...]
1163 CXXScopeSpec SS;
1164 SS.Adopt(Other: NS);
1165 ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1166 SS, /*TemplateKWLoc=*/SourceLocation(), ConceptNameInfo: NameInfo,
1167 /*FoundDecl=*/FoundDecl ? FoundDecl : NamedConcept, NamedConcept,
1168 TemplateArgs: &ConstraintArgs);
1169 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1170 return ImmediatelyDeclaredConstraint;
1171
1172 // C++2a [temp.param]p4:
1173 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1174 //
1175 // We have the following case:
1176 //
1177 // template<typename T> concept C1 = true;
1178 // template<C1... T> struct s1;
1179 //
1180 // The constraint: (C1<T> && ...)
1181 //
1182 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1183 // any unqualified lookups for 'operator&&' here.
1184 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/Callee: nullptr,
1185 /*LParenLoc=*/SourceLocation(),
1186 LHS: ImmediatelyDeclaredConstraint.get(), Operator: BO_LAnd,
1187 EllipsisLoc, /*RHS=*/nullptr,
1188 /*RParenLoc=*/SourceLocation(),
1189 /*NumExpansions=*/std::nullopt);
1190}
1191
1192bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1193 DeclarationNameInfo NameInfo,
1194 ConceptDecl *NamedConcept, NamedDecl *FoundDecl,
1195 const TemplateArgumentListInfo *TemplateArgs,
1196 TemplateTypeParmDecl *ConstrainedParameter,
1197 SourceLocation EllipsisLoc) {
1198 // C++2a [temp.param]p4:
1199 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1200 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1201 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1202 TemplateArgs ? ASTTemplateArgumentListInfo::Create(C: Context,
1203 List: *TemplateArgs) : nullptr;
1204
1205 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1206
1207 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1208 S&: *this, NS, NameInfo, NamedConcept, FoundDecl,
1209 LAngleLoc: TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1210 RAngleLoc: TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1211 ConstrainedType: ParamAsArgument, ParamNameLoc: ConstrainedParameter->getLocation(),
1212 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1213 if (TemplateArgs)
1214 for (const auto &ArgLoc : TemplateArgs->arguments())
1215 ConstraintArgs.addArgument(Loc: ArgLoc);
1216 },
1217 EllipsisLoc);
1218 if (ImmediatelyDeclaredConstraint.isInvalid())
1219 return true;
1220
1221 auto *CL = ConceptReference::Create(C: Context, /*NNS=*/NS,
1222 /*TemplateKWLoc=*/SourceLocation{},
1223 /*ConceptNameInfo=*/NameInfo,
1224 /*FoundDecl=*/FoundDecl,
1225 /*NamedConcept=*/NamedConcept,
1226 /*ArgsWritten=*/ArgsAsWritten);
1227 ConstrainedParameter->setTypeConstraint(
1228 CR: CL, ImmediatelyDeclaredConstraint: ImmediatelyDeclaredConstraint.get(), ArgPackSubstIndex: std::nullopt);
1229 return false;
1230}
1231
1232bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
1233 NonTypeTemplateParmDecl *NewConstrainedParm,
1234 NonTypeTemplateParmDecl *OrigConstrainedParm,
1235 SourceLocation EllipsisLoc) {
1236 if (NewConstrainedParm->getType().getNonPackExpansionType() != TL.getType() ||
1237 TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1238 Diag(Loc: NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1239 DiagID: diag::err_unsupported_placeholder_constraint)
1240 << NewConstrainedParm->getTypeSourceInfo()
1241 ->getTypeLoc()
1242 .getSourceRange();
1243 return true;
1244 }
1245 // FIXME: Concepts: This should be the type of the placeholder, but this is
1246 // unclear in the wording right now.
1247 DeclRefExpr *Ref =
1248 BuildDeclRefExpr(D: OrigConstrainedParm, Ty: OrigConstrainedParm->getType(),
1249 VK: VK_PRValue, Loc: OrigConstrainedParm->getLocation());
1250 if (!Ref)
1251 return true;
1252 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1253 S&: *this, NS: TL.getNestedNameSpecifierLoc(), NameInfo: TL.getConceptNameInfo(),
1254 NamedConcept: TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), LAngleLoc: TL.getLAngleLoc(),
1255 RAngleLoc: TL.getRAngleLoc(), ConstrainedType: BuildDecltypeType(E: Ref),
1256 ParamNameLoc: OrigConstrainedParm->getLocation(),
1257 Appender: [&](TemplateArgumentListInfo &ConstraintArgs) {
1258 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1259 ConstraintArgs.addArgument(Loc: TL.getArgLoc(i: I));
1260 },
1261 EllipsisLoc);
1262 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1263 !ImmediatelyDeclaredConstraint.isUsable())
1264 return true;
1265
1266 NewConstrainedParm->setPlaceholderTypeConstraint(
1267 ImmediatelyDeclaredConstraint.get());
1268 return false;
1269}
1270
1271QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1272 SourceLocation Loc) {
1273 if (TSI->getType()->isUndeducedType()) {
1274 // C++17 [temp.dep.expr]p3:
1275 // An id-expression is type-dependent if it contains
1276 // - an identifier associated by name lookup with a non-type
1277 // template-parameter declared with a type that contains a
1278 // placeholder type (7.1.7.4),
1279 TSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSI);
1280 }
1281
1282 return CheckNonTypeTemplateParameterType(T: TSI->getType(), Loc);
1283}
1284
1285bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1286 if (T->isDependentType())
1287 return false;
1288
1289 if (RequireCompleteType(Loc, T, DiagID: diag::err_template_nontype_parm_incomplete))
1290 return true;
1291
1292 if (T->isStructuralType())
1293 return false;
1294
1295 // Structural types are required to be object types or lvalue references.
1296 if (T->isRValueReferenceType()) {
1297 Diag(Loc, DiagID: diag::err_template_nontype_parm_rvalue_ref) << T;
1298 return true;
1299 }
1300
1301 // Don't mention structural types in our diagnostic prior to C++20. Also,
1302 // there's not much more we can say about non-scalar non-class types --
1303 // because we can't see functions or arrays here, those can only be language
1304 // extensions.
1305 if (!getLangOpts().CPlusPlus20 ||
1306 (!T->isScalarType() && !T->isRecordType())) {
1307 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_type) << T;
1308 return true;
1309 }
1310
1311 // Structural types are required to be literal types.
1312 if (RequireLiteralType(Loc, T, DiagID: diag::err_template_nontype_parm_not_literal))
1313 return true;
1314
1315 Diag(Loc, DiagID: diag::err_template_nontype_parm_not_structural) << T;
1316
1317 // Drill down into the reason why the class is non-structural.
1318 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1319 // All members are required to be public and non-mutable, and can't be of
1320 // rvalue reference type. Check these conditions first to prefer a "local"
1321 // reason over a more distant one.
1322 for (const FieldDecl *FD : RD->fields()) {
1323 if (FD->getAccess() != AS_public) {
1324 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_non_public) << T << 0;
1325 return true;
1326 }
1327 if (FD->isMutable()) {
1328 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_mutable_field) << T;
1329 return true;
1330 }
1331 if (FD->getType()->isRValueReferenceType()) {
1332 Diag(Loc: FD->getLocation(), DiagID: diag::note_not_structural_rvalue_ref_field)
1333 << T;
1334 return true;
1335 }
1336 }
1337
1338 // All bases are required to be public.
1339 for (const auto &BaseSpec : RD->bases()) {
1340 if (BaseSpec.getAccessSpecifier() != AS_public) {
1341 Diag(Loc: BaseSpec.getBaseTypeLoc(), DiagID: diag::note_not_structural_non_public)
1342 << T << 1;
1343 return true;
1344 }
1345 }
1346
1347 // All subobjects are required to be of structural types.
1348 SourceLocation SubLoc;
1349 QualType SubType;
1350 int Kind = -1;
1351
1352 for (const FieldDecl *FD : RD->fields()) {
1353 QualType T = Context.getBaseElementType(QT: FD->getType());
1354 if (!T->isStructuralType()) {
1355 SubLoc = FD->getLocation();
1356 SubType = T;
1357 Kind = 0;
1358 break;
1359 }
1360 }
1361
1362 if (Kind == -1) {
1363 for (const auto &BaseSpec : RD->bases()) {
1364 QualType T = BaseSpec.getType();
1365 if (!T->isStructuralType()) {
1366 SubLoc = BaseSpec.getBaseTypeLoc();
1367 SubType = T;
1368 Kind = 1;
1369 break;
1370 }
1371 }
1372 }
1373
1374 assert(Kind != -1 && "couldn't find reason why type is not structural");
1375 Diag(Loc: SubLoc, DiagID: diag::note_not_structural_subobject)
1376 << T << Kind << SubType;
1377 T = SubType;
1378 RD = T->getAsCXXRecordDecl();
1379 }
1380
1381 return true;
1382}
1383
1384QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1385 SourceLocation Loc) {
1386 // We don't allow variably-modified types as the type of non-type template
1387 // parameters.
1388 if (T->isVariablyModifiedType()) {
1389 Diag(Loc, DiagID: diag::err_variably_modified_nontype_template_param)
1390 << T;
1391 return QualType();
1392 }
1393
1394 // C++ [temp.param]p4:
1395 //
1396 // A non-type template-parameter shall have one of the following
1397 // (optionally cv-qualified) types:
1398 //
1399 // -- integral or enumeration type,
1400 if (T->isIntegralOrEnumerationType() ||
1401 // -- pointer to object or pointer to function,
1402 T->isPointerType() ||
1403 // -- lvalue reference to object or lvalue reference to function,
1404 T->isLValueReferenceType() ||
1405 // -- pointer to member,
1406 T->isMemberPointerType() ||
1407 // -- std::nullptr_t, or
1408 T->isNullPtrType() ||
1409 // -- a type that contains a placeholder type.
1410 T->isUndeducedType()) {
1411 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1412 // are ignored when determining its type.
1413 return T.getUnqualifiedType();
1414 }
1415
1416 // C++ [temp.param]p8:
1417 //
1418 // A non-type template-parameter of type "array of T" or
1419 // "function returning T" is adjusted to be of type "pointer to
1420 // T" or "pointer to function returning T", respectively.
1421 if (T->isArrayType() || T->isFunctionType())
1422 return Context.getDecayedType(T);
1423
1424 // If T is a dependent type, we can't do the check now, so we
1425 // assume that it is well-formed. Note that stripping off the
1426 // qualifiers here is not really correct if T turns out to be
1427 // an array type, but we'll recompute the type everywhere it's
1428 // used during instantiation, so that should be OK. (Using the
1429 // qualified type is equally wrong.)
1430 if (T->isDependentType())
1431 return T.getUnqualifiedType();
1432
1433 // C++20 [temp.param]p6:
1434 // -- a structural type
1435 if (RequireStructuralType(T, Loc))
1436 return QualType();
1437
1438 if (!getLangOpts().CPlusPlus20) {
1439 // FIXME: Consider allowing structural types as an extension in C++17. (In
1440 // earlier language modes, the template argument evaluation rules are too
1441 // inflexible.)
1442 Diag(Loc, DiagID: diag::err_template_nontype_parm_bad_structural_type) << T;
1443 return QualType();
1444 }
1445
1446 Diag(Loc, DiagID: diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1447 return T.getUnqualifiedType();
1448}
1449
1450NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1451 unsigned Depth,
1452 unsigned Position,
1453 SourceLocation EqualLoc,
1454 Expr *Default) {
1455 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
1456
1457 // Check that we have valid decl-specifiers specified.
1458 auto CheckValidDeclSpecifiers = [this, &D] {
1459 // C++ [temp.param]
1460 // p1
1461 // template-parameter:
1462 // ...
1463 // parameter-declaration
1464 // p2
1465 // ... A storage class shall not be specified in a template-parameter
1466 // declaration.
1467 // [dcl.typedef]p1:
1468 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1469 // of a parameter-declaration
1470 const DeclSpec &DS = D.getDeclSpec();
1471 auto EmitDiag = [this](SourceLocation Loc) {
1472 Diag(Loc, DiagID: diag::err_invalid_decl_specifier_in_nontype_parm)
1473 << FixItHint::CreateRemoval(RemoveRange: Loc);
1474 };
1475 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1476 EmitDiag(DS.getStorageClassSpecLoc());
1477
1478 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1479 EmitDiag(DS.getThreadStorageClassSpecLoc());
1480
1481 // [dcl.inline]p1:
1482 // The inline specifier can be applied only to the declaration or
1483 // definition of a variable or function.
1484
1485 if (DS.isInlineSpecified())
1486 EmitDiag(DS.getInlineSpecLoc());
1487
1488 // [dcl.constexpr]p1:
1489 // The constexpr specifier shall be applied only to the definition of a
1490 // variable or variable template or the declaration of a function or
1491 // function template.
1492
1493 if (DS.hasConstexprSpecifier())
1494 EmitDiag(DS.getConstexprSpecLoc());
1495
1496 // [dcl.fct.spec]p1:
1497 // Function-specifiers can be used only in function declarations.
1498
1499 if (DS.isVirtualSpecified())
1500 EmitDiag(DS.getVirtualSpecLoc());
1501
1502 if (DS.hasExplicitSpecifier())
1503 EmitDiag(DS.getExplicitSpecLoc());
1504
1505 if (DS.isNoreturnSpecified())
1506 EmitDiag(DS.getNoreturnSpecLoc());
1507 };
1508
1509 CheckValidDeclSpecifiers();
1510
1511 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1512 if (isa<AutoType>(Val: T))
1513 Diag(Loc: D.getIdentifierLoc(),
1514 DiagID: diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1515 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1516
1517 assert(S->isTemplateParamScope() &&
1518 "Non-type template parameter not in template parameter scope!");
1519 bool Invalid = false;
1520
1521 QualType T = CheckNonTypeTemplateParameterType(TSI&: TInfo, Loc: D.getIdentifierLoc());
1522 if (T.isNull()) {
1523 T = Context.IntTy; // Recover with an 'int' type.
1524 Invalid = true;
1525 }
1526
1527 CheckFunctionOrTemplateParamDeclarator(S, D);
1528
1529 const IdentifierInfo *ParamName = D.getIdentifier();
1530 bool IsParameterPack = D.hasEllipsis();
1531 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1532 C: Context, DC: Context.getTranslationUnitDecl(), StartLoc: D.getBeginLoc(),
1533 IdLoc: D.getIdentifierLoc(), D: Depth, P: Position, Id: ParamName, T, ParameterPack: IsParameterPack,
1534 TInfo);
1535 Param->setAccess(AS_public);
1536
1537 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1538 if (TL.isConstrained()) {
1539 if (D.getEllipsisLoc().isInvalid() &&
1540 T->containsUnexpandedParameterPack()) {
1541 assert(TL.getConceptReference()->getTemplateArgsAsWritten());
1542 for (auto &Loc :
1543 TL.getConceptReference()->getTemplateArgsAsWritten()->arguments())
1544 Invalid |= DiagnoseUnexpandedParameterPack(
1545 Arg: Loc, UPPC: UnexpandedParameterPackContext::UPPC_TypeConstraint);
1546 }
1547 if (!Invalid &&
1548 AttachTypeConstraint(TL, NewConstrainedParm: Param, OrigConstrainedParm: Param, EllipsisLoc: D.getEllipsisLoc()))
1549 Invalid = true;
1550 }
1551
1552 if (Invalid)
1553 Param->setInvalidDecl();
1554
1555 if (Param->isParameterPack())
1556 if (auto *CSI = getEnclosingLambdaOrBlock())
1557 CSI->LocalPacks.push_back(Elt: Param);
1558
1559 if (ParamName) {
1560 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: D.getIdentifierLoc(),
1561 Name: ParamName);
1562
1563 // Add the template parameter into the current scope.
1564 S->AddDecl(D: Param);
1565 IdResolver.AddDecl(D: Param);
1566 }
1567
1568 // C++0x [temp.param]p9:
1569 // A default template-argument may be specified for any kind of
1570 // template-parameter that is not a template parameter pack.
1571 if (Default && IsParameterPack) {
1572 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1573 Default = nullptr;
1574 }
1575
1576 // Check the well-formedness of the default template argument, if provided.
1577 if (Default) {
1578 // Check for unexpanded parameter packs.
1579 if (DiagnoseUnexpandedParameterPack(E: Default, UPPC: UPPC_DefaultArgument))
1580 return Param;
1581
1582 Param->setDefaultArgument(
1583 C: Context, DefArg: getTrivialTemplateArgumentLoc(
1584 Arg: TemplateArgument(Default, /*IsCanonical=*/false),
1585 NTTPType: QualType(), Loc: SourceLocation()));
1586 }
1587
1588 return Param;
1589}
1590
1591NamedDecl *Sema::ActOnTemplateTemplateParameter(
1592 Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params,
1593 bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *Name,
1594 SourceLocation NameLoc, unsigned Depth, unsigned Position,
1595 SourceLocation EqualLoc, ParsedTemplateArgument Default) {
1596 assert(S->isTemplateParamScope() &&
1597 "Template template parameter not in template parameter scope!");
1598
1599 bool IsParameterPack = EllipsisLoc.isValid();
1600
1601 bool Invalid = false;
1602 if (CheckTemplateParameterList(
1603 NewParams: Params,
1604 /*OldParams=*/nullptr,
1605 TPC: IsParameterPack ? TPC_TemplateTemplateParameterPack : TPC_Other))
1606 Invalid = true;
1607
1608 // Construct the parameter object.
1609 TemplateTemplateParmDecl *Param = TemplateTemplateParmDecl::Create(
1610 C: Context, DC: Context.getTranslationUnitDecl(),
1611 L: NameLoc.isInvalid() ? TmpLoc : NameLoc, D: Depth, P: Position, ParameterPack: IsParameterPack,
1612 Id: Name, Typename, Params);
1613 Param->setAccess(AS_public);
1614
1615 if (Param->isParameterPack())
1616 if (auto *LSI = getEnclosingLambdaOrBlock())
1617 LSI->LocalPacks.push_back(Elt: Param);
1618
1619 // If the template template parameter has a name, then link the identifier
1620 // into the scope and lookup mechanisms.
1621 if (Name) {
1622 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: NameLoc, Name);
1623
1624 S->AddDecl(D: Param);
1625 IdResolver.AddDecl(D: Param);
1626 }
1627
1628 if (Params->size() == 0) {
1629 Diag(Loc: Param->getLocation(), DiagID: diag::err_template_template_parm_no_parms)
1630 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1631 Invalid = true;
1632 }
1633
1634 if (Invalid)
1635 Param->setInvalidDecl();
1636
1637 // C++0x [temp.param]p9:
1638 // A default template-argument may be specified for any kind of
1639 // template-parameter that is not a template parameter pack.
1640 if (IsParameterPack && !Default.isInvalid()) {
1641 Diag(Loc: EqualLoc, DiagID: diag::err_template_param_pack_default_arg);
1642 Default = ParsedTemplateArgument();
1643 }
1644
1645 if (!Default.isInvalid()) {
1646 // Check only that we have a template template argument. We don't want to
1647 // try to check well-formedness now, because our template template parameter
1648 // might have dependent types in its template parameters, which we wouldn't
1649 // be able to match now.
1650 //
1651 // If none of the template template parameter's template arguments mention
1652 // other template parameters, we could actually perform more checking here.
1653 // However, it isn't worth doing.
1654 TemplateArgumentLoc DefaultArg = translateTemplateArgument(SemaRef&: *this, Arg: Default);
1655 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1656 Diag(Loc: DefaultArg.getLocation(), DiagID: diag::err_template_arg_not_valid_template)
1657 << DefaultArg.getSourceRange();
1658 return Param;
1659 }
1660
1661 // Check for unexpanded parameter packs.
1662 if (DiagnoseUnexpandedParameterPack(Loc: DefaultArg.getLocation(),
1663 Template: DefaultArg.getArgument().getAsTemplate(),
1664 UPPC: UPPC_DefaultArgument))
1665 return Param;
1666
1667 Param->setDefaultArgument(C: Context, DefArg: DefaultArg);
1668 }
1669
1670 return Param;
1671}
1672
1673namespace {
1674class ConstraintRefersToContainingTemplateChecker
1675 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1676 bool Result = false;
1677 const FunctionDecl *Friend = nullptr;
1678 unsigned TemplateDepth = 0;
1679
1680 // Check a record-decl that we've seen to see if it is a lexical parent of the
1681 // Friend, likely because it was referred to without its template arguments.
1682 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1683 CheckingRD = CheckingRD->getMostRecentDecl();
1684 if (!CheckingRD->isTemplated())
1685 return;
1686
1687 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1688 DC && !DC->isFileContext(); DC = DC->getParent())
1689 if (const auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
1690 if (CheckingRD == RD->getMostRecentDecl())
1691 Result = true;
1692 }
1693
1694 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1695 if (D->getDepth() < TemplateDepth)
1696 Result = true;
1697
1698 // Necessary because the type of the NTTP might be what refers to the parent
1699 // constriant.
1700 TransformType(T: D->getType());
1701 }
1702
1703public:
1704 using inherited = TreeTransform<ConstraintRefersToContainingTemplateChecker>;
1705
1706 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1707 const FunctionDecl *Friend,
1708 unsigned TemplateDepth)
1709 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1710 bool getResult() const { return Result; }
1711
1712 // This should be the only template parm type that we have to deal with.
1713 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1714 // FunctionParmPackExpr are all partially substituted, which cannot happen
1715 // with concepts at this point in translation.
1716 using inherited::TransformTemplateTypeParmType;
1717 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1718 TemplateTypeParmTypeLoc TL, bool) {
1719 if (TL.getDecl()->getDepth() < TemplateDepth)
1720 Result = true;
1721 return inherited::TransformTemplateTypeParmType(
1722 TLB, TL,
1723 /*SuppressObjCLifetime=*/false);
1724 }
1725
1726 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1727 if (!D)
1728 return D;
1729 // FIXME : This is possibly an incomplete list, but it is unclear what other
1730 // Decl kinds could be used to refer to the template parameters. This is a
1731 // best guess so far based on examples currently available, but the
1732 // unreachable should catch future instances/cases.
1733 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
1734 TransformType(T: TD->getUnderlyingType());
1735 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Val: D))
1736 CheckNonTypeTemplateParmDecl(D: NTTPD);
1737 else if (auto *VD = dyn_cast<ValueDecl>(Val: D))
1738 TransformType(T: VD->getType());
1739 else if (auto *TD = dyn_cast<TemplateDecl>(Val: D))
1740 TransformTemplateParameterList(TPL: TD->getTemplateParameters());
1741 else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1742 CheckIfContainingRecord(CheckingRD: RD);
1743 else if (isa<NamedDecl>(Val: D)) {
1744 // No direct types to visit here I believe.
1745 } else
1746 llvm_unreachable("Don't know how to handle this declaration type yet");
1747 return D;
1748 }
1749};
1750} // namespace
1751
1752bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1753 const FunctionDecl *Friend, unsigned TemplateDepth,
1754 const Expr *Constraint) {
1755 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1756 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1757 TemplateDepth);
1758 Checker.TransformExpr(E: const_cast<Expr *>(Constraint));
1759 return Checker.getResult();
1760}
1761
1762TemplateParameterList *
1763Sema::ActOnTemplateParameterList(unsigned Depth,
1764 SourceLocation ExportLoc,
1765 SourceLocation TemplateLoc,
1766 SourceLocation LAngleLoc,
1767 ArrayRef<NamedDecl *> Params,
1768 SourceLocation RAngleLoc,
1769 Expr *RequiresClause) {
1770 if (ExportLoc.isValid())
1771 Diag(Loc: ExportLoc, DiagID: diag::warn_template_export_unsupported);
1772
1773 for (NamedDecl *P : Params)
1774 warnOnReservedIdentifier(D: P);
1775
1776 return TemplateParameterList::Create(C: Context, TemplateLoc, LAngleLoc,
1777 Params: llvm::ArrayRef(Params), RAngleLoc,
1778 RequiresClause);
1779}
1780
1781static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1782 const CXXScopeSpec &SS) {
1783 if (SS.isSet())
1784 T->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
1785}
1786
1787// Returns the template parameter list with all default template argument
1788// information.
1789TemplateParameterList *Sema::GetTemplateParameterList(TemplateDecl *TD) {
1790 // Make sure we get the template parameter list from the most
1791 // recent declaration, since that is the only one that is guaranteed to
1792 // have all the default template argument information.
1793 Decl *D = TD->getMostRecentDecl();
1794 // C++11 N3337 [temp.param]p12:
1795 // A default template argument shall not be specified in a friend class
1796 // template declaration.
1797 //
1798 // Skip past friend *declarations* because they are not supposed to contain
1799 // default template arguments. Moreover, these declarations may introduce
1800 // template parameters living in different template depths than the
1801 // corresponding template parameters in TD, causing unmatched constraint
1802 // substitution.
1803 //
1804 // FIXME: Diagnose such cases within a class template:
1805 // template <class T>
1806 // struct S {
1807 // template <class = void> friend struct C;
1808 // };
1809 // template struct S<int>;
1810 while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
1811 D->getPreviousDecl())
1812 D = D->getPreviousDecl();
1813 return cast<TemplateDecl>(Val: D)->getTemplateParameters();
1814}
1815
1816DeclResult Sema::CheckClassTemplate(
1817 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1818 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1819 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1820 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1821 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1822 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1823 assert(TemplateParams && TemplateParams->size() > 0 &&
1824 "No template parameters");
1825 assert(TUK != TagUseKind::Reference &&
1826 "Can only declare or define class templates");
1827 bool Invalid = false;
1828
1829 // Check that we can declare a template here.
1830 if (CheckTemplateDeclScope(S, TemplateParams))
1831 return true;
1832
1833 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
1834 assert(Kind != TagTypeKind::Enum &&
1835 "can't build template of enumerated type");
1836
1837 // There is no such thing as an unnamed class template.
1838 if (!Name) {
1839 Diag(Loc: KWLoc, DiagID: diag::err_template_unnamed_class);
1840 return true;
1841 }
1842
1843 // Find any previous declaration with this name. For a friend with no
1844 // scope explicitly specified, we only look for tag declarations (per
1845 // C++11 [basic.lookup.elab]p2).
1846 DeclContext *SemanticContext;
1847 LookupResult Previous(*this, Name, NameLoc,
1848 (SS.isEmpty() && TUK == TagUseKind::Friend)
1849 ? LookupTagName
1850 : LookupOrdinaryName,
1851 forRedeclarationInCurContext());
1852 if (SS.isNotEmpty() && !SS.isInvalid()) {
1853 SemanticContext = computeDeclContext(SS, EnteringContext: true);
1854 if (!SemanticContext) {
1855 // FIXME: Horrible, horrible hack! We can't currently represent this
1856 // in the AST, and historically we have just ignored such friend
1857 // class templates, so don't complain here.
1858 Diag(Loc: NameLoc, DiagID: TUK == TagUseKind::Friend
1859 ? diag::warn_template_qualified_friend_ignored
1860 : diag::err_template_qualified_declarator_no_match)
1861 << SS.getScopeRep() << SS.getRange();
1862 return TUK != TagUseKind::Friend;
1863 }
1864
1865 if (RequireCompleteDeclContext(SS, DC: SemanticContext))
1866 return true;
1867
1868 // If we're adding a template to a dependent context, we may need to
1869 // rebuilding some of the types used within the template parameter list,
1870 // now that we know what the current instantiation is.
1871 if (SemanticContext->isDependentContext()) {
1872 ContextRAII SavedContext(*this, SemanticContext);
1873 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
1874 Invalid = true;
1875 }
1876
1877 if (TUK != TagUseKind::Friend && TUK != TagUseKind::Reference)
1878 diagnoseQualifiedDeclaration(SS, DC: SemanticContext, Name, Loc: NameLoc,
1879 /*TemplateId-*/ TemplateId: nullptr,
1880 /*IsMemberSpecialization*/ false);
1881
1882 LookupQualifiedName(R&: Previous, LookupCtx: SemanticContext);
1883 } else {
1884 SemanticContext = CurContext;
1885
1886 // C++14 [class.mem]p14:
1887 // If T is the name of a class, then each of the following shall have a
1888 // name different from T:
1889 // -- every member template of class T
1890 if (TUK != TagUseKind::Friend &&
1891 DiagnoseClassNameShadow(DC: SemanticContext,
1892 Info: DeclarationNameInfo(Name, NameLoc)))
1893 return true;
1894
1895 LookupName(R&: Previous, S);
1896 }
1897
1898 if (Previous.isAmbiguous())
1899 return true;
1900
1901 // Let the template parameter scope enter the lookup chain of the current
1902 // class template. For example, given
1903 //
1904 // namespace ns {
1905 // template <class> bool Param = false;
1906 // template <class T> struct N;
1907 // }
1908 //
1909 // template <class Param> struct ns::N { void foo(Param); };
1910 //
1911 // When we reference Param inside the function parameter list, our name lookup
1912 // chain for it should be like:
1913 // FunctionScope foo
1914 // -> RecordScope N
1915 // -> TemplateParamScope (where we will find Param)
1916 // -> NamespaceScope ns
1917 //
1918 // See also CppLookupName().
1919 if (S->isTemplateParamScope())
1920 EnterTemplatedContext(S, DC: SemanticContext);
1921
1922 NamedDecl *PrevDecl = nullptr;
1923 if (Previous.begin() != Previous.end())
1924 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1925
1926 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1927 // Maybe we will complain about the shadowed template parameter.
1928 DiagnoseTemplateParameterShadow(Loc: NameLoc, PrevDecl);
1929 // Just pretend that we didn't see the previous declaration.
1930 PrevDecl = nullptr;
1931 }
1932
1933 // If there is a previous declaration with the same name, check
1934 // whether this is a valid redeclaration.
1935 ClassTemplateDecl *PrevClassTemplate =
1936 dyn_cast_or_null<ClassTemplateDecl>(Val: PrevDecl);
1937
1938 // We may have found the injected-class-name of a class template,
1939 // class template partial specialization, or class template specialization.
1940 // In these cases, grab the template that is being defined or specialized.
1941 if (!PrevClassTemplate && isa_and_nonnull<CXXRecordDecl>(Val: PrevDecl) &&
1942 cast<CXXRecordDecl>(Val: PrevDecl)->isInjectedClassName()) {
1943 PrevDecl = cast<CXXRecordDecl>(Val: PrevDecl->getDeclContext());
1944 PrevClassTemplate
1945 = cast<CXXRecordDecl>(Val: PrevDecl)->getDescribedClassTemplate();
1946 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(Val: PrevDecl)) {
1947 PrevClassTemplate
1948 = cast<ClassTemplateSpecializationDecl>(Val: PrevDecl)
1949 ->getSpecializedTemplate();
1950 }
1951 }
1952
1953 if (TUK == TagUseKind::Friend) {
1954 // C++ [namespace.memdef]p3:
1955 // [...] When looking for a prior declaration of a class or a function
1956 // declared as a friend, and when the name of the friend class or
1957 // function is neither a qualified name nor a template-id, scopes outside
1958 // the innermost enclosing namespace scope are not considered.
1959 if (!SS.isSet()) {
1960 DeclContext *OutermostContext = CurContext;
1961 while (!OutermostContext->isFileContext())
1962 OutermostContext = OutermostContext->getLookupParent();
1963
1964 if (PrevDecl &&
1965 (OutermostContext->Equals(DC: PrevDecl->getDeclContext()) ||
1966 OutermostContext->Encloses(DC: PrevDecl->getDeclContext()))) {
1967 SemanticContext = PrevDecl->getDeclContext();
1968 } else {
1969 // Declarations in outer scopes don't matter. However, the outermost
1970 // context we computed is the semantic context for our new
1971 // declaration.
1972 PrevDecl = PrevClassTemplate = nullptr;
1973 SemanticContext = OutermostContext;
1974
1975 // Check that the chosen semantic context doesn't already contain a
1976 // declaration of this name as a non-tag type.
1977 Previous.clear(Kind: LookupOrdinaryName);
1978 DeclContext *LookupContext = SemanticContext;
1979 while (LookupContext->isTransparentContext())
1980 LookupContext = LookupContext->getLookupParent();
1981 LookupQualifiedName(R&: Previous, LookupCtx: LookupContext);
1982
1983 if (Previous.isAmbiguous())
1984 return true;
1985
1986 if (Previous.begin() != Previous.end())
1987 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1988 }
1989 }
1990 } else if (PrevDecl && !isDeclInScope(D: Previous.getRepresentativeDecl(),
1991 Ctx: SemanticContext, S, AllowInlineNamespace: SS.isValid()))
1992 PrevDecl = PrevClassTemplate = nullptr;
1993
1994 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1995 Val: PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1996 if (SS.isEmpty() &&
1997 !(PrevClassTemplate &&
1998 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1999 DC: SemanticContext->getRedeclContext()))) {
2000 Diag(Loc: KWLoc, DiagID: diag::err_using_decl_conflict_reverse);
2001 Diag(Loc: Shadow->getTargetDecl()->getLocation(),
2002 DiagID: diag::note_using_decl_target);
2003 Diag(Loc: Shadow->getIntroducer()->getLocation(), DiagID: diag::note_using_decl) << 0;
2004 // Recover by ignoring the old declaration.
2005 PrevDecl = PrevClassTemplate = nullptr;
2006 }
2007 }
2008
2009 if (PrevClassTemplate) {
2010 // Ensure that the template parameter lists are compatible. Skip this check
2011 // for a friend in a dependent context: the template parameter list itself
2012 // could be dependent.
2013 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2014 !TemplateParameterListsAreEqual(
2015 NewInstFrom: TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2016 : CurContext,
2017 CurContext, KWLoc),
2018 New: TemplateParams, OldInstFrom: PrevClassTemplate,
2019 Old: PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2020 Kind: TPL_TemplateMatch))
2021 return true;
2022
2023 // C++ [temp.class]p4:
2024 // In a redeclaration, partial specialization, explicit
2025 // specialization or explicit instantiation of a class template,
2026 // the class-key shall agree in kind with the original class
2027 // template declaration (7.1.5.3).
2028 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2029 if (!isAcceptableTagRedeclaration(
2030 Previous: PrevRecordDecl, NewTag: Kind, isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc, Name)) {
2031 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
2032 << Name
2033 << FixItHint::CreateReplacement(RemoveRange: KWLoc, Code: PrevRecordDecl->getKindName());
2034 Diag(Loc: PrevRecordDecl->getLocation(), DiagID: diag::note_previous_use);
2035 Kind = PrevRecordDecl->getTagKind();
2036 }
2037
2038 // Check for redefinition of this class template.
2039 if (TUK == TagUseKind::Definition) {
2040 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2041 // If we have a prior definition that is not visible, treat this as
2042 // simply making that previous definition visible.
2043 NamedDecl *Hidden = nullptr;
2044 if (SkipBody && !hasVisibleDefinition(D: Def, Suggested: &Hidden)) {
2045 SkipBody->ShouldSkip = true;
2046 SkipBody->Previous = Def;
2047 auto *Tmpl = cast<CXXRecordDecl>(Val: Hidden)->getDescribedClassTemplate();
2048 assert(Tmpl && "original definition of a class template is not a "
2049 "class template?");
2050 makeMergedDefinitionVisible(ND: Hidden);
2051 makeMergedDefinitionVisible(ND: Tmpl);
2052 } else {
2053 Diag(Loc: NameLoc, DiagID: diag::err_redefinition) << Name;
2054 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
2055 // FIXME: Would it make sense to try to "forget" the previous
2056 // definition, as part of error recovery?
2057 return true;
2058 }
2059 }
2060 }
2061 } else if (PrevDecl) {
2062 // C++ [temp]p5:
2063 // A class template shall not have the same name as any other
2064 // template, class, function, object, enumeration, enumerator,
2065 // namespace, or type in the same scope (3.3), except as specified
2066 // in (14.5.4).
2067 Diag(Loc: NameLoc, DiagID: diag::err_redefinition_different_kind) << Name;
2068 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
2069 return true;
2070 }
2071
2072 // Check the template parameter list of this declaration, possibly
2073 // merging in the template parameter list from the previous class
2074 // template declaration. Skip this check for a friend in a dependent
2075 // context, because the template parameter list might be dependent.
2076 if (!(TUK == TagUseKind::Friend && CurContext->isDependentContext()) &&
2077 CheckTemplateParameterList(
2078 NewParams: TemplateParams,
2079 OldParams: PrevClassTemplate ? GetTemplateParameterList(TD: PrevClassTemplate)
2080 : nullptr,
2081 TPC: (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2082 SemanticContext->isDependentContext())
2083 ? TPC_ClassTemplateMember
2084 : TUK == TagUseKind::Friend ? TPC_FriendClassTemplate
2085 : TPC_Other,
2086 SkipBody))
2087 Invalid = true;
2088
2089 if (SS.isSet()) {
2090 // If the name of the template was qualified, we must be defining the
2091 // template out-of-line.
2092 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2093 Diag(Loc: NameLoc, DiagID: TUK == TagUseKind::Friend
2094 ? diag::err_friend_decl_does_not_match
2095 : diag::err_member_decl_does_not_match)
2096 << Name << SemanticContext << /*IsDefinition*/ true << SS.getRange();
2097 Invalid = true;
2098 }
2099 }
2100
2101 // If this is a templated friend in a dependent context we should not put it
2102 // on the redecl chain. In some cases, the templated friend can be the most
2103 // recent declaration tricking the template instantiator to make substitutions
2104 // there.
2105 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2106 bool ShouldAddRedecl =
2107 !(TUK == TagUseKind::Friend && CurContext->isDependentContext());
2108
2109 CXXRecordDecl *NewClass =
2110 CXXRecordDecl::Create(C: Context, TK: Kind, DC: SemanticContext, StartLoc: KWLoc, IdLoc: NameLoc, Id: Name,
2111 PrevDecl: PrevClassTemplate && ShouldAddRedecl ?
2112 PrevClassTemplate->getTemplatedDecl() : nullptr,
2113 /*DelayTypeCreation=*/true);
2114 SetNestedNameSpecifier(S&: *this, T: NewClass, SS);
2115 if (NumOuterTemplateParamLists > 0)
2116 NewClass->setTemplateParameterListsInfo(
2117 Context,
2118 TPLists: llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2119
2120 // Add alignment attributes if necessary; these attributes are checked when
2121 // the ASTContext lays out the structure.
2122 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2123 if (LangOpts.HLSL)
2124 NewClass->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
2125 AddAlignmentAttributesForRecord(RD: NewClass);
2126 AddMsStructLayoutForRecord(RD: NewClass);
2127 }
2128
2129 ClassTemplateDecl *NewTemplate
2130 = ClassTemplateDecl::Create(C&: Context, DC: SemanticContext, L: NameLoc,
2131 Name: DeclarationName(Name), Params: TemplateParams,
2132 Decl: NewClass);
2133
2134 if (ShouldAddRedecl)
2135 NewTemplate->setPreviousDecl(PrevClassTemplate);
2136
2137 NewClass->setDescribedClassTemplate(NewTemplate);
2138
2139 if (ModulePrivateLoc.isValid())
2140 NewTemplate->setModulePrivate();
2141
2142 // Build the type for the class template declaration now.
2143 QualType T = NewTemplate->getInjectedClassNameSpecialization();
2144 T = Context.getInjectedClassNameType(Decl: NewClass, TST: T);
2145 assert(T->isDependentType() && "Class template type is not dependent?");
2146 (void)T;
2147
2148 // If we are providing an explicit specialization of a member that is a
2149 // class template, make a note of that.
2150 if (PrevClassTemplate &&
2151 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2152 PrevClassTemplate->setMemberSpecialization();
2153
2154 // Set the access specifier.
2155 if (!Invalid && TUK != TagUseKind::Friend &&
2156 NewTemplate->getDeclContext()->isRecord())
2157 SetMemberAccessSpecifier(MemberDecl: NewTemplate, PrevMemberDecl: PrevClassTemplate, LexicalAS: AS);
2158
2159 // Set the lexical context of these templates
2160 NewClass->setLexicalDeclContext(CurContext);
2161 NewTemplate->setLexicalDeclContext(CurContext);
2162
2163 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
2164 NewClass->startDefinition();
2165
2166 ProcessDeclAttributeList(S, D: NewClass, AttrList: Attr);
2167
2168 if (PrevClassTemplate)
2169 mergeDeclAttributes(New: NewClass, Old: PrevClassTemplate->getTemplatedDecl());
2170
2171 AddPushedVisibilityAttribute(RD: NewClass);
2172 inferGslOwnerPointerAttribute(Record: NewClass);
2173 inferNullableClassAttribute(CRD: NewClass);
2174
2175 if (TUK != TagUseKind::Friend) {
2176 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2177 Scope *Outer = S;
2178 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2179 Outer = Outer->getParent();
2180 PushOnScopeChains(D: NewTemplate, S: Outer);
2181 } else {
2182 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2183 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2184 NewClass->setAccess(PrevClassTemplate->getAccess());
2185 }
2186
2187 NewTemplate->setObjectOfFriendDecl();
2188
2189 // Friend templates are visible in fairly strange ways.
2190 if (!CurContext->isDependentContext()) {
2191 DeclContext *DC = SemanticContext->getRedeclContext();
2192 DC->makeDeclVisibleInContext(D: NewTemplate);
2193 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2194 PushOnScopeChains(D: NewTemplate, S: EnclosingScope,
2195 /* AddToContext = */ false);
2196 }
2197
2198 FriendDecl *Friend = FriendDecl::Create(
2199 C&: Context, DC: CurContext, L: NewClass->getLocation(), Friend_: NewTemplate, FriendL: FriendLoc);
2200 Friend->setAccess(AS_public);
2201 CurContext->addDecl(D: Friend);
2202 }
2203
2204 if (PrevClassTemplate)
2205 CheckRedeclarationInModule(New: NewTemplate, Old: PrevClassTemplate);
2206
2207 if (Invalid) {
2208 NewTemplate->setInvalidDecl();
2209 NewClass->setInvalidDecl();
2210 }
2211
2212 ActOnDocumentableDecl(D: NewTemplate);
2213
2214 if (SkipBody && SkipBody->ShouldSkip)
2215 return SkipBody->Previous;
2216
2217 return NewTemplate;
2218}
2219
2220/// Diagnose the presence of a default template argument on a
2221/// template parameter, which is ill-formed in certain contexts.
2222///
2223/// \returns true if the default template argument should be dropped.
2224static bool DiagnoseDefaultTemplateArgument(Sema &S,
2225 Sema::TemplateParamListContext TPC,
2226 SourceLocation ParamLoc,
2227 SourceRange DefArgRange) {
2228 switch (TPC) {
2229 case Sema::TPC_Other:
2230 case Sema::TPC_TemplateTemplateParameterPack:
2231 return false;
2232
2233 case Sema::TPC_FunctionTemplate:
2234 case Sema::TPC_FriendFunctionTemplateDefinition:
2235 // C++ [temp.param]p9:
2236 // A default template-argument shall not be specified in a
2237 // function template declaration or a function template
2238 // definition [...]
2239 // If a friend function template declaration specifies a default
2240 // template-argument, that declaration shall be a definition and shall be
2241 // the only declaration of the function template in the translation unit.
2242 // (C++98/03 doesn't have this wording; see DR226).
2243 S.DiagCompat(Loc: ParamLoc, CompatDiagId: diag_compat::templ_default_in_function_templ)
2244 << DefArgRange;
2245 return false;
2246
2247 case Sema::TPC_ClassTemplateMember:
2248 // C++0x [temp.param]p9:
2249 // A default template-argument shall not be specified in the
2250 // template-parameter-lists of the definition of a member of a
2251 // class template that appears outside of the member's class.
2252 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_template_member)
2253 << DefArgRange;
2254 return true;
2255
2256 case Sema::TPC_FriendClassTemplate:
2257 case Sema::TPC_FriendFunctionTemplate:
2258 // C++ [temp.param]p9:
2259 // A default template-argument shall not be specified in a
2260 // friend template declaration.
2261 S.Diag(Loc: ParamLoc, DiagID: diag::err_template_parameter_default_friend_template)
2262 << DefArgRange;
2263 return true;
2264
2265 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2266 // for friend function templates if there is only a single
2267 // declaration (and it is a definition). Strange!
2268 }
2269
2270 llvm_unreachable("Invalid TemplateParamListContext!");
2271}
2272
2273/// Check for unexpanded parameter packs within the template parameters
2274/// of a template template parameter, recursively.
2275static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2276 TemplateTemplateParmDecl *TTP) {
2277 // A template template parameter which is a parameter pack is also a pack
2278 // expansion.
2279 if (TTP->isParameterPack())
2280 return false;
2281
2282 TemplateParameterList *Params = TTP->getTemplateParameters();
2283 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2284 NamedDecl *P = Params->getParam(Idx: I);
2285 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: P)) {
2286 if (!TTP->isParameterPack())
2287 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2288 if (TC->hasExplicitTemplateArgs())
2289 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2290 if (S.DiagnoseUnexpandedParameterPack(Arg: ArgLoc,
2291 UPPC: Sema::UPPC_TypeConstraint))
2292 return true;
2293 continue;
2294 }
2295
2296 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: P)) {
2297 if (!NTTP->isParameterPack() &&
2298 S.DiagnoseUnexpandedParameterPack(Loc: NTTP->getLocation(),
2299 T: NTTP->getTypeSourceInfo(),
2300 UPPC: Sema::UPPC_NonTypeTemplateParameterType))
2301 return true;
2302
2303 continue;
2304 }
2305
2306 if (TemplateTemplateParmDecl *InnerTTP
2307 = dyn_cast<TemplateTemplateParmDecl>(Val: P))
2308 if (DiagnoseUnexpandedParameterPacks(S, TTP: InnerTTP))
2309 return true;
2310 }
2311
2312 return false;
2313}
2314
2315bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2316 TemplateParameterList *OldParams,
2317 TemplateParamListContext TPC,
2318 SkipBodyInfo *SkipBody) {
2319 bool Invalid = false;
2320
2321 // C++ [temp.param]p10:
2322 // The set of default template-arguments available for use with a
2323 // template declaration or definition is obtained by merging the
2324 // default arguments from the definition (if in scope) and all
2325 // declarations in scope in the same way default function
2326 // arguments are (8.3.6).
2327 bool SawDefaultArgument = false;
2328 SourceLocation PreviousDefaultArgLoc;
2329
2330 // Dummy initialization to avoid warnings.
2331 TemplateParameterList::iterator OldParam = NewParams->end();
2332 if (OldParams)
2333 OldParam = OldParams->begin();
2334
2335 bool RemoveDefaultArguments = false;
2336 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2337 NewParamEnd = NewParams->end();
2338 NewParam != NewParamEnd; ++NewParam) {
2339 // Whether we've seen a duplicate default argument in the same translation
2340 // unit.
2341 bool RedundantDefaultArg = false;
2342 // Whether we've found inconsis inconsitent default arguments in different
2343 // translation unit.
2344 bool InconsistentDefaultArg = false;
2345 // The name of the module which contains the inconsistent default argument.
2346 std::string PrevModuleName;
2347
2348 SourceLocation OldDefaultLoc;
2349 SourceLocation NewDefaultLoc;
2350
2351 // Variable used to diagnose missing default arguments
2352 bool MissingDefaultArg = false;
2353
2354 // Variable used to diagnose non-final parameter packs
2355 bool SawParameterPack = false;
2356
2357 if (TemplateTypeParmDecl *NewTypeParm
2358 = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam)) {
2359 // Check the presence of a default argument here.
2360 if (NewTypeParm->hasDefaultArgument() &&
2361 DiagnoseDefaultTemplateArgument(
2362 S&: *this, TPC, ParamLoc: NewTypeParm->getLocation(),
2363 DefArgRange: NewTypeParm->getDefaultArgument().getSourceRange()))
2364 NewTypeParm->removeDefaultArgument();
2365
2366 // Merge default arguments for template type parameters.
2367 TemplateTypeParmDecl *OldTypeParm
2368 = OldParams? cast<TemplateTypeParmDecl>(Val: *OldParam) : nullptr;
2369 if (NewTypeParm->isParameterPack()) {
2370 assert(!NewTypeParm->hasDefaultArgument() &&
2371 "Parameter packs can't have a default argument!");
2372 SawParameterPack = true;
2373 } else if (OldTypeParm && hasVisibleDefaultArgument(D: OldTypeParm) &&
2374 NewTypeParm->hasDefaultArgument() &&
2375 (!SkipBody || !SkipBody->ShouldSkip)) {
2376 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2377 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2378 SawDefaultArgument = true;
2379
2380 if (!OldTypeParm->getOwningModule())
2381 RedundantDefaultArg = true;
2382 else if (!getASTContext().isSameDefaultTemplateArgument(X: OldTypeParm,
2383 Y: NewTypeParm)) {
2384 InconsistentDefaultArg = true;
2385 PrevModuleName =
2386 OldTypeParm->getImportedOwningModule()->getFullModuleName();
2387 }
2388 PreviousDefaultArgLoc = NewDefaultLoc;
2389 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2390 // Merge the default argument from the old declaration to the
2391 // new declaration.
2392 NewTypeParm->setInheritedDefaultArgument(C: Context, Prev: OldTypeParm);
2393 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2394 } else if (NewTypeParm->hasDefaultArgument()) {
2395 SawDefaultArgument = true;
2396 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2397 } else if (SawDefaultArgument)
2398 MissingDefaultArg = true;
2399 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2400 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam)) {
2401 // Check for unexpanded parameter packs, except in a template template
2402 // parameter pack, as in those any unexpanded packs should be expanded
2403 // along with the parameter itself.
2404 if (TPC != TPC_TemplateTemplateParameterPack &&
2405 !NewNonTypeParm->isParameterPack() &&
2406 DiagnoseUnexpandedParameterPack(Loc: NewNonTypeParm->getLocation(),
2407 T: NewNonTypeParm->getTypeSourceInfo(),
2408 UPPC: UPPC_NonTypeTemplateParameterType)) {
2409 Invalid = true;
2410 continue;
2411 }
2412
2413 // Check the presence of a default argument here.
2414 if (NewNonTypeParm->hasDefaultArgument() &&
2415 DiagnoseDefaultTemplateArgument(
2416 S&: *this, TPC, ParamLoc: NewNonTypeParm->getLocation(),
2417 DefArgRange: NewNonTypeParm->getDefaultArgument().getSourceRange())) {
2418 NewNonTypeParm->removeDefaultArgument();
2419 }
2420
2421 // Merge default arguments for non-type template parameters
2422 NonTypeTemplateParmDecl *OldNonTypeParm
2423 = OldParams? cast<NonTypeTemplateParmDecl>(Val: *OldParam) : nullptr;
2424 if (NewNonTypeParm->isParameterPack()) {
2425 assert(!NewNonTypeParm->hasDefaultArgument() &&
2426 "Parameter packs can't have a default argument!");
2427 if (!NewNonTypeParm->isPackExpansion())
2428 SawParameterPack = true;
2429 } else if (OldNonTypeParm && hasVisibleDefaultArgument(D: OldNonTypeParm) &&
2430 NewNonTypeParm->hasDefaultArgument() &&
2431 (!SkipBody || !SkipBody->ShouldSkip)) {
2432 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2433 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2434 SawDefaultArgument = true;
2435 if (!OldNonTypeParm->getOwningModule())
2436 RedundantDefaultArg = true;
2437 else if (!getASTContext().isSameDefaultTemplateArgument(
2438 X: OldNonTypeParm, Y: NewNonTypeParm)) {
2439 InconsistentDefaultArg = true;
2440 PrevModuleName =
2441 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2442 }
2443 PreviousDefaultArgLoc = NewDefaultLoc;
2444 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2445 // Merge the default argument from the old declaration to the
2446 // new declaration.
2447 NewNonTypeParm->setInheritedDefaultArgument(C: Context, Parm: OldNonTypeParm);
2448 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2449 } else if (NewNonTypeParm->hasDefaultArgument()) {
2450 SawDefaultArgument = true;
2451 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2452 } else if (SawDefaultArgument)
2453 MissingDefaultArg = true;
2454 } else {
2455 TemplateTemplateParmDecl *NewTemplateParm
2456 = cast<TemplateTemplateParmDecl>(Val: *NewParam);
2457
2458 // Check for unexpanded parameter packs, recursively.
2459 if (::DiagnoseUnexpandedParameterPacks(S&: *this, TTP: NewTemplateParm)) {
2460 Invalid = true;
2461 continue;
2462 }
2463
2464 // Check the presence of a default argument here.
2465 if (NewTemplateParm->hasDefaultArgument() &&
2466 DiagnoseDefaultTemplateArgument(S&: *this, TPC,
2467 ParamLoc: NewTemplateParm->getLocation(),
2468 DefArgRange: NewTemplateParm->getDefaultArgument().getSourceRange()))
2469 NewTemplateParm->removeDefaultArgument();
2470
2471 // Merge default arguments for template template parameters
2472 TemplateTemplateParmDecl *OldTemplateParm
2473 = OldParams? cast<TemplateTemplateParmDecl>(Val: *OldParam) : nullptr;
2474 if (NewTemplateParm->isParameterPack()) {
2475 assert(!NewTemplateParm->hasDefaultArgument() &&
2476 "Parameter packs can't have a default argument!");
2477 if (!NewTemplateParm->isPackExpansion())
2478 SawParameterPack = true;
2479 } else if (OldTemplateParm &&
2480 hasVisibleDefaultArgument(D: OldTemplateParm) &&
2481 NewTemplateParm->hasDefaultArgument() &&
2482 (!SkipBody || !SkipBody->ShouldSkip)) {
2483 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2484 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2485 SawDefaultArgument = true;
2486 if (!OldTemplateParm->getOwningModule())
2487 RedundantDefaultArg = true;
2488 else if (!getASTContext().isSameDefaultTemplateArgument(
2489 X: OldTemplateParm, Y: NewTemplateParm)) {
2490 InconsistentDefaultArg = true;
2491 PrevModuleName =
2492 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2493 }
2494 PreviousDefaultArgLoc = NewDefaultLoc;
2495 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2496 // Merge the default argument from the old declaration to the
2497 // new declaration.
2498 NewTemplateParm->setInheritedDefaultArgument(C: Context, Prev: OldTemplateParm);
2499 PreviousDefaultArgLoc
2500 = OldTemplateParm->getDefaultArgument().getLocation();
2501 } else if (NewTemplateParm->hasDefaultArgument()) {
2502 SawDefaultArgument = true;
2503 PreviousDefaultArgLoc
2504 = NewTemplateParm->getDefaultArgument().getLocation();
2505 } else if (SawDefaultArgument)
2506 MissingDefaultArg = true;
2507 }
2508
2509 // C++11 [temp.param]p11:
2510 // If a template parameter of a primary class template or alias template
2511 // is a template parameter pack, it shall be the last template parameter.
2512 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2513 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack)) {
2514 Diag(Loc: (*NewParam)->getLocation(),
2515 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
2516 Invalid = true;
2517 }
2518
2519 // [basic.def.odr]/13:
2520 // There can be more than one definition of a
2521 // ...
2522 // default template argument
2523 // ...
2524 // in a program provided that each definition appears in a different
2525 // translation unit and the definitions satisfy the [same-meaning
2526 // criteria of the ODR].
2527 //
2528 // Simply, the design of modules allows the definition of template default
2529 // argument to be repeated across translation unit. Note that the ODR is
2530 // checked elsewhere. But it is still not allowed to repeat template default
2531 // argument in the same translation unit.
2532 if (RedundantDefaultArg) {
2533 Diag(Loc: NewDefaultLoc, DiagID: diag::err_template_param_default_arg_redefinition);
2534 Diag(Loc: OldDefaultLoc, DiagID: diag::note_template_param_prev_default_arg);
2535 Invalid = true;
2536 } else if (InconsistentDefaultArg) {
2537 // We could only diagnose about the case that the OldParam is imported.
2538 // The case NewParam is imported should be handled in ASTReader.
2539 Diag(Loc: NewDefaultLoc,
2540 DiagID: diag::err_template_param_default_arg_inconsistent_redefinition);
2541 Diag(Loc: OldDefaultLoc,
2542 DiagID: diag::note_template_param_prev_default_arg_in_other_module)
2543 << PrevModuleName;
2544 Invalid = true;
2545 } else if (MissingDefaultArg &&
2546 (TPC == TPC_Other || TPC == TPC_TemplateTemplateParameterPack ||
2547 TPC == TPC_FriendClassTemplate)) {
2548 // C++ 23[temp.param]p14:
2549 // If a template-parameter of a class template, variable template, or
2550 // alias template has a default template argument, each subsequent
2551 // template-parameter shall either have a default template argument
2552 // supplied or be a template parameter pack.
2553 Diag(Loc: (*NewParam)->getLocation(),
2554 DiagID: diag::err_template_param_default_arg_missing);
2555 Diag(Loc: PreviousDefaultArgLoc, DiagID: diag::note_template_param_prev_default_arg);
2556 Invalid = true;
2557 RemoveDefaultArguments = true;
2558 }
2559
2560 // If we have an old template parameter list that we're merging
2561 // in, move on to the next parameter.
2562 if (OldParams)
2563 ++OldParam;
2564 }
2565
2566 // We were missing some default arguments at the end of the list, so remove
2567 // all of the default arguments.
2568 if (RemoveDefaultArguments) {
2569 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2570 NewParamEnd = NewParams->end();
2571 NewParam != NewParamEnd; ++NewParam) {
2572 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam))
2573 TTP->removeDefaultArgument();
2574 else if (NonTypeTemplateParmDecl *NTTP
2575 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam))
2576 NTTP->removeDefaultArgument();
2577 else
2578 cast<TemplateTemplateParmDecl>(Val: *NewParam)->removeDefaultArgument();
2579 }
2580 }
2581
2582 return Invalid;
2583}
2584
2585namespace {
2586
2587/// A class which looks for a use of a certain level of template
2588/// parameter.
2589struct DependencyChecker : DynamicRecursiveASTVisitor {
2590 unsigned Depth;
2591
2592 // Whether we're looking for a use of a template parameter that makes the
2593 // overall construct type-dependent / a dependent type. This is strictly
2594 // best-effort for now; we may fail to match at all for a dependent type
2595 // in some cases if this is set.
2596 bool IgnoreNonTypeDependent;
2597
2598 bool Match;
2599 SourceLocation MatchLoc;
2600
2601 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2602 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2603 Match(false) {}
2604
2605 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2606 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2607 NamedDecl *ND = Params->getParam(Idx: 0);
2608 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(Val: ND)) {
2609 Depth = PD->getDepth();
2610 } else if (NonTypeTemplateParmDecl *PD =
2611 dyn_cast<NonTypeTemplateParmDecl>(Val: ND)) {
2612 Depth = PD->getDepth();
2613 } else {
2614 Depth = cast<TemplateTemplateParmDecl>(Val: ND)->getDepth();
2615 }
2616 }
2617
2618 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2619 if (ParmDepth >= Depth) {
2620 Match = true;
2621 MatchLoc = Loc;
2622 return true;
2623 }
2624 return false;
2625 }
2626
2627 bool TraverseStmt(Stmt *S) override {
2628 // Prune out non-type-dependent expressions if requested. This can
2629 // sometimes result in us failing to find a template parameter reference
2630 // (if a value-dependent expression creates a dependent type), but this
2631 // mode is best-effort only.
2632 if (auto *E = dyn_cast_or_null<Expr>(Val: S))
2633 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2634 return true;
2635 return DynamicRecursiveASTVisitor::TraverseStmt(S);
2636 }
2637
2638 bool TraverseTypeLoc(TypeLoc TL) override {
2639 if (IgnoreNonTypeDependent && !TL.isNull() &&
2640 !TL.getType()->isDependentType())
2641 return true;
2642 return DynamicRecursiveASTVisitor::TraverseTypeLoc(TL);
2643 }
2644
2645 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) override {
2646 return !Matches(ParmDepth: TL.getTypePtr()->getDepth(), Loc: TL.getNameLoc());
2647 }
2648
2649 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) override {
2650 // For a best-effort search, keep looking until we find a location.
2651 return IgnoreNonTypeDependent || !Matches(ParmDepth: T->getDepth());
2652 }
2653
2654 bool TraverseTemplateName(TemplateName N) override {
2655 if (TemplateTemplateParmDecl *PD =
2656 dyn_cast_or_null<TemplateTemplateParmDecl>(Val: N.getAsTemplateDecl()))
2657 if (Matches(ParmDepth: PD->getDepth()))
2658 return false;
2659 return DynamicRecursiveASTVisitor::TraverseTemplateName(Template: N);
2660 }
2661
2662 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2663 if (NonTypeTemplateParmDecl *PD =
2664 dyn_cast<NonTypeTemplateParmDecl>(Val: E->getDecl()))
2665 if (Matches(ParmDepth: PD->getDepth(), Loc: E->getExprLoc()))
2666 return false;
2667 return DynamicRecursiveASTVisitor::VisitDeclRefExpr(S: E);
2668 }
2669
2670 bool VisitSubstTemplateTypeParmType(SubstTemplateTypeParmType *T) override {
2671 return TraverseType(T: T->getReplacementType());
2672 }
2673
2674 bool VisitSubstTemplateTypeParmPackType(
2675 SubstTemplateTypeParmPackType *T) override {
2676 return TraverseTemplateArgument(Arg: T->getArgumentPack());
2677 }
2678
2679 bool TraverseInjectedClassNameType(InjectedClassNameType *T) override {
2680 return TraverseType(T: T->getInjectedSpecializationType());
2681 }
2682};
2683} // end anonymous namespace
2684
2685/// Determines whether a given type depends on the given parameter
2686/// list.
2687static bool
2688DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
2689 if (!Params->size())
2690 return false;
2691
2692 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
2693 Checker.TraverseType(T);
2694 return Checker.Match;
2695}
2696
2697// Find the source range corresponding to the named type in the given
2698// nested-name-specifier, if any.
2699static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
2700 QualType T,
2701 const CXXScopeSpec &SS) {
2702 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
2703 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
2704 if (const Type *CurType = NNS->getAsType()) {
2705 if (Context.hasSameUnqualifiedType(T1: T, T2: QualType(CurType, 0)))
2706 return NNSLoc.getTypeLoc().getSourceRange();
2707 } else
2708 break;
2709
2710 NNSLoc = NNSLoc.getPrefix();
2711 }
2712
2713 return SourceRange();
2714}
2715
2716TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
2717 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
2718 TemplateIdAnnotation *TemplateId,
2719 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
2720 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
2721 IsMemberSpecialization = false;
2722 Invalid = false;
2723
2724 // The sequence of nested types to which we will match up the template
2725 // parameter lists. We first build this list by starting with the type named
2726 // by the nested-name-specifier and walking out until we run out of types.
2727 SmallVector<QualType, 4> NestedTypes;
2728 QualType T;
2729 if (SS.getScopeRep()) {
2730 if (CXXRecordDecl *Record
2731 = dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: true)))
2732 T = Context.getTypeDeclType(Decl: Record);
2733 else
2734 T = QualType(SS.getScopeRep()->getAsType(), 0);
2735 }
2736
2737 // If we found an explicit specialization that prevents us from needing
2738 // 'template<>' headers, this will be set to the location of that
2739 // explicit specialization.
2740 SourceLocation ExplicitSpecLoc;
2741
2742 while (!T.isNull()) {
2743 NestedTypes.push_back(Elt: T);
2744
2745 // Retrieve the parent of a record type.
2746 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2747 // If this type is an explicit specialization, we're done.
2748 if (ClassTemplateSpecializationDecl *Spec
2749 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
2750 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Spec) &&
2751 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
2752 ExplicitSpecLoc = Spec->getLocation();
2753 break;
2754 }
2755 } else if (Record->getTemplateSpecializationKind()
2756 == TSK_ExplicitSpecialization) {
2757 ExplicitSpecLoc = Record->getLocation();
2758 break;
2759 }
2760
2761 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Record->getParent()))
2762 T = Context.getTypeDeclType(Decl: Parent);
2763 else
2764 T = QualType();
2765 continue;
2766 }
2767
2768 if (const TemplateSpecializationType *TST
2769 = T->getAs<TemplateSpecializationType>()) {
2770 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2771 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Template->getDeclContext()))
2772 T = Context.getTypeDeclType(Decl: Parent);
2773 else
2774 T = QualType();
2775 continue;
2776 }
2777 }
2778
2779 // Look one step prior in a dependent template specialization type.
2780 if (const DependentTemplateSpecializationType *DependentTST
2781 = T->getAs<DependentTemplateSpecializationType>()) {
2782 if (NestedNameSpecifier *NNS =
2783 DependentTST->getDependentTemplateName().getQualifier())
2784 T = QualType(NNS->getAsType(), 0);
2785 else
2786 T = QualType();
2787 continue;
2788 }
2789
2790 // Look one step prior in a dependent name type.
2791 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
2792 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
2793 T = QualType(NNS->getAsType(), 0);
2794 else
2795 T = QualType();
2796 continue;
2797 }
2798
2799 // Retrieve the parent of an enumeration type.
2800 if (const EnumType *EnumT = T->getAs<EnumType>()) {
2801 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
2802 // check here.
2803 EnumDecl *Enum = EnumT->getDecl();
2804
2805 // Get to the parent type.
2806 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Val: Enum->getParent()))
2807 T = Context.getTypeDeclType(Decl: Parent);
2808 else
2809 T = QualType();
2810 continue;
2811 }
2812
2813 T = QualType();
2814 }
2815 // Reverse the nested types list, since we want to traverse from the outermost
2816 // to the innermost while checking template-parameter-lists.
2817 std::reverse(first: NestedTypes.begin(), last: NestedTypes.end());
2818
2819 // C++0x [temp.expl.spec]p17:
2820 // A member or a member template may be nested within many
2821 // enclosing class templates. In an explicit specialization for
2822 // such a member, the member declaration shall be preceded by a
2823 // template<> for each enclosing class template that is
2824 // explicitly specialized.
2825 bool SawNonEmptyTemplateParameterList = false;
2826
2827 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
2828 if (SawNonEmptyTemplateParameterList) {
2829 if (!SuppressDiagnostic)
2830 Diag(Loc: DeclLoc, DiagID: diag::err_specialize_member_of_template)
2831 << !Recovery << Range;
2832 Invalid = true;
2833 IsMemberSpecialization = false;
2834 return true;
2835 }
2836
2837 return false;
2838 };
2839
2840 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
2841 // Check that we can have an explicit specialization here.
2842 if (CheckExplicitSpecialization(Range, true))
2843 return true;
2844
2845 // We don't have a template header, but we should.
2846 SourceLocation ExpectedTemplateLoc;
2847 if (!ParamLists.empty())
2848 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
2849 else
2850 ExpectedTemplateLoc = DeclStartLoc;
2851
2852 if (!SuppressDiagnostic)
2853 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_header)
2854 << Range
2855 << FixItHint::CreateInsertion(InsertionLoc: ExpectedTemplateLoc, Code: "template<> ");
2856 return false;
2857 };
2858
2859 unsigned ParamIdx = 0;
2860 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
2861 ++TypeIdx) {
2862 T = NestedTypes[TypeIdx];
2863
2864 // Whether we expect a 'template<>' header.
2865 bool NeedEmptyTemplateHeader = false;
2866
2867 // Whether we expect a template header with parameters.
2868 bool NeedNonemptyTemplateHeader = false;
2869
2870 // For a dependent type, the set of template parameters that we
2871 // expect to see.
2872 TemplateParameterList *ExpectedTemplateParams = nullptr;
2873
2874 // C++0x [temp.expl.spec]p15:
2875 // A member or a member template may be nested within many enclosing
2876 // class templates. In an explicit specialization for such a member, the
2877 // member declaration shall be preceded by a template<> for each
2878 // enclosing class template that is explicitly specialized.
2879 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
2880 if (ClassTemplatePartialSpecializationDecl *Partial
2881 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Record)) {
2882 ExpectedTemplateParams = Partial->getTemplateParameters();
2883 NeedNonemptyTemplateHeader = true;
2884 } else if (Record->isDependentType()) {
2885 if (Record->getDescribedClassTemplate()) {
2886 ExpectedTemplateParams = Record->getDescribedClassTemplate()
2887 ->getTemplateParameters();
2888 NeedNonemptyTemplateHeader = true;
2889 }
2890 } else if (ClassTemplateSpecializationDecl *Spec
2891 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
2892 // C++0x [temp.expl.spec]p4:
2893 // Members of an explicitly specialized class template are defined
2894 // in the same manner as members of normal classes, and not using
2895 // the template<> syntax.
2896 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
2897 NeedEmptyTemplateHeader = true;
2898 else
2899 continue;
2900 } else if (Record->getTemplateSpecializationKind()) {
2901 if (Record->getTemplateSpecializationKind()
2902 != TSK_ExplicitSpecialization &&
2903 TypeIdx == NumTypes - 1)
2904 IsMemberSpecialization = true;
2905
2906 continue;
2907 }
2908 } else if (const TemplateSpecializationType *TST
2909 = T->getAs<TemplateSpecializationType>()) {
2910 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
2911 ExpectedTemplateParams = Template->getTemplateParameters();
2912 NeedNonemptyTemplateHeader = true;
2913 }
2914 } else if (T->getAs<DependentTemplateSpecializationType>()) {
2915 // FIXME: We actually could/should check the template arguments here
2916 // against the corresponding template parameter list.
2917 NeedNonemptyTemplateHeader = false;
2918 }
2919
2920 // C++ [temp.expl.spec]p16:
2921 // In an explicit specialization declaration for a member of a class
2922 // template or a member template that appears in namespace scope, the
2923 // member template and some of its enclosing class templates may remain
2924 // unspecialized, except that the declaration shall not explicitly
2925 // specialize a class member template if its enclosing class templates
2926 // are not explicitly specialized as well.
2927 if (ParamIdx < ParamLists.size()) {
2928 if (ParamLists[ParamIdx]->size() == 0) {
2929 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
2930 false))
2931 return nullptr;
2932 } else
2933 SawNonEmptyTemplateParameterList = true;
2934 }
2935
2936 if (NeedEmptyTemplateHeader) {
2937 // If we're on the last of the types, and we need a 'template<>' header
2938 // here, then it's a member specialization.
2939 if (TypeIdx == NumTypes - 1)
2940 IsMemberSpecialization = true;
2941
2942 if (ParamIdx < ParamLists.size()) {
2943 if (ParamLists[ParamIdx]->size() > 0) {
2944 // The header has template parameters when it shouldn't. Complain.
2945 if (!SuppressDiagnostic)
2946 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
2947 DiagID: diag::err_template_param_list_matches_nontemplate)
2948 << T
2949 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
2950 ParamLists[ParamIdx]->getRAngleLoc())
2951 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
2952 Invalid = true;
2953 return nullptr;
2954 }
2955
2956 // Consume this template header.
2957 ++ParamIdx;
2958 continue;
2959 }
2960
2961 if (!IsFriend)
2962 if (DiagnoseMissingExplicitSpecialization(
2963 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
2964 return nullptr;
2965
2966 continue;
2967 }
2968
2969 if (NeedNonemptyTemplateHeader) {
2970 // In friend declarations we can have template-ids which don't
2971 // depend on the corresponding template parameter lists. But
2972 // assume that empty parameter lists are supposed to match this
2973 // template-id.
2974 if (IsFriend && T->isDependentType()) {
2975 if (ParamIdx < ParamLists.size() &&
2976 DependsOnTemplateParameters(T, Params: ParamLists[ParamIdx]))
2977 ExpectedTemplateParams = nullptr;
2978 else
2979 continue;
2980 }
2981
2982 if (ParamIdx < ParamLists.size()) {
2983 // Check the template parameter list, if we can.
2984 if (ExpectedTemplateParams &&
2985 !TemplateParameterListsAreEqual(New: ParamLists[ParamIdx],
2986 Old: ExpectedTemplateParams,
2987 Complain: !SuppressDiagnostic, Kind: TPL_TemplateMatch))
2988 Invalid = true;
2989
2990 if (!Invalid &&
2991 CheckTemplateParameterList(NewParams: ParamLists[ParamIdx], OldParams: nullptr,
2992 TPC: TPC_ClassTemplateMember))
2993 Invalid = true;
2994
2995 ++ParamIdx;
2996 continue;
2997 }
2998
2999 if (!SuppressDiagnostic)
3000 Diag(Loc: DeclLoc, DiagID: diag::err_template_spec_needs_template_parameters)
3001 << T
3002 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3003 Invalid = true;
3004 continue;
3005 }
3006 }
3007
3008 // If there were at least as many template-ids as there were template
3009 // parameter lists, then there are no template parameter lists remaining for
3010 // the declaration itself.
3011 if (ParamIdx >= ParamLists.size()) {
3012 if (TemplateId && !IsFriend) {
3013 // We don't have a template header for the declaration itself, but we
3014 // should.
3015 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3016 TemplateId->RAngleLoc));
3017
3018 // Fabricate an empty template parameter list for the invented header.
3019 return TemplateParameterList::Create(C: Context, TemplateLoc: SourceLocation(),
3020 LAngleLoc: SourceLocation(), Params: {},
3021 RAngleLoc: SourceLocation(), RequiresClause: nullptr);
3022 }
3023
3024 return nullptr;
3025 }
3026
3027 // If there were too many template parameter lists, complain about that now.
3028 if (ParamIdx < ParamLists.size() - 1) {
3029 bool HasAnyExplicitSpecHeader = false;
3030 bool AllExplicitSpecHeaders = true;
3031 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3032 if (ParamLists[I]->size() == 0)
3033 HasAnyExplicitSpecHeader = true;
3034 else
3035 AllExplicitSpecHeaders = false;
3036 }
3037
3038 if (!SuppressDiagnostic)
3039 Diag(Loc: ParamLists[ParamIdx]->getTemplateLoc(),
3040 DiagID: AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3041 : diag::err_template_spec_extra_headers)
3042 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3043 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3044
3045 // If there was a specialization somewhere, such that 'template<>' is
3046 // not required, and there were any 'template<>' headers, note where the
3047 // specialization occurred.
3048 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3049 !SuppressDiagnostic)
3050 Diag(Loc: ExplicitSpecLoc,
3051 DiagID: diag::note_explicit_template_spec_does_not_need_header)
3052 << NestedTypes.back();
3053
3054 // We have a template parameter list with no corresponding scope, which
3055 // means that the resulting template declaration can't be instantiated
3056 // properly (we'll end up with dependent nodes when we shouldn't).
3057 if (!AllExplicitSpecHeaders)
3058 Invalid = true;
3059 }
3060
3061 // C++ [temp.expl.spec]p16:
3062 // In an explicit specialization declaration for a member of a class
3063 // template or a member template that ap- pears in namespace scope, the
3064 // member template and some of its enclosing class templates may remain
3065 // unspecialized, except that the declaration shall not explicitly
3066 // specialize a class member template if its en- closing class templates
3067 // are not explicitly specialized as well.
3068 if (ParamLists.back()->size() == 0 &&
3069 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3070 false))
3071 return nullptr;
3072
3073 // Return the last template parameter list, which corresponds to the
3074 // entity being declared.
3075 return ParamLists.back();
3076}
3077
3078void Sema::NoteAllFoundTemplates(TemplateName Name) {
3079 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3080 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_declared_here)
3081 << (isa<FunctionTemplateDecl>(Val: Template)
3082 ? 0
3083 : isa<ClassTemplateDecl>(Val: Template)
3084 ? 1
3085 : isa<VarTemplateDecl>(Val: Template)
3086 ? 2
3087 : isa<TypeAliasTemplateDecl>(Val: Template) ? 3 : 4)
3088 << Template->getDeclName();
3089 return;
3090 }
3091
3092 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3093 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3094 IEnd = OST->end();
3095 I != IEnd; ++I)
3096 Diag(Loc: (*I)->getLocation(), DiagID: diag::note_template_declared_here)
3097 << 0 << (*I)->getDeclName();
3098
3099 return;
3100 }
3101}
3102
3103static QualType builtinCommonTypeImpl(Sema &S, TemplateName BaseTemplate,
3104 SourceLocation TemplateLoc,
3105 ArrayRef<TemplateArgument> Ts) {
3106 auto lookUpCommonType = [&](TemplateArgument T1,
3107 TemplateArgument T2) -> QualType {
3108 // Don't bother looking for other specializations if both types are
3109 // builtins - users aren't allowed to specialize for them
3110 if (T1.getAsType()->isBuiltinType() && T2.getAsType()->isBuiltinType())
3111 return builtinCommonTypeImpl(S, BaseTemplate, TemplateLoc, Ts: {T1, T2});
3112
3113 TemplateArgumentListInfo Args;
3114 Args.addArgument(Loc: TemplateArgumentLoc(
3115 T1, S.Context.getTrivialTypeSourceInfo(T: T1.getAsType())));
3116 Args.addArgument(Loc: TemplateArgumentLoc(
3117 T2, S.Context.getTrivialTypeSourceInfo(T: T2.getAsType())));
3118
3119 EnterExpressionEvaluationContext UnevaluatedContext(
3120 S, Sema::ExpressionEvaluationContext::Unevaluated);
3121 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3122 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3123
3124 QualType BaseTemplateInst =
3125 S.CheckTemplateIdType(Template: BaseTemplate, TemplateLoc, TemplateArgs&: Args);
3126
3127 if (SFINAE.hasErrorOccurred())
3128 return QualType();
3129
3130 return BaseTemplateInst;
3131 };
3132
3133 // Note A: For the common_type trait applied to a template parameter pack T of
3134 // types, the member type shall be either defined or not present as follows:
3135 switch (Ts.size()) {
3136
3137 // If sizeof...(T) is zero, there shall be no member type.
3138 case 0:
3139 return QualType();
3140
3141 // If sizeof...(T) is one, let T0 denote the sole type constituting the
3142 // pack T. The member typedef-name type shall denote the same type, if any, as
3143 // common_type_t<T0, T0>; otherwise there shall be no member type.
3144 case 1:
3145 return lookUpCommonType(Ts[0], Ts[0]);
3146
3147 // If sizeof...(T) is two, let the first and second types constituting T be
3148 // denoted by T1 and T2, respectively, and let D1 and D2 denote the same types
3149 // as decay_t<T1> and decay_t<T2>, respectively.
3150 case 2: {
3151 QualType T1 = Ts[0].getAsType();
3152 QualType T2 = Ts[1].getAsType();
3153 QualType D1 = S.BuiltinDecay(BaseType: T1, Loc: {});
3154 QualType D2 = S.BuiltinDecay(BaseType: T2, Loc: {});
3155
3156 // If is_same_v<T1, D1> is false or is_same_v<T2, D2> is false, let C denote
3157 // the same type, if any, as common_type_t<D1, D2>.
3158 if (!S.Context.hasSameType(T1, T2: D1) || !S.Context.hasSameType(T1: T2, T2: D2))
3159 return lookUpCommonType(D1, D2);
3160
3161 // Otherwise, if decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3162 // denotes a valid type, let C denote that type.
3163 {
3164 auto CheckConditionalOperands = [&](bool ConstRefQual) -> QualType {
3165 EnterExpressionEvaluationContext UnevaluatedContext(
3166 S, Sema::ExpressionEvaluationContext::Unevaluated);
3167 Sema::SFINAETrap SFINAE(S, /*ForValidityCheck=*/true);
3168 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3169
3170 // false
3171 OpaqueValueExpr CondExpr(SourceLocation(), S.Context.BoolTy,
3172 VK_PRValue);
3173 ExprResult Cond = &CondExpr;
3174
3175 auto EVK = ConstRefQual ? VK_LValue : VK_PRValue;
3176 if (ConstRefQual) {
3177 D1.addConst();
3178 D2.addConst();
3179 }
3180
3181 // declval<D1>()
3182 OpaqueValueExpr LHSExpr(TemplateLoc, D1, EVK);
3183 ExprResult LHS = &LHSExpr;
3184
3185 // declval<D2>()
3186 OpaqueValueExpr RHSExpr(TemplateLoc, D2, EVK);
3187 ExprResult RHS = &RHSExpr;
3188
3189 ExprValueKind VK = VK_PRValue;
3190 ExprObjectKind OK = OK_Ordinary;
3191
3192 // decltype(false ? declval<D1>() : declval<D2>())
3193 QualType Result =
3194 S.CheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc: TemplateLoc);
3195
3196 if (Result.isNull() || SFINAE.hasErrorOccurred())
3197 return QualType();
3198
3199 // decay_t<decltype(false ? declval<D1>() : declval<D2>())>
3200 return S.BuiltinDecay(BaseType: Result, Loc: TemplateLoc);
3201 };
3202
3203 if (auto Res = CheckConditionalOperands(false); !Res.isNull())
3204 return Res;
3205
3206 // Let:
3207 // CREF(A) be add_lvalue_reference_t<const remove_reference_t<A>>,
3208 // COND-RES(X, Y) be
3209 // decltype(false ? declval<X(&)()>()() : declval<Y(&)()>()()).
3210
3211 // C++20 only
3212 // Otherwise, if COND-RES(CREF(D1), CREF(D2)) denotes a type, let C denote
3213 // the type decay_t<COND-RES(CREF(D1), CREF(D2))>.
3214 if (!S.Context.getLangOpts().CPlusPlus20)
3215 return QualType();
3216 return CheckConditionalOperands(true);
3217 }
3218 }
3219
3220 // If sizeof...(T) is greater than two, let T1, T2, and R, respectively,
3221 // denote the first, second, and (pack of) remaining types constituting T. Let
3222 // C denote the same type, if any, as common_type_t<T1, T2>. If there is such
3223 // a type C, the member typedef-name type shall denote the same type, if any,
3224 // as common_type_t<C, R...>. Otherwise, there shall be no member type.
3225 default: {
3226 QualType Result = Ts.front().getAsType();
3227 for (auto T : llvm::drop_begin(RangeOrContainer&: Ts)) {
3228 Result = lookUpCommonType(Result, T.getAsType());
3229 if (Result.isNull())
3230 return QualType();
3231 }
3232 return Result;
3233 }
3234 }
3235}
3236
3237static bool isInVkNamespace(const RecordType *RT) {
3238 DeclContext *DC = RT->getDecl()->getDeclContext();
3239 if (!DC)
3240 return false;
3241
3242 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Val: DC);
3243 if (!ND)
3244 return false;
3245
3246 return ND->getQualifiedNameAsString() == "hlsl::vk";
3247}
3248
3249static SpirvOperand checkHLSLSpirvTypeOperand(Sema &SemaRef,
3250 QualType OperandArg,
3251 SourceLocation Loc) {
3252 if (auto *RT = OperandArg->getAs<RecordType>()) {
3253 bool Literal = false;
3254 SourceLocation LiteralLoc;
3255 if (isInVkNamespace(RT) && RT->getDecl()->getName() == "Literal") {
3256 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3257 assert(SpecDecl);
3258
3259 const TemplateArgumentList &LiteralArgs = SpecDecl->getTemplateArgs();
3260 QualType ConstantType = LiteralArgs[0].getAsType();
3261 RT = ConstantType->getAs<RecordType>();
3262 Literal = true;
3263 LiteralLoc = SpecDecl->getSourceRange().getBegin();
3264 }
3265
3266 if (RT && isInVkNamespace(RT) &&
3267 RT->getDecl()->getName() == "integral_constant") {
3268 auto SpecDecl = dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl());
3269 assert(SpecDecl);
3270
3271 const TemplateArgumentList &ConstantArgs = SpecDecl->getTemplateArgs();
3272
3273 QualType ConstantType = ConstantArgs[0].getAsType();
3274 llvm::APInt Value = ConstantArgs[1].getAsIntegral();
3275
3276 if (Literal)
3277 return SpirvOperand::createLiteral(Val: Value);
3278 return SpirvOperand::createConstant(ResultType: ConstantType, Val: Value);
3279 } else if (Literal) {
3280 SemaRef.Diag(Loc: LiteralLoc, DiagID: diag::err_hlsl_vk_literal_must_contain_constant);
3281 return SpirvOperand();
3282 }
3283 }
3284 if (SemaRef.RequireCompleteType(Loc, T: OperandArg,
3285 DiagID: diag::err_call_incomplete_argument))
3286 return SpirvOperand();
3287 return SpirvOperand::createType(T: OperandArg);
3288}
3289
3290static QualType
3291checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3292 ArrayRef<TemplateArgument> Converted,
3293 SourceLocation TemplateLoc,
3294 TemplateArgumentListInfo &TemplateArgs) {
3295 ASTContext &Context = SemaRef.getASTContext();
3296
3297 switch (BTD->getBuiltinTemplateKind()) {
3298 case BTK__make_integer_seq: {
3299 // Specializations of __make_integer_seq<S, T, N> are treated like
3300 // S<T, 0, ..., N-1>.
3301
3302 QualType OrigType = Converted[1].getAsType();
3303 // C++14 [inteseq.intseq]p1:
3304 // T shall be an integer type.
3305 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Ctx: Context)) {
3306 SemaRef.Diag(Loc: TemplateArgs[1].getLocation(),
3307 DiagID: diag::err_integer_sequence_integral_element_type);
3308 return QualType();
3309 }
3310
3311 TemplateArgument NumArgsArg = Converted[2];
3312 if (NumArgsArg.isDependent())
3313 return QualType();
3314
3315 TemplateArgumentListInfo SyntheticTemplateArgs;
3316 // The type argument, wrapped in substitution sugar, gets reused as the
3317 // first template argument in the synthetic template argument list.
3318 SyntheticTemplateArgs.addArgument(
3319 Loc: TemplateArgumentLoc(TemplateArgument(OrigType),
3320 SemaRef.Context.getTrivialTypeSourceInfo(
3321 T: OrigType, Loc: TemplateArgs[1].getLocation())));
3322
3323 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3324 // Expand N into 0 ... N-1.
3325 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3326 I < NumArgs; ++I) {
3327 TemplateArgument TA(Context, I, OrigType);
3328 SyntheticTemplateArgs.addArgument(Loc: SemaRef.getTrivialTemplateArgumentLoc(
3329 Arg: TA, NTTPType: OrigType, Loc: TemplateArgs[2].getLocation()));
3330 }
3331 } else {
3332 // C++14 [inteseq.make]p1:
3333 // If N is negative the program is ill-formed.
3334 SemaRef.Diag(Loc: TemplateArgs[2].getLocation(),
3335 DiagID: diag::err_integer_sequence_negative_length);
3336 return QualType();
3337 }
3338
3339 // The first template argument will be reused as the template decl that
3340 // our synthetic template arguments will be applied to.
3341 return SemaRef.CheckTemplateIdType(Template: Converted[0].getAsTemplate(),
3342 TemplateLoc, TemplateArgs&: SyntheticTemplateArgs);
3343 }
3344
3345 case BTK__type_pack_element: {
3346 // Specializations of
3347 // __type_pack_element<Index, T_1, ..., T_N>
3348 // are treated like T_Index.
3349 assert(Converted.size() == 2 &&
3350 "__type_pack_element should be given an index and a parameter pack");
3351
3352 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3353 if (IndexArg.isDependent() || Ts.isDependent())
3354 return QualType();
3355
3356 llvm::APSInt Index = IndexArg.getAsIntegral();
3357 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3358 "type std::size_t, and hence be non-negative");
3359 // If the Index is out of bounds, the program is ill-formed.
3360 if (Index >= Ts.pack_size()) {
3361 SemaRef.Diag(Loc: TemplateArgs[0].getLocation(),
3362 DiagID: diag::err_type_pack_element_out_of_bounds);
3363 return QualType();
3364 }
3365
3366 // We simply return the type at index `Index`.
3367 int64_t N = Index.getExtValue();
3368 return Ts.getPackAsArray()[N].getAsType();
3369 }
3370
3371 case BTK__builtin_common_type: {
3372 assert(Converted.size() == 4);
3373 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3374 return QualType();
3375
3376 TemplateName BaseTemplate = Converted[0].getAsTemplate();
3377 ArrayRef<TemplateArgument> Ts = Converted[3].getPackAsArray();
3378 if (auto CT = builtinCommonTypeImpl(S&: SemaRef, BaseTemplate, TemplateLoc, Ts);
3379 !CT.isNull()) {
3380 TemplateArgumentListInfo TAs;
3381 TAs.addArgument(Loc: TemplateArgumentLoc(
3382 TemplateArgument(CT), SemaRef.Context.getTrivialTypeSourceInfo(
3383 T: CT, Loc: TemplateArgs[1].getLocation())));
3384 TemplateName HasTypeMember = Converted[1].getAsTemplate();
3385 return SemaRef.CheckTemplateIdType(Template: HasTypeMember, TemplateLoc, TemplateArgs&: TAs);
3386 }
3387 QualType HasNoTypeMember = Converted[2].getAsType();
3388 return HasNoTypeMember;
3389 }
3390
3391 case BTK__hlsl_spirv_type: {
3392 assert(Converted.size() == 4);
3393
3394 if (!Context.getTargetInfo().getTriple().isSPIRV()) {
3395 SemaRef.Diag(Loc: TemplateLoc, DiagID: diag::err_hlsl_spirv_only) << BTD;
3396 }
3397
3398 if (llvm::any_of(Range&: Converted, P: [](auto &C) { return C.isDependent(); }))
3399 return QualType();
3400
3401 uint64_t Opcode = Converted[0].getAsIntegral().getZExtValue();
3402 uint64_t Size = Converted[1].getAsIntegral().getZExtValue();
3403 uint64_t Alignment = Converted[2].getAsIntegral().getZExtValue();
3404
3405 ArrayRef<TemplateArgument> OperandArgs = Converted[3].getPackAsArray();
3406
3407 llvm::SmallVector<SpirvOperand> Operands;
3408
3409 for (auto &OperandTA : OperandArgs) {
3410 QualType OperandArg = OperandTA.getAsType();
3411 auto Operand = checkHLSLSpirvTypeOperand(SemaRef, OperandArg,
3412 Loc: TemplateArgs[3].getLocation());
3413 if (!Operand.isValid())
3414 return QualType();
3415 Operands.push_back(Elt: Operand);
3416 }
3417
3418 return Context.getHLSLInlineSpirvType(Opcode, Size, Alignment, Operands);
3419 }
3420 }
3421 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3422}
3423
3424/// Determine whether this alias template is "enable_if_t".
3425/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3426static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3427 return AliasTemplate->getName() == "enable_if_t" ||
3428 AliasTemplate->getName() == "__enable_if_t";
3429}
3430
3431/// Collect all of the separable terms in the given condition, which
3432/// might be a conjunction.
3433///
3434/// FIXME: The right answer is to convert the logical expression into
3435/// disjunctive normal form, so we can find the first failed term
3436/// within each possible clause.
3437static void collectConjunctionTerms(Expr *Clause,
3438 SmallVectorImpl<Expr *> &Terms) {
3439 if (auto BinOp = dyn_cast<BinaryOperator>(Val: Clause->IgnoreParenImpCasts())) {
3440 if (BinOp->getOpcode() == BO_LAnd) {
3441 collectConjunctionTerms(Clause: BinOp->getLHS(), Terms);
3442 collectConjunctionTerms(Clause: BinOp->getRHS(), Terms);
3443 return;
3444 }
3445 }
3446
3447 Terms.push_back(Elt: Clause);
3448}
3449
3450// The ranges-v3 library uses an odd pattern of a top-level "||" with
3451// a left-hand side that is value-dependent but never true. Identify
3452// the idiom and ignore that term.
3453static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3454 // Top-level '||'.
3455 auto *BinOp = dyn_cast<BinaryOperator>(Val: Cond->IgnoreParenImpCasts());
3456 if (!BinOp) return Cond;
3457
3458 if (BinOp->getOpcode() != BO_LOr) return Cond;
3459
3460 // With an inner '==' that has a literal on the right-hand side.
3461 Expr *LHS = BinOp->getLHS();
3462 auto *InnerBinOp = dyn_cast<BinaryOperator>(Val: LHS->IgnoreParenImpCasts());
3463 if (!InnerBinOp) return Cond;
3464
3465 if (InnerBinOp->getOpcode() != BO_EQ ||
3466 !isa<IntegerLiteral>(Val: InnerBinOp->getRHS()))
3467 return Cond;
3468
3469 // If the inner binary operation came from a macro expansion named
3470 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3471 // of the '||', which is the real, user-provided condition.
3472 SourceLocation Loc = InnerBinOp->getExprLoc();
3473 if (!Loc.isMacroID()) return Cond;
3474
3475 StringRef MacroName = PP.getImmediateMacroName(Loc);
3476 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3477 return BinOp->getRHS();
3478
3479 return Cond;
3480}
3481
3482namespace {
3483
3484// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3485// within failing boolean expression, such as substituting template parameters
3486// for actual types.
3487class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3488public:
3489 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3490 : Policy(P) {}
3491
3492 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3493 const auto *DR = dyn_cast<DeclRefExpr>(Val: E);
3494 if (DR && DR->getQualifier()) {
3495 // If this is a qualified name, expand the template arguments in nested
3496 // qualifiers.
3497 DR->getQualifier()->print(OS, Policy, ResolveTemplateArguments: true);
3498 // Then print the decl itself.
3499 const ValueDecl *VD = DR->getDecl();
3500 OS << VD->getName();
3501 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) {
3502 // This is a template variable, print the expanded template arguments.
3503 printTemplateArgumentList(
3504 OS, Args: IV->getTemplateArgs().asArray(), Policy,
3505 TPL: IV->getSpecializedTemplate()->getTemplateParameters());
3506 }
3507 return true;
3508 }
3509 return false;
3510 }
3511
3512private:
3513 const PrintingPolicy Policy;
3514};
3515
3516} // end anonymous namespace
3517
3518std::pair<Expr *, std::string>
3519Sema::findFailedBooleanCondition(Expr *Cond) {
3520 Cond = lookThroughRangesV3Condition(PP, Cond);
3521
3522 // Separate out all of the terms in a conjunction.
3523 SmallVector<Expr *, 4> Terms;
3524 collectConjunctionTerms(Clause: Cond, Terms);
3525
3526 // Determine which term failed.
3527 Expr *FailedCond = nullptr;
3528 for (Expr *Term : Terms) {
3529 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3530
3531 // Literals are uninteresting.
3532 if (isa<CXXBoolLiteralExpr>(Val: TermAsWritten) ||
3533 isa<IntegerLiteral>(Val: TermAsWritten))
3534 continue;
3535
3536 // The initialization of the parameter from the argument is
3537 // a constant-evaluated context.
3538 EnterExpressionEvaluationContext ConstantEvaluated(
3539 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3540
3541 bool Succeeded;
3542 if (Term->EvaluateAsBooleanCondition(Result&: Succeeded, Ctx: Context) &&
3543 !Succeeded) {
3544 FailedCond = TermAsWritten;
3545 break;
3546 }
3547 }
3548 if (!FailedCond)
3549 FailedCond = Cond->IgnoreParenImpCasts();
3550
3551 std::string Description;
3552 {
3553 llvm::raw_string_ostream Out(Description);
3554 PrintingPolicy Policy = getPrintingPolicy();
3555 Policy.PrintAsCanonical = true;
3556 FailedBooleanConditionPrinterHelper Helper(Policy);
3557 FailedCond->printPretty(OS&: Out, Helper: &Helper, Policy, Indentation: 0, NewlineSymbol: "\n", Context: nullptr);
3558 }
3559 return { FailedCond, Description };
3560}
3561
3562QualType Sema::CheckTemplateIdType(TemplateName Name,
3563 SourceLocation TemplateLoc,
3564 TemplateArgumentListInfo &TemplateArgs) {
3565 // FIXME: 'getUnderlying' loses SubstTemplateTemplateParm nodes from alias
3566 // template substitutions.
3567 if (DependentTemplateName *DTN =
3568 Name.getUnderlying().getAsDependentTemplateName();
3569 DTN && DTN->getName().getIdentifier())
3570 // When building a template-id where the template-name is dependent,
3571 // assume the template is a type template. Either our assumption is
3572 // correct, or the code is ill-formed and will be diagnosed when the
3573 // dependent name is substituted.
3574 return Context.getDependentTemplateSpecializationType(
3575 Keyword: ElaboratedTypeKeyword::None, Name: *DTN, Args: TemplateArgs.arguments());
3576
3577 if (Name.getAsAssumedTemplateName() &&
3578 resolveAssumedTemplateNameAsType(/*Scope=*/S: nullptr, Name, NameLoc: TemplateLoc))
3579 return QualType();
3580
3581 TemplateDecl *Template;
3582 DefaultArguments DefaultArgs;
3583 if (const SubstTemplateTemplateParmPackStorage *S =
3584 Name.getAsSubstTemplateTemplateParmPack()) {
3585 Template = S->getParameterPack();
3586 } else {
3587 std::tie(args&: Template, args&: DefaultArgs) = Name.getTemplateDeclAndDefaultArgs();
3588 if (!Template || isa<FunctionTemplateDecl>(Val: Template) ||
3589 isa<VarTemplateDecl>(Val: Template) || isa<ConceptDecl>(Val: Template)) {
3590 Diag(Loc: TemplateLoc, DiagID: diag::err_template_id_not_a_type) << Name;
3591 NoteAllFoundTemplates(Name);
3592 return QualType();
3593 }
3594 }
3595
3596 // Check that the template argument list is well-formed for this
3597 // template.
3598 CheckTemplateArgumentInfo CTAI;
3599 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3600 DefaultArgs, /*PartialTemplateArgs=*/false,
3601 CTAI,
3602 /*UpdateArgsWithConversions=*/true))
3603 return QualType();
3604
3605 QualType CanonType;
3606
3607 if (isa<TemplateTemplateParmDecl>(Val: Template)) {
3608 // We might have a substituted template template parameter pack. If so,
3609 // build a template specialization type for it.
3610 } else if (TypeAliasTemplateDecl *AliasTemplate =
3611 dyn_cast<TypeAliasTemplateDecl>(Val: Template)) {
3612
3613 // Find the canonical type for this type alias template specialization.
3614 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3615 if (Pattern->isInvalidDecl())
3616 return QualType();
3617
3618 // Only substitute for the innermost template argument list.
3619 MultiLevelTemplateArgumentList TemplateArgLists;
3620 TemplateArgLists.addOuterTemplateArguments(AssociatedDecl: Template, Args: CTAI.SugaredConverted,
3621 /*Final=*/true);
3622 TemplateArgLists.addOuterRetainedLevels(
3623 Num: AliasTemplate->getTemplateParameters()->getDepth());
3624
3625 LocalInstantiationScope Scope(*this);
3626 InstantiatingTemplate Inst(
3627 *this, /*PointOfInstantiation=*/TemplateLoc,
3628 /*Entity=*/AliasTemplate,
3629 /*TemplateArgs=*/TemplateArgLists.getInnermost());
3630
3631 // Diagnose uses of this alias.
3632 (void)DiagnoseUseOfDecl(D: AliasTemplate, Locs: TemplateLoc);
3633
3634 if (Inst.isInvalid())
3635 return QualType();
3636
3637 std::optional<ContextRAII> SavedContext;
3638 if (!AliasTemplate->getDeclContext()->isFileContext())
3639 SavedContext.emplace(args&: *this, args: AliasTemplate->getDeclContext());
3640
3641 CanonType =
3642 SubstType(T: Pattern->getUnderlyingType(), TemplateArgs: TemplateArgLists,
3643 Loc: AliasTemplate->getLocation(), Entity: AliasTemplate->getDeclName());
3644 if (CanonType.isNull()) {
3645 // If this was enable_if and we failed to find the nested type
3646 // within enable_if in a SFINAE context, dig out the specific
3647 // enable_if condition that failed and present that instead.
3648 if (isEnableIfAliasTemplate(AliasTemplate)) {
3649 if (auto DeductionInfo = isSFINAEContext()) {
3650 if (*DeductionInfo &&
3651 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3652 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3653 diag::err_typename_nested_not_found_enable_if &&
3654 TemplateArgs[0].getArgument().getKind()
3655 == TemplateArgument::Expression) {
3656 Expr *FailedCond;
3657 std::string FailedDescription;
3658 std::tie(args&: FailedCond, args&: FailedDescription) =
3659 findFailedBooleanCondition(Cond: TemplateArgs[0].getSourceExpression());
3660
3661 // Remove the old SFINAE diagnostic.
3662 PartialDiagnosticAt OldDiag =
3663 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3664 (*DeductionInfo)->takeSFINAEDiagnostic(PD&: OldDiag);
3665
3666 // Add a new SFINAE diagnostic specifying which condition
3667 // failed.
3668 (*DeductionInfo)->addSFINAEDiagnostic(
3669 Loc: OldDiag.first,
3670 PD: PDiag(DiagID: diag::err_typename_nested_not_found_requirement)
3671 << FailedDescription
3672 << FailedCond->getSourceRange());
3673 }
3674 }
3675 }
3676
3677 return QualType();
3678 }
3679 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Val: Template)) {
3680 CanonType = checkBuiltinTemplateIdType(SemaRef&: *this, BTD, Converted: CTAI.SugaredConverted,
3681 TemplateLoc, TemplateArgs);
3682 } else if (Name.isDependent() ||
3683 TemplateSpecializationType::anyDependentTemplateArguments(
3684 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
3685 // This class template specialization is a dependent
3686 // type. Therefore, its canonical type is another class template
3687 // specialization type that contains all of the converted
3688 // arguments in canonical form. This ensures that, e.g., A<T> and
3689 // A<T, T> have identical types when A is declared as:
3690 //
3691 // template<typename T, typename U = T> struct A;
3692 CanonType = Context.getCanonicalTemplateSpecializationType(
3693 T: Context.getCanonicalTemplateName(Name, /*IgnoreDeduced=*/true),
3694 CanonicalArgs: CTAI.CanonicalConverted);
3695 assert(CanonType->isCanonicalUnqualified());
3696
3697 // This might work out to be a current instantiation, in which
3698 // case the canonical type needs to be the InjectedClassNameType.
3699 //
3700 // TODO: in theory this could be a simple hashtable lookup; most
3701 // changes to CurContext don't change the set of current
3702 // instantiations.
3703 if (isa<ClassTemplateDecl>(Val: Template)) {
3704 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3705 // If we get out to a namespace, we're done.
3706 if (Ctx->isFileContext()) break;
3707
3708 // If this isn't a record, keep looking.
3709 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Ctx);
3710 if (!Record) continue;
3711
3712 // Look for one of the two cases with InjectedClassNameTypes
3713 // and check whether it's the same template.
3714 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Record) &&
3715 !Record->getDescribedClassTemplate())
3716 continue;
3717
3718 // Fetch the injected class name type and check whether its
3719 // injected type is equal to the type we just built.
3720 QualType ICNT = Context.getTypeDeclType(Decl: Record);
3721 QualType Injected = cast<InjectedClassNameType>(Val&: ICNT)
3722 ->getInjectedSpecializationType();
3723
3724 if (CanonType != Injected->getCanonicalTypeInternal())
3725 continue;
3726
3727 // If so, the canonical type of this TST is the injected
3728 // class name type of the record we just found.
3729 assert(ICNT.isCanonical());
3730 CanonType = ICNT;
3731 break;
3732 }
3733 }
3734 } else if (ClassTemplateDecl *ClassTemplate =
3735 dyn_cast<ClassTemplateDecl>(Val: Template)) {
3736 // Find the class template specialization declaration that
3737 // corresponds to these arguments.
3738 void *InsertPos = nullptr;
3739 ClassTemplateSpecializationDecl *Decl =
3740 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
3741 if (!Decl) {
3742 // This is the first time we have referenced this class template
3743 // specialization. Create the canonical declaration and add it to
3744 // the set of specializations.
3745 Decl = ClassTemplateSpecializationDecl::Create(
3746 Context, TK: ClassTemplate->getTemplatedDecl()->getTagKind(),
3747 DC: ClassTemplate->getDeclContext(),
3748 StartLoc: ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3749 IdLoc: ClassTemplate->getLocation(), SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted,
3750 StrictPackMatch: CTAI.StrictPackMatch, PrevDecl: nullptr);
3751 ClassTemplate->AddSpecialization(D: Decl, InsertPos);
3752 if (ClassTemplate->isOutOfLine())
3753 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3754 }
3755
3756 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3757 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3758 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3759 if (!Inst.isInvalid()) {
3760 MultiLevelTemplateArgumentList TemplateArgLists(Template,
3761 CTAI.CanonicalConverted,
3762 /*Final=*/false);
3763 InstantiateAttrsForDecl(TemplateArgs: TemplateArgLists,
3764 Pattern: ClassTemplate->getTemplatedDecl(), Inst: Decl);
3765 }
3766 }
3767
3768 // Diagnose uses of this specialization.
3769 (void)DiagnoseUseOfDecl(D: Decl, Locs: TemplateLoc);
3770
3771 CanonType = Context.getTypeDeclType(Decl);
3772 assert(isa<RecordType>(CanonType) &&
3773 "type of non-dependent specialization is not a RecordType");
3774 } else {
3775 llvm_unreachable("Unhandled template kind");
3776 }
3777
3778 // Build the fully-sugared type for this class template
3779 // specialization, which refers back to the class template
3780 // specialization we created or found.
3781 return Context.getTemplateSpecializationType(
3782 T: Name, SpecifiedArgs: TemplateArgs.arguments(), CanonicalArgs: CTAI.CanonicalConverted, Canon: CanonType);
3783}
3784
3785void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3786 TemplateNameKind &TNK,
3787 SourceLocation NameLoc,
3788 IdentifierInfo *&II) {
3789 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
3790
3791 TemplateName Name = ParsedName.get();
3792 auto *ATN = Name.getAsAssumedTemplateName();
3793 assert(ATN && "not an assumed template name");
3794 II = ATN->getDeclName().getAsIdentifierInfo();
3795
3796 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3797 // Resolved to a type template name.
3798 ParsedName = TemplateTy::make(P: Name);
3799 TNK = TNK_Type_template;
3800 }
3801}
3802
3803bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3804 SourceLocation NameLoc,
3805 bool Diagnose) {
3806 // We assumed this undeclared identifier to be an (ADL-only) function
3807 // template name, but it was used in a context where a type was required.
3808 // Try to typo-correct it now.
3809 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3810 assert(ATN && "not an assumed template name");
3811
3812 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3813 struct CandidateCallback : CorrectionCandidateCallback {
3814 bool ValidateCandidate(const TypoCorrection &TC) override {
3815 return TC.getCorrectionDecl() &&
3816 getAsTypeTemplateDecl(D: TC.getCorrectionDecl());
3817 }
3818 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3819 return std::make_unique<CandidateCallback>(args&: *this);
3820 }
3821 } FilterCCC;
3822
3823 TypoCorrection Corrected =
3824 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: nullptr,
3825 CCC&: FilterCCC, Mode: CorrectTypoKind::ErrorRecovery);
3826 if (Corrected && Corrected.getFoundDecl()) {
3827 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_template_suggest)
3828 << ATN->getDeclName());
3829 Name = Context.getQualifiedTemplateName(
3830 /*NNS=*/nullptr, /*TemplateKeyword=*/false,
3831 Template: TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>()));
3832 return false;
3833 }
3834
3835 if (Diagnose)
3836 Diag(Loc: R.getNameLoc(), DiagID: diag::err_no_template) << R.getLookupName();
3837 return true;
3838}
3839
3840TypeResult Sema::ActOnTemplateIdType(
3841 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3842 TemplateTy TemplateD, const IdentifierInfo *TemplateII,
3843 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3844 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3845 bool IsCtorOrDtorName, bool IsClassName,
3846 ImplicitTypenameContext AllowImplicitTypename) {
3847 if (SS.isInvalid())
3848 return true;
3849
3850 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3851 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3852
3853 // C++ [temp.res]p3:
3854 // A qualified-id that refers to a type and in which the
3855 // nested-name-specifier depends on a template-parameter (14.6.2)
3856 // shall be prefixed by the keyword typename to indicate that the
3857 // qualified-id denotes a type, forming an
3858 // elaborated-type-specifier (7.1.5.3).
3859 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3860 // C++2a relaxes some of those restrictions in [temp.res]p5.
3861 NestedNameSpecifier *NNS =
3862 NestedNameSpecifier::Create(Context, Prefix: SS.getScopeRep(), II: TemplateII);
3863 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
3864 auto DB = DiagCompat(Loc: SS.getBeginLoc(), CompatDiagId: diag_compat::implicit_typename)
3865 << NNS;
3866 if (!getLangOpts().CPlusPlus20)
3867 DB << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "typename ");
3868 } else
3869 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_typename_missing_template) << NNS;
3870
3871 // FIXME: This is not quite correct recovery as we don't transform SS
3872 // into the corresponding dependent form (and we don't diagnose missing
3873 // 'template' keywords within SS as a result).
3874 return ActOnTypenameType(S: nullptr, TypenameLoc: SourceLocation(), SS, TemplateLoc: TemplateKWLoc,
3875 TemplateName: TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3876 TemplateArgs: TemplateArgsIn, RAngleLoc);
3877 }
3878
3879 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3880 // it's not actually allowed to be used as a type in most cases. Because
3881 // we annotate it before we know whether it's valid, we have to check for
3882 // this case here.
3883 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
3884 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3885 Diag(Loc: TemplateIILoc,
3886 DiagID: TemplateKWLoc.isInvalid()
3887 ? diag::err_out_of_line_qualified_id_type_names_constructor
3888 : diag::ext_out_of_line_qualified_id_type_names_constructor)
3889 << TemplateII << 0 /*injected-class-name used as template name*/
3890 << 1 /*if any keyword was present, it was 'template'*/;
3891 }
3892 }
3893
3894 TemplateName Template = TemplateD.get();
3895 if (Template.getAsAssumedTemplateName() &&
3896 resolveAssumedTemplateNameAsType(S, Name&: Template, NameLoc: TemplateIILoc))
3897 return true;
3898
3899 // Translate the parser's template argument list in our AST format.
3900 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3901 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3902
3903 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3904 assert(SS.getScopeRep() == DTN->getQualifier());
3905 QualType T = Context.getDependentTemplateSpecializationType(
3906 Keyword: ElaboratedTypeKeyword::None, Name: *DTN, Args: TemplateArgs.arguments());
3907 // Build type-source information.
3908 TypeLocBuilder TLB;
3909 DependentTemplateSpecializationTypeLoc SpecTL
3910 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3911 SpecTL.setElaboratedKeywordLoc(SourceLocation());
3912 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3913 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3914 SpecTL.setTemplateNameLoc(TemplateIILoc);
3915 SpecTL.setLAngleLoc(LAngleLoc);
3916 SpecTL.setRAngleLoc(RAngleLoc);
3917 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3918 SpecTL.setArgLocInfo(i: I, AI: TemplateArgs[I].getLocInfo());
3919 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
3920 }
3921
3922 QualType SpecTy = CheckTemplateIdType(Name: Template, TemplateLoc: TemplateIILoc, TemplateArgs);
3923 if (SpecTy.isNull())
3924 return true;
3925
3926 // Build type-source information.
3927 TypeLocBuilder TLB;
3928 TemplateSpecializationTypeLoc SpecTL =
3929 TLB.push<TemplateSpecializationTypeLoc>(T: SpecTy);
3930 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3931 SpecTL.setTemplateNameLoc(TemplateIILoc);
3932 SpecTL.setLAngleLoc(LAngleLoc);
3933 SpecTL.setRAngleLoc(RAngleLoc);
3934 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
3935 SpecTL.setArgLocInfo(i, AI: TemplateArgs[i].getLocInfo());
3936
3937 // Create an elaborated-type-specifier containing the nested-name-specifier.
3938 QualType ElTy =
3939 getElaboratedType(Keyword: ElaboratedTypeKeyword::None,
3940 SS: !IsCtorOrDtorName ? SS : CXXScopeSpec(), T: SpecTy);
3941 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(T: ElTy);
3942 ElabTL.setElaboratedKeywordLoc(SourceLocation());
3943 if (!ElabTL.isEmpty())
3944 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
3945 return CreateParsedType(T: ElTy, TInfo: TLB.getTypeSourceInfo(Context, T: ElTy));
3946}
3947
3948TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
3949 TypeSpecifierType TagSpec,
3950 SourceLocation TagLoc,
3951 CXXScopeSpec &SS,
3952 SourceLocation TemplateKWLoc,
3953 TemplateTy TemplateD,
3954 SourceLocation TemplateLoc,
3955 SourceLocation LAngleLoc,
3956 ASTTemplateArgsPtr TemplateArgsIn,
3957 SourceLocation RAngleLoc) {
3958 if (SS.isInvalid())
3959 return TypeResult(true);
3960
3961 TemplateName Template = TemplateD.get();
3962
3963 // Translate the parser's template argument list in our AST format.
3964 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
3965 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
3966
3967 // Determine the tag kind
3968 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
3969 ElaboratedTypeKeyword Keyword
3970 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
3971
3972 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
3973 assert(SS.getScopeRep() == DTN->getQualifier());
3974 QualType T = Context.getDependentTemplateSpecializationType(
3975 Keyword, Name: *DTN, Args: TemplateArgs.arguments());
3976
3977 // Build type-source information.
3978 TypeLocBuilder TLB;
3979 DependentTemplateSpecializationTypeLoc SpecTL
3980 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
3981 SpecTL.setElaboratedKeywordLoc(TagLoc);
3982 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
3983 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
3984 SpecTL.setTemplateNameLoc(TemplateLoc);
3985 SpecTL.setLAngleLoc(LAngleLoc);
3986 SpecTL.setRAngleLoc(RAngleLoc);
3987 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
3988 SpecTL.setArgLocInfo(i: I, AI: TemplateArgs[I].getLocInfo());
3989 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
3990 }
3991
3992 if (TypeAliasTemplateDecl *TAT =
3993 dyn_cast_or_null<TypeAliasTemplateDecl>(Val: Template.getAsTemplateDecl())) {
3994 // C++0x [dcl.type.elab]p2:
3995 // If the identifier resolves to a typedef-name or the simple-template-id
3996 // resolves to an alias template specialization, the
3997 // elaborated-type-specifier is ill-formed.
3998 Diag(Loc: TemplateLoc, DiagID: diag::err_tag_reference_non_tag)
3999 << TAT << NonTagKind::TypeAliasTemplate << TagKind;
4000 Diag(Loc: TAT->getLocation(), DiagID: diag::note_declared_at);
4001 }
4002
4003 QualType Result = CheckTemplateIdType(Name: Template, TemplateLoc, TemplateArgs);
4004 if (Result.isNull())
4005 return TypeResult(true);
4006
4007 // Check the tag kind
4008 if (const RecordType *RT = Result->getAs<RecordType>()) {
4009 RecordDecl *D = RT->getDecl();
4010
4011 IdentifierInfo *Id = D->getIdentifier();
4012 assert(Id && "templated class must have an identifier");
4013
4014 if (!isAcceptableTagRedeclaration(Previous: D, NewTag: TagKind, isDefinition: TUK == TagUseKind::Definition,
4015 NewTagLoc: TagLoc, Name: Id)) {
4016 Diag(Loc: TagLoc, DiagID: diag::err_use_with_wrong_tag)
4017 << Result
4018 << FixItHint::CreateReplacement(RemoveRange: SourceRange(TagLoc), Code: D->getKindName());
4019 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_use);
4020 }
4021 }
4022
4023 // Provide source-location information for the template specialization.
4024 TypeLocBuilder TLB;
4025 TemplateSpecializationTypeLoc SpecTL
4026 = TLB.push<TemplateSpecializationTypeLoc>(T: Result);
4027 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4028 SpecTL.setTemplateNameLoc(TemplateLoc);
4029 SpecTL.setLAngleLoc(LAngleLoc);
4030 SpecTL.setRAngleLoc(RAngleLoc);
4031 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4032 SpecTL.setArgLocInfo(i, AI: TemplateArgs[i].getLocInfo());
4033
4034 // Construct an elaborated type containing the nested-name-specifier (if any)
4035 // and tag keyword.
4036 Result = Context.getElaboratedType(Keyword, NNS: SS.getScopeRep(), NamedType: Result);
4037 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(T: Result);
4038 ElabTL.setElaboratedKeywordLoc(TagLoc);
4039 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4040 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
4041}
4042
4043static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4044 NamedDecl *PrevDecl,
4045 SourceLocation Loc,
4046 bool IsPartialSpecialization);
4047
4048static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4049
4050static bool isTemplateArgumentTemplateParameter(
4051 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
4052 switch (Arg.getKind()) {
4053 case TemplateArgument::Null:
4054 case TemplateArgument::NullPtr:
4055 case TemplateArgument::Integral:
4056 case TemplateArgument::Declaration:
4057 case TemplateArgument::StructuralValue:
4058 case TemplateArgument::Pack:
4059 case TemplateArgument::TemplateExpansion:
4060 return false;
4061
4062 case TemplateArgument::Type: {
4063 QualType Type = Arg.getAsType();
4064 const TemplateTypeParmType *TPT =
4065 Arg.getAsType()->getAs<TemplateTypeParmType>();
4066 return TPT && !Type.hasQualifiers() &&
4067 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4068 }
4069
4070 case TemplateArgument::Expression: {
4071 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg.getAsExpr());
4072 if (!DRE || !DRE->getDecl())
4073 return false;
4074 const NonTypeTemplateParmDecl *NTTP =
4075 dyn_cast<NonTypeTemplateParmDecl>(Val: DRE->getDecl());
4076 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4077 }
4078
4079 case TemplateArgument::Template:
4080 const TemplateTemplateParmDecl *TTP =
4081 dyn_cast_or_null<TemplateTemplateParmDecl>(
4082 Val: Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4083 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4084 }
4085 llvm_unreachable("unexpected kind of template argument");
4086}
4087
4088static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4089 ArrayRef<TemplateArgument> Args) {
4090 if (Params->size() != Args.size())
4091 return false;
4092
4093 unsigned Depth = Params->getDepth();
4094
4095 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4096 TemplateArgument Arg = Args[I];
4097
4098 // If the parameter is a pack expansion, the argument must be a pack
4099 // whose only element is a pack expansion.
4100 if (Params->getParam(Idx: I)->isParameterPack()) {
4101 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4102 !Arg.pack_begin()->isPackExpansion())
4103 return false;
4104 Arg = Arg.pack_begin()->getPackExpansionPattern();
4105 }
4106
4107 if (!isTemplateArgumentTemplateParameter(Arg, Depth, Index: I))
4108 return false;
4109 }
4110
4111 return true;
4112}
4113
4114template<typename PartialSpecDecl>
4115static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4116 if (Partial->getDeclContext()->isDependentContext())
4117 return;
4118
4119 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4120 // for non-substitution-failure issues?
4121 TemplateDeductionInfo Info(Partial->getLocation());
4122 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4123 return;
4124
4125 auto *Template = Partial->getSpecializedTemplate();
4126 S.Diag(Partial->getLocation(),
4127 diag::ext_partial_spec_not_more_specialized_than_primary)
4128 << isa<VarTemplateDecl>(Template);
4129
4130 if (Info.hasSFINAEDiagnostic()) {
4131 PartialDiagnosticAt Diag = {SourceLocation(),
4132 PartialDiagnostic::NullDiagnostic()};
4133 Info.takeSFINAEDiagnostic(PD&: Diag);
4134 SmallString<128> SFINAEArgString;
4135 Diag.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
4136 S.Diag(Loc: Diag.first,
4137 DiagID: diag::note_partial_spec_not_more_specialized_than_primary)
4138 << SFINAEArgString;
4139 }
4140
4141 S.NoteTemplateLocation(Decl: *Template);
4142 SmallVector<AssociatedConstraint, 3> PartialAC, TemplateAC;
4143 Template->getAssociatedConstraints(TemplateAC);
4144 Partial->getAssociatedConstraints(PartialAC);
4145 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Partial, AC1: PartialAC, D2: Template,
4146 AC2: TemplateAC);
4147}
4148
4149static void
4150noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4151 const llvm::SmallBitVector &DeducibleParams) {
4152 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4153 if (!DeducibleParams[I]) {
4154 NamedDecl *Param = TemplateParams->getParam(Idx: I);
4155 if (Param->getDeclName())
4156 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4157 << Param->getDeclName();
4158 else
4159 S.Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
4160 << "(anonymous)";
4161 }
4162 }
4163}
4164
4165
4166template<typename PartialSpecDecl>
4167static void checkTemplatePartialSpecialization(Sema &S,
4168 PartialSpecDecl *Partial) {
4169 // C++1z [temp.class.spec]p8: (DR1495)
4170 // - The specialization shall be more specialized than the primary
4171 // template (14.5.5.2).
4172 checkMoreSpecializedThanPrimary(S, Partial);
4173
4174 // C++ [temp.class.spec]p8: (DR1315)
4175 // - Each template-parameter shall appear at least once in the
4176 // template-id outside a non-deduced context.
4177 // C++1z [temp.class.spec.match]p3 (P0127R2)
4178 // If the template arguments of a partial specialization cannot be
4179 // deduced because of the structure of its template-parameter-list
4180 // and the template-id, the program is ill-formed.
4181 auto *TemplateParams = Partial->getTemplateParameters();
4182 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4183 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4184 TemplateParams->getDepth(), DeducibleParams);
4185
4186 if (!DeducibleParams.all()) {
4187 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4188 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4189 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4190 << (NumNonDeducible > 1)
4191 << SourceRange(Partial->getLocation(),
4192 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4193 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4194 }
4195}
4196
4197void Sema::CheckTemplatePartialSpecialization(
4198 ClassTemplatePartialSpecializationDecl *Partial) {
4199 checkTemplatePartialSpecialization(S&: *this, Partial);
4200}
4201
4202void Sema::CheckTemplatePartialSpecialization(
4203 VarTemplatePartialSpecializationDecl *Partial) {
4204 checkTemplatePartialSpecialization(S&: *this, Partial);
4205}
4206
4207void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4208 // C++1z [temp.param]p11:
4209 // A template parameter of a deduction guide template that does not have a
4210 // default-argument shall be deducible from the parameter-type-list of the
4211 // deduction guide template.
4212 auto *TemplateParams = TD->getTemplateParameters();
4213 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4214 MarkDeducedTemplateParameters(FunctionTemplate: TD, Deduced&: DeducibleParams);
4215 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4216 // A parameter pack is deducible (to an empty pack).
4217 auto *Param = TemplateParams->getParam(Idx: I);
4218 if (Param->isParameterPack() || hasVisibleDefaultArgument(D: Param))
4219 DeducibleParams[I] = true;
4220 }
4221
4222 if (!DeducibleParams.all()) {
4223 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4224 Diag(Loc: TD->getLocation(), DiagID: diag::err_deduction_guide_template_not_deducible)
4225 << (NumNonDeducible > 1);
4226 noteNonDeducibleParameters(S&: *this, TemplateParams, DeducibleParams);
4227 }
4228}
4229
4230DeclResult Sema::ActOnVarTemplateSpecialization(
4231 Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous,
4232 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4233 StorageClass SC, bool IsPartialSpecialization) {
4234 // D must be variable template id.
4235 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
4236 "Variable template specialization is declared with a template id.");
4237
4238 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4239 TemplateArgumentListInfo TemplateArgs =
4240 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TemplateId);
4241 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4242 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4243 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4244
4245 TemplateName Name = TemplateId->Template.get();
4246
4247 // The template-id must name a variable template.
4248 VarTemplateDecl *VarTemplate =
4249 dyn_cast_or_null<VarTemplateDecl>(Val: Name.getAsTemplateDecl());
4250 if (!VarTemplate) {
4251 NamedDecl *FnTemplate;
4252 if (auto *OTS = Name.getAsOverloadedTemplate())
4253 FnTemplate = *OTS->begin();
4254 else
4255 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Val: Name.getAsTemplateDecl());
4256 if (FnTemplate)
4257 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template_but_method)
4258 << FnTemplate->getDeclName();
4259 return Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_var_spec_no_template)
4260 << IsPartialSpecialization;
4261 }
4262
4263 if (const auto *DSA = VarTemplate->getAttr<NoSpecializationsAttr>()) {
4264 auto Message = DSA->getMessage();
4265 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
4266 << VarTemplate << !Message.empty() << Message;
4267 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
4268 }
4269
4270 // Check for unexpanded parameter packs in any of the template arguments.
4271 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4272 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
4273 UPPC: IsPartialSpecialization
4274 ? UPPC_PartialSpecialization
4275 : UPPC_ExplicitSpecialization))
4276 return true;
4277
4278 // Check that the template argument list is well-formed for this
4279 // template.
4280 CheckTemplateArgumentInfo CTAI;
4281 if (CheckTemplateArgumentList(Template: VarTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
4282 /*DefaultArgs=*/{},
4283 /*PartialTemplateArgs=*/false, CTAI,
4284 /*UpdateArgsWithConversions=*/true))
4285 return true;
4286
4287 // Find the variable template (partial) specialization declaration that
4288 // corresponds to these arguments.
4289 if (IsPartialSpecialization) {
4290 if (CheckTemplatePartialSpecializationArgs(Loc: TemplateNameLoc, PrimaryTemplate: VarTemplate,
4291 NumExplicitArgs: TemplateArgs.size(),
4292 Args: CTAI.CanonicalConverted))
4293 return true;
4294
4295 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so
4296 // we also do them during instantiation.
4297 if (!Name.isDependent() &&
4298 !TemplateSpecializationType::anyDependentTemplateArguments(
4299 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4300 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
4301 << VarTemplate->getDeclName();
4302 IsPartialSpecialization = false;
4303 }
4304
4305 if (isSameAsPrimaryTemplate(Params: VarTemplate->getTemplateParameters(),
4306 Args: CTAI.CanonicalConverted) &&
4307 (!Context.getLangOpts().CPlusPlus20 ||
4308 !TemplateParams->hasAssociatedConstraints())) {
4309 // C++ [temp.class.spec]p9b3:
4310 //
4311 // -- The argument list of the specialization shall not be identical
4312 // to the implicit argument list of the primary template.
4313 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
4314 << /*variable template*/ 1
4315 << /*is definition*/ (SC != SC_Extern && !CurContext->isRecord())
4316 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
4317 // FIXME: Recover from this by treating the declaration as a
4318 // redeclaration of the primary template.
4319 return true;
4320 }
4321 }
4322
4323 void *InsertPos = nullptr;
4324 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4325
4326 if (IsPartialSpecialization)
4327 PrevDecl = VarTemplate->findPartialSpecialization(
4328 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertPos);
4329 else
4330 PrevDecl =
4331 VarTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
4332
4333 VarTemplateSpecializationDecl *Specialization = nullptr;
4334
4335 // Check whether we can declare a variable template specialization in
4336 // the current scope.
4337 if (CheckTemplateSpecializationScope(S&: *this, Specialized: VarTemplate, PrevDecl,
4338 Loc: TemplateNameLoc,
4339 IsPartialSpecialization))
4340 return true;
4341
4342 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4343 // Since the only prior variable template specialization with these
4344 // arguments was referenced but not declared, reuse that
4345 // declaration node as our own, updating its source location and
4346 // the list of outer template parameters to reflect our new declaration.
4347 Specialization = PrevDecl;
4348 Specialization->setLocation(TemplateNameLoc);
4349 PrevDecl = nullptr;
4350 } else if (IsPartialSpecialization) {
4351 // Create a new class template partial specialization declaration node.
4352 VarTemplatePartialSpecializationDecl *PrevPartial =
4353 cast_or_null<VarTemplatePartialSpecializationDecl>(Val: PrevDecl);
4354 VarTemplatePartialSpecializationDecl *Partial =
4355 VarTemplatePartialSpecializationDecl::Create(
4356 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc,
4357 IdLoc: TemplateNameLoc, Params: TemplateParams, SpecializedTemplate: VarTemplate, T: DI->getType(), TInfo: DI, S: SC,
4358 Args: CTAI.CanonicalConverted);
4359 Partial->setTemplateArgsAsWritten(TemplateArgs);
4360
4361 if (!PrevPartial)
4362 VarTemplate->AddPartialSpecialization(D: Partial, InsertPos);
4363 Specialization = Partial;
4364
4365 // If we are providing an explicit specialization of a member variable
4366 // template specialization, make a note of that.
4367 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4368 PrevPartial->setMemberSpecialization();
4369
4370 CheckTemplatePartialSpecialization(Partial);
4371 } else {
4372 // Create a new class template specialization declaration node for
4373 // this explicit specialization or friend declaration.
4374 Specialization = VarTemplateSpecializationDecl::Create(
4375 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc, IdLoc: TemplateNameLoc,
4376 SpecializedTemplate: VarTemplate, T: DI->getType(), TInfo: DI, S: SC, Args: CTAI.CanonicalConverted);
4377 Specialization->setTemplateArgsAsWritten(TemplateArgs);
4378
4379 if (!PrevDecl)
4380 VarTemplate->AddSpecialization(D: Specialization, InsertPos);
4381 }
4382
4383 // C++ [temp.expl.spec]p6:
4384 // If a template, a member template or the member of a class template is
4385 // explicitly specialized then that specialization shall be declared
4386 // before the first use of that specialization that would cause an implicit
4387 // instantiation to take place, in every translation unit in which such a
4388 // use occurs; no diagnostic is required.
4389 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4390 bool Okay = false;
4391 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4392 // Is there any previous explicit specialization declaration?
4393 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
4394 Okay = true;
4395 break;
4396 }
4397 }
4398
4399 if (!Okay) {
4400 SourceRange Range(TemplateNameLoc, RAngleLoc);
4401 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
4402 << Name << Range;
4403
4404 Diag(Loc: PrevDecl->getPointOfInstantiation(),
4405 DiagID: diag::note_instantiation_required_here)
4406 << (PrevDecl->getTemplateSpecializationKind() !=
4407 TSK_ImplicitInstantiation);
4408 return true;
4409 }
4410 }
4411
4412 Specialization->setLexicalDeclContext(CurContext);
4413
4414 // Add the specialization into its lexical context, so that it can
4415 // be seen when iterating through the list of declarations in that
4416 // context. However, specializations are not found by name lookup.
4417 CurContext->addDecl(D: Specialization);
4418
4419 // Note that this is an explicit specialization.
4420 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4421
4422 Previous.clear();
4423 if (PrevDecl)
4424 Previous.addDecl(D: PrevDecl);
4425 else if (Specialization->isStaticDataMember() &&
4426 Specialization->isOutOfLine())
4427 Specialization->setAccess(VarTemplate->getAccess());
4428
4429 return Specialization;
4430}
4431
4432namespace {
4433/// A partial specialization whose template arguments have matched
4434/// a given template-id.
4435struct PartialSpecMatchResult {
4436 VarTemplatePartialSpecializationDecl *Partial;
4437 TemplateArgumentList *Args;
4438};
4439
4440// HACK 2025-05-13: workaround std::format_kind since libstdc++ 15.1 (2025-04)
4441// See GH139067 / https://gcc.gnu.org/bugzilla/show_bug.cgi?id=120190
4442static bool IsLibstdcxxStdFormatKind(Preprocessor &PP, VarDecl *Var) {
4443 if (Var->getName() != "format_kind" ||
4444 !Var->getDeclContext()->isStdNamespace())
4445 return false;
4446
4447 // Checking old versions of libstdc++ is not needed because 15.1 is the first
4448 // release in which users can access std::format_kind.
4449 // We can use 20250520 as the final date, see the following commits.
4450 // GCC releases/gcc-15 branch:
4451 // https://gcc.gnu.org/g:fedf81ef7b98e5c9ac899b8641bb670746c51205
4452 // https://gcc.gnu.org/g:53680c1aa92d9f78e8255fbf696c0ed36f160650
4453 // GCC master branch:
4454 // https://gcc.gnu.org/g:9361966d80f625c5accc25cbb439f0278dd8b278
4455 // https://gcc.gnu.org/g:c65725eccbabf3b9b5965f27fff2d3b9f6c75930
4456 return PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2025'05'20);
4457}
4458} // end anonymous namespace
4459
4460DeclResult
4461Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4462 SourceLocation TemplateNameLoc,
4463 const TemplateArgumentListInfo &TemplateArgs) {
4464 assert(Template && "A variable template id without template?");
4465
4466 // Check that the template argument list is well-formed for this template.
4467 CheckTemplateArgumentInfo CTAI;
4468 if (CheckTemplateArgumentList(
4469 Template, TemplateLoc: TemplateNameLoc,
4470 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(TemplateArgs),
4471 /*DefaultArgs=*/{}, /*PartialTemplateArgs=*/false, CTAI,
4472 /*UpdateArgsWithConversions=*/true))
4473 return true;
4474
4475 // Produce a placeholder value if the specialization is dependent.
4476 if (Template->getDeclContext()->isDependentContext() ||
4477 TemplateSpecializationType::anyDependentTemplateArguments(
4478 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
4479 if (ParsingInitForAutoVars.empty())
4480 return DeclResult();
4481
4482 auto IsSameTemplateArg = [&](const TemplateArgument &Arg1,
4483 const TemplateArgument &Arg2) {
4484 return Context.isSameTemplateArgument(Arg1, Arg2);
4485 };
4486
4487 if (VarDecl *Var = Template->getTemplatedDecl();
4488 ParsingInitForAutoVars.count(Ptr: Var) &&
4489 // See comments on this function definition
4490 !IsLibstdcxxStdFormatKind(PP, Var) &&
4491 llvm::equal(
4492 LRange&: CTAI.CanonicalConverted,
4493 RRange: Template->getTemplateParameters()->getInjectedTemplateArgs(Context),
4494 P: IsSameTemplateArg)) {
4495 Diag(Loc: TemplateNameLoc,
4496 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4497 << diag::ParsingInitFor::VarTemplate << Var << Var->getType();
4498 return true;
4499 }
4500
4501 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4502 Template->getPartialSpecializations(PS&: PartialSpecs);
4503 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs)
4504 if (ParsingInitForAutoVars.count(Ptr: Partial) &&
4505 llvm::equal(LRange&: CTAI.CanonicalConverted,
4506 RRange: Partial->getTemplateArgs().asArray(),
4507 P: IsSameTemplateArg)) {
4508 Diag(Loc: TemplateNameLoc,
4509 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4510 << diag::ParsingInitFor::VarTemplatePartialSpec << Partial
4511 << Partial->getType();
4512 return true;
4513 }
4514
4515 return DeclResult();
4516 }
4517
4518 // Find the variable template specialization declaration that
4519 // corresponds to these arguments.
4520 void *InsertPos = nullptr;
4521 if (VarTemplateSpecializationDecl *Spec =
4522 Template->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos)) {
4523 checkSpecializationReachability(Loc: TemplateNameLoc, Spec);
4524 if (Spec->getType()->isUndeducedType()) {
4525 if (ParsingInitForAutoVars.count(Ptr: Spec))
4526 Diag(Loc: TemplateNameLoc,
4527 DiagID: diag::err_auto_variable_cannot_appear_in_own_initializer)
4528 << diag::ParsingInitFor::VarTemplateExplicitSpec << Spec
4529 << Spec->getType();
4530 else
4531 // We are substituting the initializer of this variable template
4532 // specialization.
4533 Diag(Loc: TemplateNameLoc, DiagID: diag::err_var_template_spec_type_depends_on_self)
4534 << Spec << Spec->getType();
4535
4536 return true;
4537 }
4538 // If we already have a variable template specialization, return it.
4539 return Spec;
4540 }
4541
4542 // This is the first time we have referenced this variable template
4543 // specialization. Create the canonical declaration and add it to
4544 // the set of specializations, based on the closest partial specialization
4545 // that it represents. That is,
4546 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4547 const TemplateArgumentList *PartialSpecArgs = nullptr;
4548 bool AmbiguousPartialSpec = false;
4549 typedef PartialSpecMatchResult MatchResult;
4550 SmallVector<MatchResult, 4> Matched;
4551 SourceLocation PointOfInstantiation = TemplateNameLoc;
4552 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4553 /*ForTakingAddress=*/false);
4554
4555 // 1. Attempt to find the closest partial specialization that this
4556 // specializes, if any.
4557 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4558 // Perhaps better after unification of DeduceTemplateArguments() and
4559 // getMoreSpecializedPartialSpecialization().
4560 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4561 Template->getPartialSpecializations(PS&: PartialSpecs);
4562
4563 for (VarTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4564 // C++ [temp.spec.partial.member]p2:
4565 // If the primary member template is explicitly specialized for a given
4566 // (implicit) specialization of the enclosing class template, the partial
4567 // specializations of the member template are ignored for this
4568 // specialization of the enclosing class template. If a partial
4569 // specialization of the member template is explicitly specialized for a
4570 // given (implicit) specialization of the enclosing class template, the
4571 // primary member template and its other partial specializations are still
4572 // considered for this specialization of the enclosing class template.
4573 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4574 !Partial->getMostRecentDecl()->isMemberSpecialization())
4575 continue;
4576
4577 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4578
4579 if (TemplateDeductionResult Result =
4580 DeduceTemplateArguments(Partial, TemplateArgs: CTAI.SugaredConverted, Info);
4581 Result != TemplateDeductionResult::Success) {
4582 // Store the failed-deduction information for use in diagnostics, later.
4583 // TODO: Actually use the failed-deduction info?
4584 FailedCandidates.addCandidate().set(
4585 Found: DeclAccessPair::make(D: Template, AS: AS_public), Spec: Partial,
4586 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
4587 (void)Result;
4588 } else {
4589 Matched.push_back(Elt: PartialSpecMatchResult());
4590 Matched.back().Partial = Partial;
4591 Matched.back().Args = Info.takeSugared();
4592 }
4593 }
4594
4595 if (Matched.size() >= 1) {
4596 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4597 if (Matched.size() == 1) {
4598 // -- If exactly one matching specialization is found, the
4599 // instantiation is generated from that specialization.
4600 // We don't need to do anything for this.
4601 } else {
4602 // -- If more than one matching specialization is found, the
4603 // partial order rules (14.5.4.2) are used to determine
4604 // whether one of the specializations is more specialized
4605 // than the others. If none of the specializations is more
4606 // specialized than all of the other matching
4607 // specializations, then the use of the variable template is
4608 // ambiguous and the program is ill-formed.
4609 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4610 PEnd = Matched.end();
4611 P != PEnd; ++P) {
4612 if (getMoreSpecializedPartialSpecialization(PS1: P->Partial, PS2: Best->Partial,
4613 Loc: PointOfInstantiation) ==
4614 P->Partial)
4615 Best = P;
4616 }
4617
4618 // Determine if the best partial specialization is more specialized than
4619 // the others.
4620 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4621 PEnd = Matched.end();
4622 P != PEnd; ++P) {
4623 if (P != Best && getMoreSpecializedPartialSpecialization(
4624 PS1: P->Partial, PS2: Best->Partial,
4625 Loc: PointOfInstantiation) != Best->Partial) {
4626 AmbiguousPartialSpec = true;
4627 break;
4628 }
4629 }
4630 }
4631
4632 // Instantiate using the best variable template partial specialization.
4633 InstantiationPattern = Best->Partial;
4634 PartialSpecArgs = Best->Args;
4635 } else {
4636 // -- If no match is found, the instantiation is generated
4637 // from the primary template.
4638 // InstantiationPattern = Template->getTemplatedDecl();
4639 }
4640
4641 // 2. Create the canonical declaration.
4642 // Note that we do not instantiate a definition until we see an odr-use
4643 // in DoMarkVarDeclReferenced().
4644 // FIXME: LateAttrs et al.?
4645 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4646 VarTemplate: Template, FromVar: InstantiationPattern, PartialSpecArgs, TemplateArgsInfo: TemplateArgs,
4647 Converted&: CTAI.CanonicalConverted, PointOfInstantiation: TemplateNameLoc /*, LateAttrs, StartingScope*/);
4648 if (!Decl)
4649 return true;
4650
4651 if (AmbiguousPartialSpec) {
4652 // Partial ordering did not produce a clear winner. Complain.
4653 Decl->setInvalidDecl();
4654 Diag(Loc: PointOfInstantiation, DiagID: diag::err_partial_spec_ordering_ambiguous)
4655 << Decl;
4656
4657 // Print the matching partial specializations.
4658 for (MatchResult P : Matched)
4659 Diag(Loc: P.Partial->getLocation(), DiagID: diag::note_partial_spec_match)
4660 << getTemplateArgumentBindingsText(Params: P.Partial->getTemplateParameters(),
4661 Args: *P.Args);
4662 return true;
4663 }
4664
4665 if (VarTemplatePartialSpecializationDecl *D =
4666 dyn_cast<VarTemplatePartialSpecializationDecl>(Val: InstantiationPattern))
4667 Decl->setInstantiationOf(PartialSpec: D, TemplateArgs: PartialSpecArgs);
4668
4669 checkSpecializationReachability(Loc: TemplateNameLoc, Spec: Decl);
4670
4671 assert(Decl && "No variable template specialization?");
4672 return Decl;
4673}
4674
4675ExprResult Sema::CheckVarTemplateId(
4676 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4677 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4678 const TemplateArgumentListInfo *TemplateArgs) {
4679
4680 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, TemplateNameLoc: NameInfo.getLoc(),
4681 TemplateArgs: *TemplateArgs);
4682 if (Decl.isInvalid())
4683 return ExprError();
4684
4685 if (!Decl.get())
4686 return ExprResult();
4687
4688 VarDecl *Var = cast<VarDecl>(Val: Decl.get());
4689 if (!Var->getTemplateSpecializationKind())
4690 Var->setTemplateSpecializationKind(TSK: TSK_ImplicitInstantiation,
4691 PointOfInstantiation: NameInfo.getLoc());
4692
4693 // Build an ordinary singleton decl ref.
4694 return BuildDeclarationNameExpr(SS, NameInfo, D: Var, FoundD, TemplateArgs);
4695}
4696
4697void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4698 SourceLocation Loc) {
4699 Diag(Loc, DiagID: diag::err_template_missing_args)
4700 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4701 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4702 NoteTemplateLocation(Decl: *TD, ParamRange: TD->getTemplateParameters()->getSourceRange());
4703 }
4704}
4705
4706void Sema::diagnoseMissingTemplateArguments(const CXXScopeSpec &SS,
4707 bool TemplateKeyword,
4708 TemplateDecl *TD,
4709 SourceLocation Loc) {
4710 TemplateName Name = Context.getQualifiedTemplateName(
4711 NNS: SS.getScopeRep(), TemplateKeyword, Template: TemplateName(TD));
4712 diagnoseMissingTemplateArguments(Name, Loc);
4713}
4714
4715ExprResult
4716Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
4717 SourceLocation TemplateKWLoc,
4718 const DeclarationNameInfo &ConceptNameInfo,
4719 NamedDecl *FoundDecl,
4720 ConceptDecl *NamedConcept,
4721 const TemplateArgumentListInfo *TemplateArgs) {
4722 assert(NamedConcept && "A concept template id without a template?");
4723
4724 if (NamedConcept->isInvalidDecl())
4725 return ExprError();
4726
4727 CheckTemplateArgumentInfo CTAI;
4728 if (CheckTemplateArgumentList(
4729 Template: NamedConcept, TemplateLoc: ConceptNameInfo.getLoc(),
4730 TemplateArgs&: const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
4731 /*DefaultArgs=*/{},
4732 /*PartialTemplateArgs=*/false, CTAI,
4733 /*UpdateArgsWithConversions=*/false))
4734 return ExprError();
4735
4736 DiagnoseUseOfDecl(D: NamedConcept, Locs: ConceptNameInfo.getLoc());
4737
4738 auto *CSD = ImplicitConceptSpecializationDecl::Create(
4739 C: Context, DC: NamedConcept->getDeclContext(), SL: NamedConcept->getLocation(),
4740 ConvertedArgs: CTAI.CanonicalConverted);
4741 ConstraintSatisfaction Satisfaction;
4742 bool AreArgsDependent =
4743 TemplateSpecializationType::anyDependentTemplateArguments(
4744 *TemplateArgs, Converted: CTAI.CanonicalConverted);
4745 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CTAI.CanonicalConverted,
4746 /*Final=*/false);
4747 LocalInstantiationScope Scope(*this);
4748
4749 EnterExpressionEvaluationContext EECtx{
4750 *this, ExpressionEvaluationContext::Unevaluated, CSD};
4751
4752 if (!AreArgsDependent &&
4753 CheckConstraintSatisfaction(
4754 Template: NamedConcept, AssociatedConstraints: AssociatedConstraint(NamedConcept->getConstraintExpr()),
4755 TemplateArgLists: MLTAL,
4756 TemplateIDRange: SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4757 TemplateArgs->getRAngleLoc()),
4758 Satisfaction))
4759 return ExprError();
4760 auto *CL = ConceptReference::Create(
4761 C: Context,
4762 NNS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4763 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4764 ArgsAsWritten: ASTTemplateArgumentListInfo::Create(C: Context, List: *TemplateArgs));
4765 return ConceptSpecializationExpr::Create(
4766 C: Context, ConceptRef: CL, SpecDecl: CSD, Satisfaction: AreArgsDependent ? nullptr : &Satisfaction);
4767}
4768
4769ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4770 SourceLocation TemplateKWLoc,
4771 LookupResult &R,
4772 bool RequiresADL,
4773 const TemplateArgumentListInfo *TemplateArgs) {
4774 // FIXME: Can we do any checking at this point? I guess we could check the
4775 // template arguments that we have against the template name, if the template
4776 // name refers to a single template. That's not a terribly common case,
4777 // though.
4778 // foo<int> could identify a single function unambiguously
4779 // This approach does NOT work, since f<int>(1);
4780 // gets resolved prior to resorting to overload resolution
4781 // i.e., template<class T> void f(double);
4782 // vs template<class T, class U> void f(U);
4783
4784 // These should be filtered out by our callers.
4785 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
4786
4787 // Non-function templates require a template argument list.
4788 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4789 if (!TemplateArgs && !isa<FunctionTemplateDecl>(Val: TD)) {
4790 diagnoseMissingTemplateArguments(
4791 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD, Loc: R.getNameLoc());
4792 return ExprError();
4793 }
4794 }
4795 bool KnownDependent = false;
4796 // In C++1y, check variable template ids.
4797 if (R.getAsSingle<VarTemplateDecl>()) {
4798 ExprResult Res = CheckVarTemplateId(
4799 SS, NameInfo: R.getLookupNameInfo(), Template: R.getAsSingle<VarTemplateDecl>(),
4800 FoundD: R.getRepresentativeDecl(), TemplateLoc: TemplateKWLoc, TemplateArgs);
4801 if (Res.isInvalid() || Res.isUsable())
4802 return Res;
4803 // Result is dependent. Carry on to build an UnresolvedLookupExpr.
4804 KnownDependent = true;
4805 }
4806
4807 if (R.getAsSingle<ConceptDecl>()) {
4808 return CheckConceptTemplateId(SS, TemplateKWLoc, ConceptNameInfo: R.getLookupNameInfo(),
4809 FoundDecl: R.getRepresentativeDecl(),
4810 NamedConcept: R.getAsSingle<ConceptDecl>(), TemplateArgs);
4811 }
4812
4813 // We don't want lookup warnings at this point.
4814 R.suppressDiagnostics();
4815
4816 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
4817 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
4818 TemplateKWLoc, NameInfo: R.getLookupNameInfo(), RequiresADL, Args: TemplateArgs,
4819 Begin: R.begin(), End: R.end(), KnownDependent,
4820 /*KnownInstantiationDependent=*/false);
4821
4822 // Model the templates with UnresolvedTemplateTy. The expression should then
4823 // either be transformed in an instantiation or be diagnosed in
4824 // CheckPlaceholderExpr.
4825 if (ULE->getType() == Context.OverloadTy && R.isSingleResult() &&
4826 !R.getFoundDecl()->getAsFunction())
4827 ULE->setType(Context.UnresolvedTemplateTy);
4828
4829 return ULE;
4830}
4831
4832ExprResult Sema::BuildQualifiedTemplateIdExpr(
4833 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4834 const DeclarationNameInfo &NameInfo,
4835 const TemplateArgumentListInfo *TemplateArgs, bool IsAddressOfOperand) {
4836 assert(TemplateArgs || TemplateKWLoc.isValid());
4837
4838 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4839 if (LookupTemplateName(Found&: R, /*S=*/nullptr, SS, /*ObjectType=*/QualType(),
4840 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc))
4841 return ExprError();
4842
4843 if (R.isAmbiguous())
4844 return ExprError();
4845
4846 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
4847 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4848
4849 if (R.empty()) {
4850 DeclContext *DC = computeDeclContext(SS);
4851 Diag(Loc: NameInfo.getLoc(), DiagID: diag::err_no_member)
4852 << NameInfo.getName() << DC << SS.getRange();
4853 return ExprError();
4854 }
4855
4856 // If necessary, build an implicit class member access.
4857 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
4858 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
4859 /*S=*/nullptr);
4860
4861 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL=*/RequiresADL: false, TemplateArgs);
4862}
4863
4864TemplateNameKind Sema::ActOnTemplateName(Scope *S,
4865 CXXScopeSpec &SS,
4866 SourceLocation TemplateKWLoc,
4867 const UnqualifiedId &Name,
4868 ParsedType ObjectType,
4869 bool EnteringContext,
4870 TemplateTy &Result,
4871 bool AllowInjectedClassName) {
4872 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4873 Diag(Loc: TemplateKWLoc,
4874 DiagID: getLangOpts().CPlusPlus11 ?
4875 diag::warn_cxx98_compat_template_outside_of_template :
4876 diag::ext_template_outside_of_template)
4877 << FixItHint::CreateRemoval(RemoveRange: TemplateKWLoc);
4878
4879 if (SS.isInvalid())
4880 return TNK_Non_template;
4881
4882 // Figure out where isTemplateName is going to look.
4883 DeclContext *LookupCtx = nullptr;
4884 if (SS.isNotEmpty())
4885 LookupCtx = computeDeclContext(SS, EnteringContext);
4886 else if (ObjectType)
4887 LookupCtx = computeDeclContext(T: GetTypeFromParser(Ty: ObjectType));
4888
4889 // C++0x [temp.names]p5:
4890 // If a name prefixed by the keyword template is not the name of
4891 // a template, the program is ill-formed. [Note: the keyword
4892 // template may not be applied to non-template members of class
4893 // templates. -end note ] [ Note: as is the case with the
4894 // typename prefix, the template prefix is allowed in cases
4895 // where it is not strictly necessary; i.e., when the
4896 // nested-name-specifier or the expression on the left of the ->
4897 // or . is not dependent on a template-parameter, or the use
4898 // does not appear in the scope of a template. -end note]
4899 //
4900 // Note: C++03 was more strict here, because it banned the use of
4901 // the "template" keyword prior to a template-name that was not a
4902 // dependent name. C++ DR468 relaxed this requirement (the
4903 // "template" keyword is now permitted). We follow the C++0x
4904 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4905 bool MemberOfUnknownSpecialization;
4906 TemplateNameKind TNK = isTemplateName(S, SS, hasTemplateKeyword: TemplateKWLoc.isValid(), Name,
4907 ObjectTypePtr: ObjectType, EnteringContext, TemplateResult&: Result,
4908 MemberOfUnknownSpecialization);
4909 if (TNK != TNK_Non_template) {
4910 // We resolved this to a (non-dependent) template name. Return it.
4911 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
4912 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
4913 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4914 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4915 // C++14 [class.qual]p2:
4916 // In a lookup in which function names are not ignored and the
4917 // nested-name-specifier nominates a class C, if the name specified
4918 // [...] is the injected-class-name of C, [...] the name is instead
4919 // considered to name the constructor
4920 //
4921 // We don't get here if naming the constructor would be valid, so we
4922 // just reject immediately and recover by treating the
4923 // injected-class-name as naming the template.
4924 Diag(Loc: Name.getBeginLoc(),
4925 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
4926 << Name.Identifier
4927 << 0 /*injected-class-name used as template name*/
4928 << TemplateKWLoc.isValid();
4929 }
4930 return TNK;
4931 }
4932
4933 if (!MemberOfUnknownSpecialization) {
4934 // Didn't find a template name, and the lookup wasn't dependent.
4935 // Do the lookup again to determine if this is a "nothing found" case or
4936 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4937 // need to do this.
4938 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4939 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4940 LookupOrdinaryName);
4941 // Tell LookupTemplateName that we require a template so that it diagnoses
4942 // cases where it finds a non-template.
4943 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
4944 ? RequiredTemplateKind(TemplateKWLoc)
4945 : TemplateNameIsRequired;
4946 if (!LookupTemplateName(Found&: R, S, SS, ObjectType: ObjectType.get(), EnteringContext, RequiredTemplate: RTK,
4947 /*ATK=*/nullptr, /*AllowTypoCorrection=*/false) &&
4948 !R.isAmbiguous()) {
4949 if (LookupCtx)
4950 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_no_member)
4951 << DNI.getName() << LookupCtx << SS.getRange();
4952 else
4953 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_undeclared_use)
4954 << DNI.getName() << SS.getRange();
4955 }
4956 return TNK_Non_template;
4957 }
4958
4959 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4960
4961 switch (Name.getKind()) {
4962 case UnqualifiedIdKind::IK_Identifier:
4963 Result = TemplateTy::make(P: Context.getDependentTemplateName(
4964 Name: {Qualifier, Name.Identifier, TemplateKWLoc.isValid()}));
4965 return TNK_Dependent_template_name;
4966
4967 case UnqualifiedIdKind::IK_OperatorFunctionId:
4968 Result = TemplateTy::make(P: Context.getDependentTemplateName(
4969 Name: {Qualifier, Name.OperatorFunctionId.Operator,
4970 TemplateKWLoc.isValid()}));
4971 return TNK_Function_template;
4972
4973 case UnqualifiedIdKind::IK_LiteralOperatorId:
4974 // This is a kind of template name, but can never occur in a dependent
4975 // scope (literal operators can only be declared at namespace scope).
4976 break;
4977
4978 default:
4979 break;
4980 }
4981
4982 // This name cannot possibly name a dependent template. Diagnose this now
4983 // rather than building a dependent template name that can never be valid.
4984 Diag(Loc: Name.getBeginLoc(),
4985 DiagID: diag::err_template_kw_refers_to_dependent_non_template)
4986 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
4987 << TemplateKWLoc.isValid() << TemplateKWLoc;
4988 return TNK_Non_template;
4989}
4990
4991bool Sema::CheckTemplateTypeArgument(
4992 TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
4993 SmallVectorImpl<TemplateArgument> &SugaredConverted,
4994 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
4995 const TemplateArgument &Arg = AL.getArgument();
4996 QualType ArgType;
4997 TypeSourceInfo *TSI = nullptr;
4998
4999 // Check template type parameter.
5000 switch(Arg.getKind()) {
5001 case TemplateArgument::Type:
5002 // C++ [temp.arg.type]p1:
5003 // A template-argument for a template-parameter which is a
5004 // type shall be a type-id.
5005 ArgType = Arg.getAsType();
5006 TSI = AL.getTypeSourceInfo();
5007 break;
5008 case TemplateArgument::Template:
5009 case TemplateArgument::TemplateExpansion: {
5010 // We have a template type parameter but the template argument
5011 // is a template without any arguments.
5012 SourceRange SR = AL.getSourceRange();
5013 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
5014 diagnoseMissingTemplateArguments(Name, Loc: SR.getEnd());
5015 return true;
5016 }
5017 case TemplateArgument::Expression: {
5018 // We have a template type parameter but the template argument is an
5019 // expression; see if maybe it is missing the "typename" keyword.
5020 CXXScopeSpec SS;
5021 DeclarationNameInfo NameInfo;
5022
5023 if (DependentScopeDeclRefExpr *ArgExpr =
5024 dyn_cast<DependentScopeDeclRefExpr>(Val: Arg.getAsExpr())) {
5025 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5026 NameInfo = ArgExpr->getNameInfo();
5027 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5028 dyn_cast<CXXDependentScopeMemberExpr>(Val: Arg.getAsExpr())) {
5029 if (ArgExpr->isImplicitAccess()) {
5030 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5031 NameInfo = ArgExpr->getMemberNameInfo();
5032 }
5033 }
5034
5035 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5036 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5037 LookupParsedName(R&: Result, S: CurScope, SS: &SS, /*ObjectType=*/QualType());
5038
5039 if (Result.getAsSingle<TypeDecl>() ||
5040 Result.wasNotFoundInCurrentInstantiation()) {
5041 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5042 // Suggest that the user add 'typename' before the NNS.
5043 SourceLocation Loc = AL.getSourceRange().getBegin();
5044 Diag(Loc, DiagID: getLangOpts().MSVCCompat
5045 ? diag::ext_ms_template_type_arg_missing_typename
5046 : diag::err_template_arg_must_be_type_suggest)
5047 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
5048 NoteTemplateParameterLocation(Decl: *Param);
5049
5050 // Recover by synthesizing a type using the location information that we
5051 // already have.
5052 ArgType = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::None,
5053 NNS: SS.getScopeRep(), Name: II);
5054 TypeLocBuilder TLB;
5055 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: ArgType);
5056 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5057 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5058 TL.setNameLoc(NameInfo.getLoc());
5059 TSI = TLB.getTypeSourceInfo(Context, T: ArgType);
5060
5061 // Overwrite our input TemplateArgumentLoc so that we can recover
5062 // properly.
5063 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5064 TemplateArgumentLocInfo(TSI));
5065
5066 break;
5067 }
5068 }
5069 // fallthrough
5070 [[fallthrough]];
5071 }
5072 default: {
5073 // We allow instantiating a template with template argument packs when
5074 // building deduction guides.
5075 if (Arg.getKind() == TemplateArgument::Pack &&
5076 CodeSynthesisContexts.back().Kind ==
5077 Sema::CodeSynthesisContext::BuildingDeductionGuides) {
5078 SugaredConverted.push_back(Elt: Arg);
5079 CanonicalConverted.push_back(Elt: Arg);
5080 return false;
5081 }
5082 // We have a template type parameter but the template argument
5083 // is not a type.
5084 SourceRange SR = AL.getSourceRange();
5085 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_type) << SR;
5086 NoteTemplateParameterLocation(Decl: *Param);
5087
5088 return true;
5089 }
5090 }
5091
5092 if (CheckTemplateArgument(Arg: TSI))
5093 return true;
5094
5095 // Objective-C ARC:
5096 // If an explicitly-specified template argument type is a lifetime type
5097 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5098 if (getLangOpts().ObjCAutoRefCount &&
5099 ArgType->isObjCLifetimeType() &&
5100 !ArgType.getObjCLifetime()) {
5101 Qualifiers Qs;
5102 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5103 ArgType = Context.getQualifiedType(T: ArgType, Qs);
5104 }
5105
5106 SugaredConverted.push_back(Elt: TemplateArgument(ArgType));
5107 CanonicalConverted.push_back(
5108 Elt: TemplateArgument(Context.getCanonicalType(T: ArgType)));
5109 return false;
5110}
5111
5112/// Substitute template arguments into the default template argument for
5113/// the given template type parameter.
5114///
5115/// \param SemaRef the semantic analysis object for which we are performing
5116/// the substitution.
5117///
5118/// \param Template the template that we are synthesizing template arguments
5119/// for.
5120///
5121/// \param TemplateLoc the location of the template name that started the
5122/// template-id we are checking.
5123///
5124/// \param RAngleLoc the location of the right angle bracket ('>') that
5125/// terminates the template-id.
5126///
5127/// \param Param the template template parameter whose default we are
5128/// substituting into.
5129///
5130/// \param Converted the list of template arguments provided for template
5131/// parameters that precede \p Param in the template parameter list.
5132///
5133/// \param Output the resulting substituted template argument.
5134///
5135/// \returns true if an error occurred.
5136static bool SubstDefaultTemplateArgument(
5137 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5138 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5139 ArrayRef<TemplateArgument> SugaredConverted,
5140 ArrayRef<TemplateArgument> CanonicalConverted,
5141 TemplateArgumentLoc &Output) {
5142 Output = Param->getDefaultArgument();
5143
5144 // If the argument type is dependent, instantiate it now based
5145 // on the previously-computed template arguments.
5146 if (Output.getArgument().isInstantiationDependent()) {
5147 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5148 SugaredConverted,
5149 SourceRange(TemplateLoc, RAngleLoc));
5150 if (Inst.isInvalid())
5151 return true;
5152
5153 // Only substitute for the innermost template argument list.
5154 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5155 /*Final=*/true);
5156 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5157 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5158
5159 bool ForLambdaCallOperator = false;
5160 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Val: Template->getDeclContext()))
5161 ForLambdaCallOperator = Rec->isLambda();
5162 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5163 !ForLambdaCallOperator);
5164
5165 if (SemaRef.SubstTemplateArgument(Input: Output, TemplateArgs: TemplateArgLists, Output,
5166 Loc: Param->getDefaultArgumentLoc(),
5167 Entity: Param->getDeclName()))
5168 return true;
5169 }
5170
5171 return false;
5172}
5173
5174/// Substitute template arguments into the default template argument for
5175/// the given non-type template parameter.
5176///
5177/// \param SemaRef the semantic analysis object for which we are performing
5178/// the substitution.
5179///
5180/// \param Template the template that we are synthesizing template arguments
5181/// for.
5182///
5183/// \param TemplateLoc the location of the template name that started the
5184/// template-id we are checking.
5185///
5186/// \param RAngleLoc the location of the right angle bracket ('>') that
5187/// terminates the template-id.
5188///
5189/// \param Param the non-type template parameter whose default we are
5190/// substituting into.
5191///
5192/// \param Converted the list of template arguments provided for template
5193/// parameters that precede \p Param in the template parameter list.
5194///
5195/// \returns the substituted template argument, or NULL if an error occurred.
5196static bool SubstDefaultTemplateArgument(
5197 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5198 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5199 ArrayRef<TemplateArgument> SugaredConverted,
5200 ArrayRef<TemplateArgument> CanonicalConverted,
5201 TemplateArgumentLoc &Output) {
5202 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5203 SugaredConverted,
5204 SourceRange(TemplateLoc, RAngleLoc));
5205 if (Inst.isInvalid())
5206 return true;
5207
5208 // Only substitute for the innermost template argument list.
5209 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5210 /*Final=*/true);
5211 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5212 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5213
5214 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5215 EnterExpressionEvaluationContext ConstantEvaluated(
5216 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5217 return SemaRef.SubstTemplateArgument(Input: Param->getDefaultArgument(),
5218 TemplateArgs: TemplateArgLists, Output);
5219}
5220
5221/// Substitute template arguments into the default template argument for
5222/// the given template template parameter.
5223///
5224/// \param SemaRef the semantic analysis object for which we are performing
5225/// the substitution.
5226///
5227/// \param Template the template that we are synthesizing template arguments
5228/// for.
5229///
5230/// \param TemplateLoc the location of the template name that started the
5231/// template-id we are checking.
5232///
5233/// \param RAngleLoc the location of the right angle bracket ('>') that
5234/// terminates the template-id.
5235///
5236/// \param Param the template template parameter whose default we are
5237/// substituting into.
5238///
5239/// \param Converted the list of template arguments provided for template
5240/// parameters that precede \p Param in the template parameter list.
5241///
5242/// \param QualifierLoc Will be set to the nested-name-specifier (with
5243/// source-location information) that precedes the template name.
5244///
5245/// \returns the substituted template argument, or NULL if an error occurred.
5246static TemplateName SubstDefaultTemplateArgument(
5247 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5248 SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
5249 ArrayRef<TemplateArgument> SugaredConverted,
5250 ArrayRef<TemplateArgument> CanonicalConverted,
5251 NestedNameSpecifierLoc &QualifierLoc) {
5252 Sema::InstantiatingTemplate Inst(
5253 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
5254 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
5255 if (Inst.isInvalid())
5256 return TemplateName();
5257
5258 // Only substitute for the innermost template argument list.
5259 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5260 /*Final=*/true);
5261 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5262 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5263
5264 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5265 // Substitute into the nested-name-specifier first,
5266 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
5267 if (QualifierLoc) {
5268 QualifierLoc =
5269 SemaRef.SubstNestedNameSpecifierLoc(NNS: QualifierLoc, TemplateArgs: TemplateArgLists);
5270 if (!QualifierLoc)
5271 return TemplateName();
5272 }
5273
5274 return SemaRef.SubstTemplateName(
5275 QualifierLoc,
5276 Name: Param->getDefaultArgument().getArgument().getAsTemplate(),
5277 Loc: Param->getDefaultArgument().getTemplateNameLoc(),
5278 TemplateArgs: TemplateArgLists);
5279}
5280
5281TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
5282 TemplateDecl *Template, SourceLocation TemplateLoc,
5283 SourceLocation RAngleLoc, Decl *Param,
5284 ArrayRef<TemplateArgument> SugaredConverted,
5285 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
5286 HasDefaultArg = false;
5287
5288 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
5289 if (!hasReachableDefaultArgument(D: TypeParm))
5290 return TemplateArgumentLoc();
5291
5292 HasDefaultArg = true;
5293 TemplateArgumentLoc Output;
5294 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc, RAngleLoc,
5295 Param: TypeParm, SugaredConverted,
5296 CanonicalConverted, Output))
5297 return TemplateArgumentLoc();
5298 return Output;
5299 }
5300
5301 if (NonTypeTemplateParmDecl *NonTypeParm
5302 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5303 if (!hasReachableDefaultArgument(D: NonTypeParm))
5304 return TemplateArgumentLoc();
5305
5306 HasDefaultArg = true;
5307 TemplateArgumentLoc Output;
5308 if (SubstDefaultTemplateArgument(SemaRef&: *this, Template, TemplateLoc, RAngleLoc,
5309 Param: NonTypeParm, SugaredConverted,
5310 CanonicalConverted, Output))
5311 return TemplateArgumentLoc();
5312 return Output;
5313 }
5314
5315 TemplateTemplateParmDecl *TempTempParm
5316 = cast<TemplateTemplateParmDecl>(Val: Param);
5317 if (!hasReachableDefaultArgument(D: TempTempParm))
5318 return TemplateArgumentLoc();
5319
5320 HasDefaultArg = true;
5321 NestedNameSpecifierLoc QualifierLoc;
5322 TemplateName TName = SubstDefaultTemplateArgument(
5323 SemaRef&: *this, Template, TemplateLoc, RAngleLoc, Param: TempTempParm, SugaredConverted,
5324 CanonicalConverted, QualifierLoc);
5325 if (TName.isNull())
5326 return TemplateArgumentLoc();
5327
5328 return TemplateArgumentLoc(
5329 Context, TemplateArgument(TName),
5330 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
5331 TempTempParm->getDefaultArgument().getTemplateNameLoc());
5332}
5333
5334/// Convert a template-argument that we parsed as a type into a template, if
5335/// possible. C++ permits injected-class-names to perform dual service as
5336/// template template arguments and as template type arguments.
5337static TemplateArgumentLoc
5338convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5339 // Extract and step over any surrounding nested-name-specifier.
5340 NestedNameSpecifierLoc QualLoc;
5341 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
5342 if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
5343 return TemplateArgumentLoc();
5344
5345 QualLoc = ETLoc.getQualifierLoc();
5346 TLoc = ETLoc.getNamedTypeLoc();
5347 }
5348 // If this type was written as an injected-class-name, it can be used as a
5349 // template template argument.
5350 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
5351 return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
5352 QualLoc, InjLoc.getNameLoc());
5353
5354 // If this type was written as an injected-class-name, it may have been
5355 // converted to a RecordType during instantiation. If the RecordType is
5356 // *not* wrapped in a TemplateSpecializationType and denotes a class
5357 // template specialization, it must have come from an injected-class-name.
5358 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5359 if (auto *CTSD =
5360 dyn_cast<ClassTemplateSpecializationDecl>(Val: RecLoc.getDecl()))
5361 return TemplateArgumentLoc(Context,
5362 TemplateName(CTSD->getSpecializedTemplate()),
5363 QualLoc, RecLoc.getNameLoc());
5364
5365 return TemplateArgumentLoc();
5366}
5367
5368bool Sema::CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &ArgLoc,
5369 NamedDecl *Template,
5370 SourceLocation TemplateLoc,
5371 SourceLocation RAngleLoc,
5372 unsigned ArgumentPackIndex,
5373 CheckTemplateArgumentInfo &CTAI,
5374 CheckTemplateArgumentKind CTAK) {
5375 // Check template type parameters.
5376 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param))
5377 return CheckTemplateTypeArgument(Param: TTP, AL&: ArgLoc, SugaredConverted&: CTAI.SugaredConverted,
5378 CanonicalConverted&: CTAI.CanonicalConverted);
5379
5380 const TemplateArgument &Arg = ArgLoc.getArgument();
5381 // Check non-type template parameters.
5382 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
5383 // Do substitution on the type of the non-type template parameter
5384 // with the template arguments we've seen thus far. But if the
5385 // template has a dependent context then we cannot substitute yet.
5386 QualType NTTPType = NTTP->getType();
5387 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5388 NTTPType = NTTP->getExpansionType(I: ArgumentPackIndex);
5389
5390 if (NTTPType->isInstantiationDependentType() &&
5391 !isa<TemplateTemplateParmDecl>(Val: Template) &&
5392 !Template->getDeclContext()->isDependentContext()) {
5393 // Do substitution on the type of the non-type template parameter.
5394 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
5395 CTAI.SugaredConverted,
5396 SourceRange(TemplateLoc, RAngleLoc));
5397 if (Inst.isInvalid())
5398 return true;
5399
5400 MultiLevelTemplateArgumentList MLTAL(Template, CTAI.SugaredConverted,
5401 /*Final=*/true);
5402 // If the parameter is a pack expansion, expand this slice of the pack.
5403 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5404 Sema::ArgPackSubstIndexRAII SubstIndex(*this, ArgumentPackIndex);
5405 NTTPType = SubstType(T: PET->getPattern(), TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5406 Entity: NTTP->getDeclName());
5407 } else {
5408 NTTPType = SubstType(T: NTTPType, TemplateArgs: MLTAL, Loc: NTTP->getLocation(),
5409 Entity: NTTP->getDeclName());
5410 }
5411
5412 // If that worked, check the non-type template parameter type
5413 // for validity.
5414 if (!NTTPType.isNull())
5415 NTTPType = CheckNonTypeTemplateParameterType(T: NTTPType,
5416 Loc: NTTP->getLocation());
5417 if (NTTPType.isNull())
5418 return true;
5419 }
5420
5421 auto checkExpr = [&](Expr *E) -> Expr * {
5422 TemplateArgument SugaredResult, CanonicalResult;
5423 unsigned CurSFINAEErrors = NumSFINAEErrors;
5424 ExprResult Res = CheckTemplateArgument(
5425 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E, SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5426 /*StrictCheck=*/CTAI.MatchingTTP || CTAI.PartialOrdering, CTAK);
5427 // If the current template argument causes an error, give up now.
5428 if (Res.isInvalid() || CurSFINAEErrors < NumSFINAEErrors)
5429 return nullptr;
5430 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5431 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5432 return Res.get();
5433 };
5434
5435 switch (Arg.getKind()) {
5436 case TemplateArgument::Null:
5437 llvm_unreachable("Should never see a NULL template argument here");
5438
5439 case TemplateArgument::Expression: {
5440 Expr *E = Arg.getAsExpr();
5441 Expr *R = checkExpr(E);
5442 if (!R)
5443 return true;
5444 // If the resulting expression is new, then use it in place of the
5445 // old expression in the template argument.
5446 if (R != E) {
5447 TemplateArgument TA(R, /*IsCanonical=*/false);
5448 ArgLoc = TemplateArgumentLoc(TA, R);
5449 }
5450 break;
5451 }
5452
5453 // As for the converted NTTP kinds, they still might need another
5454 // conversion, as the new corresponding parameter might be different.
5455 // Ideally, we would always perform substitution starting with sugared types
5456 // and never need these, as we would still have expressions. Since these are
5457 // needed so rarely, it's probably a better tradeoff to just convert them
5458 // back to expressions.
5459 case TemplateArgument::Integral:
5460 case TemplateArgument::Declaration:
5461 case TemplateArgument::NullPtr:
5462 case TemplateArgument::StructuralValue: {
5463 // FIXME: StructuralValue is untested here.
5464 ExprResult R =
5465 BuildExpressionFromNonTypeTemplateArgument(Arg, Loc: SourceLocation());
5466 assert(R.isUsable());
5467 if (!checkExpr(R.get()))
5468 return true;
5469 break;
5470 }
5471
5472 case TemplateArgument::Template:
5473 case TemplateArgument::TemplateExpansion:
5474 // We were given a template template argument. It may not be ill-formed;
5475 // see below.
5476 if (DependentTemplateName *DTN = Arg.getAsTemplateOrTemplatePattern()
5477 .getAsDependentTemplateName()) {
5478 // We have a template argument such as \c T::template X, which we
5479 // parsed as a template template argument. However, since we now
5480 // know that we need a non-type template argument, convert this
5481 // template name into an expression.
5482
5483 DeclarationNameInfo NameInfo(DTN->getName().getIdentifier(),
5484 ArgLoc.getTemplateNameLoc());
5485
5486 CXXScopeSpec SS;
5487 SS.Adopt(Other: ArgLoc.getTemplateQualifierLoc());
5488 // FIXME: the template-template arg was a DependentTemplateName,
5489 // so it was provided with a template keyword. However, its source
5490 // location is not stored in the template argument structure.
5491 SourceLocation TemplateKWLoc;
5492 ExprResult E = DependentScopeDeclRefExpr::Create(
5493 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5494 TemplateArgs: nullptr);
5495
5496 // If we parsed the template argument as a pack expansion, create a
5497 // pack expansion expression.
5498 if (Arg.getKind() == TemplateArgument::TemplateExpansion) {
5499 E = ActOnPackExpansion(Pattern: E.get(), EllipsisLoc: ArgLoc.getTemplateEllipsisLoc());
5500 if (E.isInvalid())
5501 return true;
5502 }
5503
5504 TemplateArgument SugaredResult, CanonicalResult;
5505 E = CheckTemplateArgument(
5506 Param: NTTP, InstantiatedParamType: NTTPType, Arg: E.get(), SugaredConverted&: SugaredResult, CanonicalConverted&: CanonicalResult,
5507 /*StrictCheck=*/CTAI.PartialOrdering, CTAK: CTAK_Specified);
5508 if (E.isInvalid())
5509 return true;
5510
5511 CTAI.SugaredConverted.push_back(Elt: SugaredResult);
5512 CTAI.CanonicalConverted.push_back(Elt: CanonicalResult);
5513 break;
5514 }
5515
5516 // We have a template argument that actually does refer to a class
5517 // template, alias template, or template template parameter, and
5518 // therefore cannot be a non-type template argument.
5519 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_expr)
5520 << ArgLoc.getSourceRange();
5521 NoteTemplateParameterLocation(Decl: *Param);
5522
5523 return true;
5524
5525 case TemplateArgument::Type: {
5526 // We have a non-type template parameter but the template
5527 // argument is a type.
5528
5529 // C++ [temp.arg]p2:
5530 // In a template-argument, an ambiguity between a type-id and
5531 // an expression is resolved to a type-id, regardless of the
5532 // form of the corresponding template-parameter.
5533 //
5534 // We warn specifically about this case, since it can be rather
5535 // confusing for users.
5536 QualType T = Arg.getAsType();
5537 SourceRange SR = ArgLoc.getSourceRange();
5538 if (T->isFunctionType())
5539 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_nontype_ambig) << SR << T;
5540 else
5541 Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_must_be_expr) << SR;
5542 NoteTemplateParameterLocation(Decl: *Param);
5543 return true;
5544 }
5545
5546 case TemplateArgument::Pack:
5547 llvm_unreachable("Caller must expand template argument packs");
5548 }
5549
5550 return false;
5551 }
5552
5553
5554 // Check template template parameters.
5555 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Val: Param);
5556
5557 TemplateParameterList *Params = TempParm->getTemplateParameters();
5558 if (TempParm->isExpandedParameterPack())
5559 Params = TempParm->getExpansionTemplateParameters(I: ArgumentPackIndex);
5560
5561 // Substitute into the template parameter list of the template
5562 // template parameter, since previously-supplied template arguments
5563 // may appear within the template template parameter.
5564 //
5565 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5566 {
5567 // Set up a template instantiation context.
5568 LocalInstantiationScope Scope(*this);
5569 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
5570 CTAI.SugaredConverted,
5571 SourceRange(TemplateLoc, RAngleLoc));
5572 if (Inst.isInvalid())
5573 return true;
5574
5575 Params = SubstTemplateParams(
5576 Params, Owner: CurContext,
5577 TemplateArgs: MultiLevelTemplateArgumentList(Template, CTAI.SugaredConverted,
5578 /*Final=*/true),
5579 /*EvaluateConstraints=*/false);
5580 if (!Params)
5581 return true;
5582 }
5583
5584 // C++1z [temp.local]p1: (DR1004)
5585 // When [the injected-class-name] is used [...] as a template-argument for
5586 // a template template-parameter [...] it refers to the class template
5587 // itself.
5588 if (Arg.getKind() == TemplateArgument::Type) {
5589 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5590 Context, TLoc: ArgLoc.getTypeSourceInfo()->getTypeLoc());
5591 if (!ConvertedArg.getArgument().isNull())
5592 ArgLoc = ConvertedArg;
5593 }
5594
5595 switch (Arg.getKind()) {
5596 case TemplateArgument::Null:
5597 llvm_unreachable("Should never see a NULL template argument here");
5598
5599 case TemplateArgument::Template:
5600 case TemplateArgument::TemplateExpansion:
5601 if (CheckTemplateTemplateArgument(Param: TempParm, Params, Arg&: ArgLoc,
5602 PartialOrdering: CTAI.PartialOrdering,
5603 StrictPackMatch: &CTAI.StrictPackMatch))
5604 return true;
5605
5606 CTAI.SugaredConverted.push_back(Elt: Arg);
5607 CTAI.CanonicalConverted.push_back(
5608 Elt: Context.getCanonicalTemplateArgument(Arg));
5609 break;
5610
5611 case TemplateArgument::Expression:
5612 case TemplateArgument::Type:
5613 // We have a template template parameter but the template
5614 // argument does not refer to a template.
5615 Diag(Loc: ArgLoc.getLocation(), DiagID: diag::err_template_arg_must_be_template)
5616 << getLangOpts().CPlusPlus11;
5617 return true;
5618
5619 case TemplateArgument::Declaration:
5620 case TemplateArgument::Integral:
5621 case TemplateArgument::StructuralValue:
5622 case TemplateArgument::NullPtr:
5623 llvm_unreachable("non-type argument with template template parameter");
5624
5625 case TemplateArgument::Pack:
5626 llvm_unreachable("Caller must expand template argument packs");
5627 }
5628
5629 return false;
5630}
5631
5632/// Diagnose a missing template argument.
5633template<typename TemplateParmDecl>
5634static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5635 TemplateDecl *TD,
5636 const TemplateParmDecl *D,
5637 TemplateArgumentListInfo &Args) {
5638 // Dig out the most recent declaration of the template parameter; there may be
5639 // declarations of the template that are more recent than TD.
5640 D = cast<TemplateParmDecl>(cast<TemplateDecl>(Val: TD->getMostRecentDecl())
5641 ->getTemplateParameters()
5642 ->getParam(D->getIndex()));
5643
5644 // If there's a default argument that's not reachable, diagnose that we're
5645 // missing a module import.
5646 llvm::SmallVector<Module*, 8> Modules;
5647 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, Modules: &Modules)) {
5648 S.diagnoseMissingImport(Loc, cast<NamedDecl>(Val: TD),
5649 D->getDefaultArgumentLoc(), Modules,
5650 Sema::MissingImportKind::DefaultArgument,
5651 /*Recover*/true);
5652 return true;
5653 }
5654
5655 // FIXME: If there's a more recent default argument that *is* visible,
5656 // diagnose that it was declared too late.
5657
5658 TemplateParameterList *Params = TD->getTemplateParameters();
5659
5660 S.Diag(Loc, DiagID: diag::err_template_arg_list_different_arity)
5661 << /*not enough args*/0
5662 << (int)S.getTemplateNameKindForDiagnostics(Name: TemplateName(TD))
5663 << TD;
5664 S.NoteTemplateLocation(Decl: *TD, ParamRange: Params->getSourceRange());
5665 return true;
5666}
5667
5668/// Check that the given template argument list is well-formed
5669/// for specializing the given template.
5670bool Sema::CheckTemplateArgumentList(
5671 TemplateDecl *Template, SourceLocation TemplateLoc,
5672 TemplateArgumentListInfo &TemplateArgs, const DefaultArguments &DefaultArgs,
5673 bool PartialTemplateArgs, CheckTemplateArgumentInfo &CTAI,
5674 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5675
5676 if (ConstraintsNotSatisfied)
5677 *ConstraintsNotSatisfied = false;
5678
5679 // Make a copy of the template arguments for processing. Only make the
5680 // changes at the end when successful in matching the arguments to the
5681 // template.
5682 TemplateArgumentListInfo NewArgs = TemplateArgs;
5683
5684 TemplateParameterList *Params = GetTemplateParameterList(TD: Template);
5685
5686 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5687
5688 // C++23 [temp.arg.general]p1:
5689 // [...] The type and form of each template-argument specified in
5690 // a template-id shall match the type and form specified for the
5691 // corresponding parameter declared by the template in its
5692 // template-parameter-list.
5693 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Val: Template);
5694 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
5695 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
5696 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5697 LocalInstantiationScope InstScope(*this, true);
5698 for (TemplateParameterList::iterator ParamBegin = Params->begin(),
5699 ParamEnd = Params->end(),
5700 Param = ParamBegin;
5701 Param != ParamEnd;
5702 /* increment in loop */) {
5703 if (size_t ParamIdx = Param - ParamBegin;
5704 DefaultArgs && ParamIdx >= DefaultArgs.StartPos) {
5705 // All written arguments should have been consumed by this point.
5706 assert(ArgIdx == NumArgs && "bad default argument deduction");
5707 if (ParamIdx == DefaultArgs.StartPos) {
5708 assert(Param + DefaultArgs.Args.size() <= ParamEnd);
5709 // Default arguments from a DeducedTemplateName are already converted.
5710 for (const TemplateArgument &DefArg : DefaultArgs.Args) {
5711 CTAI.SugaredConverted.push_back(Elt: DefArg);
5712 CTAI.CanonicalConverted.push_back(
5713 Elt: Context.getCanonicalTemplateArgument(Arg: DefArg));
5714 ++Param;
5715 }
5716 continue;
5717 }
5718 }
5719
5720 // If we have an expanded parameter pack, make sure we don't have too
5721 // many arguments.
5722 if (UnsignedOrNone Expansions = getExpandedPackSize(Param: *Param)) {
5723 if (*Expansions == SugaredArgumentPack.size()) {
5724 // We're done with this parameter pack. Pack up its arguments and add
5725 // them to the list.
5726 CTAI.SugaredConverted.push_back(
5727 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
5728 SugaredArgumentPack.clear();
5729
5730 CTAI.CanonicalConverted.push_back(
5731 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
5732 CanonicalArgumentPack.clear();
5733
5734 // This argument is assigned to the next parameter.
5735 ++Param;
5736 continue;
5737 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5738 // Not enough arguments for this parameter pack.
5739 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
5740 << /*not enough args*/0
5741 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
5742 << Template;
5743 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
5744 return true;
5745 }
5746 }
5747
5748 if (ArgIdx < NumArgs) {
5749 TemplateArgumentLoc &ArgLoc = NewArgs[ArgIdx];
5750 bool NonPackParameter =
5751 !(*Param)->isTemplateParameterPack() || getExpandedPackSize(Param: *Param);
5752 bool ArgIsExpansion = ArgLoc.getArgument().isPackExpansion();
5753
5754 if (ArgIsExpansion && CTAI.MatchingTTP) {
5755 SmallVector<TemplateArgument, 4> Args(ParamEnd - Param);
5756 for (TemplateParameterList::iterator First = Param; Param != ParamEnd;
5757 ++Param) {
5758 TemplateArgument &Arg = Args[Param - First];
5759 Arg = ArgLoc.getArgument();
5760 if (!(*Param)->isTemplateParameterPack() ||
5761 getExpandedPackSize(Param: *Param))
5762 Arg = Arg.getPackExpansionPattern();
5763 TemplateArgumentLoc NewArgLoc(Arg, ArgLoc.getLocInfo());
5764 SaveAndRestore _1(CTAI.PartialOrdering, false);
5765 SaveAndRestore _2(CTAI.MatchingTTP, true);
5766 if (CheckTemplateArgument(Param: *Param, ArgLoc&: NewArgLoc, Template, TemplateLoc,
5767 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
5768 CTAK: CTAK_Specified))
5769 return true;
5770 Arg = NewArgLoc.getArgument();
5771 CTAI.CanonicalConverted.back().setIsDefaulted(
5772 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg, Param: *Param,
5773 Args: CTAI.CanonicalConverted,
5774 Depth: Params->getDepth()));
5775 }
5776 ArgLoc =
5777 TemplateArgumentLoc(TemplateArgument::CreatePackCopy(Context, Args),
5778 ArgLoc.getLocInfo());
5779 } else {
5780 SaveAndRestore _1(CTAI.PartialOrdering, false);
5781 if (CheckTemplateArgument(Param: *Param, ArgLoc, Template, TemplateLoc,
5782 RAngleLoc, ArgumentPackIndex: SugaredArgumentPack.size(), CTAI,
5783 CTAK: CTAK_Specified))
5784 return true;
5785 CTAI.CanonicalConverted.back().setIsDefaulted(
5786 clang::isSubstitutedDefaultArgument(Ctx&: Context, Arg: ArgLoc.getArgument(),
5787 Param: *Param, Args: CTAI.CanonicalConverted,
5788 Depth: Params->getDepth()));
5789 if (ArgIsExpansion && NonPackParameter) {
5790 // CWG1430/CWG2686: we have a pack expansion as an argument to an
5791 // alias template or concept, and it's not part of a parameter pack.
5792 // This can't be canonicalized, so reject it now.
5793 if (isa<TypeAliasTemplateDecl, ConceptDecl>(Val: Template)) {
5794 Diag(Loc: ArgLoc.getLocation(),
5795 DiagID: diag::err_template_expansion_into_fixed_list)
5796 << (isa<ConceptDecl>(Val: Template) ? 1 : 0)
5797 << ArgLoc.getSourceRange();
5798 NoteTemplateParameterLocation(Decl: **Param);
5799 return true;
5800 }
5801 }
5802 }
5803
5804 // We're now done with this argument.
5805 ++ArgIdx;
5806
5807 if (ArgIsExpansion && (CTAI.MatchingTTP || NonPackParameter)) {
5808 // Directly convert the remaining arguments, because we don't know what
5809 // parameters they'll match up with.
5810
5811 if (!SugaredArgumentPack.empty()) {
5812 // If we were part way through filling in an expanded parameter pack,
5813 // fall back to just producing individual arguments.
5814 CTAI.SugaredConverted.insert(I: CTAI.SugaredConverted.end(),
5815 From: SugaredArgumentPack.begin(),
5816 To: SugaredArgumentPack.end());
5817 SugaredArgumentPack.clear();
5818
5819 CTAI.CanonicalConverted.insert(I: CTAI.CanonicalConverted.end(),
5820 From: CanonicalArgumentPack.begin(),
5821 To: CanonicalArgumentPack.end());
5822 CanonicalArgumentPack.clear();
5823 }
5824
5825 while (ArgIdx < NumArgs) {
5826 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
5827 CTAI.SugaredConverted.push_back(Elt: Arg);
5828 CTAI.CanonicalConverted.push_back(
5829 Elt: Context.getCanonicalTemplateArgument(Arg));
5830 ++ArgIdx;
5831 }
5832
5833 return false;
5834 }
5835
5836 if ((*Param)->isTemplateParameterPack()) {
5837 // The template parameter was a template parameter pack, so take the
5838 // deduced argument and place it on the argument pack. Note that we
5839 // stay on the same template parameter so that we can deduce more
5840 // arguments.
5841 SugaredArgumentPack.push_back(Elt: CTAI.SugaredConverted.pop_back_val());
5842 CanonicalArgumentPack.push_back(Elt: CTAI.CanonicalConverted.pop_back_val());
5843 } else {
5844 // Move to the next template parameter.
5845 ++Param;
5846 }
5847 continue;
5848 }
5849
5850 // If we're checking a partial template argument list, we're done.
5851 if (PartialTemplateArgs) {
5852 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
5853 CTAI.SugaredConverted.push_back(
5854 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
5855 CTAI.CanonicalConverted.push_back(
5856 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
5857 }
5858 return false;
5859 }
5860
5861 // If we have a template parameter pack with no more corresponding
5862 // arguments, just break out now and we'll fill in the argument pack below.
5863 if ((*Param)->isTemplateParameterPack()) {
5864 assert(!getExpandedPackSize(*Param) &&
5865 "Should have dealt with this already");
5866
5867 // A non-expanded parameter pack before the end of the parameter list
5868 // only occurs for an ill-formed template parameter list, unless we've
5869 // got a partial argument list for a function template, so just bail out.
5870 if (Param + 1 != ParamEnd) {
5871 assert(
5872 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
5873 "Concept templates must have parameter packs at the end.");
5874 return true;
5875 }
5876
5877 CTAI.SugaredConverted.push_back(
5878 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
5879 SugaredArgumentPack.clear();
5880
5881 CTAI.CanonicalConverted.push_back(
5882 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
5883 CanonicalArgumentPack.clear();
5884
5885 ++Param;
5886 continue;
5887 }
5888
5889 // Check whether we have a default argument.
5890 bool HasDefaultArg;
5891
5892 // Retrieve the default template argument from the template
5893 // parameter. For each kind of template parameter, we substitute the
5894 // template arguments provided thus far and any "outer" template arguments
5895 // (when the template parameter was part of a nested template) into
5896 // the default argument.
5897 TemplateArgumentLoc Arg = SubstDefaultTemplateArgumentIfAvailable(
5898 Template, TemplateLoc, RAngleLoc, Param: *Param, SugaredConverted: CTAI.SugaredConverted,
5899 CanonicalConverted: CTAI.CanonicalConverted, HasDefaultArg);
5900
5901 if (Arg.getArgument().isNull()) {
5902 if (!HasDefaultArg) {
5903 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *Param))
5904 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: TTP,
5905 Args&: NewArgs);
5906 if (NonTypeTemplateParmDecl *NTTP =
5907 dyn_cast<NonTypeTemplateParmDecl>(Val: *Param))
5908 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: NTTP,
5909 Args&: NewArgs);
5910 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template,
5911 D: cast<TemplateTemplateParmDecl>(Val: *Param),
5912 Args&: NewArgs);
5913 }
5914 return true;
5915 }
5916
5917 // Introduce an instantiation record that describes where we are using
5918 // the default template argument. We're not actually instantiating a
5919 // template here, we just create this object to put a note into the
5920 // context stack.
5921 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
5922 CTAI.SugaredConverted,
5923 SourceRange(TemplateLoc, RAngleLoc));
5924 if (Inst.isInvalid())
5925 return true;
5926
5927 SaveAndRestore _1(CTAI.PartialOrdering, false);
5928 SaveAndRestore _2(CTAI.MatchingTTP, false);
5929 SaveAndRestore _3(CTAI.StrictPackMatch, {});
5930 // Check the default template argument.
5931 if (CheckTemplateArgument(Param: *Param, ArgLoc&: Arg, Template, TemplateLoc, RAngleLoc, ArgumentPackIndex: 0,
5932 CTAI, CTAK: CTAK_Specified))
5933 return true;
5934
5935 CTAI.SugaredConverted.back().setIsDefaulted(true);
5936 CTAI.CanonicalConverted.back().setIsDefaulted(true);
5937
5938 // Core issue 150 (assumed resolution): if this is a template template
5939 // parameter, keep track of the default template arguments from the
5940 // template definition.
5941 if (isTemplateTemplateParameter)
5942 NewArgs.addArgument(Loc: Arg);
5943
5944 // Move to the next template parameter and argument.
5945 ++Param;
5946 ++ArgIdx;
5947 }
5948
5949 // If we're performing a partial argument substitution, allow any trailing
5950 // pack expansions; they might be empty. This can happen even if
5951 // PartialTemplateArgs is false (the list of arguments is complete but
5952 // still dependent).
5953 if (CTAI.MatchingTTP ||
5954 (CurrentInstantiationScope &&
5955 CurrentInstantiationScope->getPartiallySubstitutedPack())) {
5956 while (ArgIdx < NumArgs &&
5957 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
5958 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
5959 CTAI.SugaredConverted.push_back(Elt: Arg);
5960 CTAI.CanonicalConverted.push_back(
5961 Elt: Context.getCanonicalTemplateArgument(Arg));
5962 }
5963 }
5964
5965 // If we have any leftover arguments, then there were too many arguments.
5966 // Complain and fail.
5967 if (ArgIdx < NumArgs) {
5968 Diag(Loc: TemplateLoc, DiagID: diag::err_template_arg_list_different_arity)
5969 << /*too many args*/1
5970 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(Template))
5971 << Template
5972 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5973 NoteTemplateLocation(Decl: *Template, ParamRange: Params->getSourceRange());
5974 return true;
5975 }
5976
5977 // No problems found with the new argument list, propagate changes back
5978 // to caller.
5979 if (UpdateArgsWithConversions)
5980 TemplateArgs = std::move(NewArgs);
5981
5982 if (!PartialTemplateArgs) {
5983 // Setup the context/ThisScope for the case where we are needing to
5984 // re-instantiate constraints outside of normal instantiation.
5985 DeclContext *NewContext = Template->getDeclContext();
5986
5987 // If this template is in a template, make sure we extract the templated
5988 // decl.
5989 if (auto *TD = dyn_cast<TemplateDecl>(Val: NewContext))
5990 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
5991 auto *RD = dyn_cast<CXXRecordDecl>(Val: NewContext);
5992
5993 Qualifiers ThisQuals;
5994 if (const auto *Method =
5995 dyn_cast_or_null<CXXMethodDecl>(Val: Template->getTemplatedDecl()))
5996 ThisQuals = Method->getMethodQualifiers();
5997
5998 ContextRAII Context(*this, NewContext);
5999 CXXThisScopeRAII Scope(*this, RD, ThisQuals, RD != nullptr);
6000
6001 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
6002 D: Template, DC: NewContext, /*Final=*/false, Innermost: CTAI.CanonicalConverted,
6003 /*RelativeToPrimary=*/true,
6004 /*Pattern=*/nullptr,
6005 /*ForConceptInstantiation=*/ForConstraintInstantiation: true);
6006 if (EnsureTemplateArgumentListConstraints(
6007 Template, TemplateArgs: MLTAL,
6008 TemplateIDRange: SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6009 if (ConstraintsNotSatisfied)
6010 *ConstraintsNotSatisfied = true;
6011 return true;
6012 }
6013 }
6014
6015 return false;
6016}
6017
6018namespace {
6019 class UnnamedLocalNoLinkageFinder
6020 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6021 {
6022 Sema &S;
6023 SourceRange SR;
6024
6025 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
6026
6027 public:
6028 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6029
6030 bool Visit(QualType T) {
6031 return T.isNull() ? false : inherited::Visit(T: T.getTypePtr());
6032 }
6033
6034#define TYPE(Class, Parent) \
6035 bool Visit##Class##Type(const Class##Type *);
6036#define ABSTRACT_TYPE(Class, Parent) \
6037 bool Visit##Class##Type(const Class##Type *) { return false; }
6038#define NON_CANONICAL_TYPE(Class, Parent) \
6039 bool Visit##Class##Type(const Class##Type *) { return false; }
6040#include "clang/AST/TypeNodes.inc"
6041
6042 bool VisitTagDecl(const TagDecl *Tag);
6043 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
6044 };
6045} // end anonymous namespace
6046
6047bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6048 return false;
6049}
6050
6051bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6052 return Visit(T: T->getElementType());
6053}
6054
6055bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6056 return Visit(T: T->getPointeeType());
6057}
6058
6059bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6060 const BlockPointerType* T) {
6061 return Visit(T: T->getPointeeType());
6062}
6063
6064bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6065 const LValueReferenceType* T) {
6066 return Visit(T: T->getPointeeType());
6067}
6068
6069bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6070 const RValueReferenceType* T) {
6071 return Visit(T: T->getPointeeType());
6072}
6073
6074bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6075 const MemberPointerType *T) {
6076 if (Visit(T: T->getPointeeType()))
6077 return true;
6078 if (auto *RD = T->getMostRecentCXXRecordDecl())
6079 return VisitTagDecl(Tag: RD);
6080 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6081}
6082
6083bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6084 const ConstantArrayType* T) {
6085 return Visit(T: T->getElementType());
6086}
6087
6088bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6089 const IncompleteArrayType* T) {
6090 return Visit(T: T->getElementType());
6091}
6092
6093bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6094 const VariableArrayType* T) {
6095 return Visit(T: T->getElementType());
6096}
6097
6098bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6099 const DependentSizedArrayType* T) {
6100 return Visit(T: T->getElementType());
6101}
6102
6103bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6104 const DependentSizedExtVectorType* T) {
6105 return Visit(T: T->getElementType());
6106}
6107
6108bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6109 const DependentSizedMatrixType *T) {
6110 return Visit(T: T->getElementType());
6111}
6112
6113bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6114 const DependentAddressSpaceType *T) {
6115 return Visit(T: T->getPointeeType());
6116}
6117
6118bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6119 return Visit(T: T->getElementType());
6120}
6121
6122bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6123 const DependentVectorType *T) {
6124 return Visit(T: T->getElementType());
6125}
6126
6127bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6128 return Visit(T: T->getElementType());
6129}
6130
6131bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6132 const ConstantMatrixType *T) {
6133 return Visit(T: T->getElementType());
6134}
6135
6136bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6137 const FunctionProtoType* T) {
6138 for (const auto &A : T->param_types()) {
6139 if (Visit(T: A))
6140 return true;
6141 }
6142
6143 return Visit(T: T->getReturnType());
6144}
6145
6146bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6147 const FunctionNoProtoType* T) {
6148 return Visit(T: T->getReturnType());
6149}
6150
6151bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6152 const UnresolvedUsingType*) {
6153 return false;
6154}
6155
6156bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6157 return false;
6158}
6159
6160bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6161 return Visit(T: T->getUnmodifiedType());
6162}
6163
6164bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6165 return false;
6166}
6167
6168bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6169 const PackIndexingType *) {
6170 return false;
6171}
6172
6173bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6174 const UnaryTransformType*) {
6175 return false;
6176}
6177
6178bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6179 return Visit(T: T->getDeducedType());
6180}
6181
6182bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6183 const DeducedTemplateSpecializationType *T) {
6184 return Visit(T: T->getDeducedType());
6185}
6186
6187bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6188 return VisitTagDecl(Tag: T->getDecl());
6189}
6190
6191bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6192 return VisitTagDecl(Tag: T->getDecl());
6193}
6194
6195bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6196 const TemplateTypeParmType*) {
6197 return false;
6198}
6199
6200bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6201 const SubstTemplateTypeParmPackType *) {
6202 return false;
6203}
6204
6205bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6206 const TemplateSpecializationType*) {
6207 return false;
6208}
6209
6210bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6211 const InjectedClassNameType* T) {
6212 return VisitTagDecl(Tag: T->getDecl());
6213}
6214
6215bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6216 const DependentNameType* T) {
6217 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6218}
6219
6220bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6221 const DependentTemplateSpecializationType* T) {
6222 if (auto *Q = T->getDependentTemplateName().getQualifier())
6223 return VisitNestedNameSpecifier(NNS: Q);
6224
6225 return false;
6226}
6227
6228bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6229 const PackExpansionType* T) {
6230 return Visit(T: T->getPattern());
6231}
6232
6233bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
6234 return false;
6235}
6236
6237bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
6238 const ObjCInterfaceType *) {
6239 return false;
6240}
6241
6242bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
6243 const ObjCObjectPointerType *) {
6244 return false;
6245}
6246
6247bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
6248 return Visit(T: T->getValueType());
6249}
6250
6251bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
6252 return false;
6253}
6254
6255bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
6256 return false;
6257}
6258
6259bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
6260 const ArrayParameterType *T) {
6261 return VisitConstantArrayType(T);
6262}
6263
6264bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
6265 const DependentBitIntType *T) {
6266 return false;
6267}
6268
6269bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
6270 if (Tag->getDeclContext()->isFunctionOrMethod()) {
6271 S.Diag(Loc: SR.getBegin(),
6272 DiagID: S.getLangOpts().CPlusPlus11 ?
6273 diag::warn_cxx98_compat_template_arg_local_type :
6274 diag::ext_template_arg_local_type)
6275 << S.Context.getTypeDeclType(Decl: Tag) << SR;
6276 return true;
6277 }
6278
6279 if (!Tag->hasNameForLinkage()) {
6280 S.Diag(Loc: SR.getBegin(),
6281 DiagID: S.getLangOpts().CPlusPlus11 ?
6282 diag::warn_cxx98_compat_template_arg_unnamed_type :
6283 diag::ext_template_arg_unnamed_type) << SR;
6284 S.Diag(Loc: Tag->getLocation(), DiagID: diag::note_template_unnamed_type_here);
6285 return true;
6286 }
6287
6288 return false;
6289}
6290
6291bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
6292 NestedNameSpecifier *NNS) {
6293 assert(NNS);
6294 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS: NNS->getPrefix()))
6295 return true;
6296
6297 switch (NNS->getKind()) {
6298 case NestedNameSpecifier::Identifier:
6299 case NestedNameSpecifier::Namespace:
6300 case NestedNameSpecifier::NamespaceAlias:
6301 case NestedNameSpecifier::Global:
6302 case NestedNameSpecifier::Super:
6303 return false;
6304
6305 case NestedNameSpecifier::TypeSpec:
6306 return Visit(T: QualType(NNS->getAsType(), 0));
6307 }
6308 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
6309}
6310
6311bool UnnamedLocalNoLinkageFinder::VisitHLSLAttributedResourceType(
6312 const HLSLAttributedResourceType *T) {
6313 if (T->hasContainedType() && Visit(T: T->getContainedType()))
6314 return true;
6315 return Visit(T: T->getWrappedType());
6316}
6317
6318bool UnnamedLocalNoLinkageFinder::VisitHLSLInlineSpirvType(
6319 const HLSLInlineSpirvType *T) {
6320 for (auto &Operand : T->getOperands())
6321 if (Operand.isConstant() && Operand.isLiteral())
6322 if (Visit(T: Operand.getResultType()))
6323 return true;
6324 return false;
6325}
6326
6327bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
6328 assert(ArgInfo && "invalid TypeSourceInfo");
6329 QualType Arg = ArgInfo->getType();
6330 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
6331 QualType CanonArg = Context.getCanonicalType(T: Arg);
6332
6333 if (CanonArg->isVariablyModifiedType()) {
6334 return Diag(Loc: SR.getBegin(), DiagID: diag::err_variably_modified_template_arg) << Arg;
6335 } else if (Context.hasSameUnqualifiedType(T1: Arg, T2: Context.OverloadTy)) {
6336 return Diag(Loc: SR.getBegin(), DiagID: diag::err_template_arg_overload_type) << SR;
6337 }
6338
6339 // C++03 [temp.arg.type]p2:
6340 // A local type, a type with no linkage, an unnamed type or a type
6341 // compounded from any of these types shall not be used as a
6342 // template-argument for a template type-parameter.
6343 //
6344 // C++11 allows these, and even in C++03 we allow them as an extension with
6345 // a warning.
6346 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
6347 UnnamedLocalNoLinkageFinder Finder(*this, SR);
6348 (void)Finder.Visit(T: CanonArg);
6349 }
6350
6351 return false;
6352}
6353
6354enum NullPointerValueKind {
6355 NPV_NotNullPointer,
6356 NPV_NullPointer,
6357 NPV_Error
6358};
6359
6360/// Determine whether the given template argument is a null pointer
6361/// value of the appropriate type.
6362static NullPointerValueKind
6363isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
6364 QualType ParamType, Expr *Arg,
6365 Decl *Entity = nullptr) {
6366 if (Arg->isValueDependent() || Arg->isTypeDependent())
6367 return NPV_NotNullPointer;
6368
6369 // dllimport'd entities aren't constant but are available inside of template
6370 // arguments.
6371 if (Entity && Entity->hasAttr<DLLImportAttr>())
6372 return NPV_NotNullPointer;
6373
6374 if (!S.isCompleteType(Loc: Arg->getExprLoc(), T: ParamType))
6375 llvm_unreachable(
6376 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
6377
6378 if (!S.getLangOpts().CPlusPlus11)
6379 return NPV_NotNullPointer;
6380
6381 // Determine whether we have a constant expression.
6382 ExprResult ArgRV = S.DefaultFunctionArrayConversion(E: Arg);
6383 if (ArgRV.isInvalid())
6384 return NPV_Error;
6385 Arg = ArgRV.get();
6386
6387 Expr::EvalResult EvalResult;
6388 SmallVector<PartialDiagnosticAt, 8> Notes;
6389 EvalResult.Diag = &Notes;
6390 if (!Arg->EvaluateAsRValue(Result&: EvalResult, Ctx: S.Context) ||
6391 EvalResult.HasSideEffects) {
6392 SourceLocation DiagLoc = Arg->getExprLoc();
6393
6394 // If our only note is the usual "invalid subexpression" note, just point
6395 // the caret at its location rather than producing an essentially
6396 // redundant note.
6397 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
6398 diag::note_invalid_subexpr_in_const_expr) {
6399 DiagLoc = Notes[0].first;
6400 Notes.clear();
6401 }
6402
6403 S.Diag(Loc: DiagLoc, DiagID: diag::err_template_arg_not_address_constant)
6404 << Arg->getType() << Arg->getSourceRange();
6405 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
6406 S.Diag(Loc: Notes[I].first, PD: Notes[I].second);
6407
6408 S.NoteTemplateParameterLocation(Decl: *Param);
6409 return NPV_Error;
6410 }
6411
6412 // C++11 [temp.arg.nontype]p1:
6413 // - an address constant expression of type std::nullptr_t
6414 if (Arg->getType()->isNullPtrType())
6415 return NPV_NullPointer;
6416
6417 // - a constant expression that evaluates to a null pointer value (4.10); or
6418 // - a constant expression that evaluates to a null member pointer value
6419 // (4.11); or
6420 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
6421 (EvalResult.Val.isMemberPointer() &&
6422 !EvalResult.Val.getMemberPointerDecl())) {
6423 // If our expression has an appropriate type, we've succeeded.
6424 bool ObjCLifetimeConversion;
6425 if (S.Context.hasSameUnqualifiedType(T1: Arg->getType(), T2: ParamType) ||
6426 S.IsQualificationConversion(FromType: Arg->getType(), ToType: ParamType, CStyle: false,
6427 ObjCLifetimeConversion))
6428 return NPV_NullPointer;
6429
6430 // The types didn't match, but we know we got a null pointer; complain,
6431 // then recover as if the types were correct.
6432 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_wrongtype_null_constant)
6433 << Arg->getType() << ParamType << Arg->getSourceRange();
6434 S.NoteTemplateParameterLocation(Decl: *Param);
6435 return NPV_NullPointer;
6436 }
6437
6438 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
6439 // We found a pointer that isn't null, but doesn't refer to an object.
6440 // We could just return NPV_NotNullPointer, but we can print a better
6441 // message with the information we have here.
6442 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_invalid)
6443 << EvalResult.Val.getAsString(Ctx: S.Context, Ty: ParamType);
6444 S.NoteTemplateParameterLocation(Decl: *Param);
6445 return NPV_Error;
6446 }
6447
6448 // If we don't have a null pointer value, but we do have a NULL pointer
6449 // constant, suggest a cast to the appropriate type.
6450 if (Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_NeverValueDependent)) {
6451 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
6452 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_untyped_null_constant)
6453 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code)
6454 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: Arg->getEndLoc()),
6455 Code: ")");
6456 S.NoteTemplateParameterLocation(Decl: *Param);
6457 return NPV_NullPointer;
6458 }
6459
6460 // FIXME: If we ever want to support general, address-constant expressions
6461 // as non-type template arguments, we should return the ExprResult here to
6462 // be interpreted by the caller.
6463 return NPV_NotNullPointer;
6464}
6465
6466/// Checks whether the given template argument is compatible with its
6467/// template parameter.
6468static bool CheckTemplateArgumentIsCompatibleWithParameter(
6469 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6470 Expr *Arg, QualType ArgType) {
6471 bool ObjCLifetimeConversion;
6472 if (ParamType->isPointerType() &&
6473 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
6474 S.IsQualificationConversion(FromType: ArgType, ToType: ParamType, CStyle: false,
6475 ObjCLifetimeConversion)) {
6476 // For pointer-to-object types, qualification conversions are
6477 // permitted.
6478 } else {
6479 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
6480 if (!ParamRef->getPointeeType()->isFunctionType()) {
6481 // C++ [temp.arg.nontype]p5b3:
6482 // For a non-type template-parameter of type reference to
6483 // object, no conversions apply. The type referred to by the
6484 // reference may be more cv-qualified than the (otherwise
6485 // identical) type of the template- argument. The
6486 // template-parameter is bound directly to the
6487 // template-argument, which shall be an lvalue.
6488
6489 // FIXME: Other qualifiers?
6490 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
6491 unsigned ArgQuals = ArgType.getCVRQualifiers();
6492
6493 if ((ParamQuals | ArgQuals) != ParamQuals) {
6494 S.Diag(Loc: Arg->getBeginLoc(),
6495 DiagID: diag::err_template_arg_ref_bind_ignores_quals)
6496 << ParamType << Arg->getType() << Arg->getSourceRange();
6497 S.NoteTemplateParameterLocation(Decl: *Param);
6498 return true;
6499 }
6500 }
6501 }
6502
6503 // At this point, the template argument refers to an object or
6504 // function with external linkage. We now need to check whether the
6505 // argument and parameter types are compatible.
6506 if (!S.Context.hasSameUnqualifiedType(T1: ArgType,
6507 T2: ParamType.getNonReferenceType())) {
6508 // We can't perform this conversion or binding.
6509 if (ParamType->isReferenceType())
6510 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_no_ref_bind)
6511 << ParamType << ArgIn->getType() << Arg->getSourceRange();
6512 else
6513 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
6514 << ArgIn->getType() << ParamType << Arg->getSourceRange();
6515 S.NoteTemplateParameterLocation(Decl: *Param);
6516 return true;
6517 }
6518 }
6519
6520 return false;
6521}
6522
6523/// Checks whether the given template argument is the address
6524/// of an object or function according to C++ [temp.arg.nontype]p1.
6525static bool CheckTemplateArgumentAddressOfObjectOrFunction(
6526 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
6527 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
6528 bool Invalid = false;
6529 Expr *Arg = ArgIn;
6530 QualType ArgType = Arg->getType();
6531
6532 bool AddressTaken = false;
6533 SourceLocation AddrOpLoc;
6534 if (S.getLangOpts().MicrosoftExt) {
6535 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
6536 // dereference and address-of operators.
6537 Arg = Arg->IgnoreParenCasts();
6538
6539 bool ExtWarnMSTemplateArg = false;
6540 UnaryOperatorKind FirstOpKind;
6541 SourceLocation FirstOpLoc;
6542 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6543 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
6544 if (UnOpKind == UO_Deref)
6545 ExtWarnMSTemplateArg = true;
6546 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
6547 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
6548 if (!AddrOpLoc.isValid()) {
6549 FirstOpKind = UnOpKind;
6550 FirstOpLoc = UnOp->getOperatorLoc();
6551 }
6552 } else
6553 break;
6554 }
6555 if (FirstOpLoc.isValid()) {
6556 if (ExtWarnMSTemplateArg)
6557 S.Diag(Loc: ArgIn->getBeginLoc(), DiagID: diag::ext_ms_deref_template_argument)
6558 << ArgIn->getSourceRange();
6559
6560 if (FirstOpKind == UO_AddrOf)
6561 AddressTaken = true;
6562 else if (Arg->getType()->isPointerType()) {
6563 // We cannot let pointers get dereferenced here, that is obviously not a
6564 // constant expression.
6565 assert(FirstOpKind == UO_Deref);
6566 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6567 << Arg->getSourceRange();
6568 }
6569 }
6570 } else {
6571 // See through any implicit casts we added to fix the type.
6572 Arg = Arg->IgnoreImpCasts();
6573
6574 // C++ [temp.arg.nontype]p1:
6575 //
6576 // A template-argument for a non-type, non-template
6577 // template-parameter shall be one of: [...]
6578 //
6579 // -- the address of an object or function with external
6580 // linkage, including function templates and function
6581 // template-ids but excluding non-static class members,
6582 // expressed as & id-expression where the & is optional if
6583 // the name refers to a function or array, or if the
6584 // corresponding template-parameter is a reference; or
6585
6586 // In C++98/03 mode, give an extension warning on any extra parentheses.
6587 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6588 bool ExtraParens = false;
6589 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
6590 if (!Invalid && !ExtraParens) {
6591 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_extra_parens)
6592 << Arg->getSourceRange();
6593 ExtraParens = true;
6594 }
6595
6596 Arg = Parens->getSubExpr();
6597 }
6598
6599 while (SubstNonTypeTemplateParmExpr *subst =
6600 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6601 Arg = subst->getReplacement()->IgnoreImpCasts();
6602
6603 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6604 if (UnOp->getOpcode() == UO_AddrOf) {
6605 Arg = UnOp->getSubExpr();
6606 AddressTaken = true;
6607 AddrOpLoc = UnOp->getOperatorLoc();
6608 }
6609 }
6610
6611 while (SubstNonTypeTemplateParmExpr *subst =
6612 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6613 Arg = subst->getReplacement()->IgnoreImpCasts();
6614 }
6615
6616 ValueDecl *Entity = nullptr;
6617 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg))
6618 Entity = DRE->getDecl();
6619 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Val: Arg))
6620 Entity = CUE->getGuidDecl();
6621
6622 // If our parameter has pointer type, check for a null template value.
6623 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
6624 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ArgIn,
6625 Entity)) {
6626 case NPV_NullPointer:
6627 S.Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
6628 SugaredConverted = TemplateArgument(ParamType,
6629 /*isNullPtr=*/true);
6630 CanonicalConverted =
6631 TemplateArgument(S.Context.getCanonicalType(T: ParamType),
6632 /*isNullPtr=*/true);
6633 return false;
6634
6635 case NPV_Error:
6636 return true;
6637
6638 case NPV_NotNullPointer:
6639 break;
6640 }
6641 }
6642
6643 // Stop checking the precise nature of the argument if it is value dependent,
6644 // it should be checked when instantiated.
6645 if (Arg->isValueDependent()) {
6646 SugaredConverted = TemplateArgument(ArgIn, /*IsCanonical=*/false);
6647 CanonicalConverted =
6648 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
6649 return false;
6650 }
6651
6652 if (!Entity) {
6653 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
6654 << Arg->getSourceRange();
6655 S.NoteTemplateParameterLocation(Decl: *Param);
6656 return true;
6657 }
6658
6659 // Cannot refer to non-static data members
6660 if (isa<FieldDecl>(Val: Entity) || isa<IndirectFieldDecl>(Val: Entity)) {
6661 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_field)
6662 << Entity << Arg->getSourceRange();
6663 S.NoteTemplateParameterLocation(Decl: *Param);
6664 return true;
6665 }
6666
6667 // Cannot refer to non-static member functions
6668 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Entity)) {
6669 if (!Method->isStatic()) {
6670 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_method)
6671 << Method << Arg->getSourceRange();
6672 S.NoteTemplateParameterLocation(Decl: *Param);
6673 return true;
6674 }
6675 }
6676
6677 FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Entity);
6678 VarDecl *Var = dyn_cast<VarDecl>(Val: Entity);
6679 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Val: Entity);
6680
6681 // A non-type template argument must refer to an object or function.
6682 if (!Func && !Var && !Guid) {
6683 // We found something, but we don't know specifically what it is.
6684 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_object_or_func)
6685 << Arg->getSourceRange();
6686 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_refers_here);
6687 return true;
6688 }
6689
6690 // Address / reference template args must have external linkage in C++98.
6691 if (Entity->getFormalLinkage() == Linkage::Internal) {
6692 S.Diag(Loc: Arg->getBeginLoc(),
6693 DiagID: S.getLangOpts().CPlusPlus11
6694 ? diag::warn_cxx98_compat_template_arg_object_internal
6695 : diag::ext_template_arg_object_internal)
6696 << !Func << Entity << Arg->getSourceRange();
6697 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6698 << !Func;
6699 } else if (!Entity->hasLinkage()) {
6700 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_object_no_linkage)
6701 << !Func << Entity << Arg->getSourceRange();
6702 S.Diag(Loc: Entity->getLocation(), DiagID: diag::note_template_arg_internal_object)
6703 << !Func;
6704 return true;
6705 }
6706
6707 if (Var) {
6708 // A value of reference type is not an object.
6709 if (Var->getType()->isReferenceType()) {
6710 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_reference_var)
6711 << Var->getType() << Arg->getSourceRange();
6712 S.NoteTemplateParameterLocation(Decl: *Param);
6713 return true;
6714 }
6715
6716 // A template argument must have static storage duration.
6717 if (Var->getTLSKind()) {
6718 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_thread_local)
6719 << Arg->getSourceRange();
6720 S.Diag(Loc: Var->getLocation(), DiagID: diag::note_template_arg_refers_here);
6721 return true;
6722 }
6723 }
6724
6725 if (AddressTaken && ParamType->isReferenceType()) {
6726 // If we originally had an address-of operator, but the
6727 // parameter has reference type, complain and (if things look
6728 // like they will work) drop the address-of operator.
6729 if (!S.Context.hasSameUnqualifiedType(T1: Entity->getType(),
6730 T2: ParamType.getNonReferenceType())) {
6731 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6732 << ParamType;
6733 S.NoteTemplateParameterLocation(Decl: *Param);
6734 return true;
6735 }
6736
6737 S.Diag(Loc: AddrOpLoc, DiagID: diag::err_template_arg_address_of_non_pointer)
6738 << ParamType
6739 << FixItHint::CreateRemoval(RemoveRange: AddrOpLoc);
6740 S.NoteTemplateParameterLocation(Decl: *Param);
6741
6742 ArgType = Entity->getType();
6743 }
6744
6745 // If the template parameter has pointer type, either we must have taken the
6746 // address or the argument must decay to a pointer.
6747 if (!AddressTaken && ParamType->isPointerType()) {
6748 if (Func) {
6749 // Function-to-pointer decay.
6750 ArgType = S.Context.getPointerType(T: Func->getType());
6751 } else if (Entity->getType()->isArrayType()) {
6752 // Array-to-pointer decay.
6753 ArgType = S.Context.getArrayDecayedType(T: Entity->getType());
6754 } else {
6755 // If the template parameter has pointer type but the address of
6756 // this object was not taken, complain and (possibly) recover by
6757 // taking the address of the entity.
6758 ArgType = S.Context.getPointerType(T: Entity->getType());
6759 if (!S.Context.hasSameUnqualifiedType(T1: ArgType, T2: ParamType)) {
6760 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
6761 << ParamType;
6762 S.NoteTemplateParameterLocation(Decl: *Param);
6763 return true;
6764 }
6765
6766 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_address_of)
6767 << ParamType << FixItHint::CreateInsertion(InsertionLoc: Arg->getBeginLoc(), Code: "&");
6768
6769 S.NoteTemplateParameterLocation(Decl: *Param);
6770 }
6771 }
6772
6773 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
6774 Arg, ArgType))
6775 return true;
6776
6777 // Create the template argument.
6778 SugaredConverted = TemplateArgument(Entity, ParamType);
6779 CanonicalConverted =
6780 TemplateArgument(cast<ValueDecl>(Val: Entity->getCanonicalDecl()),
6781 S.Context.getCanonicalType(T: ParamType));
6782 S.MarkAnyDeclReferenced(Loc: Arg->getBeginLoc(), D: Entity, MightBeOdrUse: false);
6783 return false;
6784}
6785
6786/// Checks whether the given template argument is a pointer to
6787/// member constant according to C++ [temp.arg.nontype]p1.
6788static bool
6789CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param,
6790 QualType ParamType, Expr *&ResultArg,
6791 TemplateArgument &SugaredConverted,
6792 TemplateArgument &CanonicalConverted) {
6793 bool Invalid = false;
6794
6795 Expr *Arg = ResultArg;
6796 bool ObjCLifetimeConversion;
6797
6798 // C++ [temp.arg.nontype]p1:
6799 //
6800 // A template-argument for a non-type, non-template
6801 // template-parameter shall be one of: [...]
6802 //
6803 // -- a pointer to member expressed as described in 5.3.1.
6804 DeclRefExpr *DRE = nullptr;
6805
6806 // In C++98/03 mode, give an extension warning on any extra parentheses.
6807 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
6808 bool ExtraParens = false;
6809 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
6810 if (!Invalid && !ExtraParens) {
6811 S.DiagCompat(Loc: Arg->getBeginLoc(), CompatDiagId: diag_compat::template_arg_extra_parens)
6812 << Arg->getSourceRange();
6813 ExtraParens = true;
6814 }
6815
6816 Arg = Parens->getSubExpr();
6817 }
6818
6819 while (SubstNonTypeTemplateParmExpr *subst =
6820 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
6821 Arg = subst->getReplacement()->IgnoreImpCasts();
6822
6823 // A pointer-to-member constant written &Class::member.
6824 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
6825 if (UnOp->getOpcode() == UO_AddrOf) {
6826 DRE = dyn_cast<DeclRefExpr>(Val: UnOp->getSubExpr());
6827 if (DRE && !DRE->getQualifier())
6828 DRE = nullptr;
6829 }
6830 }
6831 // A constant of pointer-to-member type.
6832 else if ((DRE = dyn_cast<DeclRefExpr>(Val: Arg))) {
6833 ValueDecl *VD = DRE->getDecl();
6834 if (VD->getType()->isMemberPointerType()) {
6835 if (isa<NonTypeTemplateParmDecl>(Val: VD)) {
6836 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6837 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
6838 CanonicalConverted =
6839 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
6840 } else {
6841 SugaredConverted = TemplateArgument(VD, ParamType);
6842 CanonicalConverted =
6843 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
6844 S.Context.getCanonicalType(T: ParamType));
6845 }
6846 return Invalid;
6847 }
6848 }
6849
6850 DRE = nullptr;
6851 }
6852
6853 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
6854
6855 // Check for a null pointer value.
6856 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, Arg: ResultArg,
6857 Entity)) {
6858 case NPV_Error:
6859 return true;
6860 case NPV_NullPointer:
6861 S.Diag(Loc: ResultArg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
6862 SugaredConverted = TemplateArgument(ParamType,
6863 /*isNullPtr*/ true);
6864 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(T: ParamType),
6865 /*isNullPtr*/ true);
6866 return false;
6867 case NPV_NotNullPointer:
6868 break;
6869 }
6870
6871 if (S.IsQualificationConversion(FromType: ResultArg->getType(),
6872 ToType: ParamType.getNonReferenceType(), CStyle: false,
6873 ObjCLifetimeConversion)) {
6874 ResultArg = S.ImpCastExprToType(E: ResultArg, Type: ParamType, CK: CK_NoOp,
6875 VK: ResultArg->getValueKind())
6876 .get();
6877 } else if (!S.Context.hasSameUnqualifiedType(
6878 T1: ResultArg->getType(), T2: ParamType.getNonReferenceType())) {
6879 // We can't perform this conversion.
6880 S.Diag(Loc: ResultArg->getBeginLoc(), DiagID: diag::err_template_arg_not_convertible)
6881 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
6882 S.NoteTemplateParameterLocation(Decl: *Param);
6883 return true;
6884 }
6885
6886 if (!DRE)
6887 return S.Diag(Loc: Arg->getBeginLoc(),
6888 DiagID: diag::err_template_arg_not_pointer_to_member_form)
6889 << Arg->getSourceRange();
6890
6891 if (isa<FieldDecl>(Val: DRE->getDecl()) ||
6892 isa<IndirectFieldDecl>(Val: DRE->getDecl()) ||
6893 isa<CXXMethodDecl>(Val: DRE->getDecl())) {
6894 assert((isa<FieldDecl>(DRE->getDecl()) ||
6895 isa<IndirectFieldDecl>(DRE->getDecl()) ||
6896 cast<CXXMethodDecl>(DRE->getDecl())
6897 ->isImplicitObjectMemberFunction()) &&
6898 "Only non-static member pointers can make it here");
6899
6900 // Okay: this is the address of a non-static member, and therefore
6901 // a member pointer constant.
6902 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
6903 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
6904 CanonicalConverted =
6905 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
6906 } else {
6907 ValueDecl *D = DRE->getDecl();
6908 SugaredConverted = TemplateArgument(D, ParamType);
6909 CanonicalConverted =
6910 TemplateArgument(cast<ValueDecl>(Val: D->getCanonicalDecl()),
6911 S.Context.getCanonicalType(T: ParamType));
6912 }
6913 return Invalid;
6914 }
6915
6916 // We found something else, but we don't know specifically what it is.
6917 S.Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_pointer_to_member_form)
6918 << Arg->getSourceRange();
6919 S.Diag(Loc: DRE->getDecl()->getLocation(), DiagID: diag::note_template_arg_refers_here);
6920 return true;
6921}
6922
6923ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
6924 QualType ParamType, Expr *Arg,
6925 TemplateArgument &SugaredConverted,
6926 TemplateArgument &CanonicalConverted,
6927 bool StrictCheck,
6928 CheckTemplateArgumentKind CTAK) {
6929 SourceLocation StartLoc = Arg->getBeginLoc();
6930 auto *ArgPE = dyn_cast<PackExpansionExpr>(Val: Arg);
6931 Expr *DeductionArg = ArgPE ? ArgPE->getPattern() : Arg;
6932 auto setDeductionArg = [&](Expr *NewDeductionArg) {
6933 DeductionArg = NewDeductionArg;
6934 if (ArgPE) {
6935 // Recreate a pack expansion if we unwrapped one.
6936 Arg = new (Context) PackExpansionExpr(
6937 DeductionArg, ArgPE->getEllipsisLoc(), ArgPE->getNumExpansions());
6938 } else {
6939 Arg = DeductionArg;
6940 }
6941 };
6942
6943 // If the parameter type somehow involves auto, deduce the type now.
6944 DeducedType *DeducedT = ParamType->getContainedDeducedType();
6945 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
6946 // During template argument deduction, we allow 'decltype(auto)' to
6947 // match an arbitrary dependent argument.
6948 // FIXME: The language rules don't say what happens in this case.
6949 // FIXME: We get an opaque dependent type out of decltype(auto) if the
6950 // expression is merely instantiation-dependent; is this enough?
6951 if (DeductionArg->isTypeDependent()) {
6952 auto *AT = dyn_cast<AutoType>(Val: DeducedT);
6953 if (AT && AT->isDecltypeAuto()) {
6954 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
6955 CanonicalConverted = TemplateArgument(
6956 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
6957 return Arg;
6958 }
6959 }
6960
6961 // When checking a deduced template argument, deduce from its type even if
6962 // the type is dependent, in order to check the types of non-type template
6963 // arguments line up properly in partial ordering.
6964 TypeSourceInfo *TSI =
6965 Context.getTrivialTypeSourceInfo(T: ParamType, Loc: Param->getLocation());
6966 if (isa<DeducedTemplateSpecializationType>(Val: DeducedT)) {
6967 InitializedEntity Entity =
6968 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
6969 InitializationKind Kind = InitializationKind::CreateForInit(
6970 Loc: DeductionArg->getBeginLoc(), /*DirectInit*/false, Init: DeductionArg);
6971 Expr *Inits[1] = {DeductionArg};
6972 ParamType =
6973 DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind, Init: Inits);
6974 if (ParamType.isNull())
6975 return ExprError();
6976 } else {
6977 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
6978 Param->getDepth() + 1);
6979 ParamType = QualType();
6980 TemplateDeductionResult Result =
6981 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeductionArg, Result&: ParamType, Info,
6982 /*DependentDeduction=*/true,
6983 // We do not check constraints right now because the
6984 // immediately-declared constraint of the auto type is
6985 // also an associated constraint, and will be checked
6986 // along with the other associated constraints after
6987 // checking the template argument list.
6988 /*IgnoreConstraints=*/true);
6989 if (Result == TemplateDeductionResult::AlreadyDiagnosed) {
6990 if (ParamType.isNull())
6991 return ExprError();
6992 } else if (Result != TemplateDeductionResult::Success) {
6993 Diag(Loc: Arg->getExprLoc(),
6994 DiagID: diag::err_non_type_template_parm_type_deduction_failure)
6995 << Param->getDeclName() << Param->getType() << Arg->getType()
6996 << Arg->getSourceRange();
6997 NoteTemplateParameterLocation(Decl: *Param);
6998 return ExprError();
6999 }
7000 }
7001 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7002 // an error. The error message normally references the parameter
7003 // declaration, but here we'll pass the argument location because that's
7004 // where the parameter type is deduced.
7005 ParamType = CheckNonTypeTemplateParameterType(T: ParamType, Loc: Arg->getExprLoc());
7006 if (ParamType.isNull()) {
7007 NoteTemplateParameterLocation(Decl: *Param);
7008 return ExprError();
7009 }
7010 }
7011
7012 // We should have already dropped all cv-qualifiers by now.
7013 assert(!ParamType.hasQualifiers() &&
7014 "non-type template parameter type cannot be qualified");
7015
7016 // If either the parameter has a dependent type or the argument is
7017 // type-dependent, there's nothing we can check now.
7018 if (ParamType->isDependentType() || DeductionArg->isTypeDependent()) {
7019 // Force the argument to the type of the parameter to maintain invariants.
7020 ExprResult E = ImpCastExprToType(
7021 E: DeductionArg, Type: ParamType.getNonLValueExprType(Context), CK: CK_Dependent,
7022 VK: ParamType->isLValueReferenceType() ? VK_LValue
7023 : ParamType->isRValueReferenceType() ? VK_XValue
7024 : VK_PRValue);
7025 if (E.isInvalid())
7026 return ExprError();
7027 setDeductionArg(E.get());
7028 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7029 CanonicalConverted = TemplateArgument(
7030 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7031 return Arg;
7032 }
7033
7034 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7035 if (CTAK == CTAK_Deduced && !StrictCheck &&
7036 (ParamType->isReferenceType()
7037 ? !Context.hasSameType(T1: ParamType.getNonReferenceType(),
7038 T2: DeductionArg->getType())
7039 : !Context.hasSameUnqualifiedType(T1: ParamType,
7040 T2: DeductionArg->getType()))) {
7041 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7042 // we should actually be checking the type of the template argument in P,
7043 // not the type of the template argument deduced from A, against the
7044 // template parameter type.
7045 Diag(Loc: StartLoc, DiagID: diag::err_deduced_non_type_template_arg_type_mismatch)
7046 << Arg->getType() << ParamType.getUnqualifiedType();
7047 NoteTemplateParameterLocation(Decl: *Param);
7048 return ExprError();
7049 }
7050
7051 // If the argument is a pack expansion, we don't know how many times it would
7052 // expand. If we continue checking the argument, this will make the template
7053 // definition ill-formed if it would be ill-formed for any number of
7054 // expansions during instantiation time. When partial ordering or matching
7055 // template template parameters, this is exactly what we want. Otherwise, the
7056 // normal template rules apply: we accept the template if it would be valid
7057 // for any number of expansions (i.e. none).
7058 if (ArgPE && !StrictCheck) {
7059 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7060 CanonicalConverted = TemplateArgument(
7061 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7062 return Arg;
7063 }
7064
7065 // Avoid making a copy when initializing a template parameter of class type
7066 // from a template parameter object of the same type. This is going beyond
7067 // the standard, but is required for soundness: in
7068 // template<A a> struct X { X *p; X<a> *q; };
7069 // ... we need p and q to have the same type.
7070 //
7071 // Similarly, don't inject a call to a copy constructor when initializing
7072 // from a template parameter of the same type.
7073 Expr *InnerArg = DeductionArg->IgnoreParenImpCasts();
7074 if (ParamType->isRecordType() && isa<DeclRefExpr>(Val: InnerArg) &&
7075 Context.hasSameUnqualifiedType(T1: ParamType, T2: InnerArg->getType())) {
7076 NamedDecl *ND = cast<DeclRefExpr>(Val: InnerArg)->getDecl();
7077 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(Val: ND)) {
7078
7079 SugaredConverted = TemplateArgument(TPO, ParamType);
7080 CanonicalConverted = TemplateArgument(TPO->getCanonicalDecl(),
7081 ParamType.getCanonicalType());
7082 return Arg;
7083 }
7084 if (isa<NonTypeTemplateParmDecl>(Val: ND)) {
7085 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7086 CanonicalConverted =
7087 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7088 return Arg;
7089 }
7090 }
7091
7092 // The initialization of the parameter from the argument is
7093 // a constant-evaluated context.
7094 EnterExpressionEvaluationContext ConstantEvaluated(
7095 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7096
7097 bool IsConvertedConstantExpression = true;
7098 if (isa<InitListExpr>(Val: DeductionArg) || ParamType->isRecordType()) {
7099 InitializationKind Kind = InitializationKind::CreateForInit(
7100 Loc: StartLoc, /*DirectInit=*/false, Init: DeductionArg);
7101 Expr *Inits[1] = {DeductionArg};
7102 InitializedEntity Entity =
7103 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7104 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7105 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Inits);
7106 if (Result.isInvalid() || !Result.get())
7107 return ExprError();
7108 Result = ActOnConstantExpression(Res: Result.get());
7109 if (Result.isInvalid() || !Result.get())
7110 return ExprError();
7111 setDeductionArg(ActOnFinishFullExpr(Expr: Result.get(), CC: Arg->getBeginLoc(),
7112 /*DiscardedValue=*/false,
7113 /*IsConstexpr=*/true,
7114 /*IsTemplateArgument=*/true)
7115 .get());
7116 IsConvertedConstantExpression = false;
7117 }
7118
7119 if (getLangOpts().CPlusPlus17 || StrictCheck) {
7120 // C++17 [temp.arg.nontype]p1:
7121 // A template-argument for a non-type template parameter shall be
7122 // a converted constant expression of the type of the template-parameter.
7123 APValue Value;
7124 ExprResult ArgResult;
7125 if (IsConvertedConstantExpression) {
7126 ArgResult = BuildConvertedConstantExpression(
7127 From: DeductionArg, T: ParamType,
7128 CCE: StrictCheck ? CCEKind::TempArgStrict : CCEKind::TemplateArg, Dest: Param);
7129 assert(!ArgResult.isUnset());
7130 if (ArgResult.isInvalid()) {
7131 NoteTemplateParameterLocation(Decl: *Param);
7132 return ExprError();
7133 }
7134 } else {
7135 ArgResult = DeductionArg;
7136 }
7137
7138 // For a value-dependent argument, CheckConvertedConstantExpression is
7139 // permitted (and expected) to be unable to determine a value.
7140 if (ArgResult.get()->isValueDependent()) {
7141 setDeductionArg(ArgResult.get());
7142 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7143 CanonicalConverted =
7144 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7145 return Arg;
7146 }
7147
7148 APValue PreNarrowingValue;
7149 ArgResult = EvaluateConvertedConstantExpression(
7150 E: ArgResult.get(), T: ParamType, Value, CCE: CCEKind::TemplateArg, /*RequireInt=*/
7151 false, PreNarrowingValue);
7152 if (ArgResult.isInvalid())
7153 return ExprError();
7154 setDeductionArg(ArgResult.get());
7155
7156 if (Value.isLValue()) {
7157 APValue::LValueBase Base = Value.getLValueBase();
7158 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7159 // For a non-type template-parameter of pointer or reference type,
7160 // the value of the constant expression shall not refer to
7161 assert(ParamType->isPointerOrReferenceType() ||
7162 ParamType->isNullPtrType());
7163 // -- a temporary object
7164 // -- a string literal
7165 // -- the result of a typeid expression, or
7166 // -- a predefined __func__ variable
7167 if (Base &&
7168 (!VD ||
7169 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(Val: VD))) {
7170 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::err_template_arg_not_decl_ref)
7171 << Arg->getSourceRange();
7172 return ExprError();
7173 }
7174
7175 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7176 VD->getType()->isArrayType() &&
7177 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7178 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7179 if (ArgPE) {
7180 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7181 CanonicalConverted =
7182 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7183 } else {
7184 SugaredConverted = TemplateArgument(VD, ParamType);
7185 CanonicalConverted =
7186 TemplateArgument(cast<ValueDecl>(Val: VD->getCanonicalDecl()),
7187 ParamType.getCanonicalType());
7188 }
7189 return Arg;
7190 }
7191
7192 // -- a subobject [until C++20]
7193 if (!getLangOpts().CPlusPlus20) {
7194 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7195 Value.isLValueOnePastTheEnd()) {
7196 Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_subobject)
7197 << Value.getAsString(Ctx: Context, Ty: ParamType);
7198 return ExprError();
7199 }
7200 assert((VD || !ParamType->isReferenceType()) &&
7201 "null reference should not be a constant expression");
7202 assert((!VD || !ParamType->isNullPtrType()) &&
7203 "non-null value of type nullptr_t?");
7204 }
7205 }
7206
7207 if (Value.isAddrLabelDiff())
7208 return Diag(Loc: StartLoc, DiagID: diag::err_non_type_template_arg_addr_label_diff);
7209
7210 if (ArgPE) {
7211 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7212 CanonicalConverted =
7213 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7214 } else {
7215 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7216 CanonicalConverted =
7217 TemplateArgument(Context, ParamType.getCanonicalType(), Value);
7218 }
7219 return Arg;
7220 }
7221
7222 // C++ [temp.arg.nontype]p5:
7223 // The following conversions are performed on each expression used
7224 // as a non-type template-argument. If a non-type
7225 // template-argument cannot be converted to the type of the
7226 // corresponding template-parameter then the program is
7227 // ill-formed.
7228 if (ParamType->isIntegralOrEnumerationType()) {
7229 // C++11:
7230 // -- for a non-type template-parameter of integral or
7231 // enumeration type, conversions permitted in a converted
7232 // constant expression are applied.
7233 //
7234 // C++98:
7235 // -- for a non-type template-parameter of integral or
7236 // enumeration type, integral promotions (4.5) and integral
7237 // conversions (4.7) are applied.
7238
7239 if (getLangOpts().CPlusPlus11) {
7240 // C++ [temp.arg.nontype]p1:
7241 // A template-argument for a non-type, non-template template-parameter
7242 // shall be one of:
7243 //
7244 // -- for a non-type template-parameter of integral or enumeration
7245 // type, a converted constant expression of the type of the
7246 // template-parameter; or
7247 llvm::APSInt Value;
7248 ExprResult ArgResult = CheckConvertedConstantExpression(
7249 From: DeductionArg, T: ParamType, Value, CCE: CCEKind::TemplateArg);
7250 if (ArgResult.isInvalid())
7251 return ExprError();
7252 setDeductionArg(ArgResult.get());
7253
7254 // We can't check arbitrary value-dependent arguments.
7255 if (DeductionArg->isValueDependent()) {
7256 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7257 CanonicalConverted =
7258 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7259 return Arg;
7260 }
7261
7262 // Widen the argument value to sizeof(parameter type). This is almost
7263 // always a no-op, except when the parameter type is bool. In
7264 // that case, this may extend the argument from 1 bit to 8 bits.
7265 QualType IntegerType = ParamType;
7266 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
7267 IntegerType = Enum->getDecl()->getIntegerType();
7268 Value = Value.extOrTrunc(width: IntegerType->isBitIntType()
7269 ? Context.getIntWidth(T: IntegerType)
7270 : Context.getTypeSize(T: IntegerType));
7271
7272 if (ArgPE) {
7273 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7274 CanonicalConverted =
7275 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7276 } else {
7277 SugaredConverted = TemplateArgument(Context, Value, ParamType);
7278 CanonicalConverted = TemplateArgument(
7279 Context, Value, Context.getCanonicalType(T: ParamType));
7280 }
7281 return Arg;
7282 }
7283
7284 ExprResult ArgResult = DefaultLvalueConversion(E: Arg);
7285 if (ArgResult.isInvalid())
7286 return ExprError();
7287 DeductionArg = ArgResult.get();
7288
7289 QualType ArgType = DeductionArg->getType();
7290
7291 // C++ [temp.arg.nontype]p1:
7292 // A template-argument for a non-type, non-template
7293 // template-parameter shall be one of:
7294 //
7295 // -- an integral constant-expression of integral or enumeration
7296 // type; or
7297 // -- the name of a non-type template-parameter; or
7298 llvm::APSInt Value;
7299 if (!ArgType->isIntegralOrEnumerationType()) {
7300 Diag(Loc: StartLoc, DiagID: diag::err_template_arg_not_integral_or_enumeral)
7301 << ArgType << DeductionArg->getSourceRange();
7302 NoteTemplateParameterLocation(Decl: *Param);
7303 return ExprError();
7304 } else if (!DeductionArg->isValueDependent()) {
7305 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
7306 QualType T;
7307
7308 public:
7309 TmplArgICEDiagnoser(QualType T) : T(T) { }
7310
7311 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
7312 SourceLocation Loc) override {
7313 return S.Diag(Loc, DiagID: diag::err_template_arg_not_ice) << T;
7314 }
7315 } Diagnoser(ArgType);
7316
7317 DeductionArg =
7318 VerifyIntegerConstantExpression(E: DeductionArg, Result: &Value, Diagnoser)
7319 .get();
7320 if (!DeductionArg)
7321 return ExprError();
7322 }
7323
7324 // From here on out, all we care about is the unqualified form
7325 // of the argument type.
7326 ArgType = ArgType.getUnqualifiedType();
7327
7328 // Try to convert the argument to the parameter's type.
7329 if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
7330 // Okay: no conversion necessary
7331 } else if (ParamType->isBooleanType()) {
7332 // This is an integral-to-boolean conversion.
7333 DeductionArg =
7334 ImpCastExprToType(E: DeductionArg, Type: ParamType, CK: CK_IntegralToBoolean)
7335 .get();
7336 } else if (IsIntegralPromotion(From: Arg, FromType: ArgType, ToType: ParamType) ||
7337 !ParamType->isEnumeralType()) {
7338 // This is an integral promotion or conversion.
7339 DeductionArg =
7340 ImpCastExprToType(E: DeductionArg, Type: ParamType, CK: CK_IntegralCast).get();
7341 } else {
7342 // We can't perform this conversion.
7343 Diag(Loc: StartLoc, DiagID: diag::err_template_arg_not_convertible)
7344 << DeductionArg->getType() << ParamType
7345 << DeductionArg->getSourceRange();
7346 NoteTemplateParameterLocation(Decl: *Param);
7347 return ExprError();
7348 }
7349 setDeductionArg(DeductionArg);
7350
7351 // Add the value of this argument to the list of converted
7352 // arguments. We use the bitwidth and signedness of the template
7353 // parameter.
7354 if (DeductionArg->isValueDependent()) {
7355 // The argument is value-dependent. Create a new
7356 // TemplateArgument with the converted expression.
7357 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7358 CanonicalConverted =
7359 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7360 return Arg;
7361 }
7362
7363 QualType IntegerType = ParamType;
7364 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
7365 IntegerType = Enum->getDecl()->getIntegerType();
7366 }
7367
7368 if (ParamType->isBooleanType()) {
7369 // Value must be zero or one.
7370 Value = Value != 0;
7371 unsigned AllowedBits = Context.getTypeSize(T: IntegerType);
7372 if (Value.getBitWidth() != AllowedBits)
7373 Value = Value.extOrTrunc(width: AllowedBits);
7374 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7375 } else {
7376 llvm::APSInt OldValue = Value;
7377
7378 // Coerce the template argument's value to the value it will have
7379 // based on the template parameter's type.
7380 unsigned AllowedBits = IntegerType->isBitIntType()
7381 ? Context.getIntWidth(T: IntegerType)
7382 : Context.getTypeSize(T: IntegerType);
7383 if (Value.getBitWidth() != AllowedBits)
7384 Value = Value.extOrTrunc(width: AllowedBits);
7385 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
7386
7387 // Complain if an unsigned parameter received a negative value.
7388 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
7389 (OldValue.isSigned() && OldValue.isNegative())) {
7390 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_negative)
7391 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << Param->getType()
7392 << Arg->getSourceRange();
7393 NoteTemplateParameterLocation(Decl: *Param);
7394 }
7395
7396 // Complain if we overflowed the template parameter's type.
7397 unsigned RequiredBits;
7398 if (IntegerType->isUnsignedIntegerOrEnumerationType())
7399 RequiredBits = OldValue.getActiveBits();
7400 else if (OldValue.isUnsigned())
7401 RequiredBits = OldValue.getActiveBits() + 1;
7402 else
7403 RequiredBits = OldValue.getSignificantBits();
7404 if (RequiredBits > AllowedBits) {
7405 Diag(Loc: Arg->getBeginLoc(), DiagID: diag::warn_template_arg_too_large)
7406 << toString(I: OldValue, Radix: 10) << toString(I: Value, Radix: 10) << Param->getType()
7407 << Arg->getSourceRange();
7408 NoteTemplateParameterLocation(Decl: *Param);
7409 }
7410 }
7411
7412 if (ArgPE) {
7413 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7414 CanonicalConverted =
7415 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7416 } else {
7417 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
7418 SugaredConverted = TemplateArgument(Context, Value, T);
7419 CanonicalConverted =
7420 TemplateArgument(Context, Value, Context.getCanonicalType(T));
7421 }
7422 return Arg;
7423 }
7424
7425 QualType ArgType = DeductionArg->getType();
7426 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
7427
7428 // Handle pointer-to-function, reference-to-function, and
7429 // pointer-to-member-function all in (roughly) the same way.
7430 if (// -- For a non-type template-parameter of type pointer to
7431 // function, only the function-to-pointer conversion (4.3) is
7432 // applied. If the template-argument represents a set of
7433 // overloaded functions (or a pointer to such), the matching
7434 // function is selected from the set (13.4).
7435 (ParamType->isPointerType() &&
7436 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
7437 // -- For a non-type template-parameter of type reference to
7438 // function, no conversions apply. If the template-argument
7439 // represents a set of overloaded functions, the matching
7440 // function is selected from the set (13.4).
7441 (ParamType->isReferenceType() &&
7442 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
7443 // -- For a non-type template-parameter of type pointer to
7444 // member function, no conversions apply. If the
7445 // template-argument represents a set of overloaded member
7446 // functions, the matching member function is selected from
7447 // the set (13.4).
7448 (ParamType->isMemberPointerType() &&
7449 ParamType->castAs<MemberPointerType>()->getPointeeType()
7450 ->isFunctionType())) {
7451
7452 if (DeductionArg->getType() == Context.OverloadTy) {
7453 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg, TargetType: ParamType,
7454 Complain: true,
7455 Found&: FoundResult)) {
7456 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7457 return ExprError();
7458
7459 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7460 if (Res.isInvalid())
7461 return ExprError();
7462 DeductionArg = Res.get();
7463 ArgType = Arg->getType();
7464 } else
7465 return ExprError();
7466 }
7467 setDeductionArg(DeductionArg);
7468
7469 if (!ParamType->isMemberPointerType()) {
7470 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7471 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted,
7472 CanonicalConverted))
7473 return ExprError();
7474 return Arg;
7475 }
7476
7477 if (CheckTemplateArgumentPointerToMember(
7478 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7479 return ExprError();
7480 return Arg;
7481 }
7482
7483 setDeductionArg(DeductionArg);
7484
7485 if (ParamType->isPointerType()) {
7486 // -- for a non-type template-parameter of type pointer to
7487 // object, qualification conversions (4.4) and the
7488 // array-to-pointer conversion (4.2) are applied.
7489 // C++0x also allows a value of std::nullptr_t.
7490 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
7491 "Only object pointers allowed here");
7492
7493 // FIXME: Deal with pack expansions here.
7494 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7495 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted, CanonicalConverted))
7496 return ExprError();
7497 return Arg;
7498 }
7499
7500 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
7501 // -- For a non-type template-parameter of type reference to
7502 // object, no conversions apply. The type referred to by the
7503 // reference may be more cv-qualified than the (otherwise
7504 // identical) type of the template-argument. The
7505 // template-parameter is bound directly to the
7506 // template-argument, which must be an lvalue.
7507 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
7508 "Only object references allowed here");
7509
7510 // FIXME: Deal with pack expansions here.
7511 if (Arg->getType() == Context.OverloadTy) {
7512 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg,
7513 TargetType: ParamRefType->getPointeeType(),
7514 Complain: true,
7515 Found&: FoundResult)) {
7516 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
7517 return ExprError();
7518 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
7519 if (Res.isInvalid())
7520 return ExprError();
7521 Arg = Res.get();
7522 ArgType = Arg->getType();
7523 } else
7524 return ExprError();
7525 }
7526
7527 if (CheckTemplateArgumentAddressOfObjectOrFunction(
7528 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted, CanonicalConverted))
7529 return ExprError();
7530 return Arg;
7531 }
7532
7533 // Deal with parameters of type std::nullptr_t.
7534 if (ParamType->isNullPtrType()) {
7535 if (DeductionArg->isTypeDependent() || DeductionArg->isValueDependent()) {
7536 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7537 CanonicalConverted =
7538 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7539 return Arg;
7540 }
7541
7542 switch (isNullPointerValueTemplateArgument(S&: *this, Param, ParamType,
7543 Arg: DeductionArg)) {
7544 case NPV_NotNullPointer:
7545 Diag(Loc: Arg->getExprLoc(), DiagID: diag::err_template_arg_not_convertible)
7546 << DeductionArg->getType() << ParamType;
7547 NoteTemplateParameterLocation(Decl: *Param);
7548 return ExprError();
7549
7550 case NPV_Error:
7551 return ExprError();
7552
7553 case NPV_NullPointer:
7554 Diag(Loc: Arg->getExprLoc(), DiagID: diag::warn_cxx98_compat_template_arg_null);
7555 if (ArgPE) {
7556 SugaredConverted = TemplateArgument(Arg, /*IsCanonical=*/false);
7557 CanonicalConverted =
7558 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7559 } else {
7560 SugaredConverted = TemplateArgument(ParamType,
7561 /*isNullPtr=*/true);
7562 CanonicalConverted =
7563 TemplateArgument(Context.getCanonicalType(T: ParamType),
7564 /*isNullPtr=*/true);
7565 }
7566 return Arg;
7567 }
7568 }
7569
7570 // -- For a non-type template-parameter of type pointer to data
7571 // member, qualification conversions (4.4) are applied.
7572 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
7573
7574 // FIXME: Deal with pack expansions here.
7575 if (CheckTemplateArgumentPointerToMember(
7576 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
7577 return ExprError();
7578 return Arg;
7579}
7580
7581static void DiagnoseTemplateParameterListArityMismatch(
7582 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
7583 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
7584
7585bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
7586 TemplateParameterList *Params,
7587 TemplateArgumentLoc &Arg,
7588 bool PartialOrdering,
7589 bool *StrictPackMatch) {
7590 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
7591 auto [Template, DefaultArgs] = Name.getTemplateDeclAndDefaultArgs();
7592 if (!Template) {
7593 // Any dependent template name is fine.
7594 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
7595 return false;
7596 }
7597
7598 if (Template->isInvalidDecl())
7599 return true;
7600
7601 // C++0x [temp.arg.template]p1:
7602 // A template-argument for a template template-parameter shall be
7603 // the name of a class template or an alias template, expressed as an
7604 // id-expression. When the template-argument names a class template, only
7605 // primary class templates are considered when matching the
7606 // template template argument with the corresponding parameter;
7607 // partial specializations are not considered even if their
7608 // parameter lists match that of the template template parameter.
7609 //
7610 // Note that we also allow template template parameters here, which
7611 // will happen when we are dealing with, e.g., class template
7612 // partial specializations.
7613 if (!isa<ClassTemplateDecl>(Val: Template) &&
7614 !isa<TemplateTemplateParmDecl>(Val: Template) &&
7615 !isa<TypeAliasTemplateDecl>(Val: Template) &&
7616 !isa<BuiltinTemplateDecl>(Val: Template)) {
7617 assert(isa<FunctionTemplateDecl>(Template) &&
7618 "Only function templates are possible here");
7619 Diag(Loc: Arg.getLocation(), DiagID: diag::err_template_arg_not_valid_template);
7620 Diag(Loc: Template->getLocation(), DiagID: diag::note_template_arg_refers_here_func)
7621 << Template;
7622 }
7623
7624 // C++1z [temp.arg.template]p3: (DR 150)
7625 // A template-argument matches a template template-parameter P when P
7626 // is at least as specialized as the template-argument A.
7627 if (!isTemplateTemplateParameterAtLeastAsSpecializedAs(
7628 PParam: Params, PArg: Param, AArg: Template, DefaultArgs, ArgLoc: Arg.getLocation(),
7629 PartialOrdering, StrictPackMatch))
7630 return true;
7631 // P2113
7632 // C++20[temp.func.order]p2
7633 // [...] If both deductions succeed, the partial ordering selects the
7634 // more constrained template (if one exists) as determined below.
7635 SmallVector<AssociatedConstraint, 3> ParamsAC, TemplateAC;
7636 Params->getAssociatedConstraints(AC&: ParamsAC);
7637 // C++20[temp.arg.template]p3
7638 // [...] In this comparison, if P is unconstrained, the constraints on A
7639 // are not considered.
7640 if (ParamsAC.empty())
7641 return false;
7642
7643 Template->getAssociatedConstraints(AC&: TemplateAC);
7644
7645 bool IsParamAtLeastAsConstrained;
7646 if (IsAtLeastAsConstrained(D1: Param, AC1: ParamsAC, D2: Template, AC2: TemplateAC,
7647 Result&: IsParamAtLeastAsConstrained))
7648 return true;
7649 if (!IsParamAtLeastAsConstrained) {
7650 Diag(Loc: Arg.getLocation(),
7651 DiagID: diag::err_template_template_parameter_not_at_least_as_constrained)
7652 << Template << Param << Arg.getSourceRange();
7653 Diag(Loc: Param->getLocation(), DiagID: diag::note_entity_declared_at) << Param;
7654 Diag(Loc: Template->getLocation(), DiagID: diag::note_entity_declared_at) << Template;
7655 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Param, AC1: ParamsAC, D2: Template,
7656 AC2: TemplateAC);
7657 return true;
7658 }
7659 return false;
7660}
7661
7662static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
7663 unsigned HereDiagID,
7664 unsigned ExternalDiagID) {
7665 if (Decl.getLocation().isValid())
7666 return S.Diag(Loc: Decl.getLocation(), DiagID: HereDiagID);
7667
7668 SmallString<128> Str;
7669 llvm::raw_svector_ostream Out(Str);
7670 PrintingPolicy PP = S.getPrintingPolicy();
7671 PP.TerseOutput = 1;
7672 Decl.print(Out, Policy: PP);
7673 return S.Diag(Loc: Decl.getLocation(), DiagID: ExternalDiagID) << Out.str();
7674}
7675
7676void Sema::NoteTemplateLocation(const NamedDecl &Decl,
7677 std::optional<SourceRange> ParamRange) {
7678 SemaDiagnosticBuilder DB =
7679 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_decl_here,
7680 ExternalDiagID: diag::note_template_decl_external);
7681 if (ParamRange && ParamRange->isValid()) {
7682 assert(Decl.getLocation().isValid() &&
7683 "Parameter range has location when Decl does not");
7684 DB << *ParamRange;
7685 }
7686}
7687
7688void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
7689 noteLocation(S&: *this, Decl, HereDiagID: diag::note_template_param_here,
7690 ExternalDiagID: diag::note_template_param_external);
7691}
7692
7693ExprResult Sema::BuildExpressionFromDeclTemplateArgument(
7694 const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc,
7695 NamedDecl *TemplateParam) {
7696 // C++ [temp.param]p8:
7697 //
7698 // A non-type template-parameter of type "array of T" or
7699 // "function returning T" is adjusted to be of type "pointer to
7700 // T" or "pointer to function returning T", respectively.
7701 if (ParamType->isArrayType())
7702 ParamType = Context.getArrayDecayedType(T: ParamType);
7703 else if (ParamType->isFunctionType())
7704 ParamType = Context.getPointerType(T: ParamType);
7705
7706 // For a NULL non-type template argument, return nullptr casted to the
7707 // parameter's type.
7708 if (Arg.getKind() == TemplateArgument::NullPtr) {
7709 return ImpCastExprToType(
7710 E: new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
7711 Type: ParamType,
7712 CK: ParamType->getAs<MemberPointerType>()
7713 ? CK_NullToMemberPointer
7714 : CK_NullToPointer);
7715 }
7716 assert(Arg.getKind() == TemplateArgument::Declaration &&
7717 "Only declaration template arguments permitted here");
7718
7719 ValueDecl *VD = Arg.getAsDecl();
7720
7721 CXXScopeSpec SS;
7722 if (ParamType->isMemberPointerType()) {
7723 // If this is a pointer to member, we need to use a qualified name to
7724 // form a suitable pointer-to-member constant.
7725 assert(VD->getDeclContext()->isRecord() &&
7726 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
7727 isa<IndirectFieldDecl>(VD)));
7728 QualType ClassType
7729 = Context.getTypeDeclType(Decl: cast<RecordDecl>(Val: VD->getDeclContext()));
7730 NestedNameSpecifier *Qualifier =
7731 NestedNameSpecifier::Create(Context, Prefix: nullptr, T: ClassType.getTypePtr());
7732 SS.MakeTrivial(Context, Qualifier, R: Loc);
7733 }
7734
7735 ExprResult RefExpr = BuildDeclarationNameExpr(
7736 SS, NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
7737 if (RefExpr.isInvalid())
7738 return ExprError();
7739
7740 // For a pointer, the argument declaration is the pointee. Take its address.
7741 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
7742 if (ParamType->isPointerType() && !ElemT.isNull() &&
7743 Context.hasSimilarType(T1: ElemT, T2: ParamType->getPointeeType())) {
7744 // Decay an array argument if we want a pointer to its first element.
7745 RefExpr = DefaultFunctionArrayConversion(E: RefExpr.get());
7746 if (RefExpr.isInvalid())
7747 return ExprError();
7748 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
7749 // For any other pointer, take the address (or form a pointer-to-member).
7750 RefExpr = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_AddrOf, InputExpr: RefExpr.get());
7751 if (RefExpr.isInvalid())
7752 return ExprError();
7753 } else if (ParamType->isRecordType()) {
7754 assert(isa<TemplateParamObjectDecl>(VD) &&
7755 "arg for class template param not a template parameter object");
7756 // No conversions apply in this case.
7757 return RefExpr;
7758 } else {
7759 assert(ParamType->isReferenceType() &&
7760 "unexpected type for decl template argument");
7761 if (NonTypeTemplateParmDecl *NTTP =
7762 dyn_cast_if_present<NonTypeTemplateParmDecl>(Val: TemplateParam)) {
7763 QualType TemplateParamType = NTTP->getType();
7764 const AutoType *AT = TemplateParamType->getAs<AutoType>();
7765 if (AT && AT->isDecltypeAuto()) {
7766 RefExpr = new (getASTContext()) SubstNonTypeTemplateParmExpr(
7767 ParamType->getPointeeType(), RefExpr.get()->getValueKind(),
7768 RefExpr.get()->getExprLoc(), RefExpr.get(), VD, NTTP->getIndex(),
7769 /*PackIndex=*/std::nullopt,
7770 /*RefParam=*/true, /*Final=*/true);
7771 }
7772 }
7773 }
7774
7775 // At this point we should have the right value category.
7776 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
7777 "value kind mismatch for non-type template argument");
7778
7779 // The type of the template parameter can differ from the type of the
7780 // argument in various ways; convert it now if necessary.
7781 QualType DestExprType = ParamType.getNonLValueExprType(Context);
7782 if (!Context.hasSameType(T1: RefExpr.get()->getType(), T2: DestExprType)) {
7783 CastKind CK;
7784 if (Context.hasSimilarType(T1: RefExpr.get()->getType(), T2: DestExprType) ||
7785 IsFunctionConversion(FromType: RefExpr.get()->getType(), ToType: DestExprType)) {
7786 CK = CK_NoOp;
7787 } else if (ParamType->isVoidPointerType() &&
7788 RefExpr.get()->getType()->isPointerType()) {
7789 CK = CK_BitCast;
7790 } else {
7791 // FIXME: Pointers to members can need conversion derived-to-base or
7792 // base-to-derived conversions. We currently don't retain enough
7793 // information to convert properly (we need to track a cast path or
7794 // subobject number in the template argument).
7795 llvm_unreachable(
7796 "unexpected conversion required for non-type template argument");
7797 }
7798 RefExpr = ImpCastExprToType(E: RefExpr.get(), Type: DestExprType, CK,
7799 VK: RefExpr.get()->getValueKind());
7800 }
7801
7802 return RefExpr;
7803}
7804
7805/// Construct a new expression that refers to the given
7806/// integral template argument with the given source-location
7807/// information.
7808///
7809/// This routine takes care of the mapping from an integral template
7810/// argument (which may have any integral type) to the appropriate
7811/// literal value.
7812static Expr *BuildExpressionFromIntegralTemplateArgumentValue(
7813 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
7814 assert(OrigT->isIntegralOrEnumerationType());
7815
7816 // If this is an enum type that we're instantiating, we need to use an integer
7817 // type the same size as the enumerator. We don't want to build an
7818 // IntegerLiteral with enum type. The integer type of an enum type can be of
7819 // any integral type with C++11 enum classes, make sure we create the right
7820 // type of literal for it.
7821 QualType T = OrigT;
7822 if (const EnumType *ET = OrigT->getAs<EnumType>())
7823 T = ET->getDecl()->getIntegerType();
7824
7825 Expr *E;
7826 if (T->isAnyCharacterType()) {
7827 CharacterLiteralKind Kind;
7828 if (T->isWideCharType())
7829 Kind = CharacterLiteralKind::Wide;
7830 else if (T->isChar8Type() && S.getLangOpts().Char8)
7831 Kind = CharacterLiteralKind::UTF8;
7832 else if (T->isChar16Type())
7833 Kind = CharacterLiteralKind::UTF16;
7834 else if (T->isChar32Type())
7835 Kind = CharacterLiteralKind::UTF32;
7836 else
7837 Kind = CharacterLiteralKind::Ascii;
7838
7839 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
7840 } else if (T->isBooleanType()) {
7841 E = CXXBoolLiteralExpr::Create(C: S.Context, Val: Int.getBoolValue(), Ty: T, Loc);
7842 } else {
7843 E = IntegerLiteral::Create(C: S.Context, V: Int, type: T, l: Loc);
7844 }
7845
7846 if (OrigT->isEnumeralType()) {
7847 // FIXME: This is a hack. We need a better way to handle substituted
7848 // non-type template parameters.
7849 E = CStyleCastExpr::Create(Context: S.Context, T: OrigT, VK: VK_PRValue, K: CK_IntegralCast, Op: E,
7850 BasePath: nullptr, FPO: S.CurFPFeatureOverrides(),
7851 WrittenTy: S.Context.getTrivialTypeSourceInfo(T: OrigT, Loc),
7852 L: Loc, R: Loc);
7853 }
7854
7855 return E;
7856}
7857
7858static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(
7859 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
7860 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
7861 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
7862 ILE->setType(T);
7863 return ILE;
7864 };
7865
7866 switch (Val.getKind()) {
7867 case APValue::AddrLabelDiff:
7868 // This cannot occur in a template argument at all.
7869 case APValue::Array:
7870 case APValue::Struct:
7871 case APValue::Union:
7872 // These can only occur within a template parameter object, which is
7873 // represented as a TemplateArgument::Declaration.
7874 llvm_unreachable("unexpected template argument value");
7875
7876 case APValue::Int:
7877 return BuildExpressionFromIntegralTemplateArgumentValue(S, OrigT: T, Int: Val.getInt(),
7878 Loc);
7879
7880 case APValue::Float:
7881 return FloatingLiteral::Create(C: S.Context, V: Val.getFloat(), /*IsExact=*/isexact: true,
7882 Type: T, L: Loc);
7883
7884 case APValue::FixedPoint:
7885 return FixedPointLiteral::CreateFromRawInt(
7886 C: S.Context, V: Val.getFixedPoint().getValue(), type: T, l: Loc,
7887 Scale: Val.getFixedPoint().getScale());
7888
7889 case APValue::ComplexInt: {
7890 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7891 return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(
7892 S, OrigT: ElemT, Int: Val.getComplexIntReal(), Loc),
7893 BuildExpressionFromIntegralTemplateArgumentValue(
7894 S, OrigT: ElemT, Int: Val.getComplexIntImag(), Loc)});
7895 }
7896
7897 case APValue::ComplexFloat: {
7898 QualType ElemT = T->castAs<ComplexType>()->getElementType();
7899 return MakeInitList(
7900 {FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatReal(), isexact: true,
7901 Type: ElemT, L: Loc),
7902 FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatImag(), isexact: true,
7903 Type: ElemT, L: Loc)});
7904 }
7905
7906 case APValue::Vector: {
7907 QualType ElemT = T->castAs<VectorType>()->getElementType();
7908 llvm::SmallVector<Expr *, 8> Elts;
7909 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
7910 Elts.push_back(Elt: BuildExpressionFromNonTypeTemplateArgumentValue(
7911 S, T: ElemT, Val: Val.getVectorElt(I), Loc));
7912 return MakeInitList(Elts);
7913 }
7914
7915 case APValue::None:
7916 case APValue::Indeterminate:
7917 llvm_unreachable("Unexpected APValue kind.");
7918 case APValue::LValue:
7919 case APValue::MemberPointer:
7920 // There isn't necessarily a valid equivalent source-level syntax for
7921 // these; in particular, a naive lowering might violate access control.
7922 // So for now we lower to a ConstantExpr holding the value, wrapped around
7923 // an OpaqueValueExpr.
7924 // FIXME: We should have a better representation for this.
7925 ExprValueKind VK = VK_PRValue;
7926 if (T->isReferenceType()) {
7927 T = T->getPointeeType();
7928 VK = VK_LValue;
7929 }
7930 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
7931 return ConstantExpr::Create(Context: S.Context, E: OVE, Result: Val);
7932 }
7933 llvm_unreachable("Unhandled APValue::ValueKind enum");
7934}
7935
7936ExprResult
7937Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
7938 SourceLocation Loc) {
7939 switch (Arg.getKind()) {
7940 case TemplateArgument::Null:
7941 case TemplateArgument::Type:
7942 case TemplateArgument::Template:
7943 case TemplateArgument::TemplateExpansion:
7944 case TemplateArgument::Pack:
7945 llvm_unreachable("not a non-type template argument");
7946
7947 case TemplateArgument::Expression:
7948 return Arg.getAsExpr();
7949
7950 case TemplateArgument::NullPtr:
7951 case TemplateArgument::Declaration:
7952 return BuildExpressionFromDeclTemplateArgument(
7953 Arg, ParamType: Arg.getNonTypeTemplateArgumentType(), Loc);
7954
7955 case TemplateArgument::Integral:
7956 return BuildExpressionFromIntegralTemplateArgumentValue(
7957 S&: *this, OrigT: Arg.getIntegralType(), Int: Arg.getAsIntegral(), Loc);
7958
7959 case TemplateArgument::StructuralValue:
7960 return BuildExpressionFromNonTypeTemplateArgumentValue(
7961 S&: *this, T: Arg.getStructuralValueType(), Val: Arg.getAsStructuralValue(), Loc);
7962 }
7963 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
7964}
7965
7966/// Match two template parameters within template parameter lists.
7967static bool MatchTemplateParameterKind(
7968 Sema &S, NamedDecl *New,
7969 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
7970 const NamedDecl *OldInstFrom, bool Complain,
7971 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
7972 // Check the actual kind (type, non-type, template).
7973 if (Old->getKind() != New->getKind()) {
7974 if (Complain) {
7975 unsigned NextDiag = diag::err_template_param_different_kind;
7976 if (TemplateArgLoc.isValid()) {
7977 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
7978 NextDiag = diag::note_template_param_different_kind;
7979 }
7980 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
7981 << (Kind != Sema::TPL_TemplateMatch);
7982 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_prev_declaration)
7983 << (Kind != Sema::TPL_TemplateMatch);
7984 }
7985
7986 return false;
7987 }
7988
7989 // Check that both are parameter packs or neither are parameter packs.
7990 // However, if we are matching a template template argument to a
7991 // template template parameter, the template template parameter can have
7992 // a parameter pack where the template template argument does not.
7993 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack()) {
7994 if (Complain) {
7995 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
7996 if (TemplateArgLoc.isValid()) {
7997 S.Diag(Loc: TemplateArgLoc,
7998 DiagID: diag::err_template_arg_template_params_mismatch);
7999 NextDiag = diag::note_template_parameter_pack_non_pack;
8000 }
8001
8002 unsigned ParamKind = isa<TemplateTypeParmDecl>(Val: New)? 0
8003 : isa<NonTypeTemplateParmDecl>(Val: New)? 1
8004 : 2;
8005 S.Diag(Loc: New->getLocation(), DiagID: NextDiag)
8006 << ParamKind << New->isParameterPack();
8007 S.Diag(Loc: Old->getLocation(), DiagID: diag::note_template_parameter_pack_here)
8008 << ParamKind << Old->isParameterPack();
8009 }
8010
8011 return false;
8012 }
8013
8014 // For non-type template parameters, check the type of the parameter.
8015 if (NonTypeTemplateParmDecl *OldNTTP
8016 = dyn_cast<NonTypeTemplateParmDecl>(Val: Old)) {
8017 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(Val: New);
8018
8019 // C++20 [temp.over.link]p6:
8020 // Two [non-type] template-parameters are equivalent [if] they have
8021 // equivalent types ignoring the use of type-constraints for
8022 // placeholder types
8023 QualType OldType = S.Context.getUnconstrainedType(T: OldNTTP->getType());
8024 QualType NewType = S.Context.getUnconstrainedType(T: NewNTTP->getType());
8025 if (!S.Context.hasSameType(T1: OldType, T2: NewType)) {
8026 if (Complain) {
8027 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8028 if (TemplateArgLoc.isValid()) {
8029 S.Diag(Loc: TemplateArgLoc,
8030 DiagID: diag::err_template_arg_template_params_mismatch);
8031 NextDiag = diag::note_template_nontype_parm_different_type;
8032 }
8033 S.Diag(Loc: NewNTTP->getLocation(), DiagID: NextDiag)
8034 << NewNTTP->getType() << (Kind != Sema::TPL_TemplateMatch);
8035 S.Diag(Loc: OldNTTP->getLocation(),
8036 DiagID: diag::note_template_nontype_parm_prev_declaration)
8037 << OldNTTP->getType();
8038 }
8039
8040 return false;
8041 }
8042 }
8043 // For template template parameters, check the template parameter types.
8044 // The template parameter lists of template template
8045 // parameters must agree.
8046 else if (TemplateTemplateParmDecl *OldTTP =
8047 dyn_cast<TemplateTemplateParmDecl>(Val: Old)) {
8048 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(Val: New);
8049 if (!S.TemplateParameterListsAreEqual(
8050 NewInstFrom, New: NewTTP->getTemplateParameters(), OldInstFrom,
8051 Old: OldTTP->getTemplateParameters(), Complain,
8052 Kind: (Kind == Sema::TPL_TemplateMatch
8053 ? Sema::TPL_TemplateTemplateParmMatch
8054 : Kind),
8055 TemplateArgLoc))
8056 return false;
8057 }
8058
8059 if (Kind != Sema::TPL_TemplateParamsEquivalent &&
8060 !isa<TemplateTemplateParmDecl>(Val: Old)) {
8061 const Expr *NewC = nullptr, *OldC = nullptr;
8062
8063 if (isa<TemplateTypeParmDecl>(Val: New)) {
8064 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: New)->getTypeConstraint())
8065 NewC = TC->getImmediatelyDeclaredConstraint();
8066 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: Old)->getTypeConstraint())
8067 OldC = TC->getImmediatelyDeclaredConstraint();
8068 } else if (isa<NonTypeTemplateParmDecl>(Val: New)) {
8069 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: New)
8070 ->getPlaceholderTypeConstraint())
8071 NewC = E;
8072 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: Old)
8073 ->getPlaceholderTypeConstraint())
8074 OldC = E;
8075 } else
8076 llvm_unreachable("unexpected template parameter type");
8077
8078 auto Diagnose = [&] {
8079 S.Diag(Loc: NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8080 DiagID: diag::err_template_different_type_constraint);
8081 S.Diag(Loc: OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8082 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8083 };
8084
8085 if (!NewC != !OldC) {
8086 if (Complain)
8087 Diagnose();
8088 return false;
8089 }
8090
8091 if (NewC) {
8092 if (!S.AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldC, New: NewInstFrom,
8093 NewConstr: NewC)) {
8094 if (Complain)
8095 Diagnose();
8096 return false;
8097 }
8098 }
8099 }
8100
8101 return true;
8102}
8103
8104/// Diagnose a known arity mismatch when comparing template argument
8105/// lists.
8106static
8107void DiagnoseTemplateParameterListArityMismatch(Sema &S,
8108 TemplateParameterList *New,
8109 TemplateParameterList *Old,
8110 Sema::TemplateParameterListEqualKind Kind,
8111 SourceLocation TemplateArgLoc) {
8112 unsigned NextDiag = diag::err_template_param_list_different_arity;
8113 if (TemplateArgLoc.isValid()) {
8114 S.Diag(Loc: TemplateArgLoc, DiagID: diag::err_template_arg_template_params_mismatch);
8115 NextDiag = diag::note_template_param_list_different_arity;
8116 }
8117 S.Diag(Loc: New->getTemplateLoc(), DiagID: NextDiag)
8118 << (New->size() > Old->size())
8119 << (Kind != Sema::TPL_TemplateMatch)
8120 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8121 S.Diag(Loc: Old->getTemplateLoc(), DiagID: diag::note_template_prev_declaration)
8122 << (Kind != Sema::TPL_TemplateMatch)
8123 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8124}
8125
8126bool Sema::TemplateParameterListsAreEqual(
8127 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8128 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8129 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8130 if (Old->size() != New->size()) {
8131 if (Complain)
8132 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8133 TemplateArgLoc);
8134
8135 return false;
8136 }
8137
8138 // C++0x [temp.arg.template]p3:
8139 // A template-argument matches a template template-parameter (call it P)
8140 // when each of the template parameters in the template-parameter-list of
8141 // the template-argument's corresponding class template or alias template
8142 // (call it A) matches the corresponding template parameter in the
8143 // template-parameter-list of P. [...]
8144 TemplateParameterList::iterator NewParm = New->begin();
8145 TemplateParameterList::iterator NewParmEnd = New->end();
8146 for (TemplateParameterList::iterator OldParm = Old->begin(),
8147 OldParmEnd = Old->end();
8148 OldParm != OldParmEnd; ++OldParm, ++NewParm) {
8149 if (NewParm == NewParmEnd) {
8150 if (Complain)
8151 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8152 TemplateArgLoc);
8153 return false;
8154 }
8155 if (!MatchTemplateParameterKind(S&: *this, New: *NewParm, NewInstFrom, Old: *OldParm,
8156 OldInstFrom, Complain, Kind,
8157 TemplateArgLoc))
8158 return false;
8159 }
8160
8161 // Make sure we exhausted all of the arguments.
8162 if (NewParm != NewParmEnd) {
8163 if (Complain)
8164 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8165 TemplateArgLoc);
8166
8167 return false;
8168 }
8169
8170 if (Kind != TPL_TemplateParamsEquivalent) {
8171 const Expr *NewRC = New->getRequiresClause();
8172 const Expr *OldRC = Old->getRequiresClause();
8173
8174 auto Diagnose = [&] {
8175 Diag(Loc: NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8176 DiagID: diag::err_template_different_requires_clause);
8177 Diag(Loc: OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8178 DiagID: diag::note_template_prev_declaration) << /*declaration*/0;
8179 };
8180
8181 if (!NewRC != !OldRC) {
8182 if (Complain)
8183 Diagnose();
8184 return false;
8185 }
8186
8187 if (NewRC) {
8188 if (!AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldRC, New: NewInstFrom,
8189 NewConstr: NewRC)) {
8190 if (Complain)
8191 Diagnose();
8192 return false;
8193 }
8194 }
8195 }
8196
8197 return true;
8198}
8199
8200bool
8201Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
8202 if (!S)
8203 return false;
8204
8205 // Find the nearest enclosing declaration scope.
8206 S = S->getDeclParent();
8207
8208 // C++ [temp.pre]p6: [P2096]
8209 // A template, explicit specialization, or partial specialization shall not
8210 // have C linkage.
8211 DeclContext *Ctx = S->getEntity();
8212 if (Ctx && Ctx->isExternCContext()) {
8213 SourceRange Range =
8214 TemplateParams->getTemplateLoc().isInvalid() && TemplateParams->size()
8215 ? TemplateParams->getParam(Idx: 0)->getSourceRange()
8216 : TemplateParams->getSourceRange();
8217 Diag(Loc: Range.getBegin(), DiagID: diag::err_template_linkage) << Range;
8218 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
8219 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
8220 return true;
8221 }
8222 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
8223
8224 // C++ [temp]p2:
8225 // A template-declaration can appear only as a namespace scope or
8226 // class scope declaration.
8227 // C++ [temp.expl.spec]p3:
8228 // An explicit specialization may be declared in any scope in which the
8229 // corresponding primary template may be defined.
8230 // C++ [temp.class.spec]p6: [P2096]
8231 // A partial specialization may be declared in any scope in which the
8232 // corresponding primary template may be defined.
8233 if (Ctx) {
8234 if (Ctx->isFileContext())
8235 return false;
8236 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Ctx)) {
8237 // C++ [temp.mem]p2:
8238 // A local class shall not have member templates.
8239 if (RD->isLocalClass())
8240 return Diag(Loc: TemplateParams->getTemplateLoc(),
8241 DiagID: diag::err_template_inside_local_class)
8242 << TemplateParams->getSourceRange();
8243 else
8244 return false;
8245 }
8246 }
8247
8248 return Diag(Loc: TemplateParams->getTemplateLoc(),
8249 DiagID: diag::err_template_outside_namespace_or_class_scope)
8250 << TemplateParams->getSourceRange();
8251}
8252
8253/// Determine what kind of template specialization the given declaration
8254/// is.
8255static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
8256 if (!D)
8257 return TSK_Undeclared;
8258
8259 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D))
8260 return Record->getTemplateSpecializationKind();
8261 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D))
8262 return Function->getTemplateSpecializationKind();
8263 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D))
8264 return Var->getTemplateSpecializationKind();
8265
8266 return TSK_Undeclared;
8267}
8268
8269/// Check whether a specialization is well-formed in the current
8270/// context.
8271///
8272/// This routine determines whether a template specialization can be declared
8273/// in the current context (C++ [temp.expl.spec]p2).
8274///
8275/// \param S the semantic analysis object for which this check is being
8276/// performed.
8277///
8278/// \param Specialized the entity being specialized or instantiated, which
8279/// may be a kind of template (class template, function template, etc.) or
8280/// a member of a class template (member function, static data member,
8281/// member class).
8282///
8283/// \param PrevDecl the previous declaration of this entity, if any.
8284///
8285/// \param Loc the location of the explicit specialization or instantiation of
8286/// this entity.
8287///
8288/// \param IsPartialSpecialization whether this is a partial specialization of
8289/// a class template.
8290///
8291/// \returns true if there was an error that we cannot recover from, false
8292/// otherwise.
8293static bool CheckTemplateSpecializationScope(Sema &S,
8294 NamedDecl *Specialized,
8295 NamedDecl *PrevDecl,
8296 SourceLocation Loc,
8297 bool IsPartialSpecialization) {
8298 // Keep these "kind" numbers in sync with the %select statements in the
8299 // various diagnostics emitted by this routine.
8300 int EntityKind = 0;
8301 if (isa<ClassTemplateDecl>(Val: Specialized))
8302 EntityKind = IsPartialSpecialization? 1 : 0;
8303 else if (isa<VarTemplateDecl>(Val: Specialized))
8304 EntityKind = IsPartialSpecialization ? 3 : 2;
8305 else if (isa<FunctionTemplateDecl>(Val: Specialized))
8306 EntityKind = 4;
8307 else if (isa<CXXMethodDecl>(Val: Specialized))
8308 EntityKind = 5;
8309 else if (isa<VarDecl>(Val: Specialized))
8310 EntityKind = 6;
8311 else if (isa<RecordDecl>(Val: Specialized))
8312 EntityKind = 7;
8313 else if (isa<EnumDecl>(Val: Specialized) && S.getLangOpts().CPlusPlus11)
8314 EntityKind = 8;
8315 else {
8316 S.Diag(Loc, DiagID: diag::err_template_spec_unknown_kind)
8317 << S.getLangOpts().CPlusPlus11;
8318 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8319 return true;
8320 }
8321
8322 // C++ [temp.expl.spec]p2:
8323 // An explicit specialization may be declared in any scope in which
8324 // the corresponding primary template may be defined.
8325 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8326 S.Diag(Loc, DiagID: diag::err_template_spec_decl_function_scope)
8327 << Specialized;
8328 return true;
8329 }
8330
8331 // C++ [temp.class.spec]p6:
8332 // A class template partial specialization may be declared in any
8333 // scope in which the primary template may be defined.
8334 DeclContext *SpecializedContext =
8335 Specialized->getDeclContext()->getRedeclContext();
8336 DeclContext *DC = S.CurContext->getRedeclContext();
8337
8338 // Make sure that this redeclaration (or definition) occurs in the same
8339 // scope or an enclosing namespace.
8340 if (!(DC->isFileContext() ? DC->Encloses(DC: SpecializedContext)
8341 : DC->Equals(DC: SpecializedContext))) {
8342 if (isa<TranslationUnitDecl>(Val: SpecializedContext))
8343 S.Diag(Loc, DiagID: diag::err_template_spec_redecl_global_scope)
8344 << EntityKind << Specialized;
8345 else {
8346 auto *ND = cast<NamedDecl>(Val: SpecializedContext);
8347 int Diag = diag::err_template_spec_redecl_out_of_scope;
8348 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
8349 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
8350 S.Diag(Loc, DiagID: Diag) << EntityKind << Specialized
8351 << ND << isa<CXXRecordDecl>(Val: ND);
8352 }
8353
8354 S.Diag(Loc: Specialized->getLocation(), DiagID: diag::note_specialized_entity);
8355
8356 // Don't allow specializing in the wrong class during error recovery.
8357 // Otherwise, things can go horribly wrong.
8358 if (DC->isRecord())
8359 return true;
8360 }
8361
8362 return false;
8363}
8364
8365static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
8366 if (!E->isTypeDependent())
8367 return SourceLocation();
8368 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8369 Checker.TraverseStmt(S: E);
8370 if (Checker.MatchLoc.isInvalid())
8371 return E->getSourceRange();
8372 return Checker.MatchLoc;
8373}
8374
8375static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
8376 if (!TL.getType()->isDependentType())
8377 return SourceLocation();
8378 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
8379 Checker.TraverseTypeLoc(TL);
8380 if (Checker.MatchLoc.isInvalid())
8381 return TL.getSourceRange();
8382 return Checker.MatchLoc;
8383}
8384
8385/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
8386/// that checks non-type template partial specialization arguments.
8387static bool CheckNonTypeTemplatePartialSpecializationArgs(
8388 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
8389 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
8390 for (unsigned I = 0; I != NumArgs; ++I) {
8391 if (Args[I].getKind() == TemplateArgument::Pack) {
8392 if (CheckNonTypeTemplatePartialSpecializationArgs(
8393 S, TemplateNameLoc, Param, Args: Args[I].pack_begin(),
8394 NumArgs: Args[I].pack_size(), IsDefaultArgument))
8395 return true;
8396
8397 continue;
8398 }
8399
8400 if (Args[I].getKind() != TemplateArgument::Expression)
8401 continue;
8402
8403 Expr *ArgExpr = Args[I].getAsExpr();
8404
8405 // We can have a pack expansion of any of the bullets below.
8406 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Val: ArgExpr))
8407 ArgExpr = Expansion->getPattern();
8408
8409 // Strip off any implicit casts we added as part of type checking.
8410 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
8411 ArgExpr = ICE->getSubExpr();
8412
8413 // C++ [temp.class.spec]p8:
8414 // A non-type argument is non-specialized if it is the name of a
8415 // non-type parameter. All other non-type arguments are
8416 // specialized.
8417 //
8418 // Below, we check the two conditions that only apply to
8419 // specialized non-type arguments, so skip any non-specialized
8420 // arguments.
8421 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ArgExpr))
8422 if (isa<NonTypeTemplateParmDecl>(Val: DRE->getDecl()))
8423 continue;
8424
8425 // C++ [temp.class.spec]p9:
8426 // Within the argument list of a class template partial
8427 // specialization, the following restrictions apply:
8428 // -- A partially specialized non-type argument expression
8429 // shall not involve a template parameter of the partial
8430 // specialization except when the argument expression is a
8431 // simple identifier.
8432 // -- The type of a template parameter corresponding to a
8433 // specialized non-type argument shall not be dependent on a
8434 // parameter of the specialization.
8435 // DR1315 removes the first bullet, leaving an incoherent set of rules.
8436 // We implement a compromise between the original rules and DR1315:
8437 // -- A specialized non-type template argument shall not be
8438 // type-dependent and the corresponding template parameter
8439 // shall have a non-dependent type.
8440 SourceRange ParamUseRange =
8441 findTemplateParameterInType(Depth: Param->getDepth(), E: ArgExpr);
8442 if (ParamUseRange.isValid()) {
8443 if (IsDefaultArgument) {
8444 S.Diag(Loc: TemplateNameLoc,
8445 DiagID: diag::err_dependent_non_type_arg_in_partial_spec);
8446 S.Diag(Loc: ParamUseRange.getBegin(),
8447 DiagID: diag::note_dependent_non_type_default_arg_in_partial_spec)
8448 << ParamUseRange;
8449 } else {
8450 S.Diag(Loc: ParamUseRange.getBegin(),
8451 DiagID: diag::err_dependent_non_type_arg_in_partial_spec)
8452 << ParamUseRange;
8453 }
8454 return true;
8455 }
8456
8457 ParamUseRange = findTemplateParameter(
8458 Depth: Param->getDepth(), TL: Param->getTypeSourceInfo()->getTypeLoc());
8459 if (ParamUseRange.isValid()) {
8460 S.Diag(Loc: IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
8461 DiagID: diag::err_dependent_typed_non_type_arg_in_partial_spec)
8462 << Param->getType();
8463 S.NoteTemplateParameterLocation(Decl: *Param);
8464 return true;
8465 }
8466 }
8467
8468 return false;
8469}
8470
8471bool Sema::CheckTemplatePartialSpecializationArgs(
8472 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
8473 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
8474 // We have to be conservative when checking a template in a dependent
8475 // context.
8476 if (PrimaryTemplate->getDeclContext()->isDependentContext())
8477 return false;
8478
8479 TemplateParameterList *TemplateParams =
8480 PrimaryTemplate->getTemplateParameters();
8481 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8482 NonTypeTemplateParmDecl *Param
8483 = dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: I));
8484 if (!Param)
8485 continue;
8486
8487 if (CheckNonTypeTemplatePartialSpecializationArgs(S&: *this, TemplateNameLoc,
8488 Param, Args: &TemplateArgs[I],
8489 NumArgs: 1, IsDefaultArgument: I >= NumExplicit))
8490 return true;
8491 }
8492
8493 return false;
8494}
8495
8496DeclResult Sema::ActOnClassTemplateSpecialization(
8497 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
8498 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
8499 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
8500 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
8501 assert(TUK != TagUseKind::Reference && "References are not specializations");
8502
8503 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
8504 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
8505 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
8506
8507 // Find the class template we're specializing
8508 TemplateName Name = TemplateId.Template.get();
8509 ClassTemplateDecl *ClassTemplate
8510 = dyn_cast_or_null<ClassTemplateDecl>(Val: Name.getAsTemplateDecl());
8511
8512 if (!ClassTemplate) {
8513 Diag(Loc: TemplateNameLoc, DiagID: diag::err_not_class_template_specialization)
8514 << (Name.getAsTemplateDecl() &&
8515 isa<TemplateTemplateParmDecl>(Val: Name.getAsTemplateDecl()));
8516 return true;
8517 }
8518
8519 if (const auto *DSA = ClassTemplate->getAttr<NoSpecializationsAttr>()) {
8520 auto Message = DSA->getMessage();
8521 Diag(Loc: TemplateNameLoc, DiagID: diag::warn_invalid_specialization)
8522 << ClassTemplate << !Message.empty() << Message;
8523 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
8524 }
8525
8526 if (S->isTemplateParamScope())
8527 EnterTemplatedContext(S, DC: ClassTemplate->getTemplatedDecl());
8528
8529 DeclContext *DC = ClassTemplate->getDeclContext();
8530
8531 bool isMemberSpecialization = false;
8532 bool isPartialSpecialization = false;
8533
8534 if (SS.isSet()) {
8535 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
8536 diagnoseQualifiedDeclaration(SS, DC, Name: ClassTemplate->getDeclName(),
8537 Loc: TemplateNameLoc, TemplateId: &TemplateId,
8538 /*IsMemberSpecialization=*/false))
8539 return true;
8540 }
8541
8542 // Check the validity of the template headers that introduce this
8543 // template.
8544 // FIXME: We probably shouldn't complain about these headers for
8545 // friend declarations.
8546 bool Invalid = false;
8547 TemplateParameterList *TemplateParams =
8548 MatchTemplateParametersToScopeSpecifier(
8549 DeclStartLoc: KWLoc, DeclLoc: TemplateNameLoc, SS, TemplateId: &TemplateId, ParamLists: TemplateParameterLists,
8550 IsFriend: TUK == TagUseKind::Friend, IsMemberSpecialization&: isMemberSpecialization, Invalid);
8551 if (Invalid)
8552 return true;
8553
8554 // Check that we can declare a template specialization here.
8555 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
8556 return true;
8557
8558 if (TemplateParams && DC->isDependentContext()) {
8559 ContextRAII SavedContext(*this, DC);
8560 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
8561 return true;
8562 }
8563
8564 if (TemplateParams && TemplateParams->size() > 0) {
8565 isPartialSpecialization = true;
8566
8567 if (TUK == TagUseKind::Friend) {
8568 Diag(Loc: KWLoc, DiagID: diag::err_partial_specialization_friend)
8569 << SourceRange(LAngleLoc, RAngleLoc);
8570 return true;
8571 }
8572
8573 // C++ [temp.class.spec]p10:
8574 // The template parameter list of a specialization shall not
8575 // contain default template argument values.
8576 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
8577 Decl *Param = TemplateParams->getParam(Idx: I);
8578 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
8579 if (TTP->hasDefaultArgument()) {
8580 Diag(Loc: TTP->getDefaultArgumentLoc(),
8581 DiagID: diag::err_default_arg_in_partial_spec);
8582 TTP->removeDefaultArgument();
8583 }
8584 } else if (NonTypeTemplateParmDecl *NTTP
8585 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
8586 if (NTTP->hasDefaultArgument()) {
8587 Diag(Loc: NTTP->getDefaultArgumentLoc(),
8588 DiagID: diag::err_default_arg_in_partial_spec)
8589 << NTTP->getDefaultArgument().getSourceRange();
8590 NTTP->removeDefaultArgument();
8591 }
8592 } else {
8593 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
8594 if (TTP->hasDefaultArgument()) {
8595 Diag(Loc: TTP->getDefaultArgument().getLocation(),
8596 DiagID: diag::err_default_arg_in_partial_spec)
8597 << TTP->getDefaultArgument().getSourceRange();
8598 TTP->removeDefaultArgument();
8599 }
8600 }
8601 }
8602 } else if (TemplateParams) {
8603 if (TUK == TagUseKind::Friend)
8604 Diag(Loc: KWLoc, DiagID: diag::err_template_spec_friend)
8605 << FixItHint::CreateRemoval(
8606 RemoveRange: SourceRange(TemplateParams->getTemplateLoc(),
8607 TemplateParams->getRAngleLoc()))
8608 << SourceRange(LAngleLoc, RAngleLoc);
8609 } else {
8610 assert(TUK == TagUseKind::Friend &&
8611 "should have a 'template<>' for this decl");
8612 }
8613
8614 // Check that the specialization uses the same tag kind as the
8615 // original template.
8616 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
8617 assert(Kind != TagTypeKind::Enum &&
8618 "Invalid enum tag in class template spec!");
8619 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(), NewTag: Kind,
8620 isDefinition: TUK == TagUseKind::Definition, NewTagLoc: KWLoc,
8621 Name: ClassTemplate->getIdentifier())) {
8622 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
8623 << ClassTemplate
8624 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
8625 Code: ClassTemplate->getTemplatedDecl()->getKindName());
8626 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
8627 DiagID: diag::note_previous_use);
8628 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
8629 }
8630
8631 // Translate the parser's template argument list in our AST format.
8632 TemplateArgumentListInfo TemplateArgs =
8633 makeTemplateArgumentListInfo(S&: *this, TemplateId);
8634
8635 // Check for unexpanded parameter packs in any of the template arguments.
8636 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
8637 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
8638 UPPC: isPartialSpecialization
8639 ? UPPC_PartialSpecialization
8640 : UPPC_ExplicitSpecialization))
8641 return true;
8642
8643 // Check that the template argument list is well-formed for this
8644 // template.
8645 CheckTemplateArgumentInfo CTAI;
8646 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
8647 /*DefaultArgs=*/{},
8648 /*PartialTemplateArgs=*/false, CTAI,
8649 /*UpdateArgsWithConversions=*/true))
8650 return true;
8651
8652 // Find the class template (partial) specialization declaration that
8653 // corresponds to these arguments.
8654 if (isPartialSpecialization) {
8655 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, PrimaryTemplate: ClassTemplate,
8656 NumExplicit: TemplateArgs.size(),
8657 TemplateArgs: CTAI.CanonicalConverted))
8658 return true;
8659
8660 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
8661 // also do it during instantiation.
8662 if (!Name.isDependent() &&
8663 !TemplateSpecializationType::anyDependentTemplateArguments(
8664 TemplateArgs, Converted: CTAI.CanonicalConverted)) {
8665 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_fully_specialized)
8666 << ClassTemplate->getDeclName();
8667 isPartialSpecialization = false;
8668 Invalid = true;
8669 }
8670 }
8671
8672 void *InsertPos = nullptr;
8673 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
8674
8675 if (isPartialSpecialization)
8676 PrevDecl = ClassTemplate->findPartialSpecialization(
8677 Args: CTAI.CanonicalConverted, TPL: TemplateParams, InsertPos);
8678 else
8679 PrevDecl =
8680 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
8681
8682 ClassTemplateSpecializationDecl *Specialization = nullptr;
8683
8684 // Check whether we can declare a class template specialization in
8685 // the current scope.
8686 if (TUK != TagUseKind::Friend &&
8687 CheckTemplateSpecializationScope(S&: *this, Specialized: ClassTemplate, PrevDecl,
8688 Loc: TemplateNameLoc,
8689 IsPartialSpecialization: isPartialSpecialization))
8690 return true;
8691
8692 QualType CanonType;
8693 if (!isPartialSpecialization) {
8694 // Create a new class template specialization declaration node for
8695 // this explicit specialization or friend declaration.
8696 Specialization = ClassTemplateSpecializationDecl::Create(
8697 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
8698 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
8699 Specialization->setTemplateArgsAsWritten(TemplateArgs);
8700 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
8701 if (TemplateParameterLists.size() > 0) {
8702 Specialization->setTemplateParameterListsInfo(Context,
8703 TPLists: TemplateParameterLists);
8704 }
8705
8706 if (!PrevDecl)
8707 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
8708
8709 if (!CurContext->isDependentContext())
8710 CanonType = Context.getTypeDeclType(Decl: Specialization);
8711 }
8712
8713 TypeSourceInfo *WrittenTy = Context.getTemplateSpecializationTypeInfo(
8714 T: Name, TLoc: TemplateNameLoc, SpecifiedArgs: TemplateArgs, CanonicalArgs: CTAI.CanonicalConverted, Canon: CanonType);
8715
8716 if (isPartialSpecialization) {
8717 if (Context.hasSameType(
8718 T1: WrittenTy->getType(),
8719 T2: ClassTemplate->getInjectedClassNameSpecialization()) &&
8720 (!Context.getLangOpts().CPlusPlus20 ||
8721 !TemplateParams->hasAssociatedConstraints())) {
8722 // C++ [temp.class.spec]p9b3:
8723 //
8724 // -- The argument list of the specialization shall not be identical
8725 // to the implicit argument list of the primary template.
8726 //
8727 // This rule has since been removed, because it's redundant given DR1495,
8728 // but we keep it because it produces better diagnostics and recovery.
8729 Diag(Loc: TemplateNameLoc, DiagID: diag::err_partial_spec_args_match_primary_template)
8730 << /*class template*/ 0 << (TUK == TagUseKind::Definition)
8731 << FixItHint::CreateRemoval(RemoveRange: SourceRange(LAngleLoc, RAngleLoc));
8732 return CheckClassTemplate(
8733 S, TagSpec, TUK, KWLoc, SS, Name: ClassTemplate->getIdentifier(),
8734 NameLoc: TemplateNameLoc, Attr, TemplateParams, AS: AS_none,
8735 /*ModulePrivateLoc=*/SourceLocation(),
8736 /*FriendLoc*/ SourceLocation(), NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
8737 OuterTemplateParamLists: TemplateParameterLists.data());
8738 }
8739
8740 // Create a new class template partial specialization declaration node.
8741 ClassTemplatePartialSpecializationDecl *PrevPartial
8742 = cast_or_null<ClassTemplatePartialSpecializationDecl>(Val: PrevDecl);
8743 ClassTemplatePartialSpecializationDecl *Partial =
8744 ClassTemplatePartialSpecializationDecl::Create(
8745 Context, TK: Kind, DC, StartLoc: KWLoc, IdLoc: TemplateNameLoc, Params: TemplateParams,
8746 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, CanonInjectedType: WrittenTy->getType(),
8747 PrevDecl: PrevPartial);
8748 Partial->setTemplateArgsAsWritten(TemplateArgs);
8749 SetNestedNameSpecifier(S&: *this, T: Partial, SS);
8750 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
8751 Partial->setTemplateParameterListsInfo(
8752 Context, TPLists: TemplateParameterLists.drop_back(N: 1));
8753 }
8754
8755 if (!PrevPartial)
8756 ClassTemplate->AddPartialSpecialization(D: Partial, InsertPos);
8757 Specialization = Partial;
8758
8759 // If we are providing an explicit specialization of a member class
8760 // template specialization, make a note of that.
8761 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
8762 PrevPartial->setMemberSpecialization();
8763
8764 CheckTemplatePartialSpecialization(Partial);
8765 }
8766
8767 // C++ [temp.expl.spec]p6:
8768 // If a template, a member template or the member of a class template is
8769 // explicitly specialized then that specialization shall be declared
8770 // before the first use of that specialization that would cause an implicit
8771 // instantiation to take place, in every translation unit in which such a
8772 // use occurs; no diagnostic is required.
8773 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
8774 bool Okay = false;
8775 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
8776 // Is there any previous explicit specialization declaration?
8777 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
8778 Okay = true;
8779 break;
8780 }
8781 }
8782
8783 if (!Okay) {
8784 SourceRange Range(TemplateNameLoc, RAngleLoc);
8785 Diag(Loc: TemplateNameLoc, DiagID: diag::err_specialization_after_instantiation)
8786 << Context.getTypeDeclType(Decl: Specialization) << Range;
8787
8788 Diag(Loc: PrevDecl->getPointOfInstantiation(),
8789 DiagID: diag::note_instantiation_required_here)
8790 << (PrevDecl->getTemplateSpecializationKind()
8791 != TSK_ImplicitInstantiation);
8792 return true;
8793 }
8794 }
8795
8796 // If this is not a friend, note that this is an explicit specialization.
8797 if (TUK != TagUseKind::Friend)
8798 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
8799
8800 // Check that this isn't a redefinition of this specialization.
8801 if (TUK == TagUseKind::Definition) {
8802 RecordDecl *Def = Specialization->getDefinition();
8803 NamedDecl *Hidden = nullptr;
8804 if (Def && SkipBody && !hasVisibleDefinition(D: Def, Suggested: &Hidden)) {
8805 SkipBody->ShouldSkip = true;
8806 SkipBody->Previous = Def;
8807 makeMergedDefinitionVisible(ND: Hidden);
8808 } else if (Def) {
8809 SourceRange Range(TemplateNameLoc, RAngleLoc);
8810 Diag(Loc: TemplateNameLoc, DiagID: diag::err_redefinition) << Specialization << Range;
8811 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
8812 Specialization->setInvalidDecl();
8813 return true;
8814 }
8815 }
8816
8817 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
8818 ProcessAPINotes(D: Specialization);
8819
8820 // Add alignment attributes if necessary; these attributes are checked when
8821 // the ASTContext lays out the structure.
8822 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
8823 if (LangOpts.HLSL)
8824 Specialization->addAttr(A: PackedAttr::CreateImplicit(Ctx&: Context));
8825 AddAlignmentAttributesForRecord(RD: Specialization);
8826 AddMsStructLayoutForRecord(RD: Specialization);
8827 }
8828
8829 if (ModulePrivateLoc.isValid())
8830 Diag(Loc: Specialization->getLocation(), DiagID: diag::err_module_private_specialization)
8831 << (isPartialSpecialization? 1 : 0)
8832 << FixItHint::CreateRemoval(RemoveRange: ModulePrivateLoc);
8833
8834 // C++ [temp.expl.spec]p9:
8835 // A template explicit specialization is in the scope of the
8836 // namespace in which the template was defined.
8837 //
8838 // We actually implement this paragraph where we set the semantic
8839 // context (in the creation of the ClassTemplateSpecializationDecl),
8840 // but we also maintain the lexical context where the actual
8841 // definition occurs.
8842 Specialization->setLexicalDeclContext(CurContext);
8843
8844 // We may be starting the definition of this specialization.
8845 if (TUK == TagUseKind::Definition && (!SkipBody || !SkipBody->ShouldSkip))
8846 Specialization->startDefinition();
8847
8848 if (TUK == TagUseKind::Friend) {
8849 // Build the fully-sugared type for this class template
8850 // specialization as the user wrote in the specialization
8851 // itself. This means that we'll pretty-print the type retrieved
8852 // from the specialization's declaration the way that the user
8853 // actually wrote the specialization, rather than formatting the
8854 // name based on the "canonical" representation used to store the
8855 // template arguments in the specialization.
8856 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext,
8857 L: TemplateNameLoc,
8858 Friend_: WrittenTy,
8859 /*FIXME:*/FriendL: KWLoc);
8860 Friend->setAccess(AS_public);
8861 CurContext->addDecl(D: Friend);
8862 } else {
8863 // Add the specialization into its lexical context, so that it can
8864 // be seen when iterating through the list of declarations in that
8865 // context. However, specializations are not found by name lookup.
8866 CurContext->addDecl(D: Specialization);
8867 }
8868
8869 if (SkipBody && SkipBody->ShouldSkip)
8870 return SkipBody->Previous;
8871
8872 Specialization->setInvalidDecl(Invalid);
8873 inferGslOwnerPointerAttribute(Record: Specialization);
8874 return Specialization;
8875}
8876
8877Decl *Sema::ActOnTemplateDeclarator(Scope *S,
8878 MultiTemplateParamsArg TemplateParameterLists,
8879 Declarator &D) {
8880 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
8881 ActOnDocumentableDecl(D: NewDecl);
8882 return NewDecl;
8883}
8884
8885ConceptDecl *Sema::ActOnStartConceptDefinition(
8886 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8887 const IdentifierInfo *Name, SourceLocation NameLoc) {
8888 DeclContext *DC = CurContext;
8889
8890 if (!DC->getRedeclContext()->isFileContext()) {
8891 Diag(Loc: NameLoc,
8892 DiagID: diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
8893 return nullptr;
8894 }
8895
8896 if (TemplateParameterLists.size() > 1) {
8897 Diag(Loc: NameLoc, DiagID: diag::err_concept_extra_headers);
8898 return nullptr;
8899 }
8900
8901 TemplateParameterList *Params = TemplateParameterLists.front();
8902
8903 if (Params->size() == 0) {
8904 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_parameters);
8905 return nullptr;
8906 }
8907
8908 // Ensure that the parameter pack, if present, is the last parameter in the
8909 // template.
8910 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
8911 ParamEnd = Params->end();
8912 ParamIt != ParamEnd; ++ParamIt) {
8913 Decl const *Param = *ParamIt;
8914 if (Param->isParameterPack()) {
8915 if (++ParamIt == ParamEnd)
8916 break;
8917 Diag(Loc: Param->getLocation(),
8918 DiagID: diag::err_template_param_pack_must_be_last_template_parameter);
8919 return nullptr;
8920 }
8921 }
8922
8923 ConceptDecl *NewDecl =
8924 ConceptDecl::Create(C&: Context, DC, L: NameLoc, Name, Params);
8925
8926 if (NewDecl->hasAssociatedConstraints()) {
8927 // C++2a [temp.concept]p4:
8928 // A concept shall not have associated constraints.
8929 Diag(Loc: NameLoc, DiagID: diag::err_concept_no_associated_constraints);
8930 NewDecl->setInvalidDecl();
8931 }
8932
8933 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NewDecl->getBeginLoc());
8934 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8935 forRedeclarationInCurContext());
8936 LookupName(R&: Previous, S);
8937 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
8938 /*AllowInlineNamespace*/ false);
8939
8940 // We cannot properly handle redeclarations until we parse the constraint
8941 // expression, so only inject the name if we are sure we are not redeclaring a
8942 // symbol
8943 if (Previous.empty())
8944 PushOnScopeChains(D: NewDecl, S, AddToContext: true);
8945
8946 return NewDecl;
8947}
8948
8949static bool RemoveLookupResult(LookupResult &R, NamedDecl *C) {
8950 bool Found = false;
8951 LookupResult::Filter F = R.makeFilter();
8952 while (F.hasNext()) {
8953 NamedDecl *D = F.next();
8954 if (D == C) {
8955 F.erase();
8956 Found = true;
8957 break;
8958 }
8959 }
8960 F.done();
8961 return Found;
8962}
8963
8964ConceptDecl *
8965Sema::ActOnFinishConceptDefinition(Scope *S, ConceptDecl *C,
8966 Expr *ConstraintExpr,
8967 const ParsedAttributesView &Attrs) {
8968 assert(!C->hasDefinition() && "Concept already defined");
8969 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr)) {
8970 C->setInvalidDecl();
8971 return nullptr;
8972 }
8973 C->setDefinition(ConstraintExpr);
8974 ProcessDeclAttributeList(S, D: C, AttrList: Attrs);
8975
8976 // Check for conflicting previous declaration.
8977 DeclarationNameInfo NameInfo(C->getDeclName(), C->getBeginLoc());
8978 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
8979 forRedeclarationInCurContext());
8980 LookupName(R&: Previous, S);
8981 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage=*/false,
8982 /*AllowInlineNamespace*/ false);
8983 bool WasAlreadyAdded = RemoveLookupResult(R&: Previous, C);
8984 bool AddToScope = true;
8985 CheckConceptRedefinition(NewDecl: C, Previous, AddToScope);
8986
8987 ActOnDocumentableDecl(D: C);
8988 if (!WasAlreadyAdded && AddToScope)
8989 PushOnScopeChains(D: C, S);
8990
8991 return C;
8992}
8993
8994void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
8995 LookupResult &Previous, bool &AddToScope) {
8996 AddToScope = true;
8997
8998 if (Previous.empty())
8999 return;
9000
9001 auto *OldConcept = dyn_cast<ConceptDecl>(Val: Previous.getRepresentativeDecl()->getUnderlyingDecl());
9002 if (!OldConcept) {
9003 auto *Old = Previous.getRepresentativeDecl();
9004 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_kind)
9005 << NewDecl->getDeclName();
9006 notePreviousDefinition(Old, New: NewDecl->getLocation());
9007 AddToScope = false;
9008 return;
9009 }
9010 // Check if we can merge with a concept declaration.
9011 bool IsSame = Context.isSameEntity(X: NewDecl, Y: OldConcept);
9012 if (!IsSame) {
9013 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition_different_concept)
9014 << NewDecl->getDeclName();
9015 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9016 AddToScope = false;
9017 return;
9018 }
9019 if (hasReachableDefinition(D: OldConcept) &&
9020 IsRedefinitionInModule(New: NewDecl, Old: OldConcept)) {
9021 Diag(Loc: NewDecl->getLocation(), DiagID: diag::err_redefinition)
9022 << NewDecl->getDeclName();
9023 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9024 AddToScope = false;
9025 return;
9026 }
9027 if (!Previous.isSingleResult()) {
9028 // FIXME: we should produce an error in case of ambig and failed lookups.
9029 // Other decls (e.g. namespaces) also have this shortcoming.
9030 return;
9031 }
9032 // We unwrap canonical decl late to check for module visibility.
9033 Context.setPrimaryMergedDecl(D: NewDecl, Primary: OldConcept->getCanonicalDecl());
9034}
9035
9036bool Sema::CheckConceptUseInDefinition(ConceptDecl *Concept,
9037 SourceLocation Loc) {
9038 if (!Concept->isInvalidDecl() && !Concept->hasDefinition()) {
9039 Diag(Loc, DiagID: diag::err_recursive_concept) << Concept;
9040 Diag(Loc: Concept->getLocation(), DiagID: diag::note_declared_at);
9041 return true;
9042 }
9043 return false;
9044}
9045
9046/// \brief Strips various properties off an implicit instantiation
9047/// that has just been explicitly specialized.
9048static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9049 if (MinGW || (isa<FunctionDecl>(Val: D) &&
9050 cast<FunctionDecl>(Val: D)->isFunctionTemplateSpecialization()))
9051 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9052
9053 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D))
9054 FD->setInlineSpecified(false);
9055}
9056
9057/// Compute the diagnostic location for an explicit instantiation
9058// declaration or definition.
9059static SourceLocation DiagLocForExplicitInstantiation(
9060 NamedDecl* D, SourceLocation PointOfInstantiation) {
9061 // Explicit instantiations following a specialization have no effect and
9062 // hence no PointOfInstantiation. In that case, walk decl backwards
9063 // until a valid name loc is found.
9064 SourceLocation PrevDiagLoc = PointOfInstantiation;
9065 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9066 Prev = Prev->getPreviousDecl()) {
9067 PrevDiagLoc = Prev->getLocation();
9068 }
9069 assert(PrevDiagLoc.isValid() &&
9070 "Explicit instantiation without point of instantiation?");
9071 return PrevDiagLoc;
9072}
9073
9074bool
9075Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
9076 TemplateSpecializationKind NewTSK,
9077 NamedDecl *PrevDecl,
9078 TemplateSpecializationKind PrevTSK,
9079 SourceLocation PrevPointOfInstantiation,
9080 bool &HasNoEffect) {
9081 HasNoEffect = false;
9082
9083 switch (NewTSK) {
9084 case TSK_Undeclared:
9085 case TSK_ImplicitInstantiation:
9086 assert(
9087 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9088 "previous declaration must be implicit!");
9089 return false;
9090
9091 case TSK_ExplicitSpecialization:
9092 switch (PrevTSK) {
9093 case TSK_Undeclared:
9094 case TSK_ExplicitSpecialization:
9095 // Okay, we're just specializing something that is either already
9096 // explicitly specialized or has merely been mentioned without any
9097 // instantiation.
9098 return false;
9099
9100 case TSK_ImplicitInstantiation:
9101 if (PrevPointOfInstantiation.isInvalid()) {
9102 // The declaration itself has not actually been instantiated, so it is
9103 // still okay to specialize it.
9104 StripImplicitInstantiation(
9105 D: PrevDecl, MinGW: Context.getTargetInfo().getTriple().isOSCygMing());
9106 return false;
9107 }
9108 // Fall through
9109 [[fallthrough]];
9110
9111 case TSK_ExplicitInstantiationDeclaration:
9112 case TSK_ExplicitInstantiationDefinition:
9113 assert((PrevTSK == TSK_ImplicitInstantiation ||
9114 PrevPointOfInstantiation.isValid()) &&
9115 "Explicit instantiation without point of instantiation?");
9116
9117 // C++ [temp.expl.spec]p6:
9118 // If a template, a member template or the member of a class template
9119 // is explicitly specialized then that specialization shall be declared
9120 // before the first use of that specialization that would cause an
9121 // implicit instantiation to take place, in every translation unit in
9122 // which such a use occurs; no diagnostic is required.
9123 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9124 // Is there any previous explicit specialization declaration?
9125 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization)
9126 return false;
9127 }
9128
9129 Diag(Loc: NewLoc, DiagID: diag::err_specialization_after_instantiation)
9130 << PrevDecl;
9131 Diag(Loc: PrevPointOfInstantiation, DiagID: diag::note_instantiation_required_here)
9132 << (PrevTSK != TSK_ImplicitInstantiation);
9133
9134 return true;
9135 }
9136 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9137
9138 case TSK_ExplicitInstantiationDeclaration:
9139 switch (PrevTSK) {
9140 case TSK_ExplicitInstantiationDeclaration:
9141 // This explicit instantiation declaration is redundant (that's okay).
9142 HasNoEffect = true;
9143 return false;
9144
9145 case TSK_Undeclared:
9146 case TSK_ImplicitInstantiation:
9147 // We're explicitly instantiating something that may have already been
9148 // implicitly instantiated; that's fine.
9149 return false;
9150
9151 case TSK_ExplicitSpecialization:
9152 // C++0x [temp.explicit]p4:
9153 // For a given set of template parameters, if an explicit instantiation
9154 // of a template appears after a declaration of an explicit
9155 // specialization for that template, the explicit instantiation has no
9156 // effect.
9157 HasNoEffect = true;
9158 return false;
9159
9160 case TSK_ExplicitInstantiationDefinition:
9161 // C++0x [temp.explicit]p10:
9162 // If an entity is the subject of both an explicit instantiation
9163 // declaration and an explicit instantiation definition in the same
9164 // translation unit, the definition shall follow the declaration.
9165 Diag(Loc: NewLoc,
9166 DiagID: diag::err_explicit_instantiation_declaration_after_definition);
9167
9168 // Explicit instantiations following a specialization have no effect and
9169 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9170 // until a valid name loc is found.
9171 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9172 DiagID: diag::note_explicit_instantiation_definition_here);
9173 HasNoEffect = true;
9174 return false;
9175 }
9176 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9177
9178 case TSK_ExplicitInstantiationDefinition:
9179 switch (PrevTSK) {
9180 case TSK_Undeclared:
9181 case TSK_ImplicitInstantiation:
9182 // We're explicitly instantiating something that may have already been
9183 // implicitly instantiated; that's fine.
9184 return false;
9185
9186 case TSK_ExplicitSpecialization:
9187 // C++ DR 259, C++0x [temp.explicit]p4:
9188 // For a given set of template parameters, if an explicit
9189 // instantiation of a template appears after a declaration of
9190 // an explicit specialization for that template, the explicit
9191 // instantiation has no effect.
9192 Diag(Loc: NewLoc, DiagID: diag::warn_explicit_instantiation_after_specialization)
9193 << PrevDecl;
9194 Diag(Loc: PrevDecl->getLocation(),
9195 DiagID: diag::note_previous_template_specialization);
9196 HasNoEffect = true;
9197 return false;
9198
9199 case TSK_ExplicitInstantiationDeclaration:
9200 // We're explicitly instantiating a definition for something for which we
9201 // were previously asked to suppress instantiations. That's fine.
9202
9203 // C++0x [temp.explicit]p4:
9204 // For a given set of template parameters, if an explicit instantiation
9205 // of a template appears after a declaration of an explicit
9206 // specialization for that template, the explicit instantiation has no
9207 // effect.
9208 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9209 // Is there any previous explicit specialization declaration?
9210 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9211 HasNoEffect = true;
9212 break;
9213 }
9214 }
9215
9216 return false;
9217
9218 case TSK_ExplicitInstantiationDefinition:
9219 // C++0x [temp.spec]p5:
9220 // For a given template and a given set of template-arguments,
9221 // - an explicit instantiation definition shall appear at most once
9222 // in a program,
9223
9224 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
9225 Diag(Loc: NewLoc, DiagID: (getLangOpts().MSVCCompat)
9226 ? diag::ext_explicit_instantiation_duplicate
9227 : diag::err_explicit_instantiation_duplicate)
9228 << PrevDecl;
9229 Diag(Loc: DiagLocForExplicitInstantiation(D: PrevDecl, PointOfInstantiation: PrevPointOfInstantiation),
9230 DiagID: diag::note_previous_explicit_instantiation);
9231 HasNoEffect = true;
9232 return false;
9233 }
9234 }
9235
9236 llvm_unreachable("Missing specialization/instantiation case?");
9237}
9238
9239bool Sema::CheckDependentFunctionTemplateSpecialization(
9240 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
9241 LookupResult &Previous) {
9242 // Remove anything from Previous that isn't a function template in
9243 // the correct context.
9244 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9245 LookupResult::Filter F = Previous.makeFilter();
9246 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
9247 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
9248 while (F.hasNext()) {
9249 NamedDecl *D = F.next()->getUnderlyingDecl();
9250 if (!isa<FunctionTemplateDecl>(Val: D)) {
9251 F.erase();
9252 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAFunctionTemplate, y&: D));
9253 continue;
9254 }
9255
9256 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9257 NS: D->getDeclContext()->getRedeclContext())) {
9258 F.erase();
9259 DiscardedCandidates.push_back(Elt: std::make_pair(x: NotAMemberOfEnclosing, y&: D));
9260 continue;
9261 }
9262 }
9263 F.done();
9264
9265 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
9266 if (Previous.empty()) {
9267 Diag(Loc: FD->getLocation(), DiagID: diag::err_dependent_function_template_spec_no_match)
9268 << IsFriend;
9269 for (auto &P : DiscardedCandidates)
9270 Diag(Loc: P.second->getLocation(),
9271 DiagID: diag::note_dependent_function_template_spec_discard_reason)
9272 << P.first << IsFriend;
9273 return true;
9274 }
9275
9276 FD->setDependentTemplateSpecialization(Context, Templates: Previous.asUnresolvedSet(),
9277 TemplateArgs: ExplicitTemplateArgs);
9278 return false;
9279}
9280
9281bool Sema::CheckFunctionTemplateSpecialization(
9282 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
9283 LookupResult &Previous, bool QualifiedFriend) {
9284 // The set of function template specializations that could match this
9285 // explicit function template specialization.
9286 UnresolvedSet<8> Candidates;
9287 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
9288 /*ForTakingAddress=*/false);
9289
9290 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
9291 ConvertedTemplateArgs;
9292
9293 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
9294 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9295 I != E; ++I) {
9296 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
9297 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Ovl)) {
9298 // Only consider templates found within the same semantic lookup scope as
9299 // FD.
9300 if (!FDLookupContext->InEnclosingNamespaceSetOf(
9301 NS: Ovl->getDeclContext()->getRedeclContext()))
9302 continue;
9303
9304 QualType FT = FD->getType();
9305 // C++11 [dcl.constexpr]p8:
9306 // A constexpr specifier for a non-static member function that is not
9307 // a constructor declares that member function to be const.
9308 //
9309 // When matching a constexpr member function template specialization
9310 // against the primary template, we don't yet know whether the
9311 // specialization has an implicit 'const' (because we don't know whether
9312 // it will be a static member function until we know which template it
9313 // specializes). This rule was removed in C++14.
9314 if (auto *NewMD = dyn_cast<CXXMethodDecl>(Val: FD);
9315 !getLangOpts().CPlusPlus14 && NewMD && NewMD->isConstexpr() &&
9316 !isa<CXXConstructorDecl, CXXDestructorDecl>(Val: NewMD)) {
9317 auto *OldMD = dyn_cast<CXXMethodDecl>(Val: FunTmpl->getTemplatedDecl());
9318 if (OldMD && OldMD->isConst()) {
9319 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
9320 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9321 EPI.TypeQuals.addConst();
9322 FT = Context.getFunctionType(ResultTy: FPT->getReturnType(),
9323 Args: FPT->getParamTypes(), EPI);
9324 }
9325 }
9326
9327 TemplateArgumentListInfo Args;
9328 if (ExplicitTemplateArgs)
9329 Args = *ExplicitTemplateArgs;
9330
9331 // C++ [temp.expl.spec]p11:
9332 // A trailing template-argument can be left unspecified in the
9333 // template-id naming an explicit function template specialization
9334 // provided it can be deduced from the function argument type.
9335 // Perform template argument deduction to determine whether we may be
9336 // specializing this template.
9337 // FIXME: It is somewhat wasteful to build
9338 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9339 FunctionDecl *Specialization = nullptr;
9340 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
9341 FunctionTemplate: cast<FunctionTemplateDecl>(Val: FunTmpl->getFirstDecl()),
9342 ExplicitTemplateArgs: ExplicitTemplateArgs ? &Args : nullptr, ArgFunctionType: FT, Specialization, Info);
9343 TDK != TemplateDeductionResult::Success) {
9344 // Template argument deduction failed; record why it failed, so
9345 // that we can provide nifty diagnostics.
9346 FailedCandidates.addCandidate().set(
9347 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9348 Info: MakeDeductionFailureInfo(Context, TDK, Info));
9349 (void)TDK;
9350 continue;
9351 }
9352
9353 // Target attributes are part of the cuda function signature, so
9354 // the deduced template's cuda target must match that of the
9355 // specialization. Given that C++ template deduction does not
9356 // take target attributes into account, we reject candidates
9357 // here that have a different target.
9358 if (LangOpts.CUDA &&
9359 CUDA().IdentifyTarget(D: Specialization,
9360 /* IgnoreImplicitHDAttr = */ true) !=
9361 CUDA().IdentifyTarget(D: FD, /* IgnoreImplicitHDAttr = */ true)) {
9362 FailedCandidates.addCandidate().set(
9363 Found: I.getPair(), Spec: FunTmpl->getTemplatedDecl(),
9364 Info: MakeDeductionFailureInfo(
9365 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
9366 continue;
9367 }
9368
9369 // Record this candidate.
9370 if (ExplicitTemplateArgs)
9371 ConvertedTemplateArgs[Specialization] = std::move(Args);
9372 Candidates.addDecl(D: Specialization, AS: I.getAccess());
9373 }
9374 }
9375
9376 // For a qualified friend declaration (with no explicit marker to indicate
9377 // that a template specialization was intended), note all (template and
9378 // non-template) candidates.
9379 if (QualifiedFriend && Candidates.empty()) {
9380 Diag(Loc: FD->getLocation(), DiagID: diag::err_qualified_friend_no_match)
9381 << FD->getDeclName() << FDLookupContext;
9382 // FIXME: We should form a single candidate list and diagnose all
9383 // candidates at once, to get proper sorting and limiting.
9384 for (auto *OldND : Previous) {
9385 if (auto *OldFD = dyn_cast<FunctionDecl>(Val: OldND->getUnderlyingDecl()))
9386 NoteOverloadCandidate(Found: OldND, Fn: OldFD, RewriteKind: CRK_None, DestType: FD->getType(), TakingAddress: false);
9387 }
9388 FailedCandidates.NoteCandidates(S&: *this, Loc: FD->getLocation());
9389 return true;
9390 }
9391
9392 // Find the most specialized function template.
9393 UnresolvedSetIterator Result = getMostSpecialized(
9394 SBegin: Candidates.begin(), SEnd: Candidates.end(), FailedCandidates, Loc: FD->getLocation(),
9395 NoneDiag: PDiag(DiagID: diag::err_function_template_spec_no_match) << FD->getDeclName(),
9396 AmbigDiag: PDiag(DiagID: diag::err_function_template_spec_ambiguous)
9397 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
9398 CandidateDiag: PDiag(DiagID: diag::note_function_template_spec_matched));
9399
9400 if (Result == Candidates.end())
9401 return true;
9402
9403 // Ignore access information; it doesn't figure into redeclaration checking.
9404 FunctionDecl *Specialization = cast<FunctionDecl>(Val: *Result);
9405
9406 if (const auto *PT = Specialization->getPrimaryTemplate();
9407 const auto *DSA = PT->getAttr<NoSpecializationsAttr>()) {
9408 auto Message = DSA->getMessage();
9409 Diag(Loc: FD->getLocation(), DiagID: diag::warn_invalid_specialization)
9410 << PT << !Message.empty() << Message;
9411 Diag(Loc: DSA->getLoc(), DiagID: diag::note_marked_here) << DSA;
9412 }
9413
9414 // C++23 [except.spec]p13:
9415 // An exception specification is considered to be needed when:
9416 // - [...]
9417 // - the exception specification is compared to that of another declaration
9418 // (e.g., an explicit specialization or an overriding virtual function);
9419 // - [...]
9420 //
9421 // The exception specification of a defaulted function is evaluated as
9422 // described above only when needed; similarly, the noexcept-specifier of a
9423 // specialization of a function template or member function of a class
9424 // template is instantiated only when needed.
9425 //
9426 // The standard doesn't specify what the "comparison with another declaration"
9427 // entails, nor the exact circumstances in which it occurs. Moreover, it does
9428 // not state which properties of an explicit specialization must match the
9429 // primary template.
9430 //
9431 // We assume that an explicit specialization must correspond with (per
9432 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
9433 // the declaration produced by substitution into the function template.
9434 //
9435 // Since the determination whether two function declarations correspond does
9436 // not consider exception specification, we only need to instantiate it once
9437 // we determine the primary template when comparing types per
9438 // [basic.link]p11.1.
9439 auto *SpecializationFPT =
9440 Specialization->getType()->castAs<FunctionProtoType>();
9441 // If the function has a dependent exception specification, resolve it after
9442 // we have selected the primary template so we can check whether it matches.
9443 if (getLangOpts().CPlusPlus17 &&
9444 isUnresolvedExceptionSpec(ESpecType: SpecializationFPT->getExceptionSpecType()) &&
9445 !ResolveExceptionSpec(Loc: FD->getLocation(), FPT: SpecializationFPT))
9446 return true;
9447
9448 FunctionTemplateSpecializationInfo *SpecInfo
9449 = Specialization->getTemplateSpecializationInfo();
9450 assert(SpecInfo && "Function template specialization info missing?");
9451
9452 // Note: do not overwrite location info if previous template
9453 // specialization kind was explicit.
9454 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
9455 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
9456 Specialization->setLocation(FD->getLocation());
9457 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
9458 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
9459 // function can differ from the template declaration with respect to
9460 // the constexpr specifier.
9461 // FIXME: We need an update record for this AST mutation.
9462 // FIXME: What if there are multiple such prior declarations (for instance,
9463 // from different modules)?
9464 Specialization->setConstexprKind(FD->getConstexprKind());
9465 }
9466
9467 // FIXME: Check if the prior specialization has a point of instantiation.
9468 // If so, we have run afoul of .
9469
9470 // If this is a friend declaration, then we're not really declaring
9471 // an explicit specialization.
9472 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
9473
9474 // Check the scope of this explicit specialization.
9475 if (!isFriend &&
9476 CheckTemplateSpecializationScope(S&: *this,
9477 Specialized: Specialization->getPrimaryTemplate(),
9478 PrevDecl: Specialization, Loc: FD->getLocation(),
9479 IsPartialSpecialization: false))
9480 return true;
9481
9482 // C++ [temp.expl.spec]p6:
9483 // If a template, a member template or the member of a class template is
9484 // explicitly specialized then that specialization shall be declared
9485 // before the first use of that specialization that would cause an implicit
9486 // instantiation to take place, in every translation unit in which such a
9487 // use occurs; no diagnostic is required.
9488 bool HasNoEffect = false;
9489 if (!isFriend &&
9490 CheckSpecializationInstantiationRedecl(NewLoc: FD->getLocation(),
9491 NewTSK: TSK_ExplicitSpecialization,
9492 PrevDecl: Specialization,
9493 PrevTSK: SpecInfo->getTemplateSpecializationKind(),
9494 PrevPointOfInstantiation: SpecInfo->getPointOfInstantiation(),
9495 HasNoEffect))
9496 return true;
9497
9498 // Mark the prior declaration as an explicit specialization, so that later
9499 // clients know that this is an explicit specialization.
9500 // A dependent friend specialization which has a definition should be treated
9501 // as explicit specialization, despite being invalid.
9502 if (FunctionDecl *InstFrom = FD->getInstantiatedFromMemberFunction();
9503 !isFriend || (InstFrom && InstFrom->getDependentSpecializationInfo())) {
9504 // Since explicit specializations do not inherit '=delete' from their
9505 // primary function template - check if the 'specialization' that was
9506 // implicitly generated (during template argument deduction for partial
9507 // ordering) from the most specialized of all the function templates that
9508 // 'FD' could have been specializing, has a 'deleted' definition. If so,
9509 // first check that it was implicitly generated during template argument
9510 // deduction by making sure it wasn't referenced, and then reset the deleted
9511 // flag to not-deleted, so that we can inherit that information from 'FD'.
9512 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
9513 !Specialization->getCanonicalDecl()->isReferenced()) {
9514 // FIXME: This assert will not hold in the presence of modules.
9515 assert(
9516 Specialization->getCanonicalDecl() == Specialization &&
9517 "This must be the only existing declaration of this specialization");
9518 // FIXME: We need an update record for this AST mutation.
9519 Specialization->setDeletedAsWritten(D: false);
9520 }
9521 // FIXME: We need an update record for this AST mutation.
9522 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9523 MarkUnusedFileScopedDecl(D: Specialization);
9524 }
9525
9526 // Turn the given function declaration into a function template
9527 // specialization, with the template arguments from the previous
9528 // specialization.
9529 // Take copies of (semantic and syntactic) template argument lists.
9530 TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy(
9531 Context, Args: Specialization->getTemplateSpecializationArgs()->asArray());
9532 FD->setFunctionTemplateSpecialization(
9533 Template: Specialization->getPrimaryTemplate(), TemplateArgs: TemplArgs, /*InsertPos=*/nullptr,
9534 TSK: SpecInfo->getTemplateSpecializationKind(),
9535 TemplateArgsAsWritten: ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
9536
9537 // A function template specialization inherits the target attributes
9538 // of its template. (We require the attributes explicitly in the
9539 // code to match, but a template may have implicit attributes by
9540 // virtue e.g. of being constexpr, and it passes these implicit
9541 // attributes on to its specializations.)
9542 if (LangOpts.CUDA)
9543 CUDA().inheritTargetAttrs(FD, TD: *Specialization->getPrimaryTemplate());
9544
9545 // The "previous declaration" for this function template specialization is
9546 // the prior function template specialization.
9547 Previous.clear();
9548 Previous.addDecl(D: Specialization);
9549 return false;
9550}
9551
9552bool
9553Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
9554 assert(!Member->isTemplateDecl() && !Member->getDescribedTemplate() &&
9555 "Only for non-template members");
9556
9557 // Try to find the member we are instantiating.
9558 NamedDecl *FoundInstantiation = nullptr;
9559 NamedDecl *Instantiation = nullptr;
9560 NamedDecl *InstantiatedFrom = nullptr;
9561 MemberSpecializationInfo *MSInfo = nullptr;
9562
9563 if (Previous.empty()) {
9564 // Nowhere to look anyway.
9565 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Member)) {
9566 UnresolvedSet<8> Candidates;
9567 for (NamedDecl *Candidate : Previous) {
9568 auto *Method = dyn_cast<CXXMethodDecl>(Val: Candidate->getUnderlyingDecl());
9569 // Ignore any candidates that aren't member functions.
9570 if (!Method)
9571 continue;
9572
9573 QualType Adjusted = Function->getType();
9574 if (!hasExplicitCallingConv(T: Adjusted))
9575 Adjusted = adjustCCAndNoReturn(ArgFunctionType: Adjusted, FunctionType: Method->getType());
9576 // Ignore any candidates with the wrong type.
9577 // This doesn't handle deduced return types, but both function
9578 // declarations should be undeduced at this point.
9579 // FIXME: The exception specification should probably be ignored when
9580 // comparing the types.
9581 if (!Context.hasSameType(T1: Adjusted, T2: Method->getType()))
9582 continue;
9583
9584 // Ignore any candidates with unsatisfied constraints.
9585 if (ConstraintSatisfaction Satisfaction;
9586 Method->getTrailingRequiresClause() &&
9587 (CheckFunctionConstraints(FD: Method, Satisfaction,
9588 /*UsageLoc=*/Member->getLocation(),
9589 /*ForOverloadResolution=*/true) ||
9590 !Satisfaction.IsSatisfied))
9591 continue;
9592
9593 Candidates.addDecl(D: Candidate);
9594 }
9595
9596 // If we have no viable candidates left after filtering, we are done.
9597 if (Candidates.empty())
9598 return false;
9599
9600 // Find the function that is more constrained than every other function it
9601 // has been compared to.
9602 UnresolvedSetIterator Best = Candidates.begin();
9603 CXXMethodDecl *BestMethod = nullptr;
9604 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9605 I != E; ++I) {
9606 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9607 if (I == Best ||
9608 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) == Method) {
9609 Best = I;
9610 BestMethod = Method;
9611 }
9612 }
9613
9614 FoundInstantiation = *Best;
9615 Instantiation = BestMethod;
9616 InstantiatedFrom = BestMethod->getInstantiatedFromMemberFunction();
9617 MSInfo = BestMethod->getMemberSpecializationInfo();
9618
9619 // Make sure the best candidate is more constrained than all of the others.
9620 bool Ambiguous = false;
9621 for (UnresolvedSetIterator I = Candidates.begin(), E = Candidates.end();
9622 I != E; ++I) {
9623 auto *Method = cast<CXXMethodDecl>(Val: I->getUnderlyingDecl());
9624 if (I != Best &&
9625 getMoreConstrainedFunction(FD1: Method, FD2: BestMethod) != BestMethod) {
9626 Ambiguous = true;
9627 break;
9628 }
9629 }
9630
9631 if (Ambiguous) {
9632 Diag(Loc: Member->getLocation(), DiagID: diag::err_function_member_spec_ambiguous)
9633 << Member << (InstantiatedFrom ? InstantiatedFrom : Instantiation);
9634 for (NamedDecl *Candidate : Candidates) {
9635 Candidate = Candidate->getUnderlyingDecl();
9636 Diag(Loc: Candidate->getLocation(), DiagID: diag::note_function_member_spec_matched)
9637 << Candidate;
9638 }
9639 return true;
9640 }
9641 } else if (isa<VarDecl>(Val: Member)) {
9642 VarDecl *PrevVar;
9643 if (Previous.isSingleResult() &&
9644 (PrevVar = dyn_cast<VarDecl>(Val: Previous.getFoundDecl())))
9645 if (PrevVar->isStaticDataMember()) {
9646 FoundInstantiation = Previous.getRepresentativeDecl();
9647 Instantiation = PrevVar;
9648 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
9649 MSInfo = PrevVar->getMemberSpecializationInfo();
9650 }
9651 } else if (isa<RecordDecl>(Val: Member)) {
9652 CXXRecordDecl *PrevRecord;
9653 if (Previous.isSingleResult() &&
9654 (PrevRecord = dyn_cast<CXXRecordDecl>(Val: Previous.getFoundDecl()))) {
9655 FoundInstantiation = Previous.getRepresentativeDecl();
9656 Instantiation = PrevRecord;
9657 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
9658 MSInfo = PrevRecord->getMemberSpecializationInfo();
9659 }
9660 } else if (isa<EnumDecl>(Val: Member)) {
9661 EnumDecl *PrevEnum;
9662 if (Previous.isSingleResult() &&
9663 (PrevEnum = dyn_cast<EnumDecl>(Val: Previous.getFoundDecl()))) {
9664 FoundInstantiation = Previous.getRepresentativeDecl();
9665 Instantiation = PrevEnum;
9666 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
9667 MSInfo = PrevEnum->getMemberSpecializationInfo();
9668 }
9669 }
9670
9671 if (!Instantiation) {
9672 // There is no previous declaration that matches. Since member
9673 // specializations are always out-of-line, the caller will complain about
9674 // this mismatch later.
9675 return false;
9676 }
9677
9678 // A member specialization in a friend declaration isn't really declaring
9679 // an explicit specialization, just identifying a specific (possibly implicit)
9680 // specialization. Don't change the template specialization kind.
9681 //
9682 // FIXME: Is this really valid? Other compilers reject.
9683 if (Member->getFriendObjectKind() != Decl::FOK_None) {
9684 // Preserve instantiation information.
9685 if (InstantiatedFrom && isa<CXXMethodDecl>(Val: Member)) {
9686 cast<CXXMethodDecl>(Val: Member)->setInstantiationOfMemberFunction(
9687 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom),
9688 TSK: cast<CXXMethodDecl>(Val: Instantiation)->getTemplateSpecializationKind());
9689 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Val: Member)) {
9690 cast<CXXRecordDecl>(Val: Member)->setInstantiationOfMemberClass(
9691 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom),
9692 TSK: cast<CXXRecordDecl>(Val: Instantiation)->getTemplateSpecializationKind());
9693 }
9694
9695 Previous.clear();
9696 Previous.addDecl(D: FoundInstantiation);
9697 return false;
9698 }
9699
9700 // Make sure that this is a specialization of a member.
9701 if (!InstantiatedFrom) {
9702 Diag(Loc: Member->getLocation(), DiagID: diag::err_spec_member_not_instantiated)
9703 << Member;
9704 Diag(Loc: Instantiation->getLocation(), DiagID: diag::note_specialized_decl);
9705 return true;
9706 }
9707
9708 // C++ [temp.expl.spec]p6:
9709 // If a template, a member template or the member of a class template is
9710 // explicitly specialized then that specialization shall be declared
9711 // before the first use of that specialization that would cause an implicit
9712 // instantiation to take place, in every translation unit in which such a
9713 // use occurs; no diagnostic is required.
9714 assert(MSInfo && "Member specialization info missing?");
9715
9716 bool HasNoEffect = false;
9717 if (CheckSpecializationInstantiationRedecl(NewLoc: Member->getLocation(),
9718 NewTSK: TSK_ExplicitSpecialization,
9719 PrevDecl: Instantiation,
9720 PrevTSK: MSInfo->getTemplateSpecializationKind(),
9721 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
9722 HasNoEffect))
9723 return true;
9724
9725 // Check the scope of this explicit specialization.
9726 if (CheckTemplateSpecializationScope(S&: *this,
9727 Specialized: InstantiatedFrom,
9728 PrevDecl: Instantiation, Loc: Member->getLocation(),
9729 IsPartialSpecialization: false))
9730 return true;
9731
9732 // Note that this member specialization is an "instantiation of" the
9733 // corresponding member of the original template.
9734 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Val: Member)) {
9735 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Val: Instantiation);
9736 if (InstantiationFunction->getTemplateSpecializationKind() ==
9737 TSK_ImplicitInstantiation) {
9738 // Explicit specializations of member functions of class templates do not
9739 // inherit '=delete' from the member function they are specializing.
9740 if (InstantiationFunction->isDeleted()) {
9741 // FIXME: This assert will not hold in the presence of modules.
9742 assert(InstantiationFunction->getCanonicalDecl() ==
9743 InstantiationFunction);
9744 // FIXME: We need an update record for this AST mutation.
9745 InstantiationFunction->setDeletedAsWritten(D: false);
9746 }
9747 }
9748
9749 MemberFunction->setInstantiationOfMemberFunction(
9750 FD: cast<CXXMethodDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
9751 } else if (auto *MemberVar = dyn_cast<VarDecl>(Val: Member)) {
9752 MemberVar->setInstantiationOfStaticDataMember(
9753 VD: cast<VarDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
9754 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Val: Member)) {
9755 MemberClass->setInstantiationOfMemberClass(
9756 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
9757 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Val: Member)) {
9758 MemberEnum->setInstantiationOfMemberEnum(
9759 ED: cast<EnumDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
9760 } else {
9761 llvm_unreachable("unknown member specialization kind");
9762 }
9763
9764 // Save the caller the trouble of having to figure out which declaration
9765 // this specialization matches.
9766 Previous.clear();
9767 Previous.addDecl(D: FoundInstantiation);
9768 return false;
9769}
9770
9771/// Complete the explicit specialization of a member of a class template by
9772/// updating the instantiated member to be marked as an explicit specialization.
9773///
9774/// \param OrigD The member declaration instantiated from the template.
9775/// \param Loc The location of the explicit specialization of the member.
9776template<typename DeclT>
9777static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
9778 SourceLocation Loc) {
9779 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
9780 return;
9781
9782 // FIXME: Inform AST mutation listeners of this AST mutation.
9783 // FIXME: If there are multiple in-class declarations of the member (from
9784 // multiple modules, or a declaration and later definition of a member type),
9785 // should we update all of them?
9786 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
9787 OrigD->setLocation(Loc);
9788}
9789
9790void Sema::CompleteMemberSpecialization(NamedDecl *Member,
9791 LookupResult &Previous) {
9792 NamedDecl *Instantiation = cast<NamedDecl>(Val: Member->getCanonicalDecl());
9793 if (Instantiation == Member)
9794 return;
9795
9796 if (auto *Function = dyn_cast<CXXMethodDecl>(Val: Instantiation))
9797 completeMemberSpecializationImpl(S&: *this, OrigD: Function, Loc: Member->getLocation());
9798 else if (auto *Var = dyn_cast<VarDecl>(Val: Instantiation))
9799 completeMemberSpecializationImpl(S&: *this, OrigD: Var, Loc: Member->getLocation());
9800 else if (auto *Record = dyn_cast<CXXRecordDecl>(Val: Instantiation))
9801 completeMemberSpecializationImpl(S&: *this, OrigD: Record, Loc: Member->getLocation());
9802 else if (auto *Enum = dyn_cast<EnumDecl>(Val: Instantiation))
9803 completeMemberSpecializationImpl(S&: *this, OrigD: Enum, Loc: Member->getLocation());
9804 else
9805 llvm_unreachable("unknown member specialization kind");
9806}
9807
9808/// Check the scope of an explicit instantiation.
9809///
9810/// \returns true if a serious error occurs, false otherwise.
9811static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
9812 SourceLocation InstLoc,
9813 bool WasQualifiedName) {
9814 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
9815 DeclContext *CurContext = S.CurContext->getRedeclContext();
9816
9817 if (CurContext->isRecord()) {
9818 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_in_class)
9819 << D;
9820 return true;
9821 }
9822
9823 // C++11 [temp.explicit]p3:
9824 // An explicit instantiation shall appear in an enclosing namespace of its
9825 // template. If the name declared in the explicit instantiation is an
9826 // unqualified name, the explicit instantiation shall appear in the
9827 // namespace where its template is declared or, if that namespace is inline
9828 // (7.3.1), any namespace from its enclosing namespace set.
9829 //
9830 // This is DR275, which we do not retroactively apply to C++98/03.
9831 if (WasQualifiedName) {
9832 if (CurContext->Encloses(DC: OrigContext))
9833 return false;
9834 } else {
9835 if (CurContext->InEnclosingNamespaceSetOf(NS: OrigContext))
9836 return false;
9837 }
9838
9839 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: OrigContext)) {
9840 if (WasQualifiedName)
9841 S.Diag(Loc: InstLoc,
9842 DiagID: S.getLangOpts().CPlusPlus11?
9843 diag::err_explicit_instantiation_out_of_scope :
9844 diag::warn_explicit_instantiation_out_of_scope_0x)
9845 << D << NS;
9846 else
9847 S.Diag(Loc: InstLoc,
9848 DiagID: S.getLangOpts().CPlusPlus11?
9849 diag::err_explicit_instantiation_unqualified_wrong_namespace :
9850 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
9851 << D << NS;
9852 } else
9853 S.Diag(Loc: InstLoc,
9854 DiagID: S.getLangOpts().CPlusPlus11?
9855 diag::err_explicit_instantiation_must_be_global :
9856 diag::warn_explicit_instantiation_must_be_global_0x)
9857 << D;
9858 S.Diag(Loc: D->getLocation(), DiagID: diag::note_explicit_instantiation_here);
9859 return false;
9860}
9861
9862/// Common checks for whether an explicit instantiation of \p D is valid.
9863static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
9864 SourceLocation InstLoc,
9865 bool WasQualifiedName,
9866 TemplateSpecializationKind TSK) {
9867 // C++ [temp.explicit]p13:
9868 // An explicit instantiation declaration shall not name a specialization of
9869 // a template with internal linkage.
9870 if (TSK == TSK_ExplicitInstantiationDeclaration &&
9871 D->getFormalLinkage() == Linkage::Internal) {
9872 S.Diag(Loc: InstLoc, DiagID: diag::err_explicit_instantiation_internal_linkage) << D;
9873 return true;
9874 }
9875
9876 // C++11 [temp.explicit]p3: [DR 275]
9877 // An explicit instantiation shall appear in an enclosing namespace of its
9878 // template.
9879 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
9880 return true;
9881
9882 return false;
9883}
9884
9885/// Determine whether the given scope specifier has a template-id in it.
9886static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
9887 if (!SS.isSet())
9888 return false;
9889
9890 // C++11 [temp.explicit]p3:
9891 // If the explicit instantiation is for a member function, a member class
9892 // or a static data member of a class template specialization, the name of
9893 // the class template specialization in the qualified-id for the member
9894 // name shall be a simple-template-id.
9895 //
9896 // C++98 has the same restriction, just worded differently.
9897 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
9898 NNS = NNS->getPrefix())
9899 if (const Type *T = NNS->getAsType())
9900 if (isa<TemplateSpecializationType>(Val: T))
9901 return true;
9902
9903 return false;
9904}
9905
9906/// Make a dllexport or dllimport attr on a class template specialization take
9907/// effect.
9908static void dllExportImportClassTemplateSpecialization(
9909 Sema &S, ClassTemplateSpecializationDecl *Def) {
9910 auto *A = cast_or_null<InheritableAttr>(Val: getDLLAttr(D: Def));
9911 assert(A && "dllExportImportClassTemplateSpecialization called "
9912 "on Def without dllexport or dllimport");
9913
9914 // We reject explicit instantiations in class scope, so there should
9915 // never be any delayed exported classes to worry about.
9916 assert(S.DelayedDllExportClasses.empty() &&
9917 "delayed exports present at explicit instantiation");
9918 S.checkClassLevelDLLAttribute(Class: Def);
9919
9920 // Propagate attribute to base class templates.
9921 for (auto &B : Def->bases()) {
9922 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
9923 Val: B.getType()->getAsCXXRecordDecl()))
9924 S.propagateDLLAttrToBaseClassTemplate(Class: Def, ClassAttr: A, BaseTemplateSpec: BT, BaseLoc: B.getBeginLoc());
9925 }
9926
9927 S.referenceDLLExportedClassMethods();
9928}
9929
9930DeclResult Sema::ActOnExplicitInstantiation(
9931 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
9932 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
9933 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
9934 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
9935 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
9936 // Find the class template we're specializing
9937 TemplateName Name = TemplateD.get();
9938 TemplateDecl *TD = Name.getAsTemplateDecl();
9939 // Check that the specialization uses the same tag kind as the
9940 // original template.
9941 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
9942 assert(Kind != TagTypeKind::Enum &&
9943 "Invalid enum tag in class template explicit instantiation!");
9944
9945 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: TD);
9946
9947 if (!ClassTemplate) {
9948 NonTagKind NTK = getNonTagTypeDeclKind(D: TD, TTK: Kind);
9949 Diag(Loc: TemplateNameLoc, DiagID: diag::err_tag_reference_non_tag) << TD << NTK << Kind;
9950 Diag(Loc: TD->getLocation(), DiagID: diag::note_previous_use);
9951 return true;
9952 }
9953
9954 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(),
9955 NewTag: Kind, /*isDefinition*/false, NewTagLoc: KWLoc,
9956 Name: ClassTemplate->getIdentifier())) {
9957 Diag(Loc: KWLoc, DiagID: diag::err_use_with_wrong_tag)
9958 << ClassTemplate
9959 << FixItHint::CreateReplacement(RemoveRange: KWLoc,
9960 Code: ClassTemplate->getTemplatedDecl()->getKindName());
9961 Diag(Loc: ClassTemplate->getTemplatedDecl()->getLocation(),
9962 DiagID: diag::note_previous_use);
9963 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9964 }
9965
9966 // C++0x [temp.explicit]p2:
9967 // There are two forms of explicit instantiation: an explicit instantiation
9968 // definition and an explicit instantiation declaration. An explicit
9969 // instantiation declaration begins with the extern keyword. [...]
9970 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
9971 ? TSK_ExplicitInstantiationDefinition
9972 : TSK_ExplicitInstantiationDeclaration;
9973
9974 if (TSK == TSK_ExplicitInstantiationDeclaration &&
9975 !Context.getTargetInfo().getTriple().isOSCygMing()) {
9976 // Check for dllexport class template instantiation declarations,
9977 // except for MinGW mode.
9978 for (const ParsedAttr &AL : Attr) {
9979 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
9980 Diag(Loc: ExternLoc,
9981 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
9982 Diag(Loc: AL.getLoc(), DiagID: diag::note_attribute);
9983 break;
9984 }
9985 }
9986
9987 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
9988 Diag(Loc: ExternLoc,
9989 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_decl);
9990 Diag(Loc: A->getLocation(), DiagID: diag::note_attribute);
9991 }
9992 }
9993
9994 // In MSVC mode, dllimported explicit instantiation definitions are treated as
9995 // instantiation declarations for most purposes.
9996 bool DLLImportExplicitInstantiationDef = false;
9997 if (TSK == TSK_ExplicitInstantiationDefinition &&
9998 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9999 // Check for dllimport class template instantiation definitions.
10000 bool DLLImport =
10001 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10002 for (const ParsedAttr &AL : Attr) {
10003 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10004 DLLImport = true;
10005 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10006 // dllexport trumps dllimport here.
10007 DLLImport = false;
10008 break;
10009 }
10010 }
10011 if (DLLImport) {
10012 TSK = TSK_ExplicitInstantiationDeclaration;
10013 DLLImportExplicitInstantiationDef = true;
10014 }
10015 }
10016
10017 // Translate the parser's template argument list in our AST format.
10018 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10019 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10020
10021 // Check that the template argument list is well-formed for this
10022 // template.
10023 CheckTemplateArgumentInfo CTAI;
10024 if (CheckTemplateArgumentList(Template: ClassTemplate, TemplateLoc: TemplateNameLoc, TemplateArgs,
10025 /*DefaultArgs=*/{}, PartialTemplateArgs: false, CTAI,
10026 /*UpdateArgsWithConversions=*/true,
10027 /*ConstraintsNotSatisfied=*/nullptr))
10028 return true;
10029
10030 // Find the class template specialization declaration that
10031 // corresponds to these arguments.
10032 void *InsertPos = nullptr;
10033 ClassTemplateSpecializationDecl *PrevDecl =
10034 ClassTemplate->findSpecialization(Args: CTAI.CanonicalConverted, InsertPos);
10035
10036 TemplateSpecializationKind PrevDecl_TSK
10037 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10038
10039 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10040 Context.getTargetInfo().getTriple().isOSCygMing()) {
10041 // Check for dllexport class template instantiation definitions in MinGW
10042 // mode, if a previous declaration of the instantiation was seen.
10043 for (const ParsedAttr &AL : Attr) {
10044 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10045 Diag(Loc: AL.getLoc(),
10046 DiagID: diag::warn_attribute_dllexport_explicit_instantiation_def);
10047 break;
10048 }
10049 }
10050 }
10051
10052 if (CheckExplicitInstantiation(S&: *this, D: ClassTemplate, InstLoc: TemplateNameLoc,
10053 WasQualifiedName: SS.isSet(), TSK))
10054 return true;
10055
10056 ClassTemplateSpecializationDecl *Specialization = nullptr;
10057
10058 bool HasNoEffect = false;
10059 if (PrevDecl) {
10060 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateNameLoc, NewTSK: TSK,
10061 PrevDecl, PrevTSK: PrevDecl_TSK,
10062 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
10063 HasNoEffect))
10064 return PrevDecl;
10065
10066 // Even though HasNoEffect == true means that this explicit instantiation
10067 // has no effect on semantics, we go on to put its syntax in the AST.
10068
10069 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10070 PrevDecl_TSK == TSK_Undeclared) {
10071 // Since the only prior class template specialization with these
10072 // arguments was referenced but not declared, reuse that
10073 // declaration node as our own, updating the source location
10074 // for the template name to reflect our new declaration.
10075 // (Other source locations will be updated later.)
10076 Specialization = PrevDecl;
10077 Specialization->setLocation(TemplateNameLoc);
10078 PrevDecl = nullptr;
10079 }
10080
10081 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10082 DLLImportExplicitInstantiationDef) {
10083 // The new specialization might add a dllimport attribute.
10084 HasNoEffect = false;
10085 }
10086 }
10087
10088 if (!Specialization) {
10089 // Create a new class template specialization declaration node for
10090 // this explicit specialization.
10091 Specialization = ClassTemplateSpecializationDecl::Create(
10092 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
10093 SpecializedTemplate: ClassTemplate, Args: CTAI.CanonicalConverted, StrictPackMatch: CTAI.StrictPackMatch, PrevDecl);
10094 SetNestedNameSpecifier(S&: *this, T: Specialization, SS);
10095
10096 // A MSInheritanceAttr attached to the previous declaration must be
10097 // propagated to the new node prior to instantiation.
10098 if (PrevDecl) {
10099 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10100 auto *Clone = A->clone(C&: getASTContext());
10101 Clone->setInherited(true);
10102 Specialization->addAttr(A: Clone);
10103 Consumer.AssignInheritanceModel(RD: Specialization);
10104 }
10105 }
10106
10107 if (!HasNoEffect && !PrevDecl) {
10108 // Insert the new specialization.
10109 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
10110 }
10111 }
10112
10113 Specialization->setTemplateArgsAsWritten(TemplateArgs);
10114
10115 // Set source locations for keywords.
10116 Specialization->setExternKeywordLoc(ExternLoc);
10117 Specialization->setTemplateKeywordLoc(TemplateLoc);
10118 Specialization->setBraceRange(SourceRange());
10119
10120 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10121 ProcessDeclAttributeList(S, D: Specialization, AttrList: Attr);
10122 ProcessAPINotes(D: Specialization);
10123
10124 // Add the explicit instantiation into its lexical context. However,
10125 // since explicit instantiations are never found by name lookup, we
10126 // just put it into the declaration context directly.
10127 Specialization->setLexicalDeclContext(CurContext);
10128 CurContext->addDecl(D: Specialization);
10129
10130 // Syntax is now OK, so return if it has no other effect on semantics.
10131 if (HasNoEffect) {
10132 // Set the template specialization kind.
10133 Specialization->setTemplateSpecializationKind(TSK);
10134 return Specialization;
10135 }
10136
10137 // C++ [temp.explicit]p3:
10138 // A definition of a class template or class member template
10139 // shall be in scope at the point of the explicit instantiation of
10140 // the class template or class member template.
10141 //
10142 // This check comes when we actually try to perform the
10143 // instantiation.
10144 ClassTemplateSpecializationDecl *Def
10145 = cast_or_null<ClassTemplateSpecializationDecl>(
10146 Val: Specialization->getDefinition());
10147 if (!Def)
10148 InstantiateClassTemplateSpecialization(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Specialization, TSK,
10149 /*Complain=*/true,
10150 PrimaryStrictPackMatch: CTAI.StrictPackMatch);
10151 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10152 MarkVTableUsed(Loc: TemplateNameLoc, Class: Specialization, DefinitionRequired: true);
10153 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10154 }
10155
10156 // Instantiate the members of this class template specialization.
10157 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10158 Val: Specialization->getDefinition());
10159 if (Def) {
10160 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
10161 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10162 // TSK_ExplicitInstantiationDefinition
10163 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10164 (TSK == TSK_ExplicitInstantiationDefinition ||
10165 DLLImportExplicitInstantiationDef)) {
10166 // FIXME: Need to notify the ASTMutationListener that we did this.
10167 Def->setTemplateSpecializationKind(TSK);
10168
10169 if (!getDLLAttr(D: Def) && getDLLAttr(D: Specialization) &&
10170 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10171 // An explicit instantiation definition can add a dll attribute to a
10172 // template with a previous instantiation declaration. MinGW doesn't
10173 // allow this.
10174 auto *A = cast<InheritableAttr>(
10175 Val: getDLLAttr(D: Specialization)->clone(C&: getASTContext()));
10176 A->setInherited(true);
10177 Def->addAttr(A);
10178 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10179 }
10180 }
10181
10182 // Fix a TSK_ImplicitInstantiation followed by a
10183 // TSK_ExplicitInstantiationDefinition
10184 bool NewlyDLLExported =
10185 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10186 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10187 Context.getTargetInfo().shouldDLLImportComdatSymbols()) {
10188 // An explicit instantiation definition can add a dll attribute to a
10189 // template with a previous implicit instantiation. MinGW doesn't allow
10190 // this. We limit clang to only adding dllexport, to avoid potentially
10191 // strange codegen behavior. For example, if we extend this conditional
10192 // to dllimport, and we have a source file calling a method on an
10193 // implicitly instantiated template class instance and then declaring a
10194 // dllimport explicit instantiation definition for the same template
10195 // class, the codegen for the method call will not respect the dllimport,
10196 // while it will with cl. The Def will already have the DLL attribute,
10197 // since the Def and Specialization will be the same in the case of
10198 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10199 // attribute to the Specialization; we just need to make it take effect.
10200 assert(Def == Specialization &&
10201 "Def and Specialization should match for implicit instantiation");
10202 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10203 }
10204
10205 // In MinGW mode, export the template instantiation if the declaration
10206 // was marked dllexport.
10207 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10208 Context.getTargetInfo().getTriple().isOSCygMing() &&
10209 PrevDecl->hasAttr<DLLExportAttr>()) {
10210 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10211 }
10212
10213 // Set the template specialization kind. Make sure it is set before
10214 // instantiating the members which will trigger ASTConsumer callbacks.
10215 Specialization->setTemplateSpecializationKind(TSK);
10216 InstantiateClassTemplateSpecializationMembers(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Def, TSK);
10217 } else {
10218
10219 // Set the template specialization kind.
10220 Specialization->setTemplateSpecializationKind(TSK);
10221 }
10222
10223 return Specialization;
10224}
10225
10226DeclResult
10227Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10228 SourceLocation TemplateLoc, unsigned TagSpec,
10229 SourceLocation KWLoc, CXXScopeSpec &SS,
10230 IdentifierInfo *Name, SourceLocation NameLoc,
10231 const ParsedAttributesView &Attr) {
10232
10233 bool Owned = false;
10234 bool IsDependent = false;
10235 Decl *TagD =
10236 ActOnTag(S, TagSpec, TUK: TagUseKind::Reference, KWLoc, SS, Name, NameLoc,
10237 Attr, AS: AS_none, /*ModulePrivateLoc=*/SourceLocation(),
10238 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent, ScopedEnumKWLoc: SourceLocation(),
10239 ScopedEnumUsesClassTag: false, UnderlyingType: TypeResult(), /*IsTypeSpecifier*/ false,
10240 /*IsTemplateParamOrArg*/ false, /*OOK=*/OffsetOfKind::Outside)
10241 .get();
10242 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
10243
10244 if (!TagD)
10245 return true;
10246
10247 TagDecl *Tag = cast<TagDecl>(Val: TagD);
10248 assert(!Tag->isEnum() && "shouldn't see enumerations here");
10249
10250 if (Tag->isInvalidDecl())
10251 return true;
10252
10253 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: Tag);
10254 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
10255 if (!Pattern) {
10256 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_nontemplate_type)
10257 << Context.getTypeDeclType(Decl: Record);
10258 Diag(Loc: Record->getLocation(), DiagID: diag::note_nontemplate_decl_here);
10259 return true;
10260 }
10261
10262 // C++0x [temp.explicit]p2:
10263 // If the explicit instantiation is for a class or member class, the
10264 // elaborated-type-specifier in the declaration shall include a
10265 // simple-template-id.
10266 //
10267 // C++98 has the same restriction, just worded differently.
10268 if (!ScopeSpecifierHasTemplateId(SS))
10269 Diag(Loc: TemplateLoc, DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10270 << Record << SS.getRange();
10271
10272 // C++0x [temp.explicit]p2:
10273 // There are two forms of explicit instantiation: an explicit instantiation
10274 // definition and an explicit instantiation declaration. An explicit
10275 // instantiation declaration begins with the extern keyword. [...]
10276 TemplateSpecializationKind TSK
10277 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10278 : TSK_ExplicitInstantiationDeclaration;
10279
10280 CheckExplicitInstantiation(S&: *this, D: Record, InstLoc: NameLoc, WasQualifiedName: true, TSK);
10281
10282 // Verify that it is okay to explicitly instantiate here.
10283 CXXRecordDecl *PrevDecl
10284 = cast_or_null<CXXRecordDecl>(Val: Record->getPreviousDecl());
10285 if (!PrevDecl && Record->getDefinition())
10286 PrevDecl = Record;
10287 if (PrevDecl) {
10288 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
10289 bool HasNoEffect = false;
10290 assert(MSInfo && "No member specialization information?");
10291 if (CheckSpecializationInstantiationRedecl(NewLoc: TemplateLoc, NewTSK: TSK,
10292 PrevDecl,
10293 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10294 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10295 HasNoEffect))
10296 return true;
10297 if (HasNoEffect)
10298 return TagD;
10299 }
10300
10301 CXXRecordDecl *RecordDef
10302 = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10303 if (!RecordDef) {
10304 // C++ [temp.explicit]p3:
10305 // A definition of a member class of a class template shall be in scope
10306 // at the point of an explicit instantiation of the member class.
10307 CXXRecordDecl *Def
10308 = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition());
10309 if (!Def) {
10310 Diag(Loc: TemplateLoc, DiagID: diag::err_explicit_instantiation_undefined_member)
10311 << 0 << Record->getDeclName() << Record->getDeclContext();
10312 Diag(Loc: Pattern->getLocation(), DiagID: diag::note_forward_declaration)
10313 << Pattern;
10314 return true;
10315 } else {
10316 if (InstantiateClass(PointOfInstantiation: NameLoc, Instantiation: Record, Pattern: Def,
10317 TemplateArgs: getTemplateInstantiationArgs(D: Record),
10318 TSK))
10319 return true;
10320
10321 RecordDef = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
10322 if (!RecordDef)
10323 return true;
10324 }
10325 }
10326
10327 // Instantiate all of the members of the class.
10328 InstantiateClassMembers(PointOfInstantiation: NameLoc, Instantiation: RecordDef,
10329 TemplateArgs: getTemplateInstantiationArgs(D: Record), TSK);
10330
10331 if (TSK == TSK_ExplicitInstantiationDefinition)
10332 MarkVTableUsed(Loc: NameLoc, Class: RecordDef, DefinitionRequired: true);
10333
10334 // FIXME: We don't have any representation for explicit instantiations of
10335 // member classes. Such a representation is not needed for compilation, but it
10336 // should be available for clients that want to see all of the declarations in
10337 // the source code.
10338 return TagD;
10339}
10340
10341DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
10342 SourceLocation ExternLoc,
10343 SourceLocation TemplateLoc,
10344 Declarator &D) {
10345 // Explicit instantiations always require a name.
10346 // TODO: check if/when DNInfo should replace Name.
10347 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
10348 DeclarationName Name = NameInfo.getName();
10349 if (!Name) {
10350 if (!D.isInvalidType())
10351 Diag(Loc: D.getDeclSpec().getBeginLoc(),
10352 DiagID: diag::err_explicit_instantiation_requires_name)
10353 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
10354
10355 return true;
10356 }
10357
10358 // Get the innermost enclosing declaration scope.
10359 S = S->getDeclParent();
10360
10361 // Determine the type of the declaration.
10362 TypeSourceInfo *T = GetTypeForDeclarator(D);
10363 QualType R = T->getType();
10364 if (R.isNull())
10365 return true;
10366
10367 // C++ [dcl.stc]p1:
10368 // A storage-class-specifier shall not be specified in [...] an explicit
10369 // instantiation (14.7.2) directive.
10370 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
10371 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_of_typedef)
10372 << Name;
10373 return true;
10374 } else if (D.getDeclSpec().getStorageClassSpec()
10375 != DeclSpec::SCS_unspecified) {
10376 // Complain about then remove the storage class specifier.
10377 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_storage_class)
10378 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
10379
10380 D.getMutableDeclSpec().ClearStorageClassSpecs();
10381 }
10382
10383 // C++0x [temp.explicit]p1:
10384 // [...] An explicit instantiation of a function template shall not use the
10385 // inline or constexpr specifiers.
10386 // Presumably, this also applies to member functions of class templates as
10387 // well.
10388 if (D.getDeclSpec().isInlineSpecified())
10389 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(),
10390 DiagID: getLangOpts().CPlusPlus11 ?
10391 diag::err_explicit_instantiation_inline :
10392 diag::warn_explicit_instantiation_inline_0x)
10393 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getInlineSpecLoc());
10394 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
10395 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
10396 // not already specified.
10397 Diag(Loc: D.getDeclSpec().getConstexprSpecLoc(),
10398 DiagID: diag::err_explicit_instantiation_constexpr);
10399
10400 // A deduction guide is not on the list of entities that can be explicitly
10401 // instantiated.
10402 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
10403 Diag(Loc: D.getDeclSpec().getBeginLoc(), DiagID: diag::err_deduction_guide_specialized)
10404 << /*explicit instantiation*/ 0;
10405 return true;
10406 }
10407
10408 // C++0x [temp.explicit]p2:
10409 // There are two forms of explicit instantiation: an explicit instantiation
10410 // definition and an explicit instantiation declaration. An explicit
10411 // instantiation declaration begins with the extern keyword. [...]
10412 TemplateSpecializationKind TSK
10413 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
10414 : TSK_ExplicitInstantiationDeclaration;
10415
10416 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
10417 LookupParsedName(R&: Previous, S, SS: &D.getCXXScopeSpec(),
10418 /*ObjectType=*/QualType());
10419
10420 if (!R->isFunctionType()) {
10421 // C++ [temp.explicit]p1:
10422 // A [...] static data member of a class template can be explicitly
10423 // instantiated from the member definition associated with its class
10424 // template.
10425 // C++1y [temp.explicit]p1:
10426 // A [...] variable [...] template specialization can be explicitly
10427 // instantiated from its template.
10428 if (Previous.isAmbiguous())
10429 return true;
10430
10431 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
10432 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
10433
10434 if (!PrevTemplate) {
10435 if (!Prev || !Prev->isStaticDataMember()) {
10436 // We expect to see a static data member here.
10437 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_not_known)
10438 << Name;
10439 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10440 P != PEnd; ++P)
10441 Diag(Loc: (*P)->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10442 return true;
10443 }
10444
10445 if (!Prev->getInstantiatedFromStaticDataMember()) {
10446 // FIXME: Check for explicit specialization?
10447 Diag(Loc: D.getIdentifierLoc(),
10448 DiagID: diag::err_explicit_instantiation_data_member_not_instantiated)
10449 << Prev;
10450 Diag(Loc: Prev->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10451 // FIXME: Can we provide a note showing where this was declared?
10452 return true;
10453 }
10454 } else {
10455 // Explicitly instantiate a variable template.
10456
10457 // C++1y [dcl.spec.auto]p6:
10458 // ... A program that uses auto or decltype(auto) in a context not
10459 // explicitly allowed in this section is ill-formed.
10460 //
10461 // This includes auto-typed variable template instantiations.
10462 if (R->isUndeducedType()) {
10463 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10464 DiagID: diag::err_auto_not_allowed_var_inst);
10465 return true;
10466 }
10467
10468 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
10469 // C++1y [temp.explicit]p3:
10470 // If the explicit instantiation is for a variable, the unqualified-id
10471 // in the declaration shall be a template-id.
10472 Diag(Loc: D.getIdentifierLoc(),
10473 DiagID: diag::err_explicit_instantiation_without_template_id)
10474 << PrevTemplate;
10475 Diag(Loc: PrevTemplate->getLocation(),
10476 DiagID: diag::note_explicit_instantiation_here);
10477 return true;
10478 }
10479
10480 // Translate the parser's template argument list into our AST format.
10481 TemplateArgumentListInfo TemplateArgs =
10482 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10483
10484 DeclResult Res = CheckVarTemplateId(Template: PrevTemplate, TemplateLoc,
10485 TemplateNameLoc: D.getIdentifierLoc(), TemplateArgs);
10486 if (Res.isInvalid())
10487 return true;
10488
10489 if (!Res.isUsable()) {
10490 // We somehow specified dependent template arguments in an explicit
10491 // instantiation. This should probably only happen during error
10492 // recovery.
10493 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_explicit_instantiation_dependent);
10494 return true;
10495 }
10496
10497 // Ignore access control bits, we don't need them for redeclaration
10498 // checking.
10499 Prev = cast<VarDecl>(Val: Res.get());
10500 }
10501
10502 // C++0x [temp.explicit]p2:
10503 // If the explicit instantiation is for a member function, a member class
10504 // or a static data member of a class template specialization, the name of
10505 // the class template specialization in the qualified-id for the member
10506 // name shall be a simple-template-id.
10507 //
10508 // C++98 has the same restriction, just worded differently.
10509 //
10510 // This does not apply to variable template specializations, where the
10511 // template-id is in the unqualified-id instead.
10512 if (!ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()) && !PrevTemplate)
10513 Diag(Loc: D.getIdentifierLoc(),
10514 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10515 << Prev << D.getCXXScopeSpec().getRange();
10516
10517 CheckExplicitInstantiation(S&: *this, D: Prev, InstLoc: D.getIdentifierLoc(), WasQualifiedName: true, TSK);
10518
10519 // Verify that it is okay to explicitly instantiate here.
10520 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
10521 SourceLocation POI = Prev->getPointOfInstantiation();
10522 bool HasNoEffect = false;
10523 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK, PrevDecl: Prev,
10524 PrevTSK, PrevPointOfInstantiation: POI, HasNoEffect))
10525 return true;
10526
10527 if (!HasNoEffect) {
10528 // Instantiate static data member or variable template.
10529 Prev->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
10530 if (auto *VTSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: Prev)) {
10531 VTSD->setExternKeywordLoc(ExternLoc);
10532 VTSD->setTemplateKeywordLoc(TemplateLoc);
10533 }
10534
10535 // Merge attributes.
10536 ProcessDeclAttributeList(S, D: Prev, AttrList: D.getDeclSpec().getAttributes());
10537 if (PrevTemplate)
10538 ProcessAPINotes(D: Prev);
10539
10540 if (TSK == TSK_ExplicitInstantiationDefinition)
10541 InstantiateVariableDefinition(PointOfInstantiation: D.getIdentifierLoc(), Var: Prev);
10542 }
10543
10544 // Check the new variable specialization against the parsed input.
10545 if (PrevTemplate && !Context.hasSameType(T1: Prev->getType(), T2: R)) {
10546 Diag(Loc: T->getTypeLoc().getBeginLoc(),
10547 DiagID: diag::err_invalid_var_template_spec_type)
10548 << 0 << PrevTemplate << R << Prev->getType();
10549 Diag(Loc: PrevTemplate->getLocation(), DiagID: diag::note_template_declared_here)
10550 << 2 << PrevTemplate->getDeclName();
10551 return true;
10552 }
10553
10554 // FIXME: Create an ExplicitInstantiation node?
10555 return (Decl*) nullptr;
10556 }
10557
10558 // If the declarator is a template-id, translate the parser's template
10559 // argument list into our AST format.
10560 bool HasExplicitTemplateArgs = false;
10561 TemplateArgumentListInfo TemplateArgs;
10562 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
10563 TemplateArgs = makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
10564 HasExplicitTemplateArgs = true;
10565 }
10566
10567 // C++ [temp.explicit]p1:
10568 // A [...] function [...] can be explicitly instantiated from its template.
10569 // A member function [...] of a class template can be explicitly
10570 // instantiated from the member definition associated with its class
10571 // template.
10572 UnresolvedSet<8> TemplateMatches;
10573 OverloadCandidateSet NonTemplateMatches(D.getBeginLoc(),
10574 OverloadCandidateSet::CSK_Normal);
10575 TemplateSpecCandidateSet FailedTemplateCandidates(D.getIdentifierLoc());
10576 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
10577 P != PEnd; ++P) {
10578 NamedDecl *Prev = *P;
10579 if (!HasExplicitTemplateArgs) {
10580 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Prev)) {
10581 QualType Adjusted = adjustCCAndNoReturn(ArgFunctionType: R, FunctionType: Method->getType(),
10582 /*AdjustExceptionSpec*/true);
10583 if (Context.hasSameUnqualifiedType(T1: Method->getType(), T2: Adjusted)) {
10584 if (Method->getPrimaryTemplate()) {
10585 TemplateMatches.addDecl(D: Method, AS: P.getAccess());
10586 } else {
10587 OverloadCandidate &C = NonTemplateMatches.addCandidate();
10588 C.FoundDecl = P.getPair();
10589 C.Function = Method;
10590 C.Viable = true;
10591 ConstraintSatisfaction S;
10592 if (Method->getTrailingRequiresClause() &&
10593 (CheckFunctionConstraints(FD: Method, Satisfaction&: S, UsageLoc: D.getIdentifierLoc(),
10594 /*ForOverloadResolution=*/true) ||
10595 !S.IsSatisfied)) {
10596 C.Viable = false;
10597 C.FailureKind = ovl_fail_constraints_not_satisfied;
10598 }
10599 }
10600 }
10601 }
10602 }
10603
10604 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Prev);
10605 if (!FunTmpl)
10606 continue;
10607
10608 TemplateDeductionInfo Info(FailedTemplateCandidates.getLocation());
10609 FunctionDecl *Specialization = nullptr;
10610 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
10611 FunctionTemplate: FunTmpl, ExplicitTemplateArgs: (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), ArgFunctionType: R,
10612 Specialization, Info);
10613 TDK != TemplateDeductionResult::Success) {
10614 // Keep track of almost-matches.
10615 FailedTemplateCandidates.addCandidate().set(
10616 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
10617 Info: MakeDeductionFailureInfo(Context, TDK, Info));
10618 (void)TDK;
10619 continue;
10620 }
10621
10622 // Target attributes are part of the cuda function signature, so
10623 // the cuda target of the instantiated function must match that of its
10624 // template. Given that C++ template deduction does not take
10625 // target attributes into account, we reject candidates here that
10626 // have a different target.
10627 if (LangOpts.CUDA &&
10628 CUDA().IdentifyTarget(D: Specialization,
10629 /* IgnoreImplicitHDAttr = */ true) !=
10630 CUDA().IdentifyTarget(Attrs: D.getDeclSpec().getAttributes())) {
10631 FailedTemplateCandidates.addCandidate().set(
10632 Found: P.getPair(), Spec: FunTmpl->getTemplatedDecl(),
10633 Info: MakeDeductionFailureInfo(
10634 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
10635 continue;
10636 }
10637
10638 TemplateMatches.addDecl(D: Specialization, AS: P.getAccess());
10639 }
10640
10641 FunctionDecl *Specialization = nullptr;
10642 if (!NonTemplateMatches.empty()) {
10643 unsigned Msg = 0;
10644 OverloadCandidateDisplayKind DisplayKind;
10645 OverloadCandidateSet::iterator Best;
10646 switch (NonTemplateMatches.BestViableFunction(S&: *this, Loc: D.getIdentifierLoc(),
10647 Best)) {
10648 case OR_Success:
10649 case OR_Deleted:
10650 Specialization = cast<FunctionDecl>(Val: Best->Function);
10651 break;
10652 case OR_Ambiguous:
10653 Msg = diag::err_explicit_instantiation_ambiguous;
10654 DisplayKind = OCD_AmbiguousCandidates;
10655 break;
10656 case OR_No_Viable_Function:
10657 Msg = diag::err_explicit_instantiation_no_candidate;
10658 DisplayKind = OCD_AllCandidates;
10659 break;
10660 }
10661 if (Msg) {
10662 PartialDiagnostic Diag = PDiag(DiagID: Msg) << Name;
10663 NonTemplateMatches.NoteCandidates(
10664 PA: PartialDiagnosticAt(D.getIdentifierLoc(), Diag), S&: *this, OCD: DisplayKind,
10665 Args: {});
10666 return true;
10667 }
10668 }
10669
10670 if (!Specialization) {
10671 // Find the most specialized function template specialization.
10672 UnresolvedSetIterator Result = getMostSpecialized(
10673 SBegin: TemplateMatches.begin(), SEnd: TemplateMatches.end(),
10674 FailedCandidates&: FailedTemplateCandidates, Loc: D.getIdentifierLoc(),
10675 NoneDiag: PDiag(DiagID: diag::err_explicit_instantiation_not_known) << Name,
10676 AmbigDiag: PDiag(DiagID: diag::err_explicit_instantiation_ambiguous) << Name,
10677 CandidateDiag: PDiag(DiagID: diag::note_explicit_instantiation_candidate));
10678
10679 if (Result == TemplateMatches.end())
10680 return true;
10681
10682 // Ignore access control bits, we don't need them for redeclaration checking.
10683 Specialization = cast<FunctionDecl>(Val: *Result);
10684 }
10685
10686 // C++11 [except.spec]p4
10687 // In an explicit instantiation an exception-specification may be specified,
10688 // but is not required.
10689 // If an exception-specification is specified in an explicit instantiation
10690 // directive, it shall be compatible with the exception-specifications of
10691 // other declarations of that function.
10692 if (auto *FPT = R->getAs<FunctionProtoType>())
10693 if (FPT->hasExceptionSpec()) {
10694 unsigned DiagID =
10695 diag::err_mismatched_exception_spec_explicit_instantiation;
10696 if (getLangOpts().MicrosoftExt)
10697 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
10698 bool Result = CheckEquivalentExceptionSpec(
10699 DiagID: PDiag(DiagID) << Specialization->getType(),
10700 NoteID: PDiag(DiagID: diag::note_explicit_instantiation_here),
10701 Old: Specialization->getType()->getAs<FunctionProtoType>(),
10702 OldLoc: Specialization->getLocation(), New: FPT, NewLoc: D.getBeginLoc());
10703 // In Microsoft mode, mismatching exception specifications just cause a
10704 // warning.
10705 if (!getLangOpts().MicrosoftExt && Result)
10706 return true;
10707 }
10708
10709 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
10710 Diag(Loc: D.getIdentifierLoc(),
10711 DiagID: diag::err_explicit_instantiation_member_function_not_instantiated)
10712 << Specialization
10713 << (Specialization->getTemplateSpecializationKind() ==
10714 TSK_ExplicitSpecialization);
10715 Diag(Loc: Specialization->getLocation(), DiagID: diag::note_explicit_instantiation_here);
10716 return true;
10717 }
10718
10719 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
10720 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
10721 PrevDecl = Specialization;
10722
10723 if (PrevDecl) {
10724 bool HasNoEffect = false;
10725 if (CheckSpecializationInstantiationRedecl(NewLoc: D.getIdentifierLoc(), NewTSK: TSK,
10726 PrevDecl,
10727 PrevTSK: PrevDecl->getTemplateSpecializationKind(),
10728 PrevPointOfInstantiation: PrevDecl->getPointOfInstantiation(),
10729 HasNoEffect))
10730 return true;
10731
10732 // FIXME: We may still want to build some representation of this
10733 // explicit specialization.
10734 if (HasNoEffect)
10735 return (Decl*) nullptr;
10736 }
10737
10738 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
10739 // functions
10740 // valarray<size_t>::valarray(size_t) and
10741 // valarray<size_t>::~valarray()
10742 // that it declared to have internal linkage with the internal_linkage
10743 // attribute. Ignore the explicit instantiation declaration in this case.
10744 if (Specialization->hasAttr<InternalLinkageAttr>() &&
10745 TSK == TSK_ExplicitInstantiationDeclaration) {
10746 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: Specialization->getDeclContext()))
10747 if (RD->getIdentifier() && RD->getIdentifier()->isStr(Str: "valarray") &&
10748 RD->isInStdNamespace())
10749 return (Decl*) nullptr;
10750 }
10751
10752 ProcessDeclAttributeList(S, D: Specialization, AttrList: D.getDeclSpec().getAttributes());
10753 ProcessAPINotes(D: Specialization);
10754
10755 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10756 // instantiation declarations.
10757 if (TSK == TSK_ExplicitInstantiationDefinition &&
10758 Specialization->hasAttr<DLLImportAttr>() &&
10759 Context.getTargetInfo().getCXXABI().isMicrosoft())
10760 TSK = TSK_ExplicitInstantiationDeclaration;
10761
10762 Specialization->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
10763
10764 if (Specialization->isDefined()) {
10765 // Let the ASTConsumer know that this function has been explicitly
10766 // instantiated now, and its linkage might have changed.
10767 Consumer.HandleTopLevelDecl(D: DeclGroupRef(Specialization));
10768 } else if (TSK == TSK_ExplicitInstantiationDefinition)
10769 InstantiateFunctionDefinition(PointOfInstantiation: D.getIdentifierLoc(), Function: Specialization);
10770
10771 // C++0x [temp.explicit]p2:
10772 // If the explicit instantiation is for a member function, a member class
10773 // or a static data member of a class template specialization, the name of
10774 // the class template specialization in the qualified-id for the member
10775 // name shall be a simple-template-id.
10776 //
10777 // C++98 has the same restriction, just worded differently.
10778 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
10779 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
10780 D.getCXXScopeSpec().isSet() &&
10781 !ScopeSpecifierHasTemplateId(SS: D.getCXXScopeSpec()))
10782 Diag(Loc: D.getIdentifierLoc(),
10783 DiagID: diag::ext_explicit_instantiation_without_qualified_id)
10784 << Specialization << D.getCXXScopeSpec().getRange();
10785
10786 CheckExplicitInstantiation(
10787 S&: *this,
10788 D: FunTmpl ? (NamedDecl *)FunTmpl
10789 : Specialization->getInstantiatedFromMemberFunction(),
10790 InstLoc: D.getIdentifierLoc(), WasQualifiedName: D.getCXXScopeSpec().isSet(), TSK);
10791
10792 // FIXME: Create some kind of ExplicitInstantiationDecl here.
10793 return (Decl*) nullptr;
10794}
10795
10796TypeResult Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
10797 const CXXScopeSpec &SS,
10798 const IdentifierInfo *Name,
10799 SourceLocation TagLoc,
10800 SourceLocation NameLoc) {
10801 // This has to hold, because SS is expected to be defined.
10802 assert(Name && "Expected a name in a dependent tag");
10803
10804 NestedNameSpecifier *NNS = SS.getScopeRep();
10805 if (!NNS)
10806 return true;
10807
10808 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10809
10810 if (TUK == TagUseKind::Declaration || TUK == TagUseKind::Definition) {
10811 Diag(Loc: NameLoc, DiagID: diag::err_dependent_tag_decl)
10812 << (TUK == TagUseKind::Definition) << Kind << SS.getRange();
10813 return true;
10814 }
10815
10816 // Create the resulting type.
10817 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
10818 QualType Result = Context.getDependentNameType(Keyword: Kwd, NNS, Name);
10819
10820 // Create type-source location information for this type.
10821 TypeLocBuilder TLB;
10822 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: Result);
10823 TL.setElaboratedKeywordLoc(TagLoc);
10824 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10825 TL.setNameLoc(NameLoc);
10826 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
10827}
10828
10829TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
10830 const CXXScopeSpec &SS,
10831 const IdentifierInfo &II,
10832 SourceLocation IdLoc,
10833 ImplicitTypenameContext IsImplicitTypename) {
10834 if (SS.isInvalid())
10835 return true;
10836
10837 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10838 DiagCompat(Loc: TypenameLoc, CompatDiagId: diag_compat::typename_outside_of_template)
10839 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
10840
10841 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
10842 TypeSourceInfo *TSI = nullptr;
10843 QualType T =
10844 CheckTypenameType(Keyword: TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
10845 : ElaboratedTypeKeyword::None,
10846 KeywordLoc: TypenameLoc, QualifierLoc, II, IILoc: IdLoc, TSI: &TSI,
10847 /*DeducedTSTContext=*/true);
10848 if (T.isNull())
10849 return true;
10850 return CreateParsedType(T, TInfo: TSI);
10851}
10852
10853TypeResult
10854Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
10855 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
10856 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
10857 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
10858 ASTTemplateArgsPtr TemplateArgsIn,
10859 SourceLocation RAngleLoc) {
10860 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
10861 Diag(Loc: TypenameLoc, DiagID: getLangOpts().CPlusPlus11
10862 ? diag::compat_cxx11_typename_outside_of_template
10863 : diag::compat_pre_cxx11_typename_outside_of_template)
10864 << FixItHint::CreateRemoval(RemoveRange: TypenameLoc);
10865
10866 // Strangely, non-type results are not ignored by this lookup, so the
10867 // program is ill-formed if it finds an injected-class-name.
10868 if (TypenameLoc.isValid()) {
10869 auto *LookupRD =
10870 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: false));
10871 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
10872 Diag(Loc: TemplateIILoc,
10873 DiagID: diag::ext_out_of_line_qualified_id_type_names_constructor)
10874 << TemplateII << 0 /*injected-class-name used as template name*/
10875 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
10876 }
10877 }
10878
10879 // Translate the parser's template argument list in our AST format.
10880 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10881 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10882
10883 auto Keyword = TypenameLoc.isValid() ? ElaboratedTypeKeyword::Typename
10884 : ElaboratedTypeKeyword::None;
10885
10886 TemplateName Template = TemplateIn.get();
10887 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
10888 // Construct a dependent template specialization type.
10889 assert(DTN && "dependent template has non-dependent name?");
10890 assert(DTN->getQualifier() == SS.getScopeRep());
10891
10892 if (!DTN->getName().getIdentifier()) {
10893 Diag(Loc: TemplateIILoc, DiagID: diag::err_template_id_not_a_type) << Template;
10894 NoteAllFoundTemplates(Name: Template);
10895 return true;
10896 }
10897
10898 QualType T = Context.getDependentTemplateSpecializationType(
10899 Keyword, Name: *DTN, Args: TemplateArgs.arguments());
10900
10901 // Create source-location information for this type.
10902 TypeLocBuilder Builder;
10903 DependentTemplateSpecializationTypeLoc SpecTL
10904 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
10905 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
10906 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
10907 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10908 SpecTL.setTemplateNameLoc(TemplateIILoc);
10909 SpecTL.setLAngleLoc(LAngleLoc);
10910 SpecTL.setRAngleLoc(RAngleLoc);
10911 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10912 SpecTL.setArgLocInfo(i: I, AI: TemplateArgs[I].getLocInfo());
10913 return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
10914 }
10915
10916 QualType T = CheckTemplateIdType(Name: Template, TemplateLoc: TemplateIILoc, TemplateArgs);
10917 if (T.isNull())
10918 return true;
10919
10920 // Provide source-location information for the template specialization type.
10921 TypeLocBuilder Builder;
10922 TemplateSpecializationTypeLoc SpecTL
10923 = Builder.push<TemplateSpecializationTypeLoc>(T);
10924 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
10925 SpecTL.setTemplateNameLoc(TemplateIILoc);
10926 SpecTL.setLAngleLoc(LAngleLoc);
10927 SpecTL.setRAngleLoc(RAngleLoc);
10928 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
10929 SpecTL.setArgLocInfo(i: I, AI: TemplateArgs[I].getLocInfo());
10930
10931 T = Context.getElaboratedType(Keyword, NNS: SS.getScopeRep(), NamedType: T);
10932 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
10933 TL.setElaboratedKeywordLoc(TypenameLoc);
10934 TL.setQualifierLoc(SS.getWithLocInContext(Context));
10935
10936 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
10937 return CreateParsedType(T, TInfo: TSI);
10938}
10939
10940/// Determine whether this failed name lookup should be treated as being
10941/// disabled by a usage of std::enable_if.
10942static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
10943 SourceRange &CondRange, Expr *&Cond) {
10944 // We must be looking for a ::type...
10945 if (!II.isStr(Str: "type"))
10946 return false;
10947
10948 // ... within an explicitly-written template specialization...
10949 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
10950 return false;
10951 TypeLoc EnableIfTy = NNS.getTypeLoc();
10952 TemplateSpecializationTypeLoc EnableIfTSTLoc =
10953 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
10954 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
10955 return false;
10956 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
10957
10958 // ... which names a complete class template declaration...
10959 const TemplateDecl *EnableIfDecl =
10960 EnableIfTST->getTemplateName().getAsTemplateDecl();
10961 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
10962 return false;
10963
10964 // ... called "enable_if".
10965 const IdentifierInfo *EnableIfII =
10966 EnableIfDecl->getDeclName().getAsIdentifierInfo();
10967 if (!EnableIfII || !EnableIfII->isStr(Str: "enable_if"))
10968 return false;
10969
10970 // Assume the first template argument is the condition.
10971 CondRange = EnableIfTSTLoc.getArgLoc(i: 0).getSourceRange();
10972
10973 // Dig out the condition.
10974 Cond = nullptr;
10975 if (EnableIfTSTLoc.getArgLoc(i: 0).getArgument().getKind()
10976 != TemplateArgument::Expression)
10977 return true;
10978
10979 Cond = EnableIfTSTLoc.getArgLoc(i: 0).getSourceExpression();
10980
10981 // Ignore Boolean literals; they add no value.
10982 if (isa<CXXBoolLiteralExpr>(Val: Cond->IgnoreParenCasts()))
10983 Cond = nullptr;
10984
10985 return true;
10986}
10987
10988QualType
10989Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
10990 SourceLocation KeywordLoc,
10991 NestedNameSpecifierLoc QualifierLoc,
10992 const IdentifierInfo &II,
10993 SourceLocation IILoc,
10994 TypeSourceInfo **TSI,
10995 bool DeducedTSTContext) {
10996 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
10997 DeducedTSTContext);
10998 if (T.isNull())
10999 return QualType();
11000
11001 *TSI = Context.CreateTypeSourceInfo(T);
11002 if (isa<DependentNameType>(Val: T)) {
11003 DependentNameTypeLoc TL =
11004 (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
11005 TL.setElaboratedKeywordLoc(KeywordLoc);
11006 TL.setQualifierLoc(QualifierLoc);
11007 TL.setNameLoc(IILoc);
11008 } else {
11009 ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
11010 TL.setElaboratedKeywordLoc(KeywordLoc);
11011 TL.setQualifierLoc(QualifierLoc);
11012 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
11013 }
11014 return T;
11015}
11016
11017/// Build the type that describes a C++ typename specifier,
11018/// e.g., "typename T::type".
11019QualType
11020Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11021 SourceLocation KeywordLoc,
11022 NestedNameSpecifierLoc QualifierLoc,
11023 const IdentifierInfo &II,
11024 SourceLocation IILoc, bool DeducedTSTContext) {
11025 assert((Keyword != ElaboratedTypeKeyword::None) == KeywordLoc.isValid());
11026
11027 CXXScopeSpec SS;
11028 SS.Adopt(Other: QualifierLoc);
11029
11030 DeclContext *Ctx = nullptr;
11031 if (QualifierLoc) {
11032 Ctx = computeDeclContext(SS);
11033 if (!Ctx) {
11034 // If the nested-name-specifier is dependent and couldn't be
11035 // resolved to a type, build a typename type.
11036 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
11037 return Context.getDependentNameType(Keyword,
11038 NNS: QualifierLoc.getNestedNameSpecifier(),
11039 Name: &II);
11040 }
11041
11042 // If the nested-name-specifier refers to the current instantiation,
11043 // the "typename" keyword itself is superfluous. In C++03, the
11044 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11045 // allows such extraneous "typename" keywords, and we retroactively
11046 // apply this DR to C++03 code with only a warning. In any case we continue.
11047
11048 if (RequireCompleteDeclContext(SS, DC: Ctx))
11049 return QualType();
11050 }
11051
11052 DeclarationName Name(&II);
11053 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11054 if (Ctx)
11055 LookupQualifiedName(R&: Result, LookupCtx: Ctx, SS);
11056 else
11057 LookupName(R&: Result, S: CurScope);
11058 unsigned DiagID = 0;
11059 Decl *Referenced = nullptr;
11060 switch (Result.getResultKind()) {
11061 case LookupResultKind::NotFound: {
11062 // If we're looking up 'type' within a template named 'enable_if', produce
11063 // a more specific diagnostic.
11064 SourceRange CondRange;
11065 Expr *Cond = nullptr;
11066 if (Ctx && isEnableIf(NNS: QualifierLoc, II, CondRange, Cond)) {
11067 // If we have a condition, narrow it down to the specific failed
11068 // condition.
11069 if (Cond) {
11070 Expr *FailedCond;
11071 std::string FailedDescription;
11072 std::tie(args&: FailedCond, args&: FailedDescription) =
11073 findFailedBooleanCondition(Cond);
11074
11075 Diag(Loc: FailedCond->getExprLoc(),
11076 DiagID: diag::err_typename_nested_not_found_requirement)
11077 << FailedDescription
11078 << FailedCond->getSourceRange();
11079 return QualType();
11080 }
11081
11082 Diag(Loc: CondRange.getBegin(),
11083 DiagID: diag::err_typename_nested_not_found_enable_if)
11084 << Ctx << CondRange;
11085 return QualType();
11086 }
11087
11088 DiagID = Ctx ? diag::err_typename_nested_not_found
11089 : diag::err_unknown_typename;
11090 break;
11091 }
11092
11093 case LookupResultKind::FoundUnresolvedValue: {
11094 // We found a using declaration that is a value. Most likely, the using
11095 // declaration itself is meant to have the 'typename' keyword.
11096 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11097 IILoc);
11098 Diag(Loc: IILoc, DiagID: diag::err_typename_refers_to_using_value_decl)
11099 << Name << Ctx << FullRange;
11100 if (UnresolvedUsingValueDecl *Using
11101 = dyn_cast<UnresolvedUsingValueDecl>(Val: Result.getRepresentativeDecl())){
11102 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11103 Diag(Loc, DiagID: diag::note_using_value_decl_missing_typename)
11104 << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "typename ");
11105 }
11106 }
11107 // Fall through to create a dependent typename type, from which we can
11108 // recover better.
11109 [[fallthrough]];
11110
11111 case LookupResultKind::NotFoundInCurrentInstantiation:
11112 // Okay, it's a member of an unknown instantiation.
11113 return Context.getDependentNameType(Keyword,
11114 NNS: QualifierLoc.getNestedNameSpecifier(),
11115 Name: &II);
11116
11117 case LookupResultKind::Found:
11118 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: Result.getFoundDecl())) {
11119 // C++ [class.qual]p2:
11120 // In a lookup in which function names are not ignored and the
11121 // nested-name-specifier nominates a class C, if the name specified
11122 // after the nested-name-specifier, when looked up in C, is the
11123 // injected-class-name of C [...] then the name is instead considered
11124 // to name the constructor of class C.
11125 //
11126 // Unlike in an elaborated-type-specifier, function names are not ignored
11127 // in typename-specifier lookup. However, they are ignored in all the
11128 // contexts where we form a typename type with no keyword (that is, in
11129 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11130 //
11131 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11132 // ignore functions, but that appears to be an oversight.
11133 QualType T = getTypeDeclType(LookupCtx: Ctx,
11134 DCK: Keyword == ElaboratedTypeKeyword::Typename
11135 ? DiagCtorKind::Typename
11136 : DiagCtorKind::None,
11137 TD: Type, NameLoc: IILoc);
11138 // We found a type. Build an ElaboratedType, since the
11139 // typename-specifier was just sugar.
11140 return Context.getElaboratedType(
11141 Keyword, NNS: QualifierLoc.getNestedNameSpecifier(), NamedType: T);
11142 }
11143
11144 // C++ [dcl.type.simple]p2:
11145 // A type-specifier of the form
11146 // typename[opt] nested-name-specifier[opt] template-name
11147 // is a placeholder for a deduced class type [...].
11148 if (getLangOpts().CPlusPlus17) {
11149 if (auto *TD = getAsTypeTemplateDecl(D: Result.getFoundDecl())) {
11150 if (!DeducedTSTContext) {
11151 QualType T(QualifierLoc
11152 ? QualifierLoc.getNestedNameSpecifier()->getAsType()
11153 : nullptr, 0);
11154 if (!T.isNull())
11155 Diag(Loc: IILoc, DiagID: diag::err_dependent_deduced_tst)
11156 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD)) << T;
11157 else
11158 Diag(Loc: IILoc, DiagID: diag::err_deduced_tst)
11159 << (int)getTemplateNameKindForDiagnostics(Name: TemplateName(TD));
11160 NoteTemplateLocation(Decl: *TD);
11161 return QualType();
11162 }
11163 return Context.getElaboratedType(
11164 Keyword, NNS: QualifierLoc.getNestedNameSpecifier(),
11165 NamedType: Context.getDeducedTemplateSpecializationType(Template: TemplateName(TD),
11166 DeducedType: QualType(), IsDependent: false));
11167 }
11168 }
11169
11170 DiagID = Ctx ? diag::err_typename_nested_not_type
11171 : diag::err_typename_not_type;
11172 Referenced = Result.getFoundDecl();
11173 break;
11174
11175 case LookupResultKind::FoundOverloaded:
11176 DiagID = Ctx ? diag::err_typename_nested_not_type
11177 : diag::err_typename_not_type;
11178 Referenced = *Result.begin();
11179 break;
11180
11181 case LookupResultKind::Ambiguous:
11182 return QualType();
11183 }
11184
11185 // If we get here, it's because name lookup did not find a
11186 // type. Emit an appropriate diagnostic and return an error.
11187 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11188 IILoc);
11189 if (Ctx)
11190 Diag(Loc: IILoc, DiagID) << FullRange << Name << Ctx;
11191 else
11192 Diag(Loc: IILoc, DiagID) << FullRange << Name;
11193 if (Referenced)
11194 Diag(Loc: Referenced->getLocation(),
11195 DiagID: Ctx ? diag::note_typename_member_refers_here
11196 : diag::note_typename_refers_here)
11197 << Name;
11198 return QualType();
11199}
11200
11201namespace {
11202 // See Sema::RebuildTypeInCurrentInstantiation
11203 class CurrentInstantiationRebuilder
11204 : public TreeTransform<CurrentInstantiationRebuilder> {
11205 SourceLocation Loc;
11206 DeclarationName Entity;
11207
11208 public:
11209 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11210
11211 CurrentInstantiationRebuilder(Sema &SemaRef,
11212 SourceLocation Loc,
11213 DeclarationName Entity)
11214 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11215 Loc(Loc), Entity(Entity) { }
11216
11217 /// Determine whether the given type \p T has already been
11218 /// transformed.
11219 ///
11220 /// For the purposes of type reconstruction, a type has already been
11221 /// transformed if it is NULL or if it is not dependent.
11222 bool AlreadyTransformed(QualType T) {
11223 return T.isNull() || !T->isInstantiationDependentType();
11224 }
11225
11226 /// Returns the location of the entity whose type is being
11227 /// rebuilt.
11228 SourceLocation getBaseLocation() { return Loc; }
11229
11230 /// Returns the name of the entity whose type is being rebuilt.
11231 DeclarationName getBaseEntity() { return Entity; }
11232
11233 /// Sets the "base" location and entity when that
11234 /// information is known based on another transformation.
11235 void setBase(SourceLocation Loc, DeclarationName Entity) {
11236 this->Loc = Loc;
11237 this->Entity = Entity;
11238 }
11239
11240 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11241 // Lambdas never need to be transformed.
11242 return E;
11243 }
11244 };
11245} // end anonymous namespace
11246
11247TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11248 SourceLocation Loc,
11249 DeclarationName Name) {
11250 if (!T || !T->getType()->isInstantiationDependentType())
11251 return T;
11252
11253 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
11254 return Rebuilder.TransformType(DI: T);
11255}
11256
11257ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
11258 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
11259 DeclarationName());
11260 return Rebuilder.TransformExpr(E);
11261}
11262
11263bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
11264 if (SS.isInvalid())
11265 return true;
11266
11267 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11268 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
11269 DeclarationName());
11270 NestedNameSpecifierLoc Rebuilt
11271 = Rebuilder.TransformNestedNameSpecifierLoc(NNS: QualifierLoc);
11272 if (!Rebuilt)
11273 return true;
11274
11275 SS.Adopt(Other: Rebuilt);
11276 return false;
11277}
11278
11279bool Sema::RebuildTemplateParamsInCurrentInstantiation(
11280 TemplateParameterList *Params) {
11281 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11282 Decl *Param = Params->getParam(Idx: I);
11283
11284 // There is nothing to rebuild in a type parameter.
11285 if (isa<TemplateTypeParmDecl>(Val: Param))
11286 continue;
11287
11288 // Rebuild the template parameter list of a template template parameter.
11289 if (TemplateTemplateParmDecl *TTP
11290 = dyn_cast<TemplateTemplateParmDecl>(Val: Param)) {
11291 if (RebuildTemplateParamsInCurrentInstantiation(
11292 Params: TTP->getTemplateParameters()))
11293 return true;
11294
11295 continue;
11296 }
11297
11298 // Rebuild the type of a non-type template parameter.
11299 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Val: Param);
11300 TypeSourceInfo *NewTSI
11301 = RebuildTypeInCurrentInstantiation(T: NTTP->getTypeSourceInfo(),
11302 Loc: NTTP->getLocation(),
11303 Name: NTTP->getDeclName());
11304 if (!NewTSI)
11305 return true;
11306
11307 if (NewTSI->getType()->isUndeducedType()) {
11308 // C++17 [temp.dep.expr]p3:
11309 // An id-expression is type-dependent if it contains
11310 // - an identifier associated by name lookup with a non-type
11311 // template-parameter declared with a type that contains a
11312 // placeholder type (7.1.7.4),
11313 NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: NewTSI);
11314 }
11315
11316 if (NewTSI != NTTP->getTypeSourceInfo()) {
11317 NTTP->setTypeSourceInfo(NewTSI);
11318 NTTP->setType(NewTSI->getType());
11319 }
11320 }
11321
11322 return false;
11323}
11324
11325std::string
11326Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11327 const TemplateArgumentList &Args) {
11328 return getTemplateArgumentBindingsText(Params, Args: Args.data(), NumArgs: Args.size());
11329}
11330
11331std::string
11332Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
11333 const TemplateArgument *Args,
11334 unsigned NumArgs) {
11335 SmallString<128> Str;
11336 llvm::raw_svector_ostream Out(Str);
11337
11338 if (!Params || Params->size() == 0 || NumArgs == 0)
11339 return std::string();
11340
11341 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
11342 if (I >= NumArgs)
11343 break;
11344
11345 if (I == 0)
11346 Out << "[with ";
11347 else
11348 Out << ", ";
11349
11350 if (const IdentifierInfo *Id = Params->getParam(Idx: I)->getIdentifier()) {
11351 Out << Id->getName();
11352 } else {
11353 Out << '$' << I;
11354 }
11355
11356 Out << " = ";
11357 Args[I].print(Policy: getPrintingPolicy(), Out,
11358 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
11359 Policy: getPrintingPolicy(), TPL: Params, Idx: I));
11360 }
11361
11362 Out << ']';
11363 return std::string(Out.str());
11364}
11365
11366void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
11367 CachedTokens &Toks) {
11368 if (!FD)
11369 return;
11370
11371 auto LPT = std::make_unique<LateParsedTemplate>();
11372
11373 // Take tokens to avoid allocations
11374 LPT->Toks.swap(RHS&: Toks);
11375 LPT->D = FnD;
11376 LPT->FPO = getCurFPFeatures();
11377 LateParsedTemplateMap.insert(KV: std::make_pair(x&: FD, y: std::move(LPT)));
11378
11379 FD->setLateTemplateParsed(true);
11380}
11381
11382void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
11383 if (!FD)
11384 return;
11385 FD->setLateTemplateParsed(false);
11386}
11387
11388bool Sema::IsInsideALocalClassWithinATemplateFunction() {
11389 DeclContext *DC = CurContext;
11390
11391 while (DC) {
11392 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
11393 const FunctionDecl *FD = RD->isLocalClass();
11394 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
11395 } else if (DC->isTranslationUnit() || DC->isNamespace())
11396 return false;
11397
11398 DC = DC->getParent();
11399 }
11400 return false;
11401}
11402
11403namespace {
11404/// Walk the path from which a declaration was instantiated, and check
11405/// that every explicit specialization along that path is visible. This enforces
11406/// C++ [temp.expl.spec]/6:
11407///
11408/// If a template, a member template or a member of a class template is
11409/// explicitly specialized then that specialization shall be declared before
11410/// the first use of that specialization that would cause an implicit
11411/// instantiation to take place, in every translation unit in which such a
11412/// use occurs; no diagnostic is required.
11413///
11414/// and also C++ [temp.class.spec]/1:
11415///
11416/// A partial specialization shall be declared before the first use of a
11417/// class template specialization that would make use of the partial
11418/// specialization as the result of an implicit or explicit instantiation
11419/// in every translation unit in which such a use occurs; no diagnostic is
11420/// required.
11421class ExplicitSpecializationVisibilityChecker {
11422 Sema &S;
11423 SourceLocation Loc;
11424 llvm::SmallVector<Module *, 8> Modules;
11425 Sema::AcceptableKind Kind;
11426
11427public:
11428 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
11429 Sema::AcceptableKind Kind)
11430 : S(S), Loc(Loc), Kind(Kind) {}
11431
11432 void check(NamedDecl *ND) {
11433 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
11434 return checkImpl(Spec: FD);
11435 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
11436 return checkImpl(Spec: RD);
11437 if (auto *VD = dyn_cast<VarDecl>(Val: ND))
11438 return checkImpl(Spec: VD);
11439 if (auto *ED = dyn_cast<EnumDecl>(Val: ND))
11440 return checkImpl(Spec: ED);
11441 }
11442
11443private:
11444 void diagnose(NamedDecl *D, bool IsPartialSpec) {
11445 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
11446 : Sema::MissingImportKind::ExplicitSpecialization;
11447 const bool Recover = true;
11448
11449 // If we got a custom set of modules (because only a subset of the
11450 // declarations are interesting), use them, otherwise let
11451 // diagnoseMissingImport intelligently pick some.
11452 if (Modules.empty())
11453 S.diagnoseMissingImport(Loc, Decl: D, MIK: Kind, Recover);
11454 else
11455 S.diagnoseMissingImport(Loc, Decl: D, DeclLoc: D->getLocation(), Modules, MIK: Kind, Recover);
11456 }
11457
11458 bool CheckMemberSpecialization(const NamedDecl *D) {
11459 return Kind == Sema::AcceptableKind::Visible
11460 ? S.hasVisibleMemberSpecialization(D)
11461 : S.hasReachableMemberSpecialization(D);
11462 }
11463
11464 bool CheckExplicitSpecialization(const NamedDecl *D) {
11465 return Kind == Sema::AcceptableKind::Visible
11466 ? S.hasVisibleExplicitSpecialization(D)
11467 : S.hasReachableExplicitSpecialization(D);
11468 }
11469
11470 bool CheckDeclaration(const NamedDecl *D) {
11471 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
11472 : S.hasReachableDeclaration(D);
11473 }
11474
11475 // Check a specific declaration. There are three problematic cases:
11476 //
11477 // 1) The declaration is an explicit specialization of a template
11478 // specialization.
11479 // 2) The declaration is an explicit specialization of a member of an
11480 // templated class.
11481 // 3) The declaration is an instantiation of a template, and that template
11482 // is an explicit specialization of a member of a templated class.
11483 //
11484 // We don't need to go any deeper than that, as the instantiation of the
11485 // surrounding class / etc is not triggered by whatever triggered this
11486 // instantiation, and thus should be checked elsewhere.
11487 template<typename SpecDecl>
11488 void checkImpl(SpecDecl *Spec) {
11489 bool IsHiddenExplicitSpecialization = false;
11490 TemplateSpecializationKind SpecKind = Spec->getTemplateSpecializationKind();
11491 // Some invalid friend declarations are written as specializations but are
11492 // instantiated implicitly.
11493 if constexpr (std::is_same_v<SpecDecl, FunctionDecl>)
11494 SpecKind = Spec->getTemplateSpecializationKindForInstantiation();
11495 if (SpecKind == TSK_ExplicitSpecialization) {
11496 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
11497 ? !CheckMemberSpecialization(D: Spec)
11498 : !CheckExplicitSpecialization(D: Spec);
11499 } else {
11500 checkInstantiated(Spec);
11501 }
11502
11503 if (IsHiddenExplicitSpecialization)
11504 diagnose(D: Spec->getMostRecentDecl(), IsPartialSpec: false);
11505 }
11506
11507 void checkInstantiated(FunctionDecl *FD) {
11508 if (auto *TD = FD->getPrimaryTemplate())
11509 checkTemplate(TD);
11510 }
11511
11512 void checkInstantiated(CXXRecordDecl *RD) {
11513 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD);
11514 if (!SD)
11515 return;
11516
11517 auto From = SD->getSpecializedTemplateOrPartial();
11518 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
11519 checkTemplate(TD);
11520 else if (auto *TD =
11521 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
11522 if (!CheckDeclaration(D: TD))
11523 diagnose(D: TD, IsPartialSpec: true);
11524 checkTemplate(TD);
11525 }
11526 }
11527
11528 void checkInstantiated(VarDecl *RD) {
11529 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(Val: RD);
11530 if (!SD)
11531 return;
11532
11533 auto From = SD->getSpecializedTemplateOrPartial();
11534 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
11535 checkTemplate(TD);
11536 else if (auto *TD =
11537 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
11538 if (!CheckDeclaration(D: TD))
11539 diagnose(D: TD, IsPartialSpec: true);
11540 checkTemplate(TD);
11541 }
11542 }
11543
11544 void checkInstantiated(EnumDecl *FD) {}
11545
11546 template<typename TemplDecl>
11547 void checkTemplate(TemplDecl *TD) {
11548 if (TD->isMemberSpecialization()) {
11549 if (!CheckMemberSpecialization(D: TD))
11550 diagnose(D: TD->getMostRecentDecl(), IsPartialSpec: false);
11551 }
11552 }
11553};
11554} // end anonymous namespace
11555
11556void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
11557 if (!getLangOpts().Modules)
11558 return;
11559
11560 ExplicitSpecializationVisibilityChecker(*this, Loc,
11561 Sema::AcceptableKind::Visible)
11562 .check(ND: Spec);
11563}
11564
11565void Sema::checkSpecializationReachability(SourceLocation Loc,
11566 NamedDecl *Spec) {
11567 if (!getLangOpts().CPlusPlusModules)
11568 return checkSpecializationVisibility(Loc, Spec);
11569
11570 ExplicitSpecializationVisibilityChecker(*this, Loc,
11571 Sema::AcceptableKind::Reachable)
11572 .check(ND: Spec);
11573}
11574
11575SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
11576 if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
11577 return N->getLocation();
11578 if (const auto *FD = dyn_cast<FunctionDecl>(Val: N)) {
11579 if (!FD->isFunctionTemplateSpecialization())
11580 return FD->getLocation();
11581 } else if (!isa<ClassTemplateSpecializationDecl,
11582 VarTemplateSpecializationDecl>(Val: N)) {
11583 return N->getLocation();
11584 }
11585 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
11586 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
11587 continue;
11588 return CSC.PointOfInstantiation;
11589 }
11590 return N->getLocation();
11591}
11592

source code of clang/lib/Sema/SemaTemplate.cpp