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/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/RecursiveASTVisitor.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/Stack.h"
28#include "clang/Basic/TargetInfo.h"
29#include "clang/Sema/DeclSpec.h"
30#include "clang/Sema/EnterExpressionEvaluationContext.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
34#include "clang/Sema/ParsedTemplate.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/SemaCUDA.h"
37#include "clang/Sema/SemaInternal.h"
38#include "clang/Sema/Template.h"
39#include "clang/Sema/TemplateDeduction.h"
40#include "llvm/ADT/SmallBitVector.h"
41#include "llvm/ADT/SmallString.h"
42#include "llvm/ADT/StringExtras.h"
43
44#include <iterator>
45#include <optional>
46using namespace clang;
47using namespace sema;
48
49// Exported for use by Parser.
50SourceRange
51clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
52 unsigned N) {
53 if (!N) return SourceRange();
54 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
55}
56
57unsigned Sema::getTemplateDepth(Scope *S) const {
58 unsigned Depth = 0;
59
60 // Each template parameter scope represents one level of template parameter
61 // depth.
62 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
63 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
64 ++Depth;
65 }
66
67 // Note that there are template parameters with the given depth.
68 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(a: Depth, b: D + 1); };
69
70 // Look for parameters of an enclosing generic lambda. We don't create a
71 // template parameter scope for these.
72 for (FunctionScopeInfo *FSI : getFunctionScopes()) {
73 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: FSI)) {
74 if (!LSI->TemplateParams.empty()) {
75 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
76 break;
77 }
78 if (LSI->GLTemplateParameterList) {
79 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
80 break;
81 }
82 }
83 }
84
85 // Look for parameters of an enclosing terse function template. We don't
86 // create a template parameter scope for these either.
87 for (const InventedTemplateParameterInfo &Info :
88 getInventedParameterInfos()) {
89 if (!Info.TemplateParams.empty()) {
90 ParamsAtDepth(Info.AutoTemplateParameterDepth);
91 break;
92 }
93 }
94
95 return Depth;
96}
97
98/// \brief Determine whether the declaration found is acceptable as the name
99/// of a template and, if so, return that template declaration. Otherwise,
100/// returns null.
101///
102/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
103/// is true. In all other cases it will return a TemplateDecl (or null).
104NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
105 bool AllowFunctionTemplates,
106 bool AllowDependent) {
107 D = D->getUnderlyingDecl();
108
109 if (isa<TemplateDecl>(Val: D)) {
110 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(Val: D))
111 return nullptr;
112
113 return D;
114 }
115
116 if (const auto *Record = dyn_cast<CXXRecordDecl>(Val: D)) {
117 // C++ [temp.local]p1:
118 // Like normal (non-template) classes, class templates have an
119 // injected-class-name (Clause 9). The injected-class-name
120 // can be used with or without a template-argument-list. When
121 // it is used without a template-argument-list, it is
122 // equivalent to the injected-class-name followed by the
123 // template-parameters of the class template enclosed in
124 // <>. When it is used with a template-argument-list, it
125 // refers to the specified class template specialization,
126 // which could be the current specialization or another
127 // specialization.
128 if (Record->isInjectedClassName()) {
129 Record = cast<CXXRecordDecl>(Record->getDeclContext());
130 if (Record->getDescribedClassTemplate())
131 return Record->getDescribedClassTemplate();
132
133 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record))
134 return Spec->getSpecializedTemplate();
135 }
136
137 return nullptr;
138 }
139
140 // 'using Dependent::foo;' can resolve to a template name.
141 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
142 // injected-class-name).
143 if (AllowDependent && isa<UnresolvedUsingValueDecl>(Val: D))
144 return D;
145
146 return nullptr;
147}
148
149void Sema::FilterAcceptableTemplateNames(LookupResult &R,
150 bool AllowFunctionTemplates,
151 bool AllowDependent) {
152 LookupResult::Filter filter = R.makeFilter();
153 while (filter.hasNext()) {
154 NamedDecl *Orig = filter.next();
155 if (!getAsTemplateNameDecl(D: Orig, AllowFunctionTemplates, AllowDependent))
156 filter.erase();
157 }
158 filter.done();
159}
160
161bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
162 bool AllowFunctionTemplates,
163 bool AllowDependent,
164 bool AllowNonTemplateFunctions) {
165 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
166 if (getAsTemplateNameDecl(D: *I, AllowFunctionTemplates, AllowDependent))
167 return true;
168 if (AllowNonTemplateFunctions &&
169 isa<FunctionDecl>(Val: (*I)->getUnderlyingDecl()))
170 return true;
171 }
172
173 return false;
174}
175
176TemplateNameKind Sema::isTemplateName(Scope *S,
177 CXXScopeSpec &SS,
178 bool hasTemplateKeyword,
179 const UnqualifiedId &Name,
180 ParsedType ObjectTypePtr,
181 bool EnteringContext,
182 TemplateTy &TemplateResult,
183 bool &MemberOfUnknownSpecialization,
184 bool Disambiguation) {
185 assert(getLangOpts().CPlusPlus && "No template names in C!");
186
187 DeclarationName TName;
188 MemberOfUnknownSpecialization = false;
189
190 switch (Name.getKind()) {
191 case UnqualifiedIdKind::IK_Identifier:
192 TName = DeclarationName(Name.Identifier);
193 break;
194
195 case UnqualifiedIdKind::IK_OperatorFunctionId:
196 TName = Context.DeclarationNames.getCXXOperatorName(
197 Op: Name.OperatorFunctionId.Operator);
198 break;
199
200 case UnqualifiedIdKind::IK_LiteralOperatorId:
201 TName = Context.DeclarationNames.getCXXLiteralOperatorName(II: Name.Identifier);
202 break;
203
204 default:
205 return TNK_Non_template;
206 }
207
208 QualType ObjectType = ObjectTypePtr.get();
209
210 AssumedTemplateKind AssumedTemplate;
211 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
212 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
213 MemberOfUnknownSpecialization, RequiredTemplate: SourceLocation(),
214 ATK: &AssumedTemplate,
215 /*AllowTypoCorrection=*/!Disambiguation))
216 return TNK_Non_template;
217
218 if (AssumedTemplate != AssumedTemplateKind::None) {
219 TemplateResult = TemplateTy::make(P: Context.getAssumedTemplateName(Name: TName));
220 // Let the parser know whether we found nothing or found functions; if we
221 // found nothing, we want to more carefully check whether this is actually
222 // a function template name versus some other kind of undeclared identifier.
223 return AssumedTemplate == AssumedTemplateKind::FoundNothing
224 ? TNK_Undeclared_template
225 : TNK_Function_template;
226 }
227
228 if (R.empty())
229 return TNK_Non_template;
230
231 NamedDecl *D = nullptr;
232 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: *R.begin());
233 if (R.isAmbiguous()) {
234 // If we got an ambiguity involving a non-function template, treat this
235 // as a template name, and pick an arbitrary template for error recovery.
236 bool AnyFunctionTemplates = false;
237 for (NamedDecl *FoundD : R) {
238 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(D: FoundD)) {
239 if (isa<FunctionTemplateDecl>(Val: FoundTemplate))
240 AnyFunctionTemplates = true;
241 else {
242 D = FoundTemplate;
243 FoundUsingShadow = dyn_cast<UsingShadowDecl>(Val: FoundD);
244 break;
245 }
246 }
247 }
248
249 // If we didn't find any templates at all, this isn't a template name.
250 // Leave the ambiguity for a later lookup to diagnose.
251 if (!D && !AnyFunctionTemplates) {
252 R.suppressDiagnostics();
253 return TNK_Non_template;
254 }
255
256 // If the only templates were function templates, filter out the rest.
257 // We'll diagnose the ambiguity later.
258 if (!D)
259 FilterAcceptableTemplateNames(R);
260 }
261
262 // At this point, we have either picked a single template name declaration D
263 // or we have a non-empty set of results R containing either one template name
264 // declaration or a set of function templates.
265
266 TemplateName Template;
267 TemplateNameKind TemplateKind;
268
269 unsigned ResultCount = R.end() - R.begin();
270 if (!D && ResultCount > 1) {
271 // We assume that we'll preserve the qualifier from a function
272 // template name in other ways.
273 Template = Context.getOverloadedTemplateName(Begin: R.begin(), End: R.end());
274 TemplateKind = TNK_Function_template;
275
276 // We'll do this lookup again later.
277 R.suppressDiagnostics();
278 } else {
279 if (!D) {
280 D = getAsTemplateNameDecl(D: *R.begin());
281 assert(D && "unambiguous result is not a template name");
282 }
283
284 if (isa<UnresolvedUsingValueDecl>(Val: D)) {
285 // We don't yet know whether this is a template-name or not.
286 MemberOfUnknownSpecialization = true;
287 return TNK_Non_template;
288 }
289
290 TemplateDecl *TD = cast<TemplateDecl>(Val: D);
291 Template =
292 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
293 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
294 if (SS.isSet() && !SS.isInvalid()) {
295 NestedNameSpecifier *Qualifier = SS.getScopeRep();
296 Template = Context.getQualifiedTemplateName(NNS: Qualifier, TemplateKeyword: hasTemplateKeyword,
297 Template);
298 }
299
300 if (isa<FunctionTemplateDecl>(Val: TD)) {
301 TemplateKind = TNK_Function_template;
302
303 // We'll do this lookup again later.
304 R.suppressDiagnostics();
305 } else {
306 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
307 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
308 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
309 TemplateKind =
310 isa<VarTemplateDecl>(Val: TD) ? TNK_Var_template :
311 isa<ConceptDecl>(Val: TD) ? TNK_Concept_template :
312 TNK_Type_template;
313 }
314 }
315
316 TemplateResult = TemplateTy::make(P: Template);
317 return TemplateKind;
318}
319
320bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
321 SourceLocation NameLoc, CXXScopeSpec &SS,
322 ParsedTemplateTy *Template /*=nullptr*/) {
323 bool MemberOfUnknownSpecialization = false;
324
325 // We could use redeclaration lookup here, but we don't need to: the
326 // syntactic form of a deduction guide is enough to identify it even
327 // if we can't look up the template name at all.
328 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
329 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
330 /*EnteringContext*/ false,
331 MemberOfUnknownSpecialization))
332 return false;
333
334 if (R.empty()) return false;
335 if (R.isAmbiguous()) {
336 // FIXME: Diagnose an ambiguity if we find at least one template.
337 R.suppressDiagnostics();
338 return false;
339 }
340
341 // We only treat template-names that name type templates as valid deduction
342 // guide names.
343 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
344 if (!TD || !getAsTypeTemplateDecl(TD))
345 return false;
346
347 if (Template)
348 *Template = TemplateTy::make(P: TemplateName(TD));
349 return true;
350}
351
352bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
353 SourceLocation IILoc,
354 Scope *S,
355 const CXXScopeSpec *SS,
356 TemplateTy &SuggestedTemplate,
357 TemplateNameKind &SuggestedKind) {
358 // We can't recover unless there's a dependent scope specifier preceding the
359 // template name.
360 // FIXME: Typo correction?
361 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(SS: *SS) ||
362 computeDeclContext(SS: *SS))
363 return false;
364
365 // The code is missing a 'template' keyword prior to the dependent template
366 // name.
367 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
368 Diag(IILoc, diag::err_template_kw_missing)
369 << Qualifier << II.getName()
370 << FixItHint::CreateInsertion(IILoc, "template ");
371 SuggestedTemplate
372 = TemplateTy::make(P: Context.getDependentTemplateName(NNS: Qualifier, Name: &II));
373 SuggestedKind = TNK_Dependent_template_name;
374 return true;
375}
376
377bool Sema::LookupTemplateName(LookupResult &Found,
378 Scope *S, CXXScopeSpec &SS,
379 QualType ObjectType,
380 bool EnteringContext,
381 bool &MemberOfUnknownSpecialization,
382 RequiredTemplateKind RequiredTemplate,
383 AssumedTemplateKind *ATK,
384 bool AllowTypoCorrection) {
385 if (ATK)
386 *ATK = AssumedTemplateKind::None;
387
388 if (SS.isInvalid())
389 return true;
390
391 Found.setTemplateNameLookup(true);
392
393 // Determine where to perform name lookup
394 MemberOfUnknownSpecialization = false;
395 DeclContext *LookupCtx = nullptr;
396 bool IsDependent = false;
397 if (!ObjectType.isNull()) {
398 // This nested-name-specifier occurs in a member access expression, e.g.,
399 // x->B::f, and we are looking into the type of the object.
400 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
401 LookupCtx = computeDeclContext(T: ObjectType);
402 IsDependent = !LookupCtx && ObjectType->isDependentType();
403 assert((IsDependent || !ObjectType->isIncompleteType() ||
404 !ObjectType->getAs<TagType>() ||
405 ObjectType->castAs<TagType>()->isBeingDefined()) &&
406 "Caller should have completed object type");
407
408 // Template names cannot appear inside an Objective-C class or object type
409 // or a vector type.
410 //
411 // FIXME: This is wrong. For example:
412 //
413 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
414 // Vec<int> vi;
415 // vi.Vec<int>::~Vec<int>();
416 //
417 // ... should be accepted but we will not treat 'Vec' as a template name
418 // here. The right thing to do would be to check if the name is a valid
419 // vector component name, and look up a template name if not. And similarly
420 // for lookups into Objective-C class and object types, where the same
421 // problem can arise.
422 if (ObjectType->isObjCObjectOrInterfaceType() ||
423 ObjectType->isVectorType()) {
424 Found.clear();
425 return false;
426 }
427 } else if (SS.isNotEmpty()) {
428 // This nested-name-specifier occurs after another nested-name-specifier,
429 // so long into the context associated with the prior nested-name-specifier.
430 LookupCtx = computeDeclContext(SS, EnteringContext);
431 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
432
433 // The declaration context must be complete.
434 if (LookupCtx && RequireCompleteDeclContext(SS, DC: LookupCtx))
435 return true;
436 }
437
438 bool ObjectTypeSearchedInScope = false;
439 bool AllowFunctionTemplatesInLookup = true;
440 if (LookupCtx) {
441 // Perform "qualified" name lookup into the declaration context we
442 // computed, which is either the type of the base of a member access
443 // expression or the declaration context associated with a prior
444 // nested-name-specifier.
445 LookupQualifiedName(R&: Found, LookupCtx);
446
447 // FIXME: The C++ standard does not clearly specify what happens in the
448 // case where the object type is dependent, and implementations vary. In
449 // Clang, we treat a name after a . or -> as a template-name if lookup
450 // finds a non-dependent member or member of the current instantiation that
451 // is a type template, or finds no such members and lookup in the context
452 // of the postfix-expression finds a type template. In the latter case, the
453 // name is nonetheless dependent, and we may resolve it to a member of an
454 // unknown specialization when we come to instantiate the template.
455 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
456 }
457
458 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
459 // C++ [basic.lookup.classref]p1:
460 // In a class member access expression (5.2.5), if the . or -> token is
461 // immediately followed by an identifier followed by a <, the
462 // identifier must be looked up to determine whether the < is the
463 // beginning of a template argument list (14.2) or a less-than operator.
464 // The identifier is first looked up in the class of the object
465 // expression. If the identifier is not found, it is then looked up in
466 // the context of the entire postfix-expression and shall name a class
467 // template.
468 if (S)
469 LookupName(R&: Found, S);
470
471 if (!ObjectType.isNull()) {
472 // FIXME: We should filter out all non-type templates here, particularly
473 // variable templates and concepts. But the exclusion of alias templates
474 // and template template parameters is a wording defect.
475 AllowFunctionTemplatesInLookup = false;
476 ObjectTypeSearchedInScope = true;
477 }
478
479 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
480 }
481
482 if (Found.isAmbiguous())
483 return false;
484
485 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
486 !RequiredTemplate.hasTemplateKeyword()) {
487 // C++2a [temp.names]p2:
488 // A name is also considered to refer to a template if it is an
489 // unqualified-id followed by a < and name lookup finds either one or more
490 // functions or finds nothing.
491 //
492 // To keep our behavior consistent, we apply the "finds nothing" part in
493 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
494 // successfully form a call to an undeclared template-id.
495 bool AllFunctions =
496 getLangOpts().CPlusPlus20 && llvm::all_of(Range&: Found, P: [](NamedDecl *ND) {
497 return isa<FunctionDecl>(Val: ND->getUnderlyingDecl());
498 });
499 if (AllFunctions || (Found.empty() && !IsDependent)) {
500 // If lookup found any functions, or if this is a name that can only be
501 // used for a function, then strongly assume this is a function
502 // template-id.
503 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
504 ? AssumedTemplateKind::FoundNothing
505 : AssumedTemplateKind::FoundFunctions;
506 Found.clear();
507 return false;
508 }
509 }
510
511 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
512 // If we did not find any names, and this is not a disambiguation, attempt
513 // to correct any typos.
514 DeclarationName Name = Found.getLookupName();
515 Found.clear();
516 // Simple filter callback that, for keywords, only accepts the C++ *_cast
517 DefaultFilterCCC FilterCCC{};
518 FilterCCC.WantTypeSpecifiers = false;
519 FilterCCC.WantExpressionKeywords = false;
520 FilterCCC.WantRemainingKeywords = false;
521 FilterCCC.WantCXXNamedCasts = true;
522 if (TypoCorrection Corrected =
523 CorrectTypo(Typo: Found.getLookupNameInfo(), LookupKind: Found.getLookupKind(), S,
524 SS: &SS, CCC&: FilterCCC, Mode: CTK_ErrorRecovery, MemberContext: LookupCtx)) {
525 if (auto *ND = Corrected.getFoundDecl())
526 Found.addDecl(D: ND);
527 FilterAcceptableTemplateNames(R&: Found);
528 if (Found.isAmbiguous()) {
529 Found.clear();
530 } else if (!Found.empty()) {
531 Found.setLookupName(Corrected.getCorrection());
532 if (LookupCtx) {
533 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
534 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
535 Name.getAsString() == CorrectedStr;
536 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
537 << Name << LookupCtx << DroppedSpecifier
538 << SS.getRange());
539 } else {
540 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
541 }
542 }
543 }
544 }
545
546 NamedDecl *ExampleLookupResult =
547 Found.empty() ? nullptr : Found.getRepresentativeDecl();
548 FilterAcceptableTemplateNames(R&: Found, AllowFunctionTemplates: AllowFunctionTemplatesInLookup);
549 if (Found.empty()) {
550 if (IsDependent) {
551 MemberOfUnknownSpecialization = true;
552 return false;
553 }
554
555 // If a 'template' keyword was used, a lookup that finds only non-template
556 // names is an error.
557 if (ExampleLookupResult && RequiredTemplate) {
558 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
559 << Found.getLookupName() << SS.getRange()
560 << RequiredTemplate.hasTemplateKeyword()
561 << RequiredTemplate.getTemplateKeywordLoc();
562 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
563 diag::note_template_kw_refers_to_non_template)
564 << Found.getLookupName();
565 return true;
566 }
567
568 return false;
569 }
570
571 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
572 !getLangOpts().CPlusPlus11) {
573 // C++03 [basic.lookup.classref]p1:
574 // [...] If the lookup in the class of the object expression finds a
575 // template, the name is also looked up in the context of the entire
576 // postfix-expression and [...]
577 //
578 // Note: C++11 does not perform this second lookup.
579 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
580 LookupOrdinaryName);
581 FoundOuter.setTemplateNameLookup(true);
582 LookupName(R&: FoundOuter, S);
583 // FIXME: We silently accept an ambiguous lookup here, in violation of
584 // [basic.lookup]/1.
585 FilterAcceptableTemplateNames(R&: FoundOuter, /*AllowFunctionTemplates=*/false);
586
587 NamedDecl *OuterTemplate;
588 if (FoundOuter.empty()) {
589 // - if the name is not found, the name found in the class of the
590 // object expression is used, otherwise
591 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
592 !(OuterTemplate =
593 getAsTemplateNameDecl(D: FoundOuter.getFoundDecl()))) {
594 // - if the name is found in the context of the entire
595 // postfix-expression and does not name a class template, the name
596 // found in the class of the object expression is used, otherwise
597 FoundOuter.clear();
598 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
599 // - if the name found is a class template, it must refer to the same
600 // entity as the one found in the class of the object expression,
601 // otherwise the program is ill-formed.
602 if (!Found.isSingleResult() ||
603 getAsTemplateNameDecl(D: Found.getFoundDecl())->getCanonicalDecl() !=
604 OuterTemplate->getCanonicalDecl()) {
605 Diag(Found.getNameLoc(),
606 diag::ext_nested_name_member_ref_lookup_ambiguous)
607 << Found.getLookupName()
608 << ObjectType;
609 Diag(Found.getRepresentativeDecl()->getLocation(),
610 diag::note_ambig_member_ref_object_type)
611 << ObjectType;
612 Diag(FoundOuter.getFoundDecl()->getLocation(),
613 diag::note_ambig_member_ref_scope);
614
615 // Recover by taking the template that we found in the object
616 // expression's type.
617 }
618 }
619 }
620
621 return false;
622}
623
624void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
625 SourceLocation Less,
626 SourceLocation Greater) {
627 if (TemplateName.isInvalid())
628 return;
629
630 DeclarationNameInfo NameInfo;
631 CXXScopeSpec SS;
632 LookupNameKind LookupKind;
633
634 DeclContext *LookupCtx = nullptr;
635 NamedDecl *Found = nullptr;
636 bool MissingTemplateKeyword = false;
637
638 // Figure out what name we looked up.
639 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: TemplateName.get())) {
640 NameInfo = DRE->getNameInfo();
641 SS.Adopt(Other: DRE->getQualifierLoc());
642 LookupKind = LookupOrdinaryName;
643 Found = DRE->getFoundDecl();
644 } else if (auto *ME = dyn_cast<MemberExpr>(Val: TemplateName.get())) {
645 NameInfo = ME->getMemberNameInfo();
646 SS.Adopt(Other: ME->getQualifierLoc());
647 LookupKind = LookupMemberName;
648 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
649 Found = ME->getMemberDecl();
650 } else if (auto *DSDRE =
651 dyn_cast<DependentScopeDeclRefExpr>(Val: TemplateName.get())) {
652 NameInfo = DSDRE->getNameInfo();
653 SS.Adopt(Other: DSDRE->getQualifierLoc());
654 MissingTemplateKeyword = true;
655 } else if (auto *DSME =
656 dyn_cast<CXXDependentScopeMemberExpr>(Val: TemplateName.get())) {
657 NameInfo = DSME->getMemberNameInfo();
658 SS.Adopt(Other: DSME->getQualifierLoc());
659 MissingTemplateKeyword = true;
660 } else {
661 llvm_unreachable("unexpected kind of potential template name");
662 }
663
664 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
665 // was missing.
666 if (MissingTemplateKeyword) {
667 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
668 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
669 return;
670 }
671
672 // Try to correct the name by looking for templates and C++ named casts.
673 struct TemplateCandidateFilter : CorrectionCandidateCallback {
674 Sema &S;
675 TemplateCandidateFilter(Sema &S) : S(S) {
676 WantTypeSpecifiers = false;
677 WantExpressionKeywords = false;
678 WantRemainingKeywords = false;
679 WantCXXNamedCasts = true;
680 };
681 bool ValidateCandidate(const TypoCorrection &Candidate) override {
682 if (auto *ND = Candidate.getCorrectionDecl())
683 return S.getAsTemplateNameDecl(D: ND);
684 return Candidate.isKeyword();
685 }
686
687 std::unique_ptr<CorrectionCandidateCallback> clone() override {
688 return std::make_unique<TemplateCandidateFilter>(args&: *this);
689 }
690 };
691
692 DeclarationName Name = NameInfo.getName();
693 TemplateCandidateFilter CCC(*this);
694 if (TypoCorrection Corrected = CorrectTypo(Typo: NameInfo, LookupKind, S, SS: &SS, CCC,
695 Mode: CTK_ErrorRecovery, MemberContext: LookupCtx)) {
696 auto *ND = Corrected.getFoundDecl();
697 if (ND)
698 ND = getAsTemplateNameDecl(D: ND);
699 if (ND || Corrected.isKeyword()) {
700 if (LookupCtx) {
701 std::string CorrectedStr(Corrected.getAsString(LO: getLangOpts()));
702 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
703 Name.getAsString() == CorrectedStr;
704 diagnoseTypo(Corrected,
705 PDiag(diag::err_non_template_in_member_template_id_suggest)
706 << Name << LookupCtx << DroppedSpecifier
707 << SS.getRange(), false);
708 } else {
709 diagnoseTypo(Corrected,
710 PDiag(diag::err_non_template_in_template_id_suggest)
711 << Name, false);
712 }
713 if (Found)
714 Diag(Found->getLocation(),
715 diag::note_non_template_in_template_id_found);
716 return;
717 }
718 }
719
720 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
721 << Name << SourceRange(Less, Greater);
722 if (Found)
723 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
724}
725
726/// ActOnDependentIdExpression - Handle a dependent id-expression that
727/// was just parsed. This is only possible with an explicit scope
728/// specifier naming a dependent type.
729ExprResult
730Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
731 SourceLocation TemplateKWLoc,
732 const DeclarationNameInfo &NameInfo,
733 bool isAddressOfOperand,
734 const TemplateArgumentListInfo *TemplateArgs) {
735 DeclContext *DC = getFunctionLevelDeclContext();
736
737 // C++11 [expr.prim.general]p12:
738 // An id-expression that denotes a non-static data member or non-static
739 // member function of a class can only be used:
740 // (...)
741 // - if that id-expression denotes a non-static data member and it
742 // appears in an unevaluated operand.
743 //
744 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
745 // CXXDependentScopeMemberExpr. The former can instantiate to either
746 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
747 // always a MemberExpr.
748 bool MightBeCxx11UnevalField =
749 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
750
751 // Check if the nested name specifier is an enum type.
752 bool IsEnum = false;
753 if (NestedNameSpecifier *NNS = SS.getScopeRep())
754 IsEnum = isa_and_nonnull<EnumType>(Val: NNS->getAsType());
755
756 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
757 isa<CXXMethodDecl>(Val: DC) &&
758 cast<CXXMethodDecl>(Val: DC)->isImplicitObjectMemberFunction()) {
759 QualType ThisType = cast<CXXMethodDecl>(Val: DC)->getThisType().getNonReferenceType();
760
761 // Since the 'this' expression is synthesized, we don't need to
762 // perform the double-lookup check.
763 NamedDecl *FirstQualifierInScope = nullptr;
764
765 return CXXDependentScopeMemberExpr::Create(
766 Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType,
767 /*IsArrow=*/!Context.getLangOpts().HLSL,
768 /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc,
769 FirstQualifierFoundInScope: FirstQualifierInScope, MemberNameInfo: NameInfo, TemplateArgs);
770 }
771
772 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
773}
774
775ExprResult
776Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
777 SourceLocation TemplateKWLoc,
778 const DeclarationNameInfo &NameInfo,
779 const TemplateArgumentListInfo *TemplateArgs) {
780 // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
781 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
782 if (!QualifierLoc)
783 return ExprError();
784
785 return DependentScopeDeclRefExpr::Create(
786 Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
787}
788
789
790/// Determine whether we would be unable to instantiate this template (because
791/// it either has no definition, or is in the process of being instantiated).
792bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
793 NamedDecl *Instantiation,
794 bool InstantiatedFromMember,
795 const NamedDecl *Pattern,
796 const NamedDecl *PatternDef,
797 TemplateSpecializationKind TSK,
798 bool Complain /*= true*/) {
799 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
800 isa<VarDecl>(Instantiation));
801
802 bool IsEntityBeingDefined = false;
803 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(Val: PatternDef))
804 IsEntityBeingDefined = TD->isBeingDefined();
805
806 if (PatternDef && !IsEntityBeingDefined) {
807 NamedDecl *SuggestedDef = nullptr;
808 if (!hasReachableDefinition(D: const_cast<NamedDecl *>(PatternDef),
809 Suggested: &SuggestedDef,
810 /*OnlyNeedComplete*/ false)) {
811 // If we're allowed to diagnose this and recover, do so.
812 bool Recover = Complain && !isSFINAEContext();
813 if (Complain)
814 diagnoseMissingImport(Loc: PointOfInstantiation, Decl: SuggestedDef,
815 MIK: Sema::MissingImportKind::Definition, Recover);
816 return !Recover;
817 }
818 return false;
819 }
820
821 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
822 return true;
823
824 QualType InstantiationTy;
825 if (TagDecl *TD = dyn_cast<TagDecl>(Val: Instantiation))
826 InstantiationTy = Context.getTypeDeclType(TD);
827 if (PatternDef) {
828 Diag(PointOfInstantiation,
829 diag::err_template_instantiate_within_definition)
830 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
831 << InstantiationTy;
832 // Not much point in noting the template declaration here, since
833 // we're lexically inside it.
834 Instantiation->setInvalidDecl();
835 } else if (InstantiatedFromMember) {
836 if (isa<FunctionDecl>(Val: Instantiation)) {
837 Diag(PointOfInstantiation,
838 diag::err_explicit_instantiation_undefined_member)
839 << /*member function*/ 1 << Instantiation->getDeclName()
840 << Instantiation->getDeclContext();
841 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
842 } else {
843 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
844 Diag(PointOfInstantiation,
845 diag::err_implicit_instantiate_member_undefined)
846 << InstantiationTy;
847 Diag(Pattern->getLocation(), diag::note_member_declared_at);
848 }
849 } else {
850 if (isa<FunctionDecl>(Val: Instantiation)) {
851 Diag(PointOfInstantiation,
852 diag::err_explicit_instantiation_undefined_func_template)
853 << Pattern;
854 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
855 } else if (isa<TagDecl>(Val: Instantiation)) {
856 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
857 << (TSK != TSK_ImplicitInstantiation)
858 << InstantiationTy;
859 NoteTemplateLocation(Decl: *Pattern);
860 } else {
861 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
862 if (isa<VarTemplateSpecializationDecl>(Val: Instantiation)) {
863 Diag(PointOfInstantiation,
864 diag::err_explicit_instantiation_undefined_var_template)
865 << Instantiation;
866 Instantiation->setInvalidDecl();
867 } else
868 Diag(PointOfInstantiation,
869 diag::err_explicit_instantiation_undefined_member)
870 << /*static data member*/ 2 << Instantiation->getDeclName()
871 << Instantiation->getDeclContext();
872 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
873 }
874 }
875
876 // In general, Instantiation isn't marked invalid to get more than one
877 // error for multiple undefined instantiations. But the code that does
878 // explicit declaration -> explicit definition conversion can't handle
879 // invalid declarations, so mark as invalid in that case.
880 if (TSK == TSK_ExplicitInstantiationDeclaration)
881 Instantiation->setInvalidDecl();
882 return true;
883}
884
885void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl,
886 bool SupportedForCompatibility) {
887 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
888
889 // C++23 [temp.local]p6:
890 // The name of a template-parameter shall not be bound to any following.
891 // declaration whose locus is contained by the scope to which the
892 // template-parameter belongs.
893 //
894 // When MSVC compatibility is enabled, the diagnostic is always a warning
895 // by default. Otherwise, it an error unless SupportedForCompatibility is
896 // true, in which case it is a default-to-error warning.
897 unsigned DiagId =
898 getLangOpts().MSVCCompat
899 ? diag::ext_template_param_shadow
900 : (SupportedForCompatibility ? diag::ext_compat_template_param_shadow
901 : diag::err_template_param_shadow);
902 const auto *ND = cast<NamedDecl>(Val: PrevDecl);
903 Diag(Loc, DiagId) << ND->getDeclName();
904 NoteTemplateParameterLocation(Decl: *ND);
905}
906
907/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
908/// the parameter D to reference the templated declaration and return a pointer
909/// to the template declaration. Otherwise, do nothing to D and return null.
910TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
911 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(Val: D)) {
912 D = Temp->getTemplatedDecl();
913 return Temp;
914 }
915 return nullptr;
916}
917
918ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
919 SourceLocation EllipsisLoc) const {
920 assert(Kind == Template &&
921 "Only template template arguments can be pack expansions here");
922 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
923 "Template template argument pack expansion without packs");
924 ParsedTemplateArgument Result(*this);
925 Result.EllipsisLoc = EllipsisLoc;
926 return Result;
927}
928
929static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
930 const ParsedTemplateArgument &Arg) {
931
932 switch (Arg.getKind()) {
933 case ParsedTemplateArgument::Type: {
934 TypeSourceInfo *DI;
935 QualType T = SemaRef.GetTypeFromParser(Ty: Arg.getAsType(), TInfo: &DI);
936 if (!DI)
937 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc: Arg.getLocation());
938 return TemplateArgumentLoc(TemplateArgument(T), DI);
939 }
940
941 case ParsedTemplateArgument::NonType: {
942 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
943 return TemplateArgumentLoc(TemplateArgument(E), E);
944 }
945
946 case ParsedTemplateArgument::Template: {
947 TemplateName Template = Arg.getAsTemplate().get();
948 TemplateArgument TArg;
949 if (Arg.getEllipsisLoc().isValid())
950 TArg = TemplateArgument(Template, std::optional<unsigned int>());
951 else
952 TArg = Template;
953 return TemplateArgumentLoc(
954 SemaRef.Context, TArg,
955 Arg.getScopeSpec().getWithLocInContext(Context&: SemaRef.Context),
956 Arg.getLocation(), Arg.getEllipsisLoc());
957 }
958 }
959
960 llvm_unreachable("Unhandled parsed template argument");
961}
962
963/// Translates template arguments as provided by the parser
964/// into template arguments used by semantic analysis.
965void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
966 TemplateArgumentListInfo &TemplateArgs) {
967 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
968 TemplateArgs.addArgument(Loc: translateTemplateArgument(SemaRef&: *this,
969 Arg: TemplateArgsIn[I]));
970}
971
972static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
973 SourceLocation Loc,
974 const IdentifierInfo *Name) {
975 NamedDecl *PrevDecl =
976 SemaRef.LookupSingleName(S, Name, Loc, NameKind: Sema::LookupOrdinaryName,
977 Redecl: RedeclarationKind::ForVisibleRedeclaration);
978 if (PrevDecl && PrevDecl->isTemplateParameter())
979 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
980}
981
982/// Convert a parsed type into a parsed template argument. This is mostly
983/// trivial, except that we may have parsed a C++17 deduced class template
984/// specialization type, in which case we should form a template template
985/// argument instead of a type template argument.
986ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
987 TypeSourceInfo *TInfo;
988 QualType T = GetTypeFromParser(Ty: ParsedType.get(), TInfo: &TInfo);
989 if (T.isNull())
990 return ParsedTemplateArgument();
991 assert(TInfo && "template argument with no location");
992
993 // If we might have formed a deduced template specialization type, convert
994 // it to a template template argument.
995 if (getLangOpts().CPlusPlus17) {
996 TypeLoc TL = TInfo->getTypeLoc();
997 SourceLocation EllipsisLoc;
998 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
999 EllipsisLoc = PET.getEllipsisLoc();
1000 TL = PET.getPatternLoc();
1001 }
1002
1003 CXXScopeSpec SS;
1004 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
1005 SS.Adopt(Other: ET.getQualifierLoc());
1006 TL = ET.getNamedTypeLoc();
1007 }
1008
1009 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1010 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1011 if (SS.isSet())
1012 Name = Context.getQualifiedTemplateName(NNS: SS.getScopeRep(),
1013 /*HasTemplateKeyword=*/TemplateKeyword: false,
1014 Template: Name);
1015 ParsedTemplateArgument Result(SS, TemplateTy::make(P: Name),
1016 DTST.getTemplateNameLoc());
1017 if (EllipsisLoc.isValid())
1018 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1019 return Result;
1020 }
1021 }
1022
1023 // This is a normal type template argument. Note, if the type template
1024 // argument is an injected-class-name for a template, it has a dual nature
1025 // and can be used as either a type or a template. We handle that in
1026 // convertTypeTemplateArgumentToTemplate.
1027 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1028 ParsedType.get().getAsOpaquePtr(),
1029 TInfo->getTypeLoc().getBeginLoc());
1030}
1031
1032/// ActOnTypeParameter - Called when a C++ template type parameter
1033/// (e.g., "typename T") has been parsed. Typename specifies whether
1034/// the keyword "typename" was used to declare the type parameter
1035/// (otherwise, "class" was used), and KeyLoc is the location of the
1036/// "class" or "typename" keyword. ParamName is the name of the
1037/// parameter (NULL indicates an unnamed template parameter) and
1038/// ParamNameLoc is the location of the parameter name (if any).
1039/// If the type parameter has a default argument, it will be added
1040/// later via ActOnTypeParameterDefault.
1041NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
1042 SourceLocation EllipsisLoc,
1043 SourceLocation KeyLoc,
1044 IdentifierInfo *ParamName,
1045 SourceLocation ParamNameLoc,
1046 unsigned Depth, unsigned Position,
1047 SourceLocation EqualLoc,
1048 ParsedType DefaultArg,
1049 bool HasTypeConstraint) {
1050 assert(S->isTemplateParamScope() &&
1051 "Template type parameter not in template parameter scope!");
1052
1053 bool IsParameterPack = EllipsisLoc.isValid();
1054 TemplateTypeParmDecl *Param
1055 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1056 KeyLoc, ParamNameLoc, Depth, Position,
1057 ParamName, Typename, IsParameterPack,
1058 HasTypeConstraint);
1059 Param->setAccess(AS_public);
1060
1061 if (Param->isParameterPack())
1062 if (auto *LSI = getEnclosingLambda())
1063 LSI->LocalPacks.push_back(Param);
1064
1065 if (ParamName) {
1066 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: ParamNameLoc, Name: ParamName);
1067
1068 // Add the template parameter into the current scope.
1069 S->AddDecl(Param);
1070 IdResolver.AddDecl(Param);
1071 }
1072
1073 // C++0x [temp.param]p9:
1074 // A default template-argument may be specified for any kind of
1075 // template-parameter that is not a template parameter pack.
1076 if (DefaultArg && IsParameterPack) {
1077 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1078 DefaultArg = nullptr;
1079 }
1080
1081 // Handle the default argument, if provided.
1082 if (DefaultArg) {
1083 TypeSourceInfo *DefaultTInfo;
1084 GetTypeFromParser(Ty: DefaultArg, TInfo: &DefaultTInfo);
1085
1086 assert(DefaultTInfo && "expected source information for type");
1087
1088 // Check for unexpanded parameter packs.
1089 if (DiagnoseUnexpandedParameterPack(Loc: ParamNameLoc, T: DefaultTInfo,
1090 UPPC: UPPC_DefaultArgument))
1091 return Param;
1092
1093 // Check the template argument itself.
1094 if (CheckTemplateArgument(Arg: DefaultTInfo)) {
1095 Param->setInvalidDecl();
1096 return Param;
1097 }
1098
1099 Param->setDefaultArgument(DefaultTInfo);
1100 }
1101
1102 return Param;
1103}
1104
1105/// Convert the parser's template argument list representation into our form.
1106static TemplateArgumentListInfo
1107makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1108 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1109 TemplateId.RAngleLoc);
1110 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1111 TemplateId.NumArgs);
1112 S.translateTemplateArguments(TemplateArgsIn: TemplateArgsPtr, TemplateArgs);
1113 return TemplateArgs;
1114}
1115
1116bool Sema::CheckTypeConstraint(TemplateIdAnnotation *TypeConstr) {
1117
1118 TemplateName TN = TypeConstr->Template.get();
1119 ConceptDecl *CD = cast<ConceptDecl>(Val: TN.getAsTemplateDecl());
1120
1121 // C++2a [temp.param]p4:
1122 // [...] The concept designated by a type-constraint shall be a type
1123 // concept ([temp.concept]).
1124 if (!CD->isTypeConcept()) {
1125 Diag(TypeConstr->TemplateNameLoc,
1126 diag::err_type_constraint_non_type_concept);
1127 return true;
1128 }
1129
1130 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1131
1132 if (!WereArgsSpecified &&
1133 CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
1134 Diag(TypeConstr->TemplateNameLoc,
1135 diag::err_type_constraint_missing_arguments)
1136 << CD;
1137 return true;
1138 }
1139 return false;
1140}
1141
1142bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1143 TemplateIdAnnotation *TypeConstr,
1144 TemplateTypeParmDecl *ConstrainedParameter,
1145 SourceLocation EllipsisLoc) {
1146 return BuildTypeConstraint(SS, TypeConstraint: TypeConstr, ConstrainedParameter, EllipsisLoc,
1147 AllowUnexpandedPack: false);
1148}
1149
1150bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1151 TemplateIdAnnotation *TypeConstr,
1152 TemplateTypeParmDecl *ConstrainedParameter,
1153 SourceLocation EllipsisLoc,
1154 bool AllowUnexpandedPack) {
1155
1156 if (CheckTypeConstraint(TypeConstr))
1157 return true;
1158
1159 TemplateName TN = TypeConstr->Template.get();
1160 ConceptDecl *CD = cast<ConceptDecl>(Val: TN.getAsTemplateDecl());
1161 UsingShadowDecl *USD = TN.getAsUsingShadowDecl();
1162
1163 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1164 TypeConstr->TemplateNameLoc);
1165
1166 TemplateArgumentListInfo TemplateArgs;
1167 if (TypeConstr->LAngleLoc.isValid()) {
1168 TemplateArgs =
1169 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TypeConstr);
1170
1171 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1172 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1173 if (DiagnoseUnexpandedParameterPack(Arg, UPPC: UPPC_TypeConstraint))
1174 return true;
1175 }
1176 }
1177 }
1178 return AttachTypeConstraint(
1179 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1180 ConceptName, CD, /*FoundDecl=*/USD ? cast<NamedDecl>(Val: USD) : CD,
1181 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1182 ConstrainedParameter, EllipsisLoc);
1183}
1184
1185template <typename ArgumentLocAppender>
1186static ExprResult formImmediatelyDeclaredConstraint(
1187 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1188 ConceptDecl *NamedConcept, NamedDecl *FoundDecl, SourceLocation LAngleLoc,
1189 SourceLocation RAngleLoc, QualType ConstrainedType,
1190 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1191 SourceLocation EllipsisLoc) {
1192
1193 TemplateArgumentListInfo ConstraintArgs;
1194 ConstraintArgs.addArgument(
1195 Loc: S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(ConstrainedType),
1196 /*NTTPType=*/QualType(), Loc: ParamNameLoc));
1197
1198 ConstraintArgs.setRAngleLoc(RAngleLoc);
1199 ConstraintArgs.setLAngleLoc(LAngleLoc);
1200 Appender(ConstraintArgs);
1201
1202 // C++2a [temp.param]p4:
1203 // [...] This constraint-expression E is called the immediately-declared
1204 // constraint of T. [...]
1205 CXXScopeSpec SS;
1206 SS.Adopt(Other: NS);
1207 ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1208 SS, /*TemplateKWLoc=*/SourceLocation(), ConceptNameInfo: NameInfo,
1209 /*FoundDecl=*/FoundDecl ? FoundDecl : NamedConcept, NamedConcept,
1210 TemplateArgs: &ConstraintArgs);
1211 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1212 return ImmediatelyDeclaredConstraint;
1213
1214 // C++2a [temp.param]p4:
1215 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1216 //
1217 // We have the following case:
1218 //
1219 // template<typename T> concept C1 = true;
1220 // template<C1... T> struct s1;
1221 //
1222 // The constraint: (C1<T> && ...)
1223 //
1224 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1225 // any unqualified lookups for 'operator&&' here.
1226 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/Callee: nullptr,
1227 /*LParenLoc=*/SourceLocation(),
1228 LHS: ImmediatelyDeclaredConstraint.get(), Operator: BO_LAnd,
1229 EllipsisLoc, /*RHS=*/nullptr,
1230 /*RParenLoc=*/SourceLocation(),
1231 /*NumExpansions=*/std::nullopt);
1232}
1233
1234/// Attach a type-constraint to a template parameter.
1235/// \returns true if an error occurred. This can happen if the
1236/// immediately-declared constraint could not be formed (e.g. incorrect number
1237/// of arguments for the named concept).
1238bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1239 DeclarationNameInfo NameInfo,
1240 ConceptDecl *NamedConcept, NamedDecl *FoundDecl,
1241 const TemplateArgumentListInfo *TemplateArgs,
1242 TemplateTypeParmDecl *ConstrainedParameter,
1243 SourceLocation EllipsisLoc) {
1244 // C++2a [temp.param]p4:
1245 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1246 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1247 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1248 TemplateArgs ? ASTTemplateArgumentListInfo::Create(C: Context,
1249 List: *TemplateArgs) : nullptr;
1250
1251 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1252
1253 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1254 *this, NS, NameInfo, NamedConcept, FoundDecl,
1255 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1256 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1257 ParamAsArgument, ConstrainedParameter->getLocation(),
1258 [&](TemplateArgumentListInfo &ConstraintArgs) {
1259 if (TemplateArgs)
1260 for (const auto &ArgLoc : TemplateArgs->arguments())
1261 ConstraintArgs.addArgument(Loc: ArgLoc);
1262 },
1263 EllipsisLoc);
1264 if (ImmediatelyDeclaredConstraint.isInvalid())
1265 return true;
1266
1267 auto *CL = ConceptReference::Create(C: Context, /*NNS=*/NS,
1268 /*TemplateKWLoc=*/SourceLocation{},
1269 /*ConceptNameInfo=*/NameInfo,
1270 /*FoundDecl=*/FoundDecl,
1271 /*NamedConcept=*/NamedConcept,
1272 /*ArgsWritten=*/ArgsAsWritten);
1273 ConstrainedParameter->setTypeConstraint(CR: CL,
1274 ImmediatelyDeclaredConstraint: ImmediatelyDeclaredConstraint.get());
1275 return false;
1276}
1277
1278bool Sema::AttachTypeConstraint(AutoTypeLoc TL,
1279 NonTypeTemplateParmDecl *NewConstrainedParm,
1280 NonTypeTemplateParmDecl *OrigConstrainedParm,
1281 SourceLocation EllipsisLoc) {
1282 if (NewConstrainedParm->getType() != TL.getType() ||
1283 TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1284 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1285 diag::err_unsupported_placeholder_constraint)
1286 << NewConstrainedParm->getTypeSourceInfo()
1287 ->getTypeLoc()
1288 .getSourceRange();
1289 return true;
1290 }
1291 // FIXME: Concepts: This should be the type of the placeholder, but this is
1292 // unclear in the wording right now.
1293 DeclRefExpr *Ref =
1294 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1295 VK_PRValue, OrigConstrainedParm->getLocation());
1296 if (!Ref)
1297 return true;
1298 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1299 *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
1300 TL.getNamedConcept(), /*FoundDecl=*/TL.getFoundDecl(), TL.getLAngleLoc(),
1301 TL.getRAngleLoc(), BuildDecltypeType(Ref),
1302 OrigConstrainedParm->getLocation(),
1303 [&](TemplateArgumentListInfo &ConstraintArgs) {
1304 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1305 ConstraintArgs.addArgument(Loc: TL.getArgLoc(i: I));
1306 },
1307 EllipsisLoc);
1308 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1309 !ImmediatelyDeclaredConstraint.isUsable())
1310 return true;
1311
1312 NewConstrainedParm->setPlaceholderTypeConstraint(
1313 ImmediatelyDeclaredConstraint.get());
1314 return false;
1315}
1316
1317/// Check that the type of a non-type template parameter is
1318/// well-formed.
1319///
1320/// \returns the (possibly-promoted) parameter type if valid;
1321/// otherwise, produces a diagnostic and returns a NULL type.
1322QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1323 SourceLocation Loc) {
1324 if (TSI->getType()->isUndeducedType()) {
1325 // C++17 [temp.dep.expr]p3:
1326 // An id-expression is type-dependent if it contains
1327 // - an identifier associated by name lookup with a non-type
1328 // template-parameter declared with a type that contains a
1329 // placeholder type (7.1.7.4),
1330 TSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSI);
1331 }
1332
1333 return CheckNonTypeTemplateParameterType(T: TSI->getType(), Loc);
1334}
1335
1336/// Require the given type to be a structural type, and diagnose if it is not.
1337///
1338/// \return \c true if an error was produced.
1339bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1340 if (T->isDependentType())
1341 return false;
1342
1343 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1344 return true;
1345
1346 if (T->isStructuralType())
1347 return false;
1348
1349 // Structural types are required to be object types or lvalue references.
1350 if (T->isRValueReferenceType()) {
1351 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1352 return true;
1353 }
1354
1355 // Don't mention structural types in our diagnostic prior to C++20. Also,
1356 // there's not much more we can say about non-scalar non-class types --
1357 // because we can't see functions or arrays here, those can only be language
1358 // extensions.
1359 if (!getLangOpts().CPlusPlus20 ||
1360 (!T->isScalarType() && !T->isRecordType())) {
1361 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1362 return true;
1363 }
1364
1365 // Structural types are required to be literal types.
1366 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1367 return true;
1368
1369 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1370
1371 // Drill down into the reason why the class is non-structural.
1372 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1373 // All members are required to be public and non-mutable, and can't be of
1374 // rvalue reference type. Check these conditions first to prefer a "local"
1375 // reason over a more distant one.
1376 for (const FieldDecl *FD : RD->fields()) {
1377 if (FD->getAccess() != AS_public) {
1378 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1379 return true;
1380 }
1381 if (FD->isMutable()) {
1382 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1383 return true;
1384 }
1385 if (FD->getType()->isRValueReferenceType()) {
1386 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1387 << T;
1388 return true;
1389 }
1390 }
1391
1392 // All bases are required to be public.
1393 for (const auto &BaseSpec : RD->bases()) {
1394 if (BaseSpec.getAccessSpecifier() != AS_public) {
1395 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1396 << T << 1;
1397 return true;
1398 }
1399 }
1400
1401 // All subobjects are required to be of structural types.
1402 SourceLocation SubLoc;
1403 QualType SubType;
1404 int Kind = -1;
1405
1406 for (const FieldDecl *FD : RD->fields()) {
1407 QualType T = Context.getBaseElementType(FD->getType());
1408 if (!T->isStructuralType()) {
1409 SubLoc = FD->getLocation();
1410 SubType = T;
1411 Kind = 0;
1412 break;
1413 }
1414 }
1415
1416 if (Kind == -1) {
1417 for (const auto &BaseSpec : RD->bases()) {
1418 QualType T = BaseSpec.getType();
1419 if (!T->isStructuralType()) {
1420 SubLoc = BaseSpec.getBaseTypeLoc();
1421 SubType = T;
1422 Kind = 1;
1423 break;
1424 }
1425 }
1426 }
1427
1428 assert(Kind != -1 && "couldn't find reason why type is not structural");
1429 Diag(SubLoc, diag::note_not_structural_subobject)
1430 << T << Kind << SubType;
1431 T = SubType;
1432 RD = T->getAsCXXRecordDecl();
1433 }
1434
1435 return true;
1436}
1437
1438QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1439 SourceLocation Loc) {
1440 // We don't allow variably-modified types as the type of non-type template
1441 // parameters.
1442 if (T->isVariablyModifiedType()) {
1443 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1444 << T;
1445 return QualType();
1446 }
1447
1448 // C++ [temp.param]p4:
1449 //
1450 // A non-type template-parameter shall have one of the following
1451 // (optionally cv-qualified) types:
1452 //
1453 // -- integral or enumeration type,
1454 if (T->isIntegralOrEnumerationType() ||
1455 // -- pointer to object or pointer to function,
1456 T->isPointerType() ||
1457 // -- lvalue reference to object or lvalue reference to function,
1458 T->isLValueReferenceType() ||
1459 // -- pointer to member,
1460 T->isMemberPointerType() ||
1461 // -- std::nullptr_t, or
1462 T->isNullPtrType() ||
1463 // -- a type that contains a placeholder type.
1464 T->isUndeducedType()) {
1465 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1466 // are ignored when determining its type.
1467 return T.getUnqualifiedType();
1468 }
1469
1470 // C++ [temp.param]p8:
1471 //
1472 // A non-type template-parameter of type "array of T" or
1473 // "function returning T" is adjusted to be of type "pointer to
1474 // T" or "pointer to function returning T", respectively.
1475 if (T->isArrayType() || T->isFunctionType())
1476 return Context.getDecayedType(T);
1477
1478 // If T is a dependent type, we can't do the check now, so we
1479 // assume that it is well-formed. Note that stripping off the
1480 // qualifiers here is not really correct if T turns out to be
1481 // an array type, but we'll recompute the type everywhere it's
1482 // used during instantiation, so that should be OK. (Using the
1483 // qualified type is equally wrong.)
1484 if (T->isDependentType())
1485 return T.getUnqualifiedType();
1486
1487 // C++20 [temp.param]p6:
1488 // -- a structural type
1489 if (RequireStructuralType(T, Loc))
1490 return QualType();
1491
1492 if (!getLangOpts().CPlusPlus20) {
1493 // FIXME: Consider allowing structural types as an extension in C++17. (In
1494 // earlier language modes, the template argument evaluation rules are too
1495 // inflexible.)
1496 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1497 return QualType();
1498 }
1499
1500 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1501 return T.getUnqualifiedType();
1502}
1503
1504NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1505 unsigned Depth,
1506 unsigned Position,
1507 SourceLocation EqualLoc,
1508 Expr *Default) {
1509 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
1510
1511 // Check that we have valid decl-specifiers specified.
1512 auto CheckValidDeclSpecifiers = [this, &D] {
1513 // C++ [temp.param]
1514 // p1
1515 // template-parameter:
1516 // ...
1517 // parameter-declaration
1518 // p2
1519 // ... A storage class shall not be specified in a template-parameter
1520 // declaration.
1521 // [dcl.typedef]p1:
1522 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1523 // of a parameter-declaration
1524 const DeclSpec &DS = D.getDeclSpec();
1525 auto EmitDiag = [this](SourceLocation Loc) {
1526 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1527 << FixItHint::CreateRemoval(Loc);
1528 };
1529 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1530 EmitDiag(DS.getStorageClassSpecLoc());
1531
1532 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1533 EmitDiag(DS.getThreadStorageClassSpecLoc());
1534
1535 // [dcl.inline]p1:
1536 // The inline specifier can be applied only to the declaration or
1537 // definition of a variable or function.
1538
1539 if (DS.isInlineSpecified())
1540 EmitDiag(DS.getInlineSpecLoc());
1541
1542 // [dcl.constexpr]p1:
1543 // The constexpr specifier shall be applied only to the definition of a
1544 // variable or variable template or the declaration of a function or
1545 // function template.
1546
1547 if (DS.hasConstexprSpecifier())
1548 EmitDiag(DS.getConstexprSpecLoc());
1549
1550 // [dcl.fct.spec]p1:
1551 // Function-specifiers can be used only in function declarations.
1552
1553 if (DS.isVirtualSpecified())
1554 EmitDiag(DS.getVirtualSpecLoc());
1555
1556 if (DS.hasExplicitSpecifier())
1557 EmitDiag(DS.getExplicitSpecLoc());
1558
1559 if (DS.isNoreturnSpecified())
1560 EmitDiag(DS.getNoreturnSpecLoc());
1561 };
1562
1563 CheckValidDeclSpecifiers();
1564
1565 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1566 if (isa<AutoType>(T))
1567 Diag(D.getIdentifierLoc(),
1568 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1569 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1570
1571 assert(S->isTemplateParamScope() &&
1572 "Non-type template parameter not in template parameter scope!");
1573 bool Invalid = false;
1574
1575 QualType T = CheckNonTypeTemplateParameterType(TSI&: TInfo, Loc: D.getIdentifierLoc());
1576 if (T.isNull()) {
1577 T = Context.IntTy; // Recover with an 'int' type.
1578 Invalid = true;
1579 }
1580
1581 CheckFunctionOrTemplateParamDeclarator(S, D);
1582
1583 const IdentifierInfo *ParamName = D.getIdentifier();
1584 bool IsParameterPack = D.hasEllipsis();
1585 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1586 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1587 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1588 TInfo);
1589 Param->setAccess(AS_public);
1590
1591 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1592 if (TL.isConstrained())
1593 if (AttachTypeConstraint(TL, NewConstrainedParm: Param, OrigConstrainedParm: Param, EllipsisLoc: D.getEllipsisLoc()))
1594 Invalid = true;
1595
1596 if (Invalid)
1597 Param->setInvalidDecl();
1598
1599 if (Param->isParameterPack())
1600 if (auto *LSI = getEnclosingLambda())
1601 LSI->LocalPacks.push_back(Param);
1602
1603 if (ParamName) {
1604 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: D.getIdentifierLoc(),
1605 Name: ParamName);
1606
1607 // Add the template parameter into the current scope.
1608 S->AddDecl(Param);
1609 IdResolver.AddDecl(Param);
1610 }
1611
1612 // C++0x [temp.param]p9:
1613 // A default template-argument may be specified for any kind of
1614 // template-parameter that is not a template parameter pack.
1615 if (Default && IsParameterPack) {
1616 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1617 Default = nullptr;
1618 }
1619
1620 // Check the well-formedness of the default template argument, if provided.
1621 if (Default) {
1622 // Check for unexpanded parameter packs.
1623 if (DiagnoseUnexpandedParameterPack(E: Default, UPPC: UPPC_DefaultArgument))
1624 return Param;
1625
1626 Param->setDefaultArgument(Default);
1627 }
1628
1629 return Param;
1630}
1631
1632/// ActOnTemplateTemplateParameter - Called when a C++ template template
1633/// parameter (e.g. T in template <template \<typename> class T> class array)
1634/// has been parsed. S is the current scope.
1635NamedDecl *Sema::ActOnTemplateTemplateParameter(
1636 Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params,
1637 bool Typename, SourceLocation EllipsisLoc, IdentifierInfo *Name,
1638 SourceLocation NameLoc, unsigned Depth, unsigned Position,
1639 SourceLocation EqualLoc, ParsedTemplateArgument Default) {
1640 assert(S->isTemplateParamScope() &&
1641 "Template template parameter not in template parameter scope!");
1642
1643 // Construct the parameter object.
1644 bool IsParameterPack = EllipsisLoc.isValid();
1645 TemplateTemplateParmDecl *Param = TemplateTemplateParmDecl::Create(
1646 Context, Context.getTranslationUnitDecl(),
1647 NameLoc.isInvalid() ? TmpLoc : NameLoc, Depth, Position, IsParameterPack,
1648 Name, Typename, Params);
1649 Param->setAccess(AS_public);
1650
1651 if (Param->isParameterPack())
1652 if (auto *LSI = getEnclosingLambda())
1653 LSI->LocalPacks.push_back(Param);
1654
1655 // If the template template parameter has a name, then link the identifier
1656 // into the scope and lookup mechanisms.
1657 if (Name) {
1658 maybeDiagnoseTemplateParameterShadow(SemaRef&: *this, S, Loc: NameLoc, Name);
1659
1660 S->AddDecl(Param);
1661 IdResolver.AddDecl(Param);
1662 }
1663
1664 if (Params->size() == 0) {
1665 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1666 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1667 Param->setInvalidDecl();
1668 }
1669
1670 // C++0x [temp.param]p9:
1671 // A default template-argument may be specified for any kind of
1672 // template-parameter that is not a template parameter pack.
1673 if (IsParameterPack && !Default.isInvalid()) {
1674 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1675 Default = ParsedTemplateArgument();
1676 }
1677
1678 if (!Default.isInvalid()) {
1679 // Check only that we have a template template argument. We don't want to
1680 // try to check well-formedness now, because our template template parameter
1681 // might have dependent types in its template parameters, which we wouldn't
1682 // be able to match now.
1683 //
1684 // If none of the template template parameter's template arguments mention
1685 // other template parameters, we could actually perform more checking here.
1686 // However, it isn't worth doing.
1687 TemplateArgumentLoc DefaultArg = translateTemplateArgument(SemaRef&: *this, Arg: Default);
1688 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1689 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1690 << DefaultArg.getSourceRange();
1691 return Param;
1692 }
1693
1694 // Check for unexpanded parameter packs.
1695 if (DiagnoseUnexpandedParameterPack(Loc: DefaultArg.getLocation(),
1696 Template: DefaultArg.getArgument().getAsTemplate(),
1697 UPPC: UPPC_DefaultArgument))
1698 return Param;
1699
1700 Param->setDefaultArgument(C: Context, DefArg: DefaultArg);
1701 }
1702
1703 return Param;
1704}
1705
1706namespace {
1707class ConstraintRefersToContainingTemplateChecker
1708 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1709 bool Result = false;
1710 const FunctionDecl *Friend = nullptr;
1711 unsigned TemplateDepth = 0;
1712
1713 // Check a record-decl that we've seen to see if it is a lexical parent of the
1714 // Friend, likely because it was referred to without its template arguments.
1715 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1716 CheckingRD = CheckingRD->getMostRecentDecl();
1717 if (!CheckingRD->isTemplated())
1718 return;
1719
1720 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1721 DC && !DC->isFileContext(); DC = DC->getParent())
1722 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1723 if (CheckingRD == RD->getMostRecentDecl())
1724 Result = true;
1725 }
1726
1727 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1728 assert(D->getDepth() <= TemplateDepth &&
1729 "Nothing should reference a value below the actual template depth, "
1730 "depth is likely wrong");
1731 if (D->getDepth() != TemplateDepth)
1732 Result = true;
1733
1734 // Necessary because the type of the NTTP might be what refers to the parent
1735 // constriant.
1736 TransformType(D->getType());
1737 }
1738
1739public:
1740 using inherited = TreeTransform<ConstraintRefersToContainingTemplateChecker>;
1741
1742 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1743 const FunctionDecl *Friend,
1744 unsigned TemplateDepth)
1745 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1746 bool getResult() const { return Result; }
1747
1748 // This should be the only template parm type that we have to deal with.
1749 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1750 // FunctionParmPackExpr are all partially substituted, which cannot happen
1751 // with concepts at this point in translation.
1752 using inherited::TransformTemplateTypeParmType;
1753 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1754 TemplateTypeParmTypeLoc TL, bool) {
1755 assert(TL.getDecl()->getDepth() <= TemplateDepth &&
1756 "Nothing should reference a value below the actual template depth, "
1757 "depth is likely wrong");
1758 if (TL.getDecl()->getDepth() != TemplateDepth)
1759 Result = true;
1760 return inherited::TransformTemplateTypeParmType(
1761 TLB, TL,
1762 /*SuppressObjCLifetime=*/false);
1763 }
1764
1765 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1766 if (!D)
1767 return D;
1768 // FIXME : This is possibly an incomplete list, but it is unclear what other
1769 // Decl kinds could be used to refer to the template parameters. This is a
1770 // best guess so far based on examples currently available, but the
1771 // unreachable should catch future instances/cases.
1772 if (auto *TD = dyn_cast<TypedefNameDecl>(Val: D))
1773 TransformType(TD->getUnderlyingType());
1774 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(Val: D))
1775 CheckNonTypeTemplateParmDecl(D: NTTPD);
1776 else if (auto *VD = dyn_cast<ValueDecl>(Val: D))
1777 TransformType(VD->getType());
1778 else if (auto *TD = dyn_cast<TemplateDecl>(Val: D))
1779 TransformTemplateParameterList(TD->getTemplateParameters());
1780 else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
1781 CheckIfContainingRecord(CheckingRD: RD);
1782 else if (isa<NamedDecl>(Val: D)) {
1783 // No direct types to visit here I believe.
1784 } else
1785 llvm_unreachable("Don't know how to handle this declaration type yet");
1786 return D;
1787 }
1788};
1789} // namespace
1790
1791bool Sema::ConstraintExpressionDependsOnEnclosingTemplate(
1792 const FunctionDecl *Friend, unsigned TemplateDepth,
1793 const Expr *Constraint) {
1794 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1795 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1796 TemplateDepth);
1797 Checker.TransformExpr(const_cast<Expr *>(Constraint));
1798 return Checker.getResult();
1799}
1800
1801/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1802/// constrained by RequiresClause, that contains the template parameters in
1803/// Params.
1804TemplateParameterList *
1805Sema::ActOnTemplateParameterList(unsigned Depth,
1806 SourceLocation ExportLoc,
1807 SourceLocation TemplateLoc,
1808 SourceLocation LAngleLoc,
1809 ArrayRef<NamedDecl *> Params,
1810 SourceLocation RAngleLoc,
1811 Expr *RequiresClause) {
1812 if (ExportLoc.isValid())
1813 Diag(ExportLoc, diag::warn_template_export_unsupported);
1814
1815 for (NamedDecl *P : Params)
1816 warnOnReservedIdentifier(D: P);
1817
1818 return TemplateParameterList::Create(
1819 C: Context, TemplateLoc, LAngleLoc,
1820 Params: llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1821}
1822
1823static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1824 const CXXScopeSpec &SS) {
1825 if (SS.isSet())
1826 T->setQualifierInfo(SS.getWithLocInContext(Context&: S.Context));
1827}
1828
1829// Returns the template parameter list with all default template argument
1830// information.
1831static TemplateParameterList *GetTemplateParameterList(TemplateDecl *TD) {
1832 // Make sure we get the template parameter list from the most
1833 // recent declaration, since that is the only one that is guaranteed to
1834 // have all the default template argument information.
1835 Decl *D = TD->getMostRecentDecl();
1836 // C++11 N3337 [temp.param]p12:
1837 // A default template argument shall not be specified in a friend class
1838 // template declaration.
1839 //
1840 // Skip past friend *declarations* because they are not supposed to contain
1841 // default template arguments. Moreover, these declarations may introduce
1842 // template parameters living in different template depths than the
1843 // corresponding template parameters in TD, causing unmatched constraint
1844 // substitution.
1845 //
1846 // FIXME: Diagnose such cases within a class template:
1847 // template <class T>
1848 // struct S {
1849 // template <class = void> friend struct C;
1850 // };
1851 // template struct S<int>;
1852 while (D->getFriendObjectKind() != Decl::FriendObjectKind::FOK_None &&
1853 D->getPreviousDecl())
1854 D = D->getPreviousDecl();
1855 return cast<TemplateDecl>(Val: D)->getTemplateParameters();
1856}
1857
1858DeclResult Sema::CheckClassTemplate(
1859 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1860 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1861 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1862 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1863 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1864 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1865 assert(TemplateParams && TemplateParams->size() > 0 &&
1866 "No template parameters");
1867 assert(TUK != TUK_Reference && "Can only declare or define class templates");
1868 bool Invalid = false;
1869
1870 // Check that we can declare a template here.
1871 if (CheckTemplateDeclScope(S, TemplateParams))
1872 return true;
1873
1874 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
1875 assert(Kind != TagTypeKind::Enum &&
1876 "can't build template of enumerated type");
1877
1878 // There is no such thing as an unnamed class template.
1879 if (!Name) {
1880 Diag(KWLoc, diag::err_template_unnamed_class);
1881 return true;
1882 }
1883
1884 // Find any previous declaration with this name. For a friend with no
1885 // scope explicitly specified, we only look for tag declarations (per
1886 // C++11 [basic.lookup.elab]p2).
1887 DeclContext *SemanticContext;
1888 LookupResult Previous(*this, Name, NameLoc,
1889 (SS.isEmpty() && TUK == TUK_Friend)
1890 ? LookupTagName : LookupOrdinaryName,
1891 forRedeclarationInCurContext());
1892 if (SS.isNotEmpty() && !SS.isInvalid()) {
1893 SemanticContext = computeDeclContext(SS, EnteringContext: true);
1894 if (!SemanticContext) {
1895 // FIXME: Horrible, horrible hack! We can't currently represent this
1896 // in the AST, and historically we have just ignored such friend
1897 // class templates, so don't complain here.
1898 Diag(NameLoc, TUK == TUK_Friend
1899 ? diag::warn_template_qualified_friend_ignored
1900 : diag::err_template_qualified_declarator_no_match)
1901 << SS.getScopeRep() << SS.getRange();
1902 return TUK != TUK_Friend;
1903 }
1904
1905 if (RequireCompleteDeclContext(SS, DC: SemanticContext))
1906 return true;
1907
1908 // If we're adding a template to a dependent context, we may need to
1909 // rebuilding some of the types used within the template parameter list,
1910 // now that we know what the current instantiation is.
1911 if (SemanticContext->isDependentContext()) {
1912 ContextRAII SavedContext(*this, SemanticContext);
1913 if (RebuildTemplateParamsInCurrentInstantiation(Params: TemplateParams))
1914 Invalid = true;
1915 }
1916
1917 if (TUK != TUK_Friend && TUK != TUK_Reference)
1918 diagnoseQualifiedDeclaration(SS, DC: SemanticContext, Name, Loc: NameLoc,
1919 /*TemplateId-*/ TemplateId: nullptr,
1920 /*IsMemberSpecialization*/ false);
1921
1922 LookupQualifiedName(R&: Previous, LookupCtx: SemanticContext);
1923 } else {
1924 SemanticContext = CurContext;
1925
1926 // C++14 [class.mem]p14:
1927 // If T is the name of a class, then each of the following shall have a
1928 // name different from T:
1929 // -- every member template of class T
1930 if (TUK != TUK_Friend &&
1931 DiagnoseClassNameShadow(DC: SemanticContext,
1932 Info: DeclarationNameInfo(Name, NameLoc)))
1933 return true;
1934
1935 LookupName(R&: Previous, S);
1936 }
1937
1938 if (Previous.isAmbiguous())
1939 return true;
1940
1941 NamedDecl *PrevDecl = nullptr;
1942 if (Previous.begin() != Previous.end())
1943 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1944
1945 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1946 // Maybe we will complain about the shadowed template parameter.
1947 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1948 // Just pretend that we didn't see the previous declaration.
1949 PrevDecl = nullptr;
1950 }
1951
1952 // If there is a previous declaration with the same name, check
1953 // whether this is a valid redeclaration.
1954 ClassTemplateDecl *PrevClassTemplate =
1955 dyn_cast_or_null<ClassTemplateDecl>(Val: PrevDecl);
1956
1957 // We may have found the injected-class-name of a class template,
1958 // class template partial specialization, or class template specialization.
1959 // In these cases, grab the template that is being defined or specialized.
1960 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(Val: PrevDecl) &&
1961 cast<CXXRecordDecl>(Val: PrevDecl)->isInjectedClassName()) {
1962 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1963 PrevClassTemplate
1964 = cast<CXXRecordDecl>(Val: PrevDecl)->getDescribedClassTemplate();
1965 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(Val: PrevDecl)) {
1966 PrevClassTemplate
1967 = cast<ClassTemplateSpecializationDecl>(Val: PrevDecl)
1968 ->getSpecializedTemplate();
1969 }
1970 }
1971
1972 if (TUK == TUK_Friend) {
1973 // C++ [namespace.memdef]p3:
1974 // [...] When looking for a prior declaration of a class or a function
1975 // declared as a friend, and when the name of the friend class or
1976 // function is neither a qualified name nor a template-id, scopes outside
1977 // the innermost enclosing namespace scope are not considered.
1978 if (!SS.isSet()) {
1979 DeclContext *OutermostContext = CurContext;
1980 while (!OutermostContext->isFileContext())
1981 OutermostContext = OutermostContext->getLookupParent();
1982
1983 if (PrevDecl &&
1984 (OutermostContext->Equals(DC: PrevDecl->getDeclContext()) ||
1985 OutermostContext->Encloses(DC: PrevDecl->getDeclContext()))) {
1986 SemanticContext = PrevDecl->getDeclContext();
1987 } else {
1988 // Declarations in outer scopes don't matter. However, the outermost
1989 // context we computed is the semantic context for our new
1990 // declaration.
1991 PrevDecl = PrevClassTemplate = nullptr;
1992 SemanticContext = OutermostContext;
1993
1994 // Check that the chosen semantic context doesn't already contain a
1995 // declaration of this name as a non-tag type.
1996 Previous.clear(Kind: LookupOrdinaryName);
1997 DeclContext *LookupContext = SemanticContext;
1998 while (LookupContext->isTransparentContext())
1999 LookupContext = LookupContext->getLookupParent();
2000 LookupQualifiedName(R&: Previous, LookupCtx: LookupContext);
2001
2002 if (Previous.isAmbiguous())
2003 return true;
2004
2005 if (Previous.begin() != Previous.end())
2006 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
2007 }
2008 }
2009 } else if (PrevDecl &&
2010 !isDeclInScope(D: Previous.getRepresentativeDecl(), Ctx: SemanticContext,
2011 S, AllowInlineNamespace: SS.isValid()))
2012 PrevDecl = PrevClassTemplate = nullptr;
2013
2014 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
2015 Val: PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
2016 if (SS.isEmpty() &&
2017 !(PrevClassTemplate &&
2018 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
2019 SemanticContext->getRedeclContext()))) {
2020 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
2021 Diag(Shadow->getTargetDecl()->getLocation(),
2022 diag::note_using_decl_target);
2023 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2024 // Recover by ignoring the old declaration.
2025 PrevDecl = PrevClassTemplate = nullptr;
2026 }
2027 }
2028
2029 if (PrevClassTemplate) {
2030 // Ensure that the template parameter lists are compatible. Skip this check
2031 // for a friend in a dependent context: the template parameter list itself
2032 // could be dependent.
2033 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
2034 !TemplateParameterListsAreEqual(
2035 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2036 : CurContext,
2037 CurContext, KWLoc),
2038 TemplateParams, PrevClassTemplate,
2039 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2040 TPL_TemplateMatch))
2041 return true;
2042
2043 // C++ [temp.class]p4:
2044 // In a redeclaration, partial specialization, explicit
2045 // specialization or explicit instantiation of a class template,
2046 // the class-key shall agree in kind with the original class
2047 // template declaration (7.1.5.3).
2048 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2049 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
2050 TUK == TUK_Definition, KWLoc, Name)) {
2051 Diag(KWLoc, diag::err_use_with_wrong_tag)
2052 << Name
2053 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2054 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2055 Kind = PrevRecordDecl->getTagKind();
2056 }
2057
2058 // Check for redefinition of this class template.
2059 if (TUK == TUK_Definition) {
2060 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2061 // If we have a prior definition that is not visible, treat this as
2062 // simply making that previous definition visible.
2063 NamedDecl *Hidden = nullptr;
2064 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2065 SkipBody->ShouldSkip = true;
2066 SkipBody->Previous = Def;
2067 auto *Tmpl = cast<CXXRecordDecl>(Val: Hidden)->getDescribedClassTemplate();
2068 assert(Tmpl && "original definition of a class template is not a "
2069 "class template?");
2070 makeMergedDefinitionVisible(ND: Hidden);
2071 makeMergedDefinitionVisible(Tmpl);
2072 } else {
2073 Diag(NameLoc, diag::err_redefinition) << Name;
2074 Diag(Def->getLocation(), diag::note_previous_definition);
2075 // FIXME: Would it make sense to try to "forget" the previous
2076 // definition, as part of error recovery?
2077 return true;
2078 }
2079 }
2080 }
2081 } else if (PrevDecl) {
2082 // C++ [temp]p5:
2083 // A class template shall not have the same name as any other
2084 // template, class, function, object, enumeration, enumerator,
2085 // namespace, or type in the same scope (3.3), except as specified
2086 // in (14.5.4).
2087 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2088 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2089 return true;
2090 }
2091
2092 // Check the template parameter list of this declaration, possibly
2093 // merging in the template parameter list from the previous class
2094 // template declaration. Skip this check for a friend in a dependent
2095 // context, because the template parameter list might be dependent.
2096 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
2097 CheckTemplateParameterList(
2098 NewParams: TemplateParams,
2099 OldParams: PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2100 : nullptr,
2101 TPC: (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2102 SemanticContext->isDependentContext())
2103 ? TPC_ClassTemplateMember
2104 : TUK == TUK_Friend ? TPC_FriendClassTemplate
2105 : TPC_ClassTemplate,
2106 SkipBody))
2107 Invalid = true;
2108
2109 if (SS.isSet()) {
2110 // If the name of the template was qualified, we must be defining the
2111 // template out-of-line.
2112 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2113 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
2114 : diag::err_member_decl_does_not_match)
2115 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
2116 Invalid = true;
2117 }
2118 }
2119
2120 // If this is a templated friend in a dependent context we should not put it
2121 // on the redecl chain. In some cases, the templated friend can be the most
2122 // recent declaration tricking the template instantiator to make substitutions
2123 // there.
2124 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2125 bool ShouldAddRedecl
2126 = !(TUK == TUK_Friend && CurContext->isDependentContext());
2127
2128 CXXRecordDecl *NewClass =
2129 CXXRecordDecl::Create(C: Context, TK: Kind, DC: SemanticContext, StartLoc: KWLoc, IdLoc: NameLoc, Id: Name,
2130 PrevDecl: PrevClassTemplate && ShouldAddRedecl ?
2131 PrevClassTemplate->getTemplatedDecl() : nullptr,
2132 /*DelayTypeCreation=*/true);
2133 SetNestedNameSpecifier(*this, NewClass, SS);
2134 if (NumOuterTemplateParamLists > 0)
2135 NewClass->setTemplateParameterListsInfo(
2136 Context,
2137 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2138
2139 // Add alignment attributes if necessary; these attributes are checked when
2140 // the ASTContext lays out the structure.
2141 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2142 AddAlignmentAttributesForRecord(NewClass);
2143 AddMsStructLayoutForRecord(NewClass);
2144 }
2145
2146 ClassTemplateDecl *NewTemplate
2147 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2148 DeclarationName(Name), TemplateParams,
2149 NewClass);
2150
2151 if (ShouldAddRedecl)
2152 NewTemplate->setPreviousDecl(PrevClassTemplate);
2153
2154 NewClass->setDescribedClassTemplate(NewTemplate);
2155
2156 if (ModulePrivateLoc.isValid())
2157 NewTemplate->setModulePrivate();
2158
2159 // Build the type for the class template declaration now.
2160 QualType T = NewTemplate->getInjectedClassNameSpecialization();
2161 T = Context.getInjectedClassNameType(Decl: NewClass, TST: T);
2162 assert(T->isDependentType() && "Class template type is not dependent?");
2163 (void)T;
2164
2165 // If we are providing an explicit specialization of a member that is a
2166 // class template, make a note of that.
2167 if (PrevClassTemplate &&
2168 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2169 PrevClassTemplate->setMemberSpecialization();
2170
2171 // Set the access specifier.
2172 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
2173 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2174
2175 // Set the lexical context of these templates
2176 NewClass->setLexicalDeclContext(CurContext);
2177 NewTemplate->setLexicalDeclContext(CurContext);
2178
2179 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
2180 NewClass->startDefinition();
2181
2182 ProcessDeclAttributeList(S, NewClass, Attr);
2183 ProcessAPINotes(NewClass);
2184
2185 if (PrevClassTemplate)
2186 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2187
2188 AddPushedVisibilityAttribute(NewClass);
2189 inferGslOwnerPointerAttribute(Record: NewClass);
2190 inferNullableClassAttribute(CRD: NewClass);
2191
2192 if (TUK != TUK_Friend) {
2193 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2194 Scope *Outer = S;
2195 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2196 Outer = Outer->getParent();
2197 PushOnScopeChains(NewTemplate, Outer);
2198 } else {
2199 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2200 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2201 NewClass->setAccess(PrevClassTemplate->getAccess());
2202 }
2203
2204 NewTemplate->setObjectOfFriendDecl();
2205
2206 // Friend templates are visible in fairly strange ways.
2207 if (!CurContext->isDependentContext()) {
2208 DeclContext *DC = SemanticContext->getRedeclContext();
2209 DC->makeDeclVisibleInContext(NewTemplate);
2210 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2211 PushOnScopeChains(NewTemplate, EnclosingScope,
2212 /* AddToContext = */ false);
2213 }
2214
2215 FriendDecl *Friend = FriendDecl::Create(
2216 C&: Context, DC: CurContext, L: NewClass->getLocation(), Friend_: NewTemplate, FriendL: FriendLoc);
2217 Friend->setAccess(AS_public);
2218 CurContext->addDecl(Friend);
2219 }
2220
2221 if (PrevClassTemplate)
2222 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2223
2224 if (Invalid) {
2225 NewTemplate->setInvalidDecl();
2226 NewClass->setInvalidDecl();
2227 }
2228
2229 ActOnDocumentableDecl(NewTemplate);
2230
2231 if (SkipBody && SkipBody->ShouldSkip)
2232 return SkipBody->Previous;
2233
2234 return NewTemplate;
2235}
2236
2237namespace {
2238/// Tree transform to "extract" a transformed type from a class template's
2239/// constructor to a deduction guide.
2240class ExtractTypeForDeductionGuide
2241 : public TreeTransform<ExtractTypeForDeductionGuide> {
2242 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
2243
2244public:
2245 typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
2246 ExtractTypeForDeductionGuide(
2247 Sema &SemaRef,
2248 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs)
2249 : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {}
2250
2251 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
2252
2253 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
2254 ASTContext &Context = SemaRef.getASTContext();
2255 TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
2256 TypedefNameDecl *Decl = OrigDecl;
2257 // Transform the underlying type of the typedef and clone the Decl only if
2258 // the typedef has a dependent context.
2259 if (OrigDecl->getDeclContext()->isDependentContext()) {
2260 TypeLocBuilder InnerTLB;
2261 QualType Transformed =
2262 TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
2263 TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, T: Transformed);
2264 if (isa<TypeAliasDecl>(Val: OrigDecl))
2265 Decl = TypeAliasDecl::Create(
2266 C&: Context, DC: Context.getTranslationUnitDecl(), StartLoc: OrigDecl->getBeginLoc(),
2267 IdLoc: OrigDecl->getLocation(), Id: OrigDecl->getIdentifier(), TInfo: TSI);
2268 else {
2269 assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef");
2270 Decl = TypedefDecl::Create(
2271 C&: Context, DC: Context.getTranslationUnitDecl(), StartLoc: OrigDecl->getBeginLoc(),
2272 IdLoc: OrigDecl->getLocation(), Id: OrigDecl->getIdentifier(), TInfo: TSI);
2273 }
2274 MaterializedTypedefs.push_back(Elt: Decl);
2275 }
2276
2277 QualType TDTy = Context.getTypedefType(Decl);
2278 TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(T: TDTy);
2279 TypedefTL.setNameLoc(TL.getNameLoc());
2280
2281 return TDTy;
2282 }
2283};
2284
2285// Build a deduction guide with the specified parameter types.
2286FunctionTemplateDecl *buildDeductionGuide(
2287 Sema &SemaRef, TemplateDecl *OriginalTemplate,
2288 TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor,
2289 ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart,
2290 SourceLocation Loc, SourceLocation LocEnd, bool IsImplicit,
2291 llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
2292 DeclContext *DC = OriginalTemplate->getDeclContext();
2293 auto DeductionGuideName =
2294 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(
2295 TD: OriginalTemplate);
2296
2297 DeclarationNameInfo Name(DeductionGuideName, Loc);
2298 ArrayRef<ParmVarDecl *> Params =
2299 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2300
2301 // Build the implicit deduction guide template.
2302 auto *Guide =
2303 CXXDeductionGuideDecl::Create(C&: SemaRef.Context, DC, StartLoc: LocStart, ES, NameInfo: Name,
2304 T: TInfo->getType(), TInfo, EndLocation: LocEnd, Ctor);
2305 Guide->setImplicit(IsImplicit);
2306 Guide->setParams(Params);
2307
2308 for (auto *Param : Params)
2309 Param->setDeclContext(Guide);
2310 for (auto *TD : MaterializedTypedefs)
2311 TD->setDeclContext(Guide);
2312
2313 auto *GuideTemplate = FunctionTemplateDecl::Create(
2314 C&: SemaRef.Context, DC, L: Loc, Name: DeductionGuideName, Params: TemplateParams, Decl: Guide);
2315 GuideTemplate->setImplicit(IsImplicit);
2316 Guide->setDescribedFunctionTemplate(GuideTemplate);
2317
2318 if (isa<CXXRecordDecl>(Val: DC)) {
2319 Guide->setAccess(AS_public);
2320 GuideTemplate->setAccess(AS_public);
2321 }
2322
2323 DC->addDecl(D: GuideTemplate);
2324 return GuideTemplate;
2325}
2326
2327// Transform a given template type parameter `TTP`.
2328TemplateTypeParmDecl *
2329transformTemplateTypeParam(Sema &SemaRef, DeclContext *DC,
2330 TemplateTypeParmDecl *TTP,
2331 MultiLevelTemplateArgumentList &Args,
2332 unsigned NewDepth, unsigned NewIndex) {
2333 // TemplateTypeParmDecl's index cannot be changed after creation, so
2334 // substitute it directly.
2335 auto *NewTTP = TemplateTypeParmDecl::Create(
2336 C: SemaRef.Context, DC, KeyLoc: TTP->getBeginLoc(), NameLoc: TTP->getLocation(), D: NewDepth,
2337 P: NewIndex, Id: TTP->getIdentifier(), Typename: TTP->wasDeclaredWithTypename(),
2338 ParameterPack: TTP->isParameterPack(), HasTypeConstraint: TTP->hasTypeConstraint(),
2339 NumExpanded: TTP->isExpandedParameterPack()
2340 ? std::optional<unsigned>(TTP->getNumExpansionParameters())
2341 : std::nullopt);
2342 if (const auto *TC = TTP->getTypeConstraint())
2343 SemaRef.SubstTypeConstraint(Inst: NewTTP, TC, TemplateArgs: Args,
2344 /*EvaluateConstraint=*/true);
2345 if (TTP->hasDefaultArgument()) {
2346 TypeSourceInfo *InstantiatedDefaultArg =
2347 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
2348 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
2349 if (InstantiatedDefaultArg)
2350 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
2351 }
2352 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D: TTP, Inst: NewTTP);
2353 return NewTTP;
2354}
2355// Similar to above, but for non-type template or template template parameters.
2356template <typename NonTypeTemplateOrTemplateTemplateParmDecl>
2357NonTypeTemplateOrTemplateTemplateParmDecl *
2358transformTemplateParam(Sema &SemaRef, DeclContext *DC,
2359 NonTypeTemplateOrTemplateTemplateParmDecl *OldParam,
2360 MultiLevelTemplateArgumentList &Args, unsigned NewIndex,
2361 unsigned NewDepth) {
2362 // Ask the template instantiator to do the heavy lifting for us, then adjust
2363 // the index of the parameter once it's done.
2364 auto *NewParam = cast<NonTypeTemplateOrTemplateTemplateParmDecl>(
2365 SemaRef.SubstDecl(D: OldParam, Owner: DC, TemplateArgs: Args));
2366 NewParam->setPosition(NewIndex);
2367 NewParam->setDepth(NewDepth);
2368 return NewParam;
2369}
2370
2371/// Transform to convert portions of a constructor declaration into the
2372/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
2373struct ConvertConstructorToDeductionGuideTransform {
2374 ConvertConstructorToDeductionGuideTransform(Sema &S,
2375 ClassTemplateDecl *Template)
2376 : SemaRef(S), Template(Template) {
2377 // If the template is nested, then we need to use the original
2378 // pattern to iterate over the constructors.
2379 ClassTemplateDecl *Pattern = Template;
2380 while (Pattern->getInstantiatedFromMemberTemplate()) {
2381 if (Pattern->isMemberSpecialization())
2382 break;
2383 Pattern = Pattern->getInstantiatedFromMemberTemplate();
2384 NestedPattern = Pattern;
2385 }
2386
2387 if (NestedPattern)
2388 OuterInstantiationArgs = SemaRef.getTemplateInstantiationArgs(Template);
2389 }
2390
2391 Sema &SemaRef;
2392 ClassTemplateDecl *Template;
2393 ClassTemplateDecl *NestedPattern = nullptr;
2394
2395 DeclContext *DC = Template->getDeclContext();
2396 CXXRecordDecl *Primary = Template->getTemplatedDecl();
2397 DeclarationName DeductionGuideName =
2398 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
2399
2400 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
2401
2402 // Index adjustment to apply to convert depth-1 template parameters into
2403 // depth-0 template parameters.
2404 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
2405
2406 // Instantiation arguments for the outermost depth-1 templates
2407 // when the template is nested
2408 MultiLevelTemplateArgumentList OuterInstantiationArgs;
2409
2410 /// Transform a constructor declaration into a deduction guide.
2411 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
2412 CXXConstructorDecl *CD) {
2413 SmallVector<TemplateArgument, 16> SubstArgs;
2414
2415 LocalInstantiationScope Scope(SemaRef);
2416
2417 // C++ [over.match.class.deduct]p1:
2418 // -- For each constructor of the class template designated by the
2419 // template-name, a function template with the following properties:
2420
2421 // -- The template parameters are the template parameters of the class
2422 // template followed by the template parameters (including default
2423 // template arguments) of the constructor, if any.
2424 TemplateParameterList *TemplateParams = GetTemplateParameterList(Template);
2425 if (FTD) {
2426 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
2427 SmallVector<NamedDecl *, 16> AllParams;
2428 SmallVector<TemplateArgument, 16> Depth1Args;
2429 AllParams.reserve(N: TemplateParams->size() + InnerParams->size());
2430 AllParams.insert(I: AllParams.begin(),
2431 From: TemplateParams->begin(), To: TemplateParams->end());
2432 SubstArgs.reserve(N: InnerParams->size());
2433 Depth1Args.reserve(N: InnerParams->size());
2434
2435 // Later template parameters could refer to earlier ones, so build up
2436 // a list of substituted template arguments as we go.
2437 for (NamedDecl *Param : *InnerParams) {
2438 MultiLevelTemplateArgumentList Args;
2439 Args.setKind(TemplateSubstitutionKind::Rewrite);
2440 Args.addOuterTemplateArguments(Depth1Args);
2441 Args.addOuterRetainedLevel();
2442 if (NestedPattern)
2443 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
2444 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
2445 if (!NewParam)
2446 return nullptr;
2447 // Constraints require that we substitute depth-1 arguments
2448 // to match depths when substituted for evaluation later
2449 Depth1Args.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2450 SemaRef.Context.getInjectedTemplateArg(NewParam)));
2451
2452 if (NestedPattern) {
2453 TemplateDeclInstantiator Instantiator(SemaRef, DC,
2454 OuterInstantiationArgs);
2455 Instantiator.setEvaluateConstraints(false);
2456 SemaRef.runWithSufficientStackSpace(NewParam->getLocation(), [&] {
2457 NewParam = cast<NamedDecl>(Instantiator.Visit(NewParam));
2458 });
2459 }
2460
2461 assert(NewParam->getTemplateDepth() == 0 &&
2462 "Unexpected template parameter depth");
2463
2464 AllParams.push_back(NewParam);
2465 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2466 SemaRef.Context.getInjectedTemplateArg(NewParam)));
2467 }
2468
2469 // Substitute new template parameters into requires-clause if present.
2470 Expr *RequiresClause = nullptr;
2471 if (Expr *InnerRC = InnerParams->getRequiresClause()) {
2472 MultiLevelTemplateArgumentList Args;
2473 Args.setKind(TemplateSubstitutionKind::Rewrite);
2474 Args.addOuterTemplateArguments(Args: Depth1Args);
2475 Args.addOuterRetainedLevel();
2476 if (NestedPattern)
2477 Args.addOuterRetainedLevels(Num: NestedPattern->getTemplateDepth());
2478 ExprResult E = SemaRef.SubstExpr(E: InnerRC, TemplateArgs: Args);
2479 if (E.isInvalid())
2480 return nullptr;
2481 RequiresClause = E.getAs<Expr>();
2482 }
2483
2484 TemplateParams = TemplateParameterList::Create(
2485 C: SemaRef.Context, TemplateLoc: InnerParams->getTemplateLoc(),
2486 LAngleLoc: InnerParams->getLAngleLoc(), Params: AllParams, RAngleLoc: InnerParams->getRAngleLoc(),
2487 RequiresClause);
2488 }
2489
2490 // If we built a new template-parameter-list, track that we need to
2491 // substitute references to the old parameters into references to the
2492 // new ones.
2493 MultiLevelTemplateArgumentList Args;
2494 Args.setKind(TemplateSubstitutionKind::Rewrite);
2495 if (FTD) {
2496 Args.addOuterTemplateArguments(Args: SubstArgs);
2497 Args.addOuterRetainedLevel();
2498 }
2499
2500 if (NestedPattern)
2501 Args.addOuterRetainedLevels(Num: NestedPattern->getTemplateDepth());
2502
2503 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
2504 .getAsAdjusted<FunctionProtoTypeLoc>();
2505 assert(FPTL && "no prototype for constructor declaration");
2506
2507 // Transform the type of the function, adjusting the return type and
2508 // replacing references to the old parameters with references to the
2509 // new ones.
2510 TypeLocBuilder TLB;
2511 SmallVector<ParmVarDecl*, 8> Params;
2512 SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
2513 QualType NewType = transformFunctionProtoType(TLB, TL: FPTL, Params, Args,
2514 MaterializedTypedefs);
2515 if (NewType.isNull())
2516 return nullptr;
2517 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(Context&: SemaRef.Context, T: NewType);
2518
2519 return buildDeductionGuide(
2520 SemaRef, Template, TemplateParams, CD, CD->getExplicitSpecifier(),
2521 NewTInfo, CD->getBeginLoc(), CD->getLocation(), CD->getEndLoc(),
2522 /*IsImplicit=*/true, MaterializedTypedefs);
2523 }
2524
2525 /// Build a deduction guide with the specified parameter types.
2526 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
2527 SourceLocation Loc = Template->getLocation();
2528
2529 // Build the requested type.
2530 FunctionProtoType::ExtProtoInfo EPI;
2531 EPI.HasTrailingReturn = true;
2532 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
2533 DeductionGuideName, EPI);
2534 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(T: Result, Loc);
2535 if (NestedPattern)
2536 TSI = SemaRef.SubstType(T: TSI, TemplateArgs: OuterInstantiationArgs, Loc,
2537 Entity: DeductionGuideName);
2538
2539 FunctionProtoTypeLoc FPTL =
2540 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
2541
2542 // Build the parameters, needed during deduction / substitution.
2543 SmallVector<ParmVarDecl*, 4> Params;
2544 for (auto T : ParamTypes) {
2545 auto *TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc);
2546 if (NestedPattern)
2547 TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
2548 DeclarationName());
2549 ParmVarDecl *NewParam =
2550 ParmVarDecl::Create(C&: SemaRef.Context, DC, StartLoc: Loc, IdLoc: Loc, Id: nullptr,
2551 T: TSI->getType(), TInfo: TSI, S: SC_None, DefArg: nullptr);
2552 NewParam->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
2553 FPTL.setParam(Params.size(), NewParam);
2554 Params.push_back(Elt: NewParam);
2555 }
2556
2557 return buildDeductionGuide(
2558 SemaRef, Template, GetTemplateParameterList(Template), nullptr,
2559 ExplicitSpecifier(), TSI, Loc, Loc, Loc, /*IsImplicit=*/true);
2560 }
2561
2562private:
2563 /// Transform a constructor template parameter into a deduction guide template
2564 /// parameter, rebuilding any internal references to earlier parameters and
2565 /// renumbering as we go.
2566 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
2567 MultiLevelTemplateArgumentList &Args) {
2568 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: TemplateParam))
2569 return transformTemplateTypeParam(
2570 SemaRef, DC, TTP, Args, NewDepth: TTP->getDepth() - 1,
2571 NewIndex: Depth1IndexAdjustment + TTP->getIndex());
2572 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: TemplateParam))
2573 return transformTemplateParam(SemaRef, DC, TTP, Args,
2574 Depth1IndexAdjustment + TTP->getIndex(),
2575 TTP->getDepth() - 1);
2576 auto *NTTP = cast<NonTypeTemplateParmDecl>(Val: TemplateParam);
2577 return transformTemplateParam(SemaRef, DC, NTTP, Args,
2578 Depth1IndexAdjustment + NTTP->getIndex(),
2579 NTTP->getDepth() - 1);
2580 }
2581
2582 QualType transformFunctionProtoType(
2583 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL,
2584 SmallVectorImpl<ParmVarDecl *> &Params,
2585 MultiLevelTemplateArgumentList &Args,
2586 SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2587 SmallVector<QualType, 4> ParamTypes;
2588 const FunctionProtoType *T = TL.getTypePtr();
2589
2590 // -- The types of the function parameters are those of the constructor.
2591 for (auto *OldParam : TL.getParams()) {
2592 ParmVarDecl *NewParam =
2593 transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs);
2594 if (NestedPattern && NewParam)
2595 NewParam = transformFunctionTypeParam(NewParam, OuterInstantiationArgs,
2596 MaterializedTypedefs);
2597 if (!NewParam)
2598 return QualType();
2599 ParamTypes.push_back(NewParam->getType());
2600 Params.push_back(NewParam);
2601 }
2602
2603 // -- The return type is the class template specialization designated by
2604 // the template-name and template arguments corresponding to the
2605 // template parameters obtained from the class template.
2606 //
2607 // We use the injected-class-name type of the primary template instead.
2608 // This has the convenient property that it is different from any type that
2609 // the user can write in a deduction-guide (because they cannot enter the
2610 // context of the template), so implicit deduction guides can never collide
2611 // with explicit ones.
2612 QualType ReturnType = DeducedType;
2613 TLB.pushTypeSpec(T: ReturnType).setNameLoc(Primary->getLocation());
2614
2615 // Resolving a wording defect, we also inherit the variadicness of the
2616 // constructor.
2617 FunctionProtoType::ExtProtoInfo EPI;
2618 EPI.Variadic = T->isVariadic();
2619 EPI.HasTrailingReturn = true;
2620
2621 QualType Result = SemaRef.BuildFunctionType(
2622 T: ReturnType, ParamTypes, Loc: TL.getBeginLoc(), Entity: DeductionGuideName, EPI);
2623 if (Result.isNull())
2624 return QualType();
2625
2626 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(T: Result);
2627 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
2628 NewTL.setLParenLoc(TL.getLParenLoc());
2629 NewTL.setRParenLoc(TL.getRParenLoc());
2630 NewTL.setExceptionSpecRange(SourceRange());
2631 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
2632 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
2633 NewTL.setParam(I, Params[I]);
2634
2635 return Result;
2636 }
2637
2638 ParmVarDecl *transformFunctionTypeParam(
2639 ParmVarDecl *OldParam, MultiLevelTemplateArgumentList &Args,
2640 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2641 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2642 TypeSourceInfo *NewDI;
2643 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2644 // Expand out the one and only element in each inner pack.
2645 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2646 NewDI =
2647 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2648 OldParam->getLocation(), OldParam->getDeclName());
2649 if (!NewDI) return nullptr;
2650 NewDI =
2651 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2652 PackTL.getTypePtr()->getNumExpansions());
2653 } else
2654 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2655 OldParam->getDeclName());
2656 if (!NewDI)
2657 return nullptr;
2658
2659 // Extract the type. This (for instance) replaces references to typedef
2660 // members of the current instantiations with the definitions of those
2661 // typedefs, avoiding triggering instantiation of the deduced type during
2662 // deduction.
2663 NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs)
2664 .transform(TSI: NewDI);
2665
2666 // Resolving a wording defect, we also inherit default arguments from the
2667 // constructor.
2668 ExprResult NewDefArg;
2669 if (OldParam->hasDefaultArg()) {
2670 // We don't care what the value is (we won't use it); just create a
2671 // placeholder to indicate there is a default argument.
2672 QualType ParamTy = NewDI->getType();
2673 NewDefArg = new (SemaRef.Context)
2674 OpaqueValueExpr(OldParam->getDefaultArg()->getBeginLoc(),
2675 ParamTy.getNonLValueExprType(Context: SemaRef.Context),
2676 ParamTy->isLValueReferenceType() ? VK_LValue
2677 : ParamTy->isRValueReferenceType() ? VK_XValue
2678 : VK_PRValue);
2679 }
2680 // Handle arrays and functions decay.
2681 auto NewType = NewDI->getType();
2682 if (NewType->isArrayType() || NewType->isFunctionType())
2683 NewType = SemaRef.Context.getDecayedType(T: NewType);
2684
2685 ParmVarDecl *NewParam = ParmVarDecl::Create(
2686 C&: SemaRef.Context, DC, StartLoc: OldParam->getInnerLocStart(),
2687 IdLoc: OldParam->getLocation(), Id: OldParam->getIdentifier(), T: NewType, TInfo: NewDI,
2688 S: OldParam->getStorageClass(), DefArg: NewDefArg.get());
2689 NewParam->setScopeInfo(scopeDepth: OldParam->getFunctionScopeDepth(),
2690 parameterIndex: OldParam->getFunctionScopeIndex());
2691 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2692 return NewParam;
2693 }
2694};
2695
2696// Find all template parameters that appear in the given DeducedArgs.
2697// Return the indices of the template parameters in the TemplateParams.
2698SmallVector<unsigned> TemplateParamsReferencedInTemplateArgumentList(
2699 ArrayRef<NamedDecl *> TemplateParams,
2700 ArrayRef<TemplateArgument> DeducedArgs) {
2701 struct TemplateParamsReferencedFinder
2702 : public RecursiveASTVisitor<TemplateParamsReferencedFinder> {
2703 llvm::DenseSet<NamedDecl *> TemplateParams;
2704 llvm::DenseSet<const NamedDecl *> ReferencedTemplateParams;
2705
2706 TemplateParamsReferencedFinder(ArrayRef<NamedDecl *> TemplateParams)
2707 : TemplateParams(TemplateParams.begin(), TemplateParams.end()) {}
2708
2709 bool VisitTemplateTypeParmType(TemplateTypeParmType *TTP) {
2710 MarkAppeared(TTP->getDecl());
2711 return true;
2712 }
2713 bool VisitDeclRefExpr(DeclRefExpr *DRE) {
2714 MarkAppeared(ND: DRE->getFoundDecl());
2715 return true;
2716 }
2717
2718 bool TraverseTemplateName(TemplateName Template) {
2719 if (auto *TD = Template.getAsTemplateDecl())
2720 MarkAppeared(TD);
2721 return RecursiveASTVisitor::TraverseTemplateName(Template);
2722 }
2723
2724 void MarkAppeared(NamedDecl *ND) {
2725 if (TemplateParams.contains(V: ND))
2726 ReferencedTemplateParams.insert(V: ND);
2727 }
2728 };
2729 TemplateParamsReferencedFinder Finder(TemplateParams);
2730 Finder.TraverseTemplateArguments(Args: DeducedArgs);
2731
2732 SmallVector<unsigned> Results;
2733 for (unsigned Index = 0; Index < TemplateParams.size(); ++Index) {
2734 if (Finder.ReferencedTemplateParams.contains(V: TemplateParams[Index]))
2735 Results.push_back(Elt: Index);
2736 }
2737 return Results;
2738}
2739
2740bool hasDeclaredDeductionGuides(DeclarationName Name, DeclContext *DC) {
2741 // Check whether we've already declared deduction guides for this template.
2742 // FIXME: Consider storing a flag on the template to indicate this.
2743 assert(Name.getNameKind() ==
2744 DeclarationName::NameKind::CXXDeductionGuideName &&
2745 "name must be a deduction guide name");
2746 auto Existing = DC->lookup(Name);
2747 for (auto *D : Existing)
2748 if (D->isImplicit())
2749 return true;
2750 return false;
2751}
2752
2753NamedDecl *transformTemplateParameter(Sema &SemaRef, DeclContext *DC,
2754 NamedDecl *TemplateParam,
2755 MultiLevelTemplateArgumentList &Args,
2756 unsigned NewIndex) {
2757 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Val: TemplateParam))
2758 return transformTemplateTypeParam(SemaRef, DC, TTP, Args, NewDepth: TTP->getDepth(),
2759 NewIndex);
2760 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: TemplateParam))
2761 return transformTemplateParam(SemaRef, DC, TTP, Args, NewIndex,
2762 TTP->getDepth());
2763 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParam))
2764 return transformTemplateParam(SemaRef, DC, NTTP, Args, NewIndex,
2765 NTTP->getDepth());
2766 llvm_unreachable("Unhandled template parameter types");
2767}
2768
2769Expr *transformRequireClause(Sema &SemaRef, FunctionTemplateDecl *FTD,
2770 llvm::ArrayRef<TemplateArgument> TransformedArgs) {
2771 Expr *RC = FTD->getTemplateParameters()->getRequiresClause();
2772 if (!RC)
2773 return nullptr;
2774 MultiLevelTemplateArgumentList Args;
2775 Args.setKind(TemplateSubstitutionKind::Rewrite);
2776 Args.addOuterTemplateArguments(Args: TransformedArgs);
2777 ExprResult E = SemaRef.SubstExpr(E: RC, TemplateArgs: Args);
2778 if (E.isInvalid())
2779 return nullptr;
2780 return E.getAs<Expr>();
2781}
2782
2783std::pair<TemplateDecl *, llvm::ArrayRef<TemplateArgument>>
2784getRHSTemplateDeclAndArgs(Sema &SemaRef, TypeAliasTemplateDecl *AliasTemplate) {
2785 // Unwrap the sugared ElaboratedType.
2786 auto RhsType = AliasTemplate->getTemplatedDecl()
2787 ->getUnderlyingType()
2788 .getSingleStepDesugaredType(SemaRef.Context);
2789 TemplateDecl *Template = nullptr;
2790 llvm::ArrayRef<TemplateArgument> AliasRhsTemplateArgs;
2791 if (const auto *TST = RhsType->getAs<TemplateSpecializationType>()) {
2792 // Cases where the RHS of the alias is dependent. e.g.
2793 // template<typename T>
2794 // using AliasFoo1 = Foo<T>; // a class/type alias template specialization
2795 Template = TST->getTemplateName().getAsTemplateDecl();
2796 AliasRhsTemplateArgs = TST->template_arguments();
2797 } else if (const auto *RT = RhsType->getAs<RecordType>()) {
2798 // Cases where template arguments in the RHS of the alias are not
2799 // dependent. e.g.
2800 // using AliasFoo = Foo<bool>;
2801 if (const auto *CTSD = llvm::dyn_cast<ClassTemplateSpecializationDecl>(
2802 RT->getAsCXXRecordDecl())) {
2803 Template = CTSD->getSpecializedTemplate();
2804 AliasRhsTemplateArgs = CTSD->getTemplateArgs().asArray();
2805 }
2806 } else {
2807 assert(false && "unhandled RHS type of the alias");
2808 }
2809 return {Template, AliasRhsTemplateArgs};
2810}
2811
2812// Build deduction guides for a type alias template.
2813void DeclareImplicitDeductionGuidesForTypeAlias(
2814 Sema &SemaRef, TypeAliasTemplateDecl *AliasTemplate, SourceLocation Loc) {
2815 if (AliasTemplate->isInvalidDecl())
2816 return;
2817 auto &Context = SemaRef.Context;
2818 // FIXME: if there is an explicit deduction guide after the first use of the
2819 // type alias usage, we will not cover this explicit deduction guide. fix this
2820 // case.
2821 if (hasDeclaredDeductionGuides(
2822 Context.DeclarationNames.getCXXDeductionGuideName(AliasTemplate),
2823 AliasTemplate->getDeclContext()))
2824 return;
2825 auto [Template, AliasRhsTemplateArgs] =
2826 getRHSTemplateDeclAndArgs(SemaRef, AliasTemplate);
2827 if (!Template)
2828 return;
2829 DeclarationNameInfo NameInfo(
2830 Context.DeclarationNames.getCXXDeductionGuideName(TD: Template), Loc);
2831 LookupResult Guides(SemaRef, NameInfo, clang::Sema::LookupOrdinaryName);
2832 SemaRef.LookupQualifiedName(Guides, Template->getDeclContext());
2833 Guides.suppressDiagnostics();
2834
2835 for (auto *G : Guides) {
2836 FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(Val: G);
2837 if (!F)
2838 continue;
2839 // The **aggregate** deduction guides are handled in a different code path
2840 // (DeclareImplicitDeductionGuideFromInitList), which involves the tricky
2841 // cache.
2842 if (cast<CXXDeductionGuideDecl>(Val: F->getTemplatedDecl())
2843 ->getDeductionCandidateKind() == DeductionCandidate::Aggregate)
2844 continue;
2845
2846 auto RType = F->getTemplatedDecl()->getReturnType();
2847 // The (trailing) return type of the deduction guide.
2848 const TemplateSpecializationType *FReturnType =
2849 RType->getAs<TemplateSpecializationType>();
2850 if (const auto *InjectedCNT = RType->getAs<InjectedClassNameType>())
2851 // implicitly-generated deduction guide.
2852 FReturnType = InjectedCNT->getInjectedTST();
2853 else if (const auto *ET = RType->getAs<ElaboratedType>())
2854 // explicit deduction guide.
2855 FReturnType = ET->getNamedType()->getAs<TemplateSpecializationType>();
2856 assert(FReturnType && "expected to see a return type");
2857 // Deduce template arguments of the deduction guide f from the RHS of
2858 // the alias.
2859 //
2860 // C++ [over.match.class.deduct]p3: ...For each function or function
2861 // template f in the guides of the template named by the
2862 // simple-template-id of the defining-type-id, the template arguments
2863 // of the return type of f are deduced from the defining-type-id of A
2864 // according to the process in [temp.deduct.type] with the exception
2865 // that deduction does not fail if not all template arguments are
2866 // deduced.
2867 //
2868 //
2869 // template<typename X, typename Y>
2870 // f(X, Y) -> f<Y, X>;
2871 //
2872 // template<typename U>
2873 // using alias = f<int, U>;
2874 //
2875 // The RHS of alias is f<int, U>, we deduced the template arguments of
2876 // the return type of the deduction guide from it: Y->int, X->U
2877 sema::TemplateDeductionInfo TDeduceInfo(Loc);
2878 // Must initialize n elements, this is required by DeduceTemplateArguments.
2879 SmallVector<DeducedTemplateArgument> DeduceResults(
2880 F->getTemplateParameters()->size());
2881
2882 // FIXME: DeduceTemplateArguments stops immediately at the first
2883 // non-deducible template argument. However, this doesn't seem to casue
2884 // issues for practice cases, we probably need to extend it to continue
2885 // performing deduction for rest of arguments to align with the C++
2886 // standard.
2887 SemaRef.DeduceTemplateArguments(
2888 F->getTemplateParameters(), FReturnType->template_arguments(),
2889 AliasRhsTemplateArgs, TDeduceInfo, DeduceResults,
2890 /*NumberOfArgumentsMustMatch=*/false);
2891
2892 SmallVector<TemplateArgument> DeducedArgs;
2893 SmallVector<unsigned> NonDeducedTemplateParamsInFIndex;
2894 // !!NOTE: DeduceResults respects the sequence of template parameters of
2895 // the deduction guide f.
2896 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
2897 if (const auto &D = DeduceResults[Index]; !D.isNull()) // Deduced
2898 DeducedArgs.push_back(Elt: D);
2899 else
2900 NonDeducedTemplateParamsInFIndex.push_back(Elt: Index);
2901 }
2902 auto DeducedAliasTemplateParams =
2903 TemplateParamsReferencedInTemplateArgumentList(
2904 AliasTemplate->getTemplateParameters()->asArray(), DeducedArgs);
2905 // All template arguments null by default.
2906 SmallVector<TemplateArgument> TemplateArgsForBuildingFPrime(
2907 F->getTemplateParameters()->size());
2908
2909 Sema::InstantiatingTemplate BuildingDeductionGuides(
2910 SemaRef, AliasTemplate->getLocation(), F,
2911 Sema::InstantiatingTemplate::BuildingDeductionGuidesTag{});
2912 if (BuildingDeductionGuides.isInvalid())
2913 return;
2914 LocalInstantiationScope Scope(SemaRef);
2915
2916 // Create a template parameter list for the synthesized deduction guide f'.
2917 //
2918 // C++ [over.match.class.deduct]p3.2:
2919 // If f is a function template, f' is a function template whose template
2920 // parameter list consists of all the template parameters of A
2921 // (including their default template arguments) that appear in the above
2922 // deductions or (recursively) in their default template arguments
2923 SmallVector<NamedDecl *> FPrimeTemplateParams;
2924 // Store template arguments that refer to the newly-created template
2925 // parameters, used for building `TemplateArgsForBuildingFPrime`.
2926 SmallVector<TemplateArgument, 16> TransformedDeducedAliasArgs(
2927 AliasTemplate->getTemplateParameters()->size());
2928
2929 for (unsigned AliasTemplateParamIdx : DeducedAliasTemplateParams) {
2930 auto *TP = AliasTemplate->getTemplateParameters()->getParam(
2931 AliasTemplateParamIdx);
2932 // Rebuild any internal references to earlier parameters and reindex as
2933 // we go.
2934 MultiLevelTemplateArgumentList Args;
2935 Args.setKind(TemplateSubstitutionKind::Rewrite);
2936 Args.addOuterTemplateArguments(TransformedDeducedAliasArgs);
2937 NamedDecl *NewParam = transformTemplateParameter(
2938 SemaRef, AliasTemplate->getDeclContext(), TP, Args,
2939 /*NewIndex*/ FPrimeTemplateParams.size());
2940 FPrimeTemplateParams.push_back(NewParam);
2941
2942 auto NewTemplateArgument = Context.getCanonicalTemplateArgument(
2943 Context.getInjectedTemplateArg(NewParam));
2944 TransformedDeducedAliasArgs[AliasTemplateParamIdx] = NewTemplateArgument;
2945 }
2946 // ...followed by the template parameters of f that were not deduced
2947 // (including their default template arguments)
2948 for (unsigned FTemplateParamIdx : NonDeducedTemplateParamsInFIndex) {
2949 auto *TP = F->getTemplateParameters()->getParam(FTemplateParamIdx);
2950 MultiLevelTemplateArgumentList Args;
2951 Args.setKind(TemplateSubstitutionKind::Rewrite);
2952 // We take a shortcut here, it is ok to reuse the
2953 // TemplateArgsForBuildingFPrime.
2954 Args.addOuterTemplateArguments(Args: TemplateArgsForBuildingFPrime);
2955 NamedDecl *NewParam = transformTemplateParameter(
2956 SemaRef, F->getDeclContext(), TP, Args, FPrimeTemplateParams.size());
2957 FPrimeTemplateParams.push_back(Elt: NewParam);
2958
2959 assert(TemplateArgsForBuildingFPrime[FTemplateParamIdx].isNull() &&
2960 "The argument must be null before setting");
2961 TemplateArgsForBuildingFPrime[FTemplateParamIdx] =
2962 Context.getCanonicalTemplateArgument(
2963 Arg: Context.getInjectedTemplateArg(ParamDecl: NewParam));
2964 }
2965
2966 // To form a deduction guide f' from f, we leverage clang's instantiation
2967 // mechanism, we construct a template argument list where the template
2968 // arguments refer to the newly-created template parameters of f', and
2969 // then apply instantiation on this template argument list to instantiate
2970 // f, this ensures all template parameter occurrences are updated
2971 // correctly.
2972 //
2973 // The template argument list is formed from the `DeducedArgs`, two parts:
2974 // 1) appeared template parameters of alias: transfrom the deduced
2975 // template argument;
2976 // 2) non-deduced template parameters of f: rebuild a
2977 // template argument;
2978 //
2979 // 2) has been built already (when rebuilding the new template
2980 // parameters), we now perform 1).
2981 MultiLevelTemplateArgumentList Args;
2982 Args.setKind(TemplateSubstitutionKind::Rewrite);
2983 Args.addOuterTemplateArguments(Args: TransformedDeducedAliasArgs);
2984 for (unsigned Index = 0; Index < DeduceResults.size(); ++Index) {
2985 const auto &D = DeduceResults[Index];
2986 if (D.isNull()) {
2987 // 2): Non-deduced template parameter has been built already.
2988 assert(!TemplateArgsForBuildingFPrime[Index].isNull() &&
2989 "template arguments for non-deduced template parameters should "
2990 "be been set!");
2991 continue;
2992 }
2993 TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc(
2994 Arg: D, NTTPType: QualType(), Loc: SourceLocation{});
2995 TemplateArgumentLoc Output;
2996 if (!SemaRef.SubstTemplateArgument(Input, TemplateArgs: Args, Output)) {
2997 assert(TemplateArgsForBuildingFPrime[Index].isNull() &&
2998 "InstantiatedArgs must be null before setting");
2999 TemplateArgsForBuildingFPrime[Index] = (Output.getArgument());
3000 }
3001 }
3002
3003 auto *TemplateArgListForBuildingFPrime = TemplateArgumentList::CreateCopy(
3004 Context, Args: TemplateArgsForBuildingFPrime);
3005 // Form the f' by substituting the template arguments into f.
3006 if (auto *FPrime = SemaRef.InstantiateFunctionDeclaration(
3007 F, TemplateArgListForBuildingFPrime, AliasTemplate->getLocation(),
3008 Sema::CodeSynthesisContext::BuildingDeductionGuides)) {
3009 auto *GG = cast<CXXDeductionGuideDecl>(FPrime);
3010 // Substitute new template parameters into requires-clause if present.
3011 Expr *RequiresClause =
3012 transformRequireClause(SemaRef, FTD: F, TransformedArgs: TemplateArgsForBuildingFPrime);
3013 // FIXME: implement the is_deducible constraint per C++
3014 // [over.match.class.deduct]p3.3:
3015 // ... and a constraint that is satisfied if and only if the arguments
3016 // of A are deducible (see below) from the return type.
3017 auto *FPrimeTemplateParamList = TemplateParameterList::Create(
3018 C: Context, TemplateLoc: AliasTemplate->getTemplateParameters()->getTemplateLoc(),
3019 LAngleLoc: AliasTemplate->getTemplateParameters()->getLAngleLoc(),
3020 Params: FPrimeTemplateParams,
3021 RAngleLoc: AliasTemplate->getTemplateParameters()->getRAngleLoc(),
3022 /*RequiresClause=*/RequiresClause);
3023
3024 buildDeductionGuide(SemaRef, AliasTemplate, FPrimeTemplateParamList,
3025 GG->getCorrespondingConstructor(),
3026 GG->getExplicitSpecifier(), GG->getTypeSourceInfo(),
3027 AliasTemplate->getBeginLoc(),
3028 AliasTemplate->getLocation(),
3029 AliasTemplate->getEndLoc(), F->isImplicit());
3030 }
3031 }
3032}
3033
3034// Build an aggregate deduction guide for a type alias template.
3035FunctionTemplateDecl *DeclareAggregateDeductionGuideForTypeAlias(
3036 Sema &SemaRef, TypeAliasTemplateDecl *AliasTemplate,
3037 MutableArrayRef<QualType> ParamTypes, SourceLocation Loc) {
3038 TemplateDecl *RHSTemplate =
3039 getRHSTemplateDeclAndArgs(SemaRef, AliasTemplate).first;
3040 if (!RHSTemplate)
3041 return nullptr;
3042 auto *RHSDeductionGuide = SemaRef.DeclareAggregateDeductionGuideFromInitList(
3043 Template: RHSTemplate, ParamTypes, Loc);
3044 if (!RHSDeductionGuide)
3045 return nullptr;
3046
3047 LocalInstantiationScope Scope(SemaRef);
3048 Sema::InstantiatingTemplate BuildingDeductionGuides(
3049 SemaRef, AliasTemplate->getLocation(), RHSDeductionGuide,
3050 Sema::InstantiatingTemplate::BuildingDeductionGuidesTag{});
3051 if (BuildingDeductionGuides.isInvalid())
3052 return nullptr;
3053
3054 // Build a new template parameter list for the synthesized aggregate deduction
3055 // guide by transforming the one from RHSDeductionGuide.
3056 SmallVector<NamedDecl *> TransformedTemplateParams;
3057 // Template args that refer to the rebuilt template parameters.
3058 // All template arguments must be initialized in advance.
3059 SmallVector<TemplateArgument> TransformedTemplateArgs(
3060 RHSDeductionGuide->getTemplateParameters()->size());
3061 for (auto *TP : *RHSDeductionGuide->getTemplateParameters()) {
3062 // Rebuild any internal references to earlier parameters and reindex as
3063 // we go.
3064 MultiLevelTemplateArgumentList Args;
3065 Args.setKind(TemplateSubstitutionKind::Rewrite);
3066 Args.addOuterTemplateArguments(TransformedTemplateArgs);
3067 NamedDecl *NewParam = transformTemplateParameter(
3068 SemaRef, AliasTemplate->getDeclContext(), TP, Args,
3069 /*NewIndex=*/TransformedTemplateParams.size());
3070
3071 TransformedTemplateArgs[TransformedTemplateParams.size()] =
3072 SemaRef.Context.getCanonicalTemplateArgument(
3073 SemaRef.Context.getInjectedTemplateArg(NewParam));
3074 TransformedTemplateParams.push_back(NewParam);
3075 }
3076 // FIXME: implement the is_deducible constraint per C++
3077 // [over.match.class.deduct]p3.3.
3078 Expr *TransformedRequiresClause = transformRequireClause(
3079 SemaRef, FTD: RHSDeductionGuide, TransformedArgs: TransformedTemplateArgs);
3080 auto *TransformedTemplateParameterList = TemplateParameterList::Create(
3081 C: SemaRef.Context, TemplateLoc: AliasTemplate->getTemplateParameters()->getTemplateLoc(),
3082 LAngleLoc: AliasTemplate->getTemplateParameters()->getLAngleLoc(),
3083 Params: TransformedTemplateParams,
3084 RAngleLoc: AliasTemplate->getTemplateParameters()->getRAngleLoc(),
3085 RequiresClause: TransformedRequiresClause);
3086 auto *TransformedTemplateArgList = TemplateArgumentList::CreateCopy(
3087 Context&: SemaRef.Context, Args: TransformedTemplateArgs);
3088
3089 if (auto *TransformedDeductionGuide = SemaRef.InstantiateFunctionDeclaration(
3090 RHSDeductionGuide, TransformedTemplateArgList,
3091 AliasTemplate->getLocation(),
3092 Sema::CodeSynthesisContext::BuildingDeductionGuides)) {
3093 auto *GD =
3094 llvm::dyn_cast<clang::CXXDeductionGuideDecl>(TransformedDeductionGuide);
3095 FunctionTemplateDecl *Result = buildDeductionGuide(
3096 SemaRef, AliasTemplate, TransformedTemplateParameterList,
3097 GD->getCorrespondingConstructor(), GD->getExplicitSpecifier(),
3098 GD->getTypeSourceInfo(), AliasTemplate->getBeginLoc(),
3099 AliasTemplate->getLocation(), AliasTemplate->getEndLoc(),
3100 GD->isImplicit());
3101 cast<CXXDeductionGuideDecl>(Val: Result->getTemplatedDecl())
3102 ->setDeductionCandidateKind(DeductionCandidate::Aggregate);
3103 return Result;
3104 }
3105 return nullptr;
3106}
3107
3108} // namespace
3109
3110FunctionTemplateDecl *Sema::DeclareAggregateDeductionGuideFromInitList(
3111 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
3112 SourceLocation Loc) {
3113 llvm::FoldingSetNodeID ID;
3114 ID.AddPointer(Ptr: Template);
3115 for (auto &T : ParamTypes)
3116 T.getCanonicalType().Profile(ID);
3117 unsigned Hash = ID.ComputeHash();
3118
3119 auto Found = AggregateDeductionCandidates.find(Val: Hash);
3120 if (Found != AggregateDeductionCandidates.end()) {
3121 CXXDeductionGuideDecl *GD = Found->getSecond();
3122 return GD->getDescribedFunctionTemplate();
3123 }
3124
3125 if (auto *AliasTemplate = llvm::dyn_cast<TypeAliasTemplateDecl>(Val: Template)) {
3126 if (auto *FTD = DeclareAggregateDeductionGuideForTypeAlias(
3127 SemaRef&: *this, AliasTemplate, ParamTypes, Loc)) {
3128 auto *GD = cast<CXXDeductionGuideDecl>(Val: FTD->getTemplatedDecl());
3129 GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
3130 AggregateDeductionCandidates[Hash] = GD;
3131 return FTD;
3132 }
3133 }
3134
3135 if (CXXRecordDecl *DefRecord =
3136 cast<CXXRecordDecl>(Val: Template->getTemplatedDecl())->getDefinition()) {
3137 if (TemplateDecl *DescribedTemplate =
3138 DefRecord->getDescribedClassTemplate())
3139 Template = DescribedTemplate;
3140 }
3141
3142 DeclContext *DC = Template->getDeclContext();
3143 if (DC->isDependentContext())
3144 return nullptr;
3145
3146 ConvertConstructorToDeductionGuideTransform Transform(
3147 *this, cast<ClassTemplateDecl>(Val: Template));
3148 if (!isCompleteType(Loc, T: Transform.DeducedType))
3149 return nullptr;
3150
3151 // In case we were expanding a pack when we attempted to declare deduction
3152 // guides, turn off pack expansion for everything we're about to do.
3153 ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
3154 /*NewSubstitutionIndex=*/-1);
3155 // Create a template instantiation record to track the "instantiation" of
3156 // constructors into deduction guides.
3157 InstantiatingTemplate BuildingDeductionGuides(
3158 *this, Loc, Template,
3159 Sema::InstantiatingTemplate::BuildingDeductionGuidesTag{});
3160 if (BuildingDeductionGuides.isInvalid())
3161 return nullptr;
3162
3163 ClassTemplateDecl *Pattern =
3164 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
3165 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
3166
3167 auto *FTD = cast<FunctionTemplateDecl>(
3168 Val: Transform.buildSimpleDeductionGuide(ParamTypes));
3169 SavedContext.pop();
3170 auto *GD = cast<CXXDeductionGuideDecl>(Val: FTD->getTemplatedDecl());
3171 GD->setDeductionCandidateKind(DeductionCandidate::Aggregate);
3172 AggregateDeductionCandidates[Hash] = GD;
3173 return FTD;
3174}
3175
3176void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
3177 SourceLocation Loc) {
3178 if (auto *AliasTemplate = llvm::dyn_cast<TypeAliasTemplateDecl>(Val: Template)) {
3179 DeclareImplicitDeductionGuidesForTypeAlias(SemaRef&: *this, AliasTemplate, Loc);
3180 return;
3181 }
3182 if (CXXRecordDecl *DefRecord =
3183 cast<CXXRecordDecl>(Val: Template->getTemplatedDecl())->getDefinition()) {
3184 if (TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate())
3185 Template = DescribedTemplate;
3186 }
3187
3188 DeclContext *DC = Template->getDeclContext();
3189 if (DC->isDependentContext())
3190 return;
3191
3192 ConvertConstructorToDeductionGuideTransform Transform(
3193 *this, cast<ClassTemplateDecl>(Val: Template));
3194 if (!isCompleteType(Loc, T: Transform.DeducedType))
3195 return;
3196
3197 if (hasDeclaredDeductionGuides(Name: Transform.DeductionGuideName, DC))
3198 return;
3199
3200 // In case we were expanding a pack when we attempted to declare deduction
3201 // guides, turn off pack expansion for everything we're about to do.
3202 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3203 // Create a template instantiation record to track the "instantiation" of
3204 // constructors into deduction guides.
3205 InstantiatingTemplate BuildingDeductionGuides(
3206 *this, Loc, Template,
3207 Sema::InstantiatingTemplate::BuildingDeductionGuidesTag{});
3208 if (BuildingDeductionGuides.isInvalid())
3209 return;
3210
3211 // Convert declared constructors into deduction guide templates.
3212 // FIXME: Skip constructors for which deduction must necessarily fail (those
3213 // for which some class template parameter without a default argument never
3214 // appears in a deduced context).
3215 ClassTemplateDecl *Pattern =
3216 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
3217 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
3218 llvm::SmallPtrSet<NamedDecl *, 8> ProcessedCtors;
3219 bool AddedAny = false;
3220 for (NamedDecl *D : LookupConstructors(Class: Pattern->getTemplatedDecl())) {
3221 D = D->getUnderlyingDecl();
3222 if (D->isInvalidDecl() || D->isImplicit())
3223 continue;
3224
3225 D = cast<NamedDecl>(D->getCanonicalDecl());
3226
3227 // Within C++20 modules, we may have multiple same constructors in
3228 // multiple same RecordDecls. And it doesn't make sense to create
3229 // duplicated deduction guides for the duplicated constructors.
3230 if (ProcessedCtors.count(Ptr: D))
3231 continue;
3232
3233 auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: D);
3234 auto *CD =
3235 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
3236 // Class-scope explicit specializations (MS extension) do not result in
3237 // deduction guides.
3238 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
3239 continue;
3240
3241 // Cannot make a deduction guide when unparsed arguments are present.
3242 if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) {
3243 return !P || P->hasUnparsedDefaultArg();
3244 }))
3245 continue;
3246
3247 ProcessedCtors.insert(Ptr: D);
3248 Transform.transformConstructor(FTD, CD: CD);
3249 AddedAny = true;
3250 }
3251
3252 // C++17 [over.match.class.deduct]
3253 // -- If C is not defined or does not declare any constructors, an
3254 // additional function template derived as above from a hypothetical
3255 // constructor C().
3256 if (!AddedAny)
3257 Transform.buildSimpleDeductionGuide(ParamTypes: std::nullopt);
3258
3259 // -- An additional function template derived as above from a hypothetical
3260 // constructor C(C), called the copy deduction candidate.
3261 cast<CXXDeductionGuideDecl>(
3262 cast<FunctionTemplateDecl>(
3263 Transform.buildSimpleDeductionGuide(ParamTypes: Transform.DeducedType))
3264 ->getTemplatedDecl())
3265 ->setDeductionCandidateKind(DeductionCandidate::Copy);
3266
3267 SavedContext.pop();
3268}
3269
3270/// Diagnose the presence of a default template argument on a
3271/// template parameter, which is ill-formed in certain contexts.
3272///
3273/// \returns true if the default template argument should be dropped.
3274static bool DiagnoseDefaultTemplateArgument(Sema &S,
3275 Sema::TemplateParamListContext TPC,
3276 SourceLocation ParamLoc,
3277 SourceRange DefArgRange) {
3278 switch (TPC) {
3279 case Sema::TPC_ClassTemplate:
3280 case Sema::TPC_VarTemplate:
3281 case Sema::TPC_TypeAliasTemplate:
3282 return false;
3283
3284 case Sema::TPC_FunctionTemplate:
3285 case Sema::TPC_FriendFunctionTemplateDefinition:
3286 // C++ [temp.param]p9:
3287 // A default template-argument shall not be specified in a
3288 // function template declaration or a function template
3289 // definition [...]
3290 // If a friend function template declaration specifies a default
3291 // template-argument, that declaration shall be a definition and shall be
3292 // the only declaration of the function template in the translation unit.
3293 // (C++98/03 doesn't have this wording; see DR226).
3294 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
3295 diag::warn_cxx98_compat_template_parameter_default_in_function_template
3296 : diag::ext_template_parameter_default_in_function_template)
3297 << DefArgRange;
3298 return false;
3299
3300 case Sema::TPC_ClassTemplateMember:
3301 // C++0x [temp.param]p9:
3302 // A default template-argument shall not be specified in the
3303 // template-parameter-lists of the definition of a member of a
3304 // class template that appears outside of the member's class.
3305 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
3306 << DefArgRange;
3307 return true;
3308
3309 case Sema::TPC_FriendClassTemplate:
3310 case Sema::TPC_FriendFunctionTemplate:
3311 // C++ [temp.param]p9:
3312 // A default template-argument shall not be specified in a
3313 // friend template declaration.
3314 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
3315 << DefArgRange;
3316 return true;
3317
3318 // FIXME: C++0x [temp.param]p9 allows default template-arguments
3319 // for friend function templates if there is only a single
3320 // declaration (and it is a definition). Strange!
3321 }
3322
3323 llvm_unreachable("Invalid TemplateParamListContext!");
3324}
3325
3326/// Check for unexpanded parameter packs within the template parameters
3327/// of a template template parameter, recursively.
3328static bool DiagnoseUnexpandedParameterPacks(Sema &S,
3329 TemplateTemplateParmDecl *TTP) {
3330 // A template template parameter which is a parameter pack is also a pack
3331 // expansion.
3332 if (TTP->isParameterPack())
3333 return false;
3334
3335 TemplateParameterList *Params = TTP->getTemplateParameters();
3336 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
3337 NamedDecl *P = Params->getParam(Idx: I);
3338 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: P)) {
3339 if (!TTP->isParameterPack())
3340 if (const TypeConstraint *TC = TTP->getTypeConstraint())
3341 if (TC->hasExplicitTemplateArgs())
3342 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
3343 if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
3344 Sema::UPPC_TypeConstraint))
3345 return true;
3346 continue;
3347 }
3348
3349 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: P)) {
3350 if (!NTTP->isParameterPack() &&
3351 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
3352 NTTP->getTypeSourceInfo(),
3353 Sema::UPPC_NonTypeTemplateParameterType))
3354 return true;
3355
3356 continue;
3357 }
3358
3359 if (TemplateTemplateParmDecl *InnerTTP
3360 = dyn_cast<TemplateTemplateParmDecl>(Val: P))
3361 if (DiagnoseUnexpandedParameterPacks(S, TTP: InnerTTP))
3362 return true;
3363 }
3364
3365 return false;
3366}
3367
3368/// Checks the validity of a template parameter list, possibly
3369/// considering the template parameter list from a previous
3370/// declaration.
3371///
3372/// If an "old" template parameter list is provided, it must be
3373/// equivalent (per TemplateParameterListsAreEqual) to the "new"
3374/// template parameter list.
3375///
3376/// \param NewParams Template parameter list for a new template
3377/// declaration. This template parameter list will be updated with any
3378/// default arguments that are carried through from the previous
3379/// template parameter list.
3380///
3381/// \param OldParams If provided, template parameter list from a
3382/// previous declaration of the same template. Default template
3383/// arguments will be merged from the old template parameter list to
3384/// the new template parameter list.
3385///
3386/// \param TPC Describes the context in which we are checking the given
3387/// template parameter list.
3388///
3389/// \param SkipBody If we might have already made a prior merged definition
3390/// of this template visible, the corresponding body-skipping information.
3391/// Default argument redefinition is not an error when skipping such a body,
3392/// because (under the ODR) we can assume the default arguments are the same
3393/// as the prior merged definition.
3394///
3395/// \returns true if an error occurred, false otherwise.
3396bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
3397 TemplateParameterList *OldParams,
3398 TemplateParamListContext TPC,
3399 SkipBodyInfo *SkipBody) {
3400 bool Invalid = false;
3401
3402 // C++ [temp.param]p10:
3403 // The set of default template-arguments available for use with a
3404 // template declaration or definition is obtained by merging the
3405 // default arguments from the definition (if in scope) and all
3406 // declarations in scope in the same way default function
3407 // arguments are (8.3.6).
3408 bool SawDefaultArgument = false;
3409 SourceLocation PreviousDefaultArgLoc;
3410
3411 // Dummy initialization to avoid warnings.
3412 TemplateParameterList::iterator OldParam = NewParams->end();
3413 if (OldParams)
3414 OldParam = OldParams->begin();
3415
3416 bool RemoveDefaultArguments = false;
3417 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
3418 NewParamEnd = NewParams->end();
3419 NewParam != NewParamEnd; ++NewParam) {
3420 // Whether we've seen a duplicate default argument in the same translation
3421 // unit.
3422 bool RedundantDefaultArg = false;
3423 // Whether we've found inconsis inconsitent default arguments in different
3424 // translation unit.
3425 bool InconsistentDefaultArg = false;
3426 // The name of the module which contains the inconsistent default argument.
3427 std::string PrevModuleName;
3428
3429 SourceLocation OldDefaultLoc;
3430 SourceLocation NewDefaultLoc;
3431
3432 // Variable used to diagnose missing default arguments
3433 bool MissingDefaultArg = false;
3434
3435 // Variable used to diagnose non-final parameter packs
3436 bool SawParameterPack = false;
3437
3438 if (TemplateTypeParmDecl *NewTypeParm
3439 = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam)) {
3440 // Check the presence of a default argument here.
3441 if (NewTypeParm->hasDefaultArgument() &&
3442 DiagnoseDefaultTemplateArgument(*this, TPC,
3443 NewTypeParm->getLocation(),
3444 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
3445 .getSourceRange()))
3446 NewTypeParm->removeDefaultArgument();
3447
3448 // Merge default arguments for template type parameters.
3449 TemplateTypeParmDecl *OldTypeParm
3450 = OldParams? cast<TemplateTypeParmDecl>(Val: *OldParam) : nullptr;
3451 if (NewTypeParm->isParameterPack()) {
3452 assert(!NewTypeParm->hasDefaultArgument() &&
3453 "Parameter packs can't have a default argument!");
3454 SawParameterPack = true;
3455 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
3456 NewTypeParm->hasDefaultArgument() &&
3457 (!SkipBody || !SkipBody->ShouldSkip)) {
3458 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
3459 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
3460 SawDefaultArgument = true;
3461
3462 if (!OldTypeParm->getOwningModule())
3463 RedundantDefaultArg = true;
3464 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
3465 NewTypeParm)) {
3466 InconsistentDefaultArg = true;
3467 PrevModuleName =
3468 OldTypeParm->getImportedOwningModule()->getFullModuleName();
3469 }
3470 PreviousDefaultArgLoc = NewDefaultLoc;
3471 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
3472 // Merge the default argument from the old declaration to the
3473 // new declaration.
3474 NewTypeParm->setInheritedDefaultArgument(C: Context, Prev: OldTypeParm);
3475 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
3476 } else if (NewTypeParm->hasDefaultArgument()) {
3477 SawDefaultArgument = true;
3478 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
3479 } else if (SawDefaultArgument)
3480 MissingDefaultArg = true;
3481 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
3482 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam)) {
3483 // Check for unexpanded parameter packs.
3484 if (!NewNonTypeParm->isParameterPack() &&
3485 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
3486 NewNonTypeParm->getTypeSourceInfo(),
3487 UPPC_NonTypeTemplateParameterType)) {
3488 Invalid = true;
3489 continue;
3490 }
3491
3492 // Check the presence of a default argument here.
3493 if (NewNonTypeParm->hasDefaultArgument() &&
3494 DiagnoseDefaultTemplateArgument(*this, TPC,
3495 NewNonTypeParm->getLocation(),
3496 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
3497 NewNonTypeParm->removeDefaultArgument();
3498 }
3499
3500 // Merge default arguments for non-type template parameters
3501 NonTypeTemplateParmDecl *OldNonTypeParm
3502 = OldParams? cast<NonTypeTemplateParmDecl>(Val: *OldParam) : nullptr;
3503 if (NewNonTypeParm->isParameterPack()) {
3504 assert(!NewNonTypeParm->hasDefaultArgument() &&
3505 "Parameter packs can't have a default argument!");
3506 if (!NewNonTypeParm->isPackExpansion())
3507 SawParameterPack = true;
3508 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
3509 NewNonTypeParm->hasDefaultArgument() &&
3510 (!SkipBody || !SkipBody->ShouldSkip)) {
3511 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
3512 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
3513 SawDefaultArgument = true;
3514 if (!OldNonTypeParm->getOwningModule())
3515 RedundantDefaultArg = true;
3516 else if (!getASTContext().isSameDefaultTemplateArgument(
3517 OldNonTypeParm, NewNonTypeParm)) {
3518 InconsistentDefaultArg = true;
3519 PrevModuleName =
3520 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
3521 }
3522 PreviousDefaultArgLoc = NewDefaultLoc;
3523 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
3524 // Merge the default argument from the old declaration to the
3525 // new declaration.
3526 NewNonTypeParm->setInheritedDefaultArgument(C: Context, Parm: OldNonTypeParm);
3527 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
3528 } else if (NewNonTypeParm->hasDefaultArgument()) {
3529 SawDefaultArgument = true;
3530 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
3531 } else if (SawDefaultArgument)
3532 MissingDefaultArg = true;
3533 } else {
3534 TemplateTemplateParmDecl *NewTemplateParm
3535 = cast<TemplateTemplateParmDecl>(Val: *NewParam);
3536
3537 // Check for unexpanded parameter packs, recursively.
3538 if (::DiagnoseUnexpandedParameterPacks(S&: *this, TTP: NewTemplateParm)) {
3539 Invalid = true;
3540 continue;
3541 }
3542
3543 // Check the presence of a default argument here.
3544 if (NewTemplateParm->hasDefaultArgument() &&
3545 DiagnoseDefaultTemplateArgument(*this, TPC,
3546 NewTemplateParm->getLocation(),
3547 NewTemplateParm->getDefaultArgument().getSourceRange()))
3548 NewTemplateParm->removeDefaultArgument();
3549
3550 // Merge default arguments for template template parameters
3551 TemplateTemplateParmDecl *OldTemplateParm
3552 = OldParams? cast<TemplateTemplateParmDecl>(Val: *OldParam) : nullptr;
3553 if (NewTemplateParm->isParameterPack()) {
3554 assert(!NewTemplateParm->hasDefaultArgument() &&
3555 "Parameter packs can't have a default argument!");
3556 if (!NewTemplateParm->isPackExpansion())
3557 SawParameterPack = true;
3558 } else if (OldTemplateParm &&
3559 hasVisibleDefaultArgument(OldTemplateParm) &&
3560 NewTemplateParm->hasDefaultArgument() &&
3561 (!SkipBody || !SkipBody->ShouldSkip)) {
3562 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
3563 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
3564 SawDefaultArgument = true;
3565 if (!OldTemplateParm->getOwningModule())
3566 RedundantDefaultArg = true;
3567 else if (!getASTContext().isSameDefaultTemplateArgument(
3568 OldTemplateParm, NewTemplateParm)) {
3569 InconsistentDefaultArg = true;
3570 PrevModuleName =
3571 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
3572 }
3573 PreviousDefaultArgLoc = NewDefaultLoc;
3574 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
3575 // Merge the default argument from the old declaration to the
3576 // new declaration.
3577 NewTemplateParm->setInheritedDefaultArgument(C: Context, Prev: OldTemplateParm);
3578 PreviousDefaultArgLoc
3579 = OldTemplateParm->getDefaultArgument().getLocation();
3580 } else if (NewTemplateParm->hasDefaultArgument()) {
3581 SawDefaultArgument = true;
3582 PreviousDefaultArgLoc
3583 = NewTemplateParm->getDefaultArgument().getLocation();
3584 } else if (SawDefaultArgument)
3585 MissingDefaultArg = true;
3586 }
3587
3588 // C++11 [temp.param]p11:
3589 // If a template parameter of a primary class template or alias template
3590 // is a template parameter pack, it shall be the last template parameter.
3591 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
3592 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
3593 TPC == TPC_TypeAliasTemplate)) {
3594 Diag((*NewParam)->getLocation(),
3595 diag::err_template_param_pack_must_be_last_template_parameter);
3596 Invalid = true;
3597 }
3598
3599 // [basic.def.odr]/13:
3600 // There can be more than one definition of a
3601 // ...
3602 // default template argument
3603 // ...
3604 // in a program provided that each definition appears in a different
3605 // translation unit and the definitions satisfy the [same-meaning
3606 // criteria of the ODR].
3607 //
3608 // Simply, the design of modules allows the definition of template default
3609 // argument to be repeated across translation unit. Note that the ODR is
3610 // checked elsewhere. But it is still not allowed to repeat template default
3611 // argument in the same translation unit.
3612 if (RedundantDefaultArg) {
3613 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
3614 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
3615 Invalid = true;
3616 } else if (InconsistentDefaultArg) {
3617 // We could only diagnose about the case that the OldParam is imported.
3618 // The case NewParam is imported should be handled in ASTReader.
3619 Diag(NewDefaultLoc,
3620 diag::err_template_param_default_arg_inconsistent_redefinition);
3621 Diag(OldDefaultLoc,
3622 diag::note_template_param_prev_default_arg_in_other_module)
3623 << PrevModuleName;
3624 Invalid = true;
3625 } else if (MissingDefaultArg &&
3626 (TPC == TPC_ClassTemplate || TPC == TPC_FriendClassTemplate ||
3627 TPC == TPC_VarTemplate || TPC == TPC_TypeAliasTemplate)) {
3628 // C++ 23[temp.param]p14:
3629 // If a template-parameter of a class template, variable template, or
3630 // alias template has a default template argument, each subsequent
3631 // template-parameter shall either have a default template argument
3632 // supplied or be a template parameter pack.
3633 Diag((*NewParam)->getLocation(),
3634 diag::err_template_param_default_arg_missing);
3635 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
3636 Invalid = true;
3637 RemoveDefaultArguments = true;
3638 }
3639
3640 // If we have an old template parameter list that we're merging
3641 // in, move on to the next parameter.
3642 if (OldParams)
3643 ++OldParam;
3644 }
3645
3646 // We were missing some default arguments at the end of the list, so remove
3647 // all of the default arguments.
3648 if (RemoveDefaultArguments) {
3649 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
3650 NewParamEnd = NewParams->end();
3651 NewParam != NewParamEnd; ++NewParam) {
3652 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *NewParam))
3653 TTP->removeDefaultArgument();
3654 else if (NonTypeTemplateParmDecl *NTTP
3655 = dyn_cast<NonTypeTemplateParmDecl>(Val: *NewParam))
3656 NTTP->removeDefaultArgument();
3657 else
3658 cast<TemplateTemplateParmDecl>(Val: *NewParam)->removeDefaultArgument();
3659 }
3660 }
3661
3662 return Invalid;
3663}
3664
3665namespace {
3666
3667/// A class which looks for a use of a certain level of template
3668/// parameter.
3669struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
3670 typedef RecursiveASTVisitor<DependencyChecker> super;
3671
3672 unsigned Depth;
3673
3674 // Whether we're looking for a use of a template parameter that makes the
3675 // overall construct type-dependent / a dependent type. This is strictly
3676 // best-effort for now; we may fail to match at all for a dependent type
3677 // in some cases if this is set.
3678 bool IgnoreNonTypeDependent;
3679
3680 bool Match;
3681 SourceLocation MatchLoc;
3682
3683 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
3684 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
3685 Match(false) {}
3686
3687 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
3688 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
3689 NamedDecl *ND = Params->getParam(Idx: 0);
3690 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(Val: ND)) {
3691 Depth = PD->getDepth();
3692 } else if (NonTypeTemplateParmDecl *PD =
3693 dyn_cast<NonTypeTemplateParmDecl>(Val: ND)) {
3694 Depth = PD->getDepth();
3695 } else {
3696 Depth = cast<TemplateTemplateParmDecl>(Val: ND)->getDepth();
3697 }
3698 }
3699
3700 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
3701 if (ParmDepth >= Depth) {
3702 Match = true;
3703 MatchLoc = Loc;
3704 return true;
3705 }
3706 return false;
3707 }
3708
3709 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
3710 // Prune out non-type-dependent expressions if requested. This can
3711 // sometimes result in us failing to find a template parameter reference
3712 // (if a value-dependent expression creates a dependent type), but this
3713 // mode is best-effort only.
3714 if (auto *E = dyn_cast_or_null<Expr>(Val: S))
3715 if (IgnoreNonTypeDependent && !E->isTypeDependent())
3716 return true;
3717 return super::TraverseStmt(S, Queue: Q);
3718 }
3719
3720 bool TraverseTypeLoc(TypeLoc TL) {
3721 if (IgnoreNonTypeDependent && !TL.isNull() &&
3722 !TL.getType()->isDependentType())
3723 return true;
3724 return super::TraverseTypeLoc(TL);
3725 }
3726
3727 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
3728 return !Matches(ParmDepth: TL.getTypePtr()->getDepth(), Loc: TL.getNameLoc());
3729 }
3730
3731 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
3732 // For a best-effort search, keep looking until we find a location.
3733 return IgnoreNonTypeDependent || !Matches(ParmDepth: T->getDepth());
3734 }
3735
3736 bool TraverseTemplateName(TemplateName N) {
3737 if (TemplateTemplateParmDecl *PD =
3738 dyn_cast_or_null<TemplateTemplateParmDecl>(Val: N.getAsTemplateDecl()))
3739 if (Matches(ParmDepth: PD->getDepth()))
3740 return false;
3741 return super::TraverseTemplateName(Template: N);
3742 }
3743
3744 bool VisitDeclRefExpr(DeclRefExpr *E) {
3745 if (NonTypeTemplateParmDecl *PD =
3746 dyn_cast<NonTypeTemplateParmDecl>(Val: E->getDecl()))
3747 if (Matches(ParmDepth: PD->getDepth(), Loc: E->getExprLoc()))
3748 return false;
3749 return super::VisitDeclRefExpr(E);
3750 }
3751
3752 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
3753 return TraverseType(T: T->getReplacementType());
3754 }
3755
3756 bool
3757 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
3758 return TraverseTemplateArgument(Arg: T->getArgumentPack());
3759 }
3760
3761 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
3762 return TraverseType(T: T->getInjectedSpecializationType());
3763 }
3764};
3765} // end anonymous namespace
3766
3767/// Determines whether a given type depends on the given parameter
3768/// list.
3769static bool
3770DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
3771 if (!Params->size())
3772 return false;
3773
3774 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
3775 Checker.TraverseType(T);
3776 return Checker.Match;
3777}
3778
3779// Find the source range corresponding to the named type in the given
3780// nested-name-specifier, if any.
3781static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
3782 QualType T,
3783 const CXXScopeSpec &SS) {
3784 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
3785 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
3786 if (const Type *CurType = NNS->getAsType()) {
3787 if (Context.hasSameUnqualifiedType(T1: T, T2: QualType(CurType, 0)))
3788 return NNSLoc.getTypeLoc().getSourceRange();
3789 } else
3790 break;
3791
3792 NNSLoc = NNSLoc.getPrefix();
3793 }
3794
3795 return SourceRange();
3796}
3797
3798/// Match the given template parameter lists to the given scope
3799/// specifier, returning the template parameter list that applies to the
3800/// name.
3801///
3802/// \param DeclStartLoc the start of the declaration that has a scope
3803/// specifier or a template parameter list.
3804///
3805/// \param DeclLoc The location of the declaration itself.
3806///
3807/// \param SS the scope specifier that will be matched to the given template
3808/// parameter lists. This scope specifier precedes a qualified name that is
3809/// being declared.
3810///
3811/// \param TemplateId The template-id following the scope specifier, if there
3812/// is one. Used to check for a missing 'template<>'.
3813///
3814/// \param ParamLists the template parameter lists, from the outermost to the
3815/// innermost template parameter lists.
3816///
3817/// \param IsFriend Whether to apply the slightly different rules for
3818/// matching template parameters to scope specifiers in friend
3819/// declarations.
3820///
3821/// \param IsMemberSpecialization will be set true if the scope specifier
3822/// denotes a fully-specialized type, and therefore this is a declaration of
3823/// a member specialization.
3824///
3825/// \returns the template parameter list, if any, that corresponds to the
3826/// name that is preceded by the scope specifier @p SS. This template
3827/// parameter list may have template parameters (if we're declaring a
3828/// template) or may have no template parameters (if we're declaring a
3829/// template specialization), or may be NULL (if what we're declaring isn't
3830/// itself a template).
3831TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
3832 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
3833 TemplateIdAnnotation *TemplateId,
3834 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
3835 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
3836 IsMemberSpecialization = false;
3837 Invalid = false;
3838
3839 // The sequence of nested types to which we will match up the template
3840 // parameter lists. We first build this list by starting with the type named
3841 // by the nested-name-specifier and walking out until we run out of types.
3842 SmallVector<QualType, 4> NestedTypes;
3843 QualType T;
3844 if (SS.getScopeRep()) {
3845 if (CXXRecordDecl *Record
3846 = dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: true)))
3847 T = Context.getTypeDeclType(Record);
3848 else
3849 T = QualType(SS.getScopeRep()->getAsType(), 0);
3850 }
3851
3852 // If we found an explicit specialization that prevents us from needing
3853 // 'template<>' headers, this will be set to the location of that
3854 // explicit specialization.
3855 SourceLocation ExplicitSpecLoc;
3856
3857 while (!T.isNull()) {
3858 NestedTypes.push_back(Elt: T);
3859
3860 // Retrieve the parent of a record type.
3861 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3862 // If this type is an explicit specialization, we're done.
3863 if (ClassTemplateSpecializationDecl *Spec
3864 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
3865 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Spec) &&
3866 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
3867 ExplicitSpecLoc = Spec->getLocation();
3868 break;
3869 }
3870 } else if (Record->getTemplateSpecializationKind()
3871 == TSK_ExplicitSpecialization) {
3872 ExplicitSpecLoc = Record->getLocation();
3873 break;
3874 }
3875
3876 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
3877 T = Context.getTypeDeclType(Decl: Parent);
3878 else
3879 T = QualType();
3880 continue;
3881 }
3882
3883 if (const TemplateSpecializationType *TST
3884 = T->getAs<TemplateSpecializationType>()) {
3885 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3886 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
3887 T = Context.getTypeDeclType(Decl: Parent);
3888 else
3889 T = QualType();
3890 continue;
3891 }
3892 }
3893
3894 // Look one step prior in a dependent template specialization type.
3895 if (const DependentTemplateSpecializationType *DependentTST
3896 = T->getAs<DependentTemplateSpecializationType>()) {
3897 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
3898 T = QualType(NNS->getAsType(), 0);
3899 else
3900 T = QualType();
3901 continue;
3902 }
3903
3904 // Look one step prior in a dependent name type.
3905 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
3906 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
3907 T = QualType(NNS->getAsType(), 0);
3908 else
3909 T = QualType();
3910 continue;
3911 }
3912
3913 // Retrieve the parent of an enumeration type.
3914 if (const EnumType *EnumT = T->getAs<EnumType>()) {
3915 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
3916 // check here.
3917 EnumDecl *Enum = EnumT->getDecl();
3918
3919 // Get to the parent type.
3920 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
3921 T = Context.getTypeDeclType(Decl: Parent);
3922 else
3923 T = QualType();
3924 continue;
3925 }
3926
3927 T = QualType();
3928 }
3929 // Reverse the nested types list, since we want to traverse from the outermost
3930 // to the innermost while checking template-parameter-lists.
3931 std::reverse(first: NestedTypes.begin(), last: NestedTypes.end());
3932
3933 // C++0x [temp.expl.spec]p17:
3934 // A member or a member template may be nested within many
3935 // enclosing class templates. In an explicit specialization for
3936 // such a member, the member declaration shall be preceded by a
3937 // template<> for each enclosing class template that is
3938 // explicitly specialized.
3939 bool SawNonEmptyTemplateParameterList = false;
3940
3941 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
3942 if (SawNonEmptyTemplateParameterList) {
3943 if (!SuppressDiagnostic)
3944 Diag(DeclLoc, diag::err_specialize_member_of_template)
3945 << !Recovery << Range;
3946 Invalid = true;
3947 IsMemberSpecialization = false;
3948 return true;
3949 }
3950
3951 return false;
3952 };
3953
3954 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
3955 // Check that we can have an explicit specialization here.
3956 if (CheckExplicitSpecialization(Range, true))
3957 return true;
3958
3959 // We don't have a template header, but we should.
3960 SourceLocation ExpectedTemplateLoc;
3961 if (!ParamLists.empty())
3962 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
3963 else
3964 ExpectedTemplateLoc = DeclStartLoc;
3965
3966 if (!SuppressDiagnostic)
3967 Diag(DeclLoc, diag::err_template_spec_needs_header)
3968 << Range
3969 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
3970 return false;
3971 };
3972
3973 unsigned ParamIdx = 0;
3974 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
3975 ++TypeIdx) {
3976 T = NestedTypes[TypeIdx];
3977
3978 // Whether we expect a 'template<>' header.
3979 bool NeedEmptyTemplateHeader = false;
3980
3981 // Whether we expect a template header with parameters.
3982 bool NeedNonemptyTemplateHeader = false;
3983
3984 // For a dependent type, the set of template parameters that we
3985 // expect to see.
3986 TemplateParameterList *ExpectedTemplateParams = nullptr;
3987
3988 // C++0x [temp.expl.spec]p15:
3989 // A member or a member template may be nested within many enclosing
3990 // class templates. In an explicit specialization for such a member, the
3991 // member declaration shall be preceded by a template<> for each
3992 // enclosing class template that is explicitly specialized.
3993 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3994 if (ClassTemplatePartialSpecializationDecl *Partial
3995 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Record)) {
3996 ExpectedTemplateParams = Partial->getTemplateParameters();
3997 NeedNonemptyTemplateHeader = true;
3998 } else if (Record->isDependentType()) {
3999 if (Record->getDescribedClassTemplate()) {
4000 ExpectedTemplateParams = Record->getDescribedClassTemplate()
4001 ->getTemplateParameters();
4002 NeedNonemptyTemplateHeader = true;
4003 }
4004 } else if (ClassTemplateSpecializationDecl *Spec
4005 = dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) {
4006 // C++0x [temp.expl.spec]p4:
4007 // Members of an explicitly specialized class template are defined
4008 // in the same manner as members of normal classes, and not using
4009 // the template<> syntax.
4010 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
4011 NeedEmptyTemplateHeader = true;
4012 else
4013 continue;
4014 } else if (Record->getTemplateSpecializationKind()) {
4015 if (Record->getTemplateSpecializationKind()
4016 != TSK_ExplicitSpecialization &&
4017 TypeIdx == NumTypes - 1)
4018 IsMemberSpecialization = true;
4019
4020 continue;
4021 }
4022 } else if (const TemplateSpecializationType *TST
4023 = T->getAs<TemplateSpecializationType>()) {
4024 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
4025 ExpectedTemplateParams = Template->getTemplateParameters();
4026 NeedNonemptyTemplateHeader = true;
4027 }
4028 } else if (T->getAs<DependentTemplateSpecializationType>()) {
4029 // FIXME: We actually could/should check the template arguments here
4030 // against the corresponding template parameter list.
4031 NeedNonemptyTemplateHeader = false;
4032 }
4033
4034 // C++ [temp.expl.spec]p16:
4035 // In an explicit specialization declaration for a member of a class
4036 // template or a member template that ap- pears in namespace scope, the
4037 // member template and some of its enclosing class templates may remain
4038 // unspecialized, except that the declaration shall not explicitly
4039 // specialize a class member template if its en- closing class templates
4040 // are not explicitly specialized as well.
4041 if (ParamIdx < ParamLists.size()) {
4042 if (ParamLists[ParamIdx]->size() == 0) {
4043 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
4044 false))
4045 return nullptr;
4046 } else
4047 SawNonEmptyTemplateParameterList = true;
4048 }
4049
4050 if (NeedEmptyTemplateHeader) {
4051 // If we're on the last of the types, and we need a 'template<>' header
4052 // here, then it's a member specialization.
4053 if (TypeIdx == NumTypes - 1)
4054 IsMemberSpecialization = true;
4055
4056 if (ParamIdx < ParamLists.size()) {
4057 if (ParamLists[ParamIdx]->size() > 0) {
4058 // The header has template parameters when it shouldn't. Complain.
4059 if (!SuppressDiagnostic)
4060 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
4061 diag::err_template_param_list_matches_nontemplate)
4062 << T
4063 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
4064 ParamLists[ParamIdx]->getRAngleLoc())
4065 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
4066 Invalid = true;
4067 return nullptr;
4068 }
4069
4070 // Consume this template header.
4071 ++ParamIdx;
4072 continue;
4073 }
4074
4075 if (!IsFriend)
4076 if (DiagnoseMissingExplicitSpecialization(
4077 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
4078 return nullptr;
4079
4080 continue;
4081 }
4082
4083 if (NeedNonemptyTemplateHeader) {
4084 // In friend declarations we can have template-ids which don't
4085 // depend on the corresponding template parameter lists. But
4086 // assume that empty parameter lists are supposed to match this
4087 // template-id.
4088 if (IsFriend && T->isDependentType()) {
4089 if (ParamIdx < ParamLists.size() &&
4090 DependsOnTemplateParameters(T, Params: ParamLists[ParamIdx]))
4091 ExpectedTemplateParams = nullptr;
4092 else
4093 continue;
4094 }
4095
4096 if (ParamIdx < ParamLists.size()) {
4097 // Check the template parameter list, if we can.
4098 if (ExpectedTemplateParams &&
4099 !TemplateParameterListsAreEqual(New: ParamLists[ParamIdx],
4100 Old: ExpectedTemplateParams,
4101 Complain: !SuppressDiagnostic, Kind: TPL_TemplateMatch))
4102 Invalid = true;
4103
4104 if (!Invalid &&
4105 CheckTemplateParameterList(NewParams: ParamLists[ParamIdx], OldParams: nullptr,
4106 TPC: TPC_ClassTemplateMember))
4107 Invalid = true;
4108
4109 ++ParamIdx;
4110 continue;
4111 }
4112
4113 if (!SuppressDiagnostic)
4114 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
4115 << T
4116 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
4117 Invalid = true;
4118 continue;
4119 }
4120 }
4121
4122 // If there were at least as many template-ids as there were template
4123 // parameter lists, then there are no template parameter lists remaining for
4124 // the declaration itself.
4125 if (ParamIdx >= ParamLists.size()) {
4126 if (TemplateId && !IsFriend) {
4127 // We don't have a template header for the declaration itself, but we
4128 // should.
4129 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
4130 TemplateId->RAngleLoc));
4131
4132 // Fabricate an empty template parameter list for the invented header.
4133 return TemplateParameterList::Create(C: Context, TemplateLoc: SourceLocation(),
4134 LAngleLoc: SourceLocation(), Params: std::nullopt,
4135 RAngleLoc: SourceLocation(), RequiresClause: nullptr);
4136 }
4137
4138 return nullptr;
4139 }
4140
4141 // If there were too many template parameter lists, complain about that now.
4142 if (ParamIdx < ParamLists.size() - 1) {
4143 bool HasAnyExplicitSpecHeader = false;
4144 bool AllExplicitSpecHeaders = true;
4145 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
4146 if (ParamLists[I]->size() == 0)
4147 HasAnyExplicitSpecHeader = true;
4148 else
4149 AllExplicitSpecHeaders = false;
4150 }
4151
4152 if (!SuppressDiagnostic)
4153 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
4154 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
4155 : diag::err_template_spec_extra_headers)
4156 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
4157 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
4158
4159 // If there was a specialization somewhere, such that 'template<>' is
4160 // not required, and there were any 'template<>' headers, note where the
4161 // specialization occurred.
4162 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
4163 !SuppressDiagnostic)
4164 Diag(ExplicitSpecLoc,
4165 diag::note_explicit_template_spec_does_not_need_header)
4166 << NestedTypes.back();
4167
4168 // We have a template parameter list with no corresponding scope, which
4169 // means that the resulting template declaration can't be instantiated
4170 // properly (we'll end up with dependent nodes when we shouldn't).
4171 if (!AllExplicitSpecHeaders)
4172 Invalid = true;
4173 }
4174
4175 // C++ [temp.expl.spec]p16:
4176 // In an explicit specialization declaration for a member of a class
4177 // template or a member template that ap- pears in namespace scope, the
4178 // member template and some of its enclosing class templates may remain
4179 // unspecialized, except that the declaration shall not explicitly
4180 // specialize a class member template if its en- closing class templates
4181 // are not explicitly specialized as well.
4182 if (ParamLists.back()->size() == 0 &&
4183 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
4184 false))
4185 return nullptr;
4186
4187 // Return the last template parameter list, which corresponds to the
4188 // entity being declared.
4189 return ParamLists.back();
4190}
4191
4192void Sema::NoteAllFoundTemplates(TemplateName Name) {
4193 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4194 Diag(Template->getLocation(), diag::note_template_declared_here)
4195 << (isa<FunctionTemplateDecl>(Template)
4196 ? 0
4197 : isa<ClassTemplateDecl>(Template)
4198 ? 1
4199 : isa<VarTemplateDecl>(Template)
4200 ? 2
4201 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
4202 << Template->getDeclName();
4203 return;
4204 }
4205
4206 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
4207 for (OverloadedTemplateStorage::iterator I = OST->begin(),
4208 IEnd = OST->end();
4209 I != IEnd; ++I)
4210 Diag((*I)->getLocation(), diag::note_template_declared_here)
4211 << 0 << (*I)->getDeclName();
4212
4213 return;
4214 }
4215}
4216
4217static QualType
4218checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
4219 ArrayRef<TemplateArgument> Converted,
4220 SourceLocation TemplateLoc,
4221 TemplateArgumentListInfo &TemplateArgs) {
4222 ASTContext &Context = SemaRef.getASTContext();
4223
4224 switch (BTD->getBuiltinTemplateKind()) {
4225 case BTK__make_integer_seq: {
4226 // Specializations of __make_integer_seq<S, T, N> are treated like
4227 // S<T, 0, ..., N-1>.
4228
4229 QualType OrigType = Converted[1].getAsType();
4230 // C++14 [inteseq.intseq]p1:
4231 // T shall be an integer type.
4232 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Ctx: Context)) {
4233 SemaRef.Diag(TemplateArgs[1].getLocation(),
4234 diag::err_integer_sequence_integral_element_type);
4235 return QualType();
4236 }
4237
4238 TemplateArgument NumArgsArg = Converted[2];
4239 if (NumArgsArg.isDependent())
4240 return Context.getCanonicalTemplateSpecializationType(T: TemplateName(BTD),
4241 Args: Converted);
4242
4243 TemplateArgumentListInfo SyntheticTemplateArgs;
4244 // The type argument, wrapped in substitution sugar, gets reused as the
4245 // first template argument in the synthetic template argument list.
4246 SyntheticTemplateArgs.addArgument(
4247 Loc: TemplateArgumentLoc(TemplateArgument(OrigType),
4248 SemaRef.Context.getTrivialTypeSourceInfo(
4249 T: OrigType, Loc: TemplateArgs[1].getLocation())));
4250
4251 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
4252 // Expand N into 0 ... N-1.
4253 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
4254 I < NumArgs; ++I) {
4255 TemplateArgument TA(Context, I, OrigType);
4256 SyntheticTemplateArgs.addArgument(Loc: SemaRef.getTrivialTemplateArgumentLoc(
4257 Arg: TA, NTTPType: OrigType, Loc: TemplateArgs[2].getLocation()));
4258 }
4259 } else {
4260 // C++14 [inteseq.make]p1:
4261 // If N is negative the program is ill-formed.
4262 SemaRef.Diag(TemplateArgs[2].getLocation(),
4263 diag::err_integer_sequence_negative_length);
4264 return QualType();
4265 }
4266
4267 // The first template argument will be reused as the template decl that
4268 // our synthetic template arguments will be applied to.
4269 return SemaRef.CheckTemplateIdType(Template: Converted[0].getAsTemplate(),
4270 TemplateLoc, TemplateArgs&: SyntheticTemplateArgs);
4271 }
4272
4273 case BTK__type_pack_element:
4274 // Specializations of
4275 // __type_pack_element<Index, T_1, ..., T_N>
4276 // are treated like T_Index.
4277 assert(Converted.size() == 2 &&
4278 "__type_pack_element should be given an index and a parameter pack");
4279
4280 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
4281 if (IndexArg.isDependent() || Ts.isDependent())
4282 return Context.getCanonicalTemplateSpecializationType(T: TemplateName(BTD),
4283 Args: Converted);
4284
4285 llvm::APSInt Index = IndexArg.getAsIntegral();
4286 assert(Index >= 0 && "the index used with __type_pack_element should be of "
4287 "type std::size_t, and hence be non-negative");
4288 // If the Index is out of bounds, the program is ill-formed.
4289 if (Index >= Ts.pack_size()) {
4290 SemaRef.Diag(TemplateArgs[0].getLocation(),
4291 diag::err_type_pack_element_out_of_bounds);
4292 return QualType();
4293 }
4294
4295 // We simply return the type at index `Index`.
4296 int64_t N = Index.getExtValue();
4297 return Ts.getPackAsArray()[N].getAsType();
4298 }
4299 llvm_unreachable("unexpected BuiltinTemplateDecl!");
4300}
4301
4302/// Determine whether this alias template is "enable_if_t".
4303/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
4304static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
4305 return AliasTemplate->getName().equals("enable_if_t") ||
4306 AliasTemplate->getName().equals("__enable_if_t");
4307}
4308
4309/// Collect all of the separable terms in the given condition, which
4310/// might be a conjunction.
4311///
4312/// FIXME: The right answer is to convert the logical expression into
4313/// disjunctive normal form, so we can find the first failed term
4314/// within each possible clause.
4315static void collectConjunctionTerms(Expr *Clause,
4316 SmallVectorImpl<Expr *> &Terms) {
4317 if (auto BinOp = dyn_cast<BinaryOperator>(Val: Clause->IgnoreParenImpCasts())) {
4318 if (BinOp->getOpcode() == BO_LAnd) {
4319 collectConjunctionTerms(Clause: BinOp->getLHS(), Terms);
4320 collectConjunctionTerms(Clause: BinOp->getRHS(), Terms);
4321 return;
4322 }
4323 }
4324
4325 Terms.push_back(Elt: Clause);
4326}
4327
4328// The ranges-v3 library uses an odd pattern of a top-level "||" with
4329// a left-hand side that is value-dependent but never true. Identify
4330// the idiom and ignore that term.
4331static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
4332 // Top-level '||'.
4333 auto *BinOp = dyn_cast<BinaryOperator>(Val: Cond->IgnoreParenImpCasts());
4334 if (!BinOp) return Cond;
4335
4336 if (BinOp->getOpcode() != BO_LOr) return Cond;
4337
4338 // With an inner '==' that has a literal on the right-hand side.
4339 Expr *LHS = BinOp->getLHS();
4340 auto *InnerBinOp = dyn_cast<BinaryOperator>(Val: LHS->IgnoreParenImpCasts());
4341 if (!InnerBinOp) return Cond;
4342
4343 if (InnerBinOp->getOpcode() != BO_EQ ||
4344 !isa<IntegerLiteral>(Val: InnerBinOp->getRHS()))
4345 return Cond;
4346
4347 // If the inner binary operation came from a macro expansion named
4348 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
4349 // of the '||', which is the real, user-provided condition.
4350 SourceLocation Loc = InnerBinOp->getExprLoc();
4351 if (!Loc.isMacroID()) return Cond;
4352
4353 StringRef MacroName = PP.getImmediateMacroName(Loc);
4354 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
4355 return BinOp->getRHS();
4356
4357 return Cond;
4358}
4359
4360namespace {
4361
4362// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
4363// within failing boolean expression, such as substituting template parameters
4364// for actual types.
4365class FailedBooleanConditionPrinterHelper : public PrinterHelper {
4366public:
4367 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
4368 : Policy(P) {}
4369
4370 bool handledStmt(Stmt *E, raw_ostream &OS) override {
4371 const auto *DR = dyn_cast<DeclRefExpr>(Val: E);
4372 if (DR && DR->getQualifier()) {
4373 // If this is a qualified name, expand the template arguments in nested
4374 // qualifiers.
4375 DR->getQualifier()->print(OS, Policy, ResolveTemplateArguments: true);
4376 // Then print the decl itself.
4377 const ValueDecl *VD = DR->getDecl();
4378 OS << VD->getName();
4379 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(Val: VD)) {
4380 // This is a template variable, print the expanded template arguments.
4381 printTemplateArgumentList(
4382 OS, IV->getTemplateArgs().asArray(), Policy,
4383 IV->getSpecializedTemplate()->getTemplateParameters());
4384 }
4385 return true;
4386 }
4387 return false;
4388 }
4389
4390private:
4391 const PrintingPolicy Policy;
4392};
4393
4394} // end anonymous namespace
4395
4396std::pair<Expr *, std::string>
4397Sema::findFailedBooleanCondition(Expr *Cond) {
4398 Cond = lookThroughRangesV3Condition(PP, Cond);
4399
4400 // Separate out all of the terms in a conjunction.
4401 SmallVector<Expr *, 4> Terms;
4402 collectConjunctionTerms(Clause: Cond, Terms);
4403
4404 // Determine which term failed.
4405 Expr *FailedCond = nullptr;
4406 for (Expr *Term : Terms) {
4407 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
4408
4409 // Literals are uninteresting.
4410 if (isa<CXXBoolLiteralExpr>(Val: TermAsWritten) ||
4411 isa<IntegerLiteral>(Val: TermAsWritten))
4412 continue;
4413
4414 // The initialization of the parameter from the argument is
4415 // a constant-evaluated context.
4416 EnterExpressionEvaluationContext ConstantEvaluated(
4417 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
4418
4419 bool Succeeded;
4420 if (Term->EvaluateAsBooleanCondition(Result&: Succeeded, Ctx: Context) &&
4421 !Succeeded) {
4422 FailedCond = TermAsWritten;
4423 break;
4424 }
4425 }
4426 if (!FailedCond)
4427 FailedCond = Cond->IgnoreParenImpCasts();
4428
4429 std::string Description;
4430 {
4431 llvm::raw_string_ostream Out(Description);
4432 PrintingPolicy Policy = getPrintingPolicy();
4433 Policy.PrintCanonicalTypes = true;
4434 FailedBooleanConditionPrinterHelper Helper(Policy);
4435 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
4436 }
4437 return { FailedCond, Description };
4438}
4439
4440QualType Sema::CheckTemplateIdType(TemplateName Name,
4441 SourceLocation TemplateLoc,
4442 TemplateArgumentListInfo &TemplateArgs) {
4443 DependentTemplateName *DTN
4444 = Name.getUnderlying().getAsDependentTemplateName();
4445 if (DTN && DTN->isIdentifier())
4446 // When building a template-id where the template-name is dependent,
4447 // assume the template is a type template. Either our assumption is
4448 // correct, or the code is ill-formed and will be diagnosed when the
4449 // dependent name is substituted.
4450 return Context.getDependentTemplateSpecializationType(
4451 Keyword: ElaboratedTypeKeyword::None, NNS: DTN->getQualifier(), Name: DTN->getIdentifier(),
4452 Args: TemplateArgs.arguments());
4453
4454 if (Name.getAsAssumedTemplateName() &&
4455 resolveAssumedTemplateNameAsType(/*Scope*/S: nullptr, Name, NameLoc: TemplateLoc))
4456 return QualType();
4457
4458 TemplateDecl *Template = Name.getAsTemplateDecl();
4459 if (!Template || isa<FunctionTemplateDecl>(Val: Template) ||
4460 isa<VarTemplateDecl>(Val: Template) || isa<ConceptDecl>(Val: Template)) {
4461 // We might have a substituted template template parameter pack. If so,
4462 // build a template specialization type for it.
4463 if (Name.getAsSubstTemplateTemplateParmPack())
4464 return Context.getTemplateSpecializationType(T: Name,
4465 Args: TemplateArgs.arguments());
4466
4467 Diag(TemplateLoc, diag::err_template_id_not_a_type)
4468 << Name;
4469 NoteAllFoundTemplates(Name);
4470 return QualType();
4471 }
4472
4473 // Check that the template argument list is well-formed for this
4474 // template.
4475 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4476 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, PartialTemplateArgs: false,
4477 SugaredConverted, CanonicalConverted,
4478 /*UpdateArgsWithConversions=*/true))
4479 return QualType();
4480
4481 QualType CanonType;
4482
4483 if (TypeAliasTemplateDecl *AliasTemplate =
4484 dyn_cast<TypeAliasTemplateDecl>(Val: Template)) {
4485
4486 // Find the canonical type for this type alias template specialization.
4487 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
4488 if (Pattern->isInvalidDecl())
4489 return QualType();
4490
4491 // Only substitute for the innermost template argument list.
4492 MultiLevelTemplateArgumentList TemplateArgLists;
4493 TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted,
4494 /*Final=*/false);
4495 TemplateArgLists.addOuterRetainedLevels(
4496 Num: AliasTemplate->getTemplateParameters()->getDepth());
4497
4498 LocalInstantiationScope Scope(*this);
4499 InstantiatingTemplate Inst(
4500 *this, /*PointOfInstantiation=*/TemplateLoc,
4501 /*Entity=*/AliasTemplate,
4502 /*TemplateArgs=*/TemplateArgLists.getInnermost());
4503 if (Inst.isInvalid())
4504 return QualType();
4505
4506 std::optional<ContextRAII> SavedContext;
4507 if (!AliasTemplate->getDeclContext()->isFileContext())
4508 SavedContext.emplace(*this, AliasTemplate->getDeclContext());
4509
4510 CanonType =
4511 SubstType(Pattern->getUnderlyingType(), TemplateArgLists,
4512 AliasTemplate->getLocation(), AliasTemplate->getDeclName());
4513 if (CanonType.isNull()) {
4514 // If this was enable_if and we failed to find the nested type
4515 // within enable_if in a SFINAE context, dig out the specific
4516 // enable_if condition that failed and present that instead.
4517 if (isEnableIfAliasTemplate(AliasTemplate)) {
4518 if (auto DeductionInfo = isSFINAEContext()) {
4519 if (*DeductionInfo &&
4520 (*DeductionInfo)->hasSFINAEDiagnostic() &&
4521 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
4522 diag::err_typename_nested_not_found_enable_if &&
4523 TemplateArgs[0].getArgument().getKind()
4524 == TemplateArgument::Expression) {
4525 Expr *FailedCond;
4526 std::string FailedDescription;
4527 std::tie(args&: FailedCond, args&: FailedDescription) =
4528 findFailedBooleanCondition(Cond: TemplateArgs[0].getSourceExpression());
4529
4530 // Remove the old SFINAE diagnostic.
4531 PartialDiagnosticAt OldDiag =
4532 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
4533 (*DeductionInfo)->takeSFINAEDiagnostic(PD&: OldDiag);
4534
4535 // Add a new SFINAE diagnostic specifying which condition
4536 // failed.
4537 (*DeductionInfo)->addSFINAEDiagnostic(
4538 OldDiag.first,
4539 PDiag(diag::err_typename_nested_not_found_requirement)
4540 << FailedDescription
4541 << FailedCond->getSourceRange());
4542 }
4543 }
4544 }
4545
4546 return QualType();
4547 }
4548 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Val: Template)) {
4549 CanonType = checkBuiltinTemplateIdType(SemaRef&: *this, BTD, Converted: SugaredConverted,
4550 TemplateLoc, TemplateArgs);
4551 } else if (Name.isDependent() ||
4552 TemplateSpecializationType::anyDependentTemplateArguments(
4553 TemplateArgs, Converted: CanonicalConverted)) {
4554 // This class template specialization is a dependent
4555 // type. Therefore, its canonical type is another class template
4556 // specialization type that contains all of the converted
4557 // arguments in canonical form. This ensures that, e.g., A<T> and
4558 // A<T, T> have identical types when A is declared as:
4559 //
4560 // template<typename T, typename U = T> struct A;
4561 CanonType = Context.getCanonicalTemplateSpecializationType(
4562 T: Name, Args: CanonicalConverted);
4563
4564 // This might work out to be a current instantiation, in which
4565 // case the canonical type needs to be the InjectedClassNameType.
4566 //
4567 // TODO: in theory this could be a simple hashtable lookup; most
4568 // changes to CurContext don't change the set of current
4569 // instantiations.
4570 if (isa<ClassTemplateDecl>(Val: Template)) {
4571 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
4572 // If we get out to a namespace, we're done.
4573 if (Ctx->isFileContext()) break;
4574
4575 // If this isn't a record, keep looking.
4576 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: Ctx);
4577 if (!Record) continue;
4578
4579 // Look for one of the two cases with InjectedClassNameTypes
4580 // and check whether it's the same template.
4581 if (!isa<ClassTemplatePartialSpecializationDecl>(Val: Record) &&
4582 !Record->getDescribedClassTemplate())
4583 continue;
4584
4585 // Fetch the injected class name type and check whether its
4586 // injected type is equal to the type we just built.
4587 QualType ICNT = Context.getTypeDeclType(Record);
4588 QualType Injected = cast<InjectedClassNameType>(Val&: ICNT)
4589 ->getInjectedSpecializationType();
4590
4591 if (CanonType != Injected->getCanonicalTypeInternal())
4592 continue;
4593
4594 // If so, the canonical type of this TST is the injected
4595 // class name type of the record we just found.
4596 assert(ICNT.isCanonical());
4597 CanonType = ICNT;
4598 break;
4599 }
4600 }
4601 } else if (ClassTemplateDecl *ClassTemplate =
4602 dyn_cast<ClassTemplateDecl>(Val: Template)) {
4603 // Find the class template specialization declaration that
4604 // corresponds to these arguments.
4605 void *InsertPos = nullptr;
4606 ClassTemplateSpecializationDecl *Decl =
4607 ClassTemplate->findSpecialization(Args: CanonicalConverted, InsertPos);
4608 if (!Decl) {
4609 // This is the first time we have referenced this class template
4610 // specialization. Create the canonical declaration and add it to
4611 // the set of specializations.
4612 Decl = ClassTemplateSpecializationDecl::Create(
4613 Context, TK: ClassTemplate->getTemplatedDecl()->getTagKind(),
4614 DC: ClassTemplate->getDeclContext(),
4615 StartLoc: ClassTemplate->getTemplatedDecl()->getBeginLoc(),
4616 IdLoc: ClassTemplate->getLocation(), SpecializedTemplate: ClassTemplate, Args: CanonicalConverted,
4617 PrevDecl: nullptr);
4618 ClassTemplate->AddSpecialization(D: Decl, InsertPos);
4619 if (ClassTemplate->isOutOfLine())
4620 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
4621 }
4622
4623 if (Decl->getSpecializationKind() == TSK_Undeclared &&
4624 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4625 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4626 if (!Inst.isInvalid()) {
4627 MultiLevelTemplateArgumentList TemplateArgLists(Template,
4628 CanonicalConverted,
4629 /*Final=*/false);
4630 InstantiateAttrsForDecl(TemplateArgLists,
4631 ClassTemplate->getTemplatedDecl(), Decl);
4632 }
4633 }
4634
4635 // Diagnose uses of this specialization.
4636 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4637
4638 CanonType = Context.getTypeDeclType(Decl);
4639 assert(isa<RecordType>(CanonType) &&
4640 "type of non-dependent specialization is not a RecordType");
4641 } else {
4642 llvm_unreachable("Unhandled template kind");
4643 }
4644
4645 // Build the fully-sugared type for this class template
4646 // specialization, which refers back to the class template
4647 // specialization we created or found.
4648 return Context.getTemplateSpecializationType(T: Name, Args: TemplateArgs.arguments(),
4649 Canon: CanonType);
4650}
4651
4652void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
4653 TemplateNameKind &TNK,
4654 SourceLocation NameLoc,
4655 IdentifierInfo *&II) {
4656 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4657
4658 TemplateName Name = ParsedName.get();
4659 auto *ATN = Name.getAsAssumedTemplateName();
4660 assert(ATN && "not an assumed template name");
4661 II = ATN->getDeclName().getAsIdentifierInfo();
4662
4663 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
4664 // Resolved to a type template name.
4665 ParsedName = TemplateTy::make(P: Name);
4666 TNK = TNK_Type_template;
4667 }
4668}
4669
4670bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
4671 SourceLocation NameLoc,
4672 bool Diagnose) {
4673 // We assumed this undeclared identifier to be an (ADL-only) function
4674 // template name, but it was used in a context where a type was required.
4675 // Try to typo-correct it now.
4676 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
4677 assert(ATN && "not an assumed template name");
4678
4679 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
4680 struct CandidateCallback : CorrectionCandidateCallback {
4681 bool ValidateCandidate(const TypoCorrection &TC) override {
4682 return TC.getCorrectionDecl() &&
4683 getAsTypeTemplateDecl(TC.getCorrectionDecl());
4684 }
4685 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4686 return std::make_unique<CandidateCallback>(args&: *this);
4687 }
4688 } FilterCCC;
4689
4690 TypoCorrection Corrected =
4691 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: nullptr,
4692 CCC&: FilterCCC, Mode: CTK_ErrorRecovery);
4693 if (Corrected && Corrected.getFoundDecl()) {
4694 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
4695 << ATN->getDeclName());
4696 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
4697 return false;
4698 }
4699
4700 if (Diagnose)
4701 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
4702 return true;
4703}
4704
4705TypeResult Sema::ActOnTemplateIdType(
4706 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4707 TemplateTy TemplateD, const IdentifierInfo *TemplateII,
4708 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
4709 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
4710 bool IsCtorOrDtorName, bool IsClassName,
4711 ImplicitTypenameContext AllowImplicitTypename) {
4712 if (SS.isInvalid())
4713 return true;
4714
4715 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4716 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4717
4718 // C++ [temp.res]p3:
4719 // A qualified-id that refers to a type and in which the
4720 // nested-name-specifier depends on a template-parameter (14.6.2)
4721 // shall be prefixed by the keyword typename to indicate that the
4722 // qualified-id denotes a type, forming an
4723 // elaborated-type-specifier (7.1.5.3).
4724 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4725 // C++2a relaxes some of those restrictions in [temp.res]p5.
4726 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4727 if (getLangOpts().CPlusPlus20)
4728 Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
4729 else
4730 Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
4731 << SS.getScopeRep() << TemplateII->getName()
4732 << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4733 } else
4734 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
4735 << SS.getScopeRep() << TemplateII->getName();
4736
4737 // FIXME: This is not quite correct recovery as we don't transform SS
4738 // into the corresponding dependent form (and we don't diagnose missing
4739 // 'template' keywords within SS as a result).
4740 return ActOnTypenameType(S: nullptr, TypenameLoc: SourceLocation(), SS, TemplateLoc: TemplateKWLoc,
4741 TemplateName: TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4742 TemplateArgs: TemplateArgsIn, RAngleLoc);
4743 }
4744
4745 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4746 // it's not actually allowed to be used as a type in most cases. Because
4747 // we annotate it before we know whether it's valid, we have to check for
4748 // this case here.
4749 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
4750 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4751 Diag(TemplateIILoc,
4752 TemplateKWLoc.isInvalid()
4753 ? diag::err_out_of_line_qualified_id_type_names_constructor
4754 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4755 << TemplateII << 0 /*injected-class-name used as template name*/
4756 << 1 /*if any keyword was present, it was 'template'*/;
4757 }
4758 }
4759
4760 TemplateName Template = TemplateD.get();
4761 if (Template.getAsAssumedTemplateName() &&
4762 resolveAssumedTemplateNameAsType(S, Name&: Template, NameLoc: TemplateIILoc))
4763 return true;
4764
4765 // Translate the parser's template argument list in our AST format.
4766 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4767 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4768
4769 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4770 assert(SS.getScopeRep() == DTN->getQualifier());
4771 QualType T = Context.getDependentTemplateSpecializationType(
4772 Keyword: ElaboratedTypeKeyword::None, NNS: DTN->getQualifier(), Name: DTN->getIdentifier(),
4773 Args: TemplateArgs.arguments());
4774 // Build type-source information.
4775 TypeLocBuilder TLB;
4776 DependentTemplateSpecializationTypeLoc SpecTL
4777 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
4778 SpecTL.setElaboratedKeywordLoc(SourceLocation());
4779 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
4780 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4781 SpecTL.setTemplateNameLoc(TemplateIILoc);
4782 SpecTL.setLAngleLoc(LAngleLoc);
4783 SpecTL.setRAngleLoc(RAngleLoc);
4784 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4785 SpecTL.setArgLocInfo(i: I, AI: TemplateArgs[I].getLocInfo());
4786 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
4787 }
4788
4789 QualType SpecTy = CheckTemplateIdType(Name: Template, TemplateLoc: TemplateIILoc, TemplateArgs);
4790 if (SpecTy.isNull())
4791 return true;
4792
4793 // Build type-source information.
4794 TypeLocBuilder TLB;
4795 TemplateSpecializationTypeLoc SpecTL =
4796 TLB.push<TemplateSpecializationTypeLoc>(T: SpecTy);
4797 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4798 SpecTL.setTemplateNameLoc(TemplateIILoc);
4799 SpecTL.setLAngleLoc(LAngleLoc);
4800 SpecTL.setRAngleLoc(RAngleLoc);
4801 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4802 SpecTL.setArgLocInfo(i, AI: TemplateArgs[i].getLocInfo());
4803
4804 // Create an elaborated-type-specifier containing the nested-name-specifier.
4805 QualType ElTy =
4806 getElaboratedType(Keyword: ElaboratedTypeKeyword::None,
4807 SS: !IsCtorOrDtorName ? SS : CXXScopeSpec(), T: SpecTy);
4808 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(T: ElTy);
4809 ElabTL.setElaboratedKeywordLoc(SourceLocation());
4810 if (!ElabTL.isEmpty())
4811 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4812 return CreateParsedType(T: ElTy, TInfo: TLB.getTypeSourceInfo(Context, T: ElTy));
4813}
4814
4815TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
4816 TypeSpecifierType TagSpec,
4817 SourceLocation TagLoc,
4818 CXXScopeSpec &SS,
4819 SourceLocation TemplateKWLoc,
4820 TemplateTy TemplateD,
4821 SourceLocation TemplateLoc,
4822 SourceLocation LAngleLoc,
4823 ASTTemplateArgsPtr TemplateArgsIn,
4824 SourceLocation RAngleLoc) {
4825 if (SS.isInvalid())
4826 return TypeResult(true);
4827
4828 TemplateName Template = TemplateD.get();
4829
4830 // Translate the parser's template argument list in our AST format.
4831 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4832 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4833
4834 // Determine the tag kind
4835 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
4836 ElaboratedTypeKeyword Keyword
4837 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: TagKind);
4838
4839 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4840 assert(SS.getScopeRep() == DTN->getQualifier());
4841 QualType T = Context.getDependentTemplateSpecializationType(
4842 Keyword, NNS: DTN->getQualifier(), Name: DTN->getIdentifier(),
4843 Args: TemplateArgs.arguments());
4844
4845 // Build type-source information.
4846 TypeLocBuilder TLB;
4847 DependentTemplateSpecializationTypeLoc SpecTL
4848 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
4849 SpecTL.setElaboratedKeywordLoc(TagLoc);
4850 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
4851 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4852 SpecTL.setTemplateNameLoc(TemplateLoc);
4853 SpecTL.setLAngleLoc(LAngleLoc);
4854 SpecTL.setRAngleLoc(RAngleLoc);
4855 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4856 SpecTL.setArgLocInfo(i: I, AI: TemplateArgs[I].getLocInfo());
4857 return CreateParsedType(T, TInfo: TLB.getTypeSourceInfo(Context, T));
4858 }
4859
4860 if (TypeAliasTemplateDecl *TAT =
4861 dyn_cast_or_null<TypeAliasTemplateDecl>(Val: Template.getAsTemplateDecl())) {
4862 // C++0x [dcl.type.elab]p2:
4863 // If the identifier resolves to a typedef-name or the simple-template-id
4864 // resolves to an alias template specialization, the
4865 // elaborated-type-specifier is ill-formed.
4866 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
4867 << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
4868 Diag(TAT->getLocation(), diag::note_declared_at);
4869 }
4870
4871 QualType Result = CheckTemplateIdType(Name: Template, TemplateLoc, TemplateArgs);
4872 if (Result.isNull())
4873 return TypeResult(true);
4874
4875 // Check the tag kind
4876 if (const RecordType *RT = Result->getAs<RecordType>()) {
4877 RecordDecl *D = RT->getDecl();
4878
4879 IdentifierInfo *Id = D->getIdentifier();
4880 assert(Id && "templated class must have an identifier");
4881
4882 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
4883 TagLoc, Id)) {
4884 Diag(TagLoc, diag::err_use_with_wrong_tag)
4885 << Result
4886 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
4887 Diag(D->getLocation(), diag::note_previous_use);
4888 }
4889 }
4890
4891 // Provide source-location information for the template specialization.
4892 TypeLocBuilder TLB;
4893 TemplateSpecializationTypeLoc SpecTL
4894 = TLB.push<TemplateSpecializationTypeLoc>(T: Result);
4895 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4896 SpecTL.setTemplateNameLoc(TemplateLoc);
4897 SpecTL.setLAngleLoc(LAngleLoc);
4898 SpecTL.setRAngleLoc(RAngleLoc);
4899 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4900 SpecTL.setArgLocInfo(i, AI: TemplateArgs[i].getLocInfo());
4901
4902 // Construct an elaborated type containing the nested-name-specifier (if any)
4903 // and tag keyword.
4904 Result = Context.getElaboratedType(Keyword, NNS: SS.getScopeRep(), NamedType: Result);
4905 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(T: Result);
4906 ElabTL.setElaboratedKeywordLoc(TagLoc);
4907 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4908 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
4909}
4910
4911static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4912 NamedDecl *PrevDecl,
4913 SourceLocation Loc,
4914 bool IsPartialSpecialization);
4915
4916static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4917
4918static bool isTemplateArgumentTemplateParameter(
4919 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
4920 switch (Arg.getKind()) {
4921 case TemplateArgument::Null:
4922 case TemplateArgument::NullPtr:
4923 case TemplateArgument::Integral:
4924 case TemplateArgument::Declaration:
4925 case TemplateArgument::StructuralValue:
4926 case TemplateArgument::Pack:
4927 case TemplateArgument::TemplateExpansion:
4928 return false;
4929
4930 case TemplateArgument::Type: {
4931 QualType Type = Arg.getAsType();
4932 const TemplateTypeParmType *TPT =
4933 Arg.getAsType()->getAs<TemplateTypeParmType>();
4934 return TPT && !Type.hasQualifiers() &&
4935 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4936 }
4937
4938 case TemplateArgument::Expression: {
4939 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg.getAsExpr());
4940 if (!DRE || !DRE->getDecl())
4941 return false;
4942 const NonTypeTemplateParmDecl *NTTP =
4943 dyn_cast<NonTypeTemplateParmDecl>(Val: DRE->getDecl());
4944 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4945 }
4946
4947 case TemplateArgument::Template:
4948 const TemplateTemplateParmDecl *TTP =
4949 dyn_cast_or_null<TemplateTemplateParmDecl>(
4950 Val: Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4951 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4952 }
4953 llvm_unreachable("unexpected kind of template argument");
4954}
4955
4956static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4957 ArrayRef<TemplateArgument> Args) {
4958 if (Params->size() != Args.size())
4959 return false;
4960
4961 unsigned Depth = Params->getDepth();
4962
4963 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4964 TemplateArgument Arg = Args[I];
4965
4966 // If the parameter is a pack expansion, the argument must be a pack
4967 // whose only element is a pack expansion.
4968 if (Params->getParam(Idx: I)->isParameterPack()) {
4969 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4970 !Arg.pack_begin()->isPackExpansion())
4971 return false;
4972 Arg = Arg.pack_begin()->getPackExpansionPattern();
4973 }
4974
4975 if (!isTemplateArgumentTemplateParameter(Arg, Depth, Index: I))
4976 return false;
4977 }
4978
4979 return true;
4980}
4981
4982template<typename PartialSpecDecl>
4983static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4984 if (Partial->getDeclContext()->isDependentContext())
4985 return;
4986
4987 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4988 // for non-substitution-failure issues?
4989 TemplateDeductionInfo Info(Partial->getLocation());
4990 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4991 return;
4992
4993 auto *Template = Partial->getSpecializedTemplate();
4994 S.Diag(Partial->getLocation(),
4995 diag::ext_partial_spec_not_more_specialized_than_primary)
4996 << isa<VarTemplateDecl>(Template);
4997
4998 if (Info.hasSFINAEDiagnostic()) {
4999 PartialDiagnosticAt Diag = {SourceLocation(),
5000 PartialDiagnostic::NullDiagnostic()};
5001 Info.takeSFINAEDiagnostic(PD&: Diag);
5002 SmallString<128> SFINAEArgString;
5003 Diag.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: SFINAEArgString);
5004 S.Diag(Diag.first,
5005 diag::note_partial_spec_not_more_specialized_than_primary)
5006 << SFINAEArgString;
5007 }
5008
5009 S.NoteTemplateLocation(Decl: *Template);
5010 SmallVector<const Expr *, 3> PartialAC, TemplateAC;
5011 Template->getAssociatedConstraints(TemplateAC);
5012 Partial->getAssociatedConstraints(PartialAC);
5013 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(D1: Partial, AC1: PartialAC, D2: Template,
5014 AC2: TemplateAC);
5015}
5016
5017static void
5018noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
5019 const llvm::SmallBitVector &DeducibleParams) {
5020 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
5021 if (!DeducibleParams[I]) {
5022 NamedDecl *Param = TemplateParams->getParam(Idx: I);
5023 if (Param->getDeclName())
5024 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
5025 << Param->getDeclName();
5026 else
5027 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
5028 << "(anonymous)";
5029 }
5030 }
5031}
5032
5033
5034template<typename PartialSpecDecl>
5035static void checkTemplatePartialSpecialization(Sema &S,
5036 PartialSpecDecl *Partial) {
5037 // C++1z [temp.class.spec]p8: (DR1495)
5038 // - The specialization shall be more specialized than the primary
5039 // template (14.5.5.2).
5040 checkMoreSpecializedThanPrimary(S, Partial);
5041
5042 // C++ [temp.class.spec]p8: (DR1315)
5043 // - Each template-parameter shall appear at least once in the
5044 // template-id outside a non-deduced context.
5045 // C++1z [temp.class.spec.match]p3 (P0127R2)
5046 // If the template arguments of a partial specialization cannot be
5047 // deduced because of the structure of its template-parameter-list
5048 // and the template-id, the program is ill-formed.
5049 auto *TemplateParams = Partial->getTemplateParameters();
5050 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
5051 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
5052 TemplateParams->getDepth(), DeducibleParams);
5053
5054 if (!DeducibleParams.all()) {
5055 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
5056 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
5057 << isa<VarTemplatePartialSpecializationDecl>(Partial)
5058 << (NumNonDeducible > 1)
5059 << SourceRange(Partial->getLocation(),
5060 Partial->getTemplateArgsAsWritten()->RAngleLoc);
5061 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
5062 }
5063}
5064
5065void Sema::CheckTemplatePartialSpecialization(
5066 ClassTemplatePartialSpecializationDecl *Partial) {
5067 checkTemplatePartialSpecialization(S&: *this, Partial);
5068}
5069
5070void Sema::CheckTemplatePartialSpecialization(
5071 VarTemplatePartialSpecializationDecl *Partial) {
5072 checkTemplatePartialSpecialization(S&: *this, Partial);
5073}
5074
5075void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
5076 // C++1z [temp.param]p11:
5077 // A template parameter of a deduction guide template that does not have a
5078 // default-argument shall be deducible from the parameter-type-list of the
5079 // deduction guide template.
5080 auto *TemplateParams = TD->getTemplateParameters();
5081 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
5082 MarkDeducedTemplateParameters(FunctionTemplate: TD, Deduced&: DeducibleParams);
5083 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
5084 // A parameter pack is deducible (to an empty pack).
5085 auto *Param = TemplateParams->getParam(I);
5086 if (Param->isParameterPack() || hasVisibleDefaultArgument(D: Param))
5087 DeducibleParams[I] = true;
5088 }
5089
5090 if (!DeducibleParams.all()) {
5091 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
5092 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
5093 << (NumNonDeducible > 1);
5094 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
5095 }
5096}
5097
5098DeclResult Sema::ActOnVarTemplateSpecialization(
5099 Scope *S, Declarator &D, TypeSourceInfo *DI, LookupResult &Previous,
5100 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
5101 StorageClass SC, bool IsPartialSpecialization) {
5102 // D must be variable template id.
5103 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&
5104 "Variable template specialization is declared with a template id.");
5105
5106 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
5107 TemplateArgumentListInfo TemplateArgs =
5108 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *TemplateId);
5109 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
5110 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
5111 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
5112
5113 TemplateName Name = TemplateId->Template.get();
5114
5115 // The template-id must name a variable template.
5116 VarTemplateDecl *VarTemplate =
5117 dyn_cast_or_null<VarTemplateDecl>(Val: Name.getAsTemplateDecl());
5118 if (!VarTemplate) {
5119 NamedDecl *FnTemplate;
5120 if (auto *OTS = Name.getAsOverloadedTemplate())
5121 FnTemplate = *OTS->begin();
5122 else
5123 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Val: Name.getAsTemplateDecl());
5124 if (FnTemplate)
5125 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
5126 << FnTemplate->getDeclName();
5127 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
5128 << IsPartialSpecialization;
5129 }
5130
5131 // Check for unexpanded parameter packs in any of the template arguments.
5132 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
5133 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
5134 UPPC: IsPartialSpecialization
5135 ? UPPC_PartialSpecialization
5136 : UPPC_ExplicitSpecialization))
5137 return true;
5138
5139 // Check that the template argument list is well-formed for this
5140 // template.
5141 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5142 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
5143 false, SugaredConverted, CanonicalConverted,
5144 /*UpdateArgsWithConversions=*/true))
5145 return true;
5146
5147 // Find the variable template (partial) specialization declaration that
5148 // corresponds to these arguments.
5149 if (IsPartialSpecialization) {
5150 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
5151 TemplateArgs.size(),
5152 CanonicalConverted))
5153 return true;
5154
5155 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
5156 // also do them during instantiation.
5157 if (!Name.isDependent() &&
5158 !TemplateSpecializationType::anyDependentTemplateArguments(
5159 TemplateArgs, Converted: CanonicalConverted)) {
5160 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
5161 << VarTemplate->getDeclName();
5162 IsPartialSpecialization = false;
5163 }
5164
5165 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
5166 CanonicalConverted) &&
5167 (!Context.getLangOpts().CPlusPlus20 ||
5168 !TemplateParams->hasAssociatedConstraints())) {
5169 // C++ [temp.class.spec]p9b3:
5170 //
5171 // -- The argument list of the specialization shall not be identical
5172 // to the implicit argument list of the primary template.
5173 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
5174 << /*variable template*/ 1
5175 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
5176 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
5177 // FIXME: Recover from this by treating the declaration as a redeclaration
5178 // of the primary template.
5179 return true;
5180 }
5181 }
5182
5183 void *InsertPos = nullptr;
5184 VarTemplateSpecializationDecl *PrevDecl = nullptr;
5185
5186 if (IsPartialSpecialization)
5187 PrevDecl = VarTemplate->findPartialSpecialization(
5188 Args: CanonicalConverted, TPL: TemplateParams, InsertPos);
5189 else
5190 PrevDecl = VarTemplate->findSpecialization(Args: CanonicalConverted, InsertPos);
5191
5192 VarTemplateSpecializationDecl *Specialization = nullptr;
5193
5194 // Check whether we can declare a variable template specialization in
5195 // the current scope.
5196 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
5197 TemplateNameLoc,
5198 IsPartialSpecialization))
5199 return true;
5200
5201 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
5202 // Since the only prior variable template specialization with these
5203 // arguments was referenced but not declared, reuse that
5204 // declaration node as our own, updating its source location and
5205 // the list of outer template parameters to reflect our new declaration.
5206 Specialization = PrevDecl;
5207 Specialization->setLocation(TemplateNameLoc);
5208 PrevDecl = nullptr;
5209 } else if (IsPartialSpecialization) {
5210 // Create a new class template partial specialization declaration node.
5211 VarTemplatePartialSpecializationDecl *PrevPartial =
5212 cast_or_null<VarTemplatePartialSpecializationDecl>(Val: PrevDecl);
5213 VarTemplatePartialSpecializationDecl *Partial =
5214 VarTemplatePartialSpecializationDecl::Create(
5215 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc,
5216 IdLoc: TemplateNameLoc, Params: TemplateParams, SpecializedTemplate: VarTemplate, T: DI->getType(), TInfo: DI, S: SC,
5217 Args: CanonicalConverted, ArgInfos: TemplateArgs);
5218
5219 if (!PrevPartial)
5220 VarTemplate->AddPartialSpecialization(D: Partial, InsertPos);
5221 Specialization = Partial;
5222
5223 // If we are providing an explicit specialization of a member variable
5224 // template specialization, make a note of that.
5225 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
5226 PrevPartial->setMemberSpecialization();
5227
5228 CheckTemplatePartialSpecialization(Partial);
5229 } else {
5230 // Create a new class template specialization declaration node for
5231 // this explicit specialization or friend declaration.
5232 Specialization = VarTemplateSpecializationDecl::Create(
5233 Context, DC: VarTemplate->getDeclContext(), StartLoc: TemplateKWLoc, IdLoc: TemplateNameLoc,
5234 SpecializedTemplate: VarTemplate, T: DI->getType(), TInfo: DI, S: SC, Args: CanonicalConverted);
5235 Specialization->setTemplateArgsInfo(TemplateArgs);
5236
5237 if (!PrevDecl)
5238 VarTemplate->AddSpecialization(D: Specialization, InsertPos);
5239 }
5240
5241 // C++ [temp.expl.spec]p6:
5242 // If a template, a member template or the member of a class template is
5243 // explicitly specialized then that specialization shall be declared
5244 // before the first use of that specialization that would cause an implicit
5245 // instantiation to take place, in every translation unit in which such a
5246 // use occurs; no diagnostic is required.
5247 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
5248 bool Okay = false;
5249 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
5250 // Is there any previous explicit specialization declaration?
5251 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
5252 Okay = true;
5253 break;
5254 }
5255 }
5256
5257 if (!Okay) {
5258 SourceRange Range(TemplateNameLoc, RAngleLoc);
5259 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
5260 << Name << Range;
5261
5262 Diag(PrevDecl->getPointOfInstantiation(),
5263 diag::note_instantiation_required_here)
5264 << (PrevDecl->getTemplateSpecializationKind() !=
5265 TSK_ImplicitInstantiation);
5266 return true;
5267 }
5268 }
5269
5270 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
5271 Specialization->setLexicalDeclContext(CurContext);
5272
5273 // Add the specialization into its lexical context, so that it can
5274 // be seen when iterating through the list of declarations in that
5275 // context. However, specializations are not found by name lookup.
5276 CurContext->addDecl(Specialization);
5277
5278 // Note that this is an explicit specialization.
5279 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
5280
5281 Previous.clear();
5282 if (PrevDecl)
5283 Previous.addDecl(PrevDecl);
5284 else if (Specialization->isStaticDataMember() &&
5285 Specialization->isOutOfLine())
5286 Specialization->setAccess(VarTemplate->getAccess());
5287
5288 return Specialization;
5289}
5290
5291namespace {
5292/// A partial specialization whose template arguments have matched
5293/// a given template-id.
5294struct PartialSpecMatchResult {
5295 VarTemplatePartialSpecializationDecl *Partial;
5296 TemplateArgumentList *Args;
5297};
5298} // end anonymous namespace
5299
5300DeclResult
5301Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
5302 SourceLocation TemplateNameLoc,
5303 const TemplateArgumentListInfo &TemplateArgs) {
5304 assert(Template && "A variable template id without template?");
5305
5306 // Check that the template argument list is well-formed for this template.
5307 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5308 if (CheckTemplateArgumentList(
5309 Template, TemplateNameLoc,
5310 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
5311 SugaredConverted, CanonicalConverted,
5312 /*UpdateArgsWithConversions=*/true))
5313 return true;
5314
5315 // Produce a placeholder value if the specialization is dependent.
5316 if (Template->getDeclContext()->isDependentContext() ||
5317 TemplateSpecializationType::anyDependentTemplateArguments(
5318 TemplateArgs, Converted: CanonicalConverted))
5319 return DeclResult();
5320
5321 // Find the variable template specialization declaration that
5322 // corresponds to these arguments.
5323 void *InsertPos = nullptr;
5324 if (VarTemplateSpecializationDecl *Spec =
5325 Template->findSpecialization(Args: CanonicalConverted, InsertPos)) {
5326 checkSpecializationReachability(TemplateNameLoc, Spec);
5327 // If we already have a variable template specialization, return it.
5328 return Spec;
5329 }
5330
5331 // This is the first time we have referenced this variable template
5332 // specialization. Create the canonical declaration and add it to
5333 // the set of specializations, based on the closest partial specialization
5334 // that it represents. That is,
5335 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
5336 const TemplateArgumentList *PartialSpecArgs = nullptr;
5337 bool AmbiguousPartialSpec = false;
5338 typedef PartialSpecMatchResult MatchResult;
5339 SmallVector<MatchResult, 4> Matched;
5340 SourceLocation PointOfInstantiation = TemplateNameLoc;
5341 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
5342 /*ForTakingAddress=*/false);
5343
5344 // 1. Attempt to find the closest partial specialization that this
5345 // specializes, if any.
5346 // TODO: Unify with InstantiateClassTemplateSpecialization()?
5347 // Perhaps better after unification of DeduceTemplateArguments() and
5348 // getMoreSpecializedPartialSpecialization().
5349 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
5350 Template->getPartialSpecializations(PS&: PartialSpecs);
5351
5352 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
5353 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
5354 TemplateDeductionInfo Info(FailedCandidates.getLocation());
5355
5356 if (TemplateDeductionResult Result =
5357 DeduceTemplateArguments(Partial, TemplateArgs: CanonicalConverted, Info);
5358 Result != TemplateDeductionResult::Success) {
5359 // Store the failed-deduction information for use in diagnostics, later.
5360 // TODO: Actually use the failed-deduction info?
5361 FailedCandidates.addCandidate().set(
5362 Found: DeclAccessPair::make(Template, AS_public), Spec: Partial,
5363 Info: MakeDeductionFailureInfo(Context, TDK: Result, Info));
5364 (void)Result;
5365 } else {
5366 Matched.push_back(Elt: PartialSpecMatchResult());
5367 Matched.back().Partial = Partial;
5368 Matched.back().Args = Info.takeCanonical();
5369 }
5370 }
5371
5372 if (Matched.size() >= 1) {
5373 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
5374 if (Matched.size() == 1) {
5375 // -- If exactly one matching specialization is found, the
5376 // instantiation is generated from that specialization.
5377 // We don't need to do anything for this.
5378 } else {
5379 // -- If more than one matching specialization is found, the
5380 // partial order rules (14.5.4.2) are used to determine
5381 // whether one of the specializations is more specialized
5382 // than the others. If none of the specializations is more
5383 // specialized than all of the other matching
5384 // specializations, then the use of the variable template is
5385 // ambiguous and the program is ill-formed.
5386 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
5387 PEnd = Matched.end();
5388 P != PEnd; ++P) {
5389 if (getMoreSpecializedPartialSpecialization(PS1: P->Partial, PS2: Best->Partial,
5390 Loc: PointOfInstantiation) ==
5391 P->Partial)
5392 Best = P;
5393 }
5394
5395 // Determine if the best partial specialization is more specialized than
5396 // the others.
5397 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
5398 PEnd = Matched.end();
5399 P != PEnd; ++P) {
5400 if (P != Best && getMoreSpecializedPartialSpecialization(
5401 PS1: P->Partial, PS2: Best->Partial,
5402 Loc: PointOfInstantiation) != Best->Partial) {
5403 AmbiguousPartialSpec = true;
5404 break;
5405 }
5406 }
5407 }
5408
5409 // Instantiate using the best variable template partial specialization.
5410 InstantiationPattern = Best->Partial;
5411 PartialSpecArgs = Best->Args;
5412 } else {
5413 // -- If no match is found, the instantiation is generated
5414 // from the primary template.
5415 // InstantiationPattern = Template->getTemplatedDecl();
5416 }
5417
5418 // 2. Create the canonical declaration.
5419 // Note that we do not instantiate a definition until we see an odr-use
5420 // in DoMarkVarDeclReferenced().
5421 // FIXME: LateAttrs et al.?
5422 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
5423 VarTemplate: Template, FromVar: InstantiationPattern, PartialSpecArgs, TemplateArgsInfo: TemplateArgs,
5424 Converted&: CanonicalConverted, PointOfInstantiation: TemplateNameLoc /*, LateAttrs, StartingScope*/);
5425 if (!Decl)
5426 return true;
5427
5428 if (AmbiguousPartialSpec) {
5429 // Partial ordering did not produce a clear winner. Complain.
5430 Decl->setInvalidDecl();
5431 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
5432 << Decl;
5433
5434 // Print the matching partial specializations.
5435 for (MatchResult P : Matched)
5436 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
5437 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
5438 *P.Args);
5439 return true;
5440 }
5441
5442 if (VarTemplatePartialSpecializationDecl *D =
5443 dyn_cast<VarTemplatePartialSpecializationDecl>(Val: InstantiationPattern))
5444 Decl->setInstantiationOf(PartialSpec: D, TemplateArgs: PartialSpecArgs);
5445
5446 checkSpecializationReachability(TemplateNameLoc, Decl);
5447
5448 assert(Decl && "No variable template specialization?");
5449 return Decl;
5450}
5451
5452ExprResult Sema::CheckVarTemplateId(
5453 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
5454 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
5455 const TemplateArgumentListInfo *TemplateArgs) {
5456
5457 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, TemplateNameLoc: NameInfo.getLoc(),
5458 TemplateArgs: *TemplateArgs);
5459 if (Decl.isInvalid())
5460 return ExprError();
5461
5462 if (!Decl.get())
5463 return ExprResult();
5464
5465 VarDecl *Var = cast<VarDecl>(Val: Decl.get());
5466 if (!Var->getTemplateSpecializationKind())
5467 Var->setTemplateSpecializationKind(TSK: TSK_ImplicitInstantiation,
5468 PointOfInstantiation: NameInfo.getLoc());
5469
5470 // Build an ordinary singleton decl ref.
5471 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
5472}
5473
5474void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
5475 SourceLocation Loc) {
5476 Diag(Loc, diag::err_template_missing_args)
5477 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
5478 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
5479 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
5480 }
5481}
5482
5483ExprResult
5484Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
5485 SourceLocation TemplateKWLoc,
5486 const DeclarationNameInfo &ConceptNameInfo,
5487 NamedDecl *FoundDecl,
5488 ConceptDecl *NamedConcept,
5489 const TemplateArgumentListInfo *TemplateArgs) {
5490 assert(NamedConcept && "A concept template id without a template?");
5491
5492 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5493 if (CheckTemplateArgumentList(
5494 NamedConcept, ConceptNameInfo.getLoc(),
5495 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
5496 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
5497 /*UpdateArgsWithConversions=*/false))
5498 return ExprError();
5499
5500 auto *CSD = ImplicitConceptSpecializationDecl::Create(
5501 C: Context, DC: NamedConcept->getDeclContext(), SL: NamedConcept->getLocation(),
5502 ConvertedArgs: CanonicalConverted);
5503 ConstraintSatisfaction Satisfaction;
5504 bool AreArgsDependent =
5505 TemplateSpecializationType::anyDependentTemplateArguments(
5506 *TemplateArgs, Converted: CanonicalConverted);
5507 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
5508 /*Final=*/false);
5509 LocalInstantiationScope Scope(*this);
5510
5511 EnterExpressionEvaluationContext EECtx{
5512 *this, ExpressionEvaluationContext::ConstantEvaluated, CSD};
5513
5514 if (!AreArgsDependent &&
5515 CheckConstraintSatisfaction(
5516 NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
5517 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
5518 TemplateArgs->getRAngleLoc()),
5519 Satisfaction))
5520 return ExprError();
5521 auto *CL = ConceptReference::Create(
5522 C: Context,
5523 NNS: SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
5524 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
5525 ArgsAsWritten: ASTTemplateArgumentListInfo::Create(C: Context, List: *TemplateArgs));
5526 return ConceptSpecializationExpr::Create(
5527 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
5528}
5529
5530ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
5531 SourceLocation TemplateKWLoc,
5532 LookupResult &R,
5533 bool RequiresADL,
5534 const TemplateArgumentListInfo *TemplateArgs) {
5535 // FIXME: Can we do any checking at this point? I guess we could check the
5536 // template arguments that we have against the template name, if the template
5537 // name refers to a single template. That's not a terribly common case,
5538 // though.
5539 // foo<int> could identify a single function unambiguously
5540 // This approach does NOT work, since f<int>(1);
5541 // gets resolved prior to resorting to overload resolution
5542 // i.e., template<class T> void f(double);
5543 // vs template<class T, class U> void f(U);
5544
5545 // These should be filtered out by our callers.
5546 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
5547
5548 // Non-function templates require a template argument list.
5549 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
5550 if (!TemplateArgs && !isa<FunctionTemplateDecl>(Val: TD)) {
5551 diagnoseMissingTemplateArguments(Name: TemplateName(TD), Loc: R.getNameLoc());
5552 return ExprError();
5553 }
5554 }
5555 bool KnownDependent = false;
5556 // In C++1y, check variable template ids.
5557 if (R.getAsSingle<VarTemplateDecl>()) {
5558 ExprResult Res = CheckVarTemplateId(
5559 SS, NameInfo: R.getLookupNameInfo(), Template: R.getAsSingle<VarTemplateDecl>(),
5560 FoundD: R.getRepresentativeDecl(), TemplateLoc: TemplateKWLoc, TemplateArgs);
5561 if (Res.isInvalid() || Res.isUsable())
5562 return Res;
5563 // Result is dependent. Carry on to build an UnresolvedLookupEpxr.
5564 KnownDependent = true;
5565 }
5566
5567 if (R.getAsSingle<ConceptDecl>()) {
5568 return CheckConceptTemplateId(SS, TemplateKWLoc, ConceptNameInfo: R.getLookupNameInfo(),
5569 FoundDecl: R.getRepresentativeDecl(),
5570 NamedConcept: R.getAsSingle<ConceptDecl>(), TemplateArgs);
5571 }
5572
5573 // We don't want lookup warnings at this point.
5574 R.suppressDiagnostics();
5575
5576 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
5577 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
5578 TemplateKWLoc, NameInfo: R.getLookupNameInfo(), RequiresADL, Args: TemplateArgs,
5579 Begin: R.begin(), End: R.end(), KnownDependent);
5580
5581 return ULE;
5582}
5583
5584// We actually only call this from template instantiation.
5585ExprResult
5586Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
5587 SourceLocation TemplateKWLoc,
5588 const DeclarationNameInfo &NameInfo,
5589 const TemplateArgumentListInfo *TemplateArgs) {
5590
5591 assert(TemplateArgs || TemplateKWLoc.isValid());
5592 DeclContext *DC;
5593 if (!(DC = computeDeclContext(SS, EnteringContext: false)) ||
5594 DC->isDependentContext() ||
5595 RequireCompleteDeclContext(SS, DC))
5596 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5597
5598 bool MemberOfUnknownSpecialization;
5599 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5600 if (LookupTemplateName(Found&: R, S: (Scope *)nullptr, SS, ObjectType: QualType(),
5601 /*Entering*/EnteringContext: false, MemberOfUnknownSpecialization,
5602 RequiredTemplate: TemplateKWLoc))
5603 return ExprError();
5604
5605 if (R.isAmbiguous())
5606 return ExprError();
5607
5608 if (R.empty()) {
5609 Diag(NameInfo.getLoc(), diag::err_no_member)
5610 << NameInfo.getName() << DC << SS.getRange();
5611 return ExprError();
5612 }
5613
5614 auto DiagnoseTypeTemplateDecl = [&](TemplateDecl *Temp,
5615 bool isTypeAliasTemplateDecl) {
5616 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
5617 << SS.getScopeRep() << NameInfo.getName().getAsString() << SS.getRange()
5618 << isTypeAliasTemplateDecl;
5619 Diag(Temp->getLocation(), diag::note_referenced_type_template) << 0;
5620 return ExprError();
5621 };
5622
5623 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>())
5624 return DiagnoseTypeTemplateDecl(Temp, false);
5625
5626 if (TypeAliasTemplateDecl *Temp = R.getAsSingle<TypeAliasTemplateDecl>())
5627 return DiagnoseTypeTemplateDecl(Temp, true);
5628
5629 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ RequiresADL: false, TemplateArgs);
5630}
5631
5632/// Form a template name from a name that is syntactically required to name a
5633/// template, either due to use of the 'template' keyword or because a name in
5634/// this syntactic context is assumed to name a template (C++ [temp.names]p2-4).
5635///
5636/// This action forms a template name given the name of the template and its
5637/// optional scope specifier. This is used when the 'template' keyword is used
5638/// or when the parsing context unambiguously treats a following '<' as
5639/// introducing a template argument list. Note that this may produce a
5640/// non-dependent template name if we can perform the lookup now and identify
5641/// the named template.
5642///
5643/// For example, given "x.MetaFun::template apply", the scope specifier
5644/// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
5645/// of the "template" keyword, and "apply" is the \p Name.
5646TemplateNameKind Sema::ActOnTemplateName(Scope *S,
5647 CXXScopeSpec &SS,
5648 SourceLocation TemplateKWLoc,
5649 const UnqualifiedId &Name,
5650 ParsedType ObjectType,
5651 bool EnteringContext,
5652 TemplateTy &Result,
5653 bool AllowInjectedClassName) {
5654 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
5655 Diag(TemplateKWLoc,
5656 getLangOpts().CPlusPlus11 ?
5657 diag::warn_cxx98_compat_template_outside_of_template :
5658 diag::ext_template_outside_of_template)
5659 << FixItHint::CreateRemoval(TemplateKWLoc);
5660
5661 if (SS.isInvalid())
5662 return TNK_Non_template;
5663
5664 // Figure out where isTemplateName is going to look.
5665 DeclContext *LookupCtx = nullptr;
5666 if (SS.isNotEmpty())
5667 LookupCtx = computeDeclContext(SS, EnteringContext);
5668 else if (ObjectType)
5669 LookupCtx = computeDeclContext(T: GetTypeFromParser(Ty: ObjectType));
5670
5671 // C++0x [temp.names]p5:
5672 // If a name prefixed by the keyword template is not the name of
5673 // a template, the program is ill-formed. [Note: the keyword
5674 // template may not be applied to non-template members of class
5675 // templates. -end note ] [ Note: as is the case with the
5676 // typename prefix, the template prefix is allowed in cases
5677 // where it is not strictly necessary; i.e., when the
5678 // nested-name-specifier or the expression on the left of the ->
5679 // or . is not dependent on a template-parameter, or the use
5680 // does not appear in the scope of a template. -end note]
5681 //
5682 // Note: C++03 was more strict here, because it banned the use of
5683 // the "template" keyword prior to a template-name that was not a
5684 // dependent name. C++ DR468 relaxed this requirement (the
5685 // "template" keyword is now permitted). We follow the C++0x
5686 // rules, even in C++03 mode with a warning, retroactively applying the DR.
5687 bool MemberOfUnknownSpecialization;
5688 TemplateNameKind TNK = isTemplateName(S, SS, hasTemplateKeyword: TemplateKWLoc.isValid(), Name,
5689 ObjectTypePtr: ObjectType, EnteringContext, TemplateResult&: Result,
5690 MemberOfUnknownSpecialization);
5691 if (TNK != TNK_Non_template) {
5692 // We resolved this to a (non-dependent) template name. Return it.
5693 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: LookupCtx);
5694 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
5695 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
5696 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
5697 // C++14 [class.qual]p2:
5698 // In a lookup in which function names are not ignored and the
5699 // nested-name-specifier nominates a class C, if the name specified
5700 // [...] is the injected-class-name of C, [...] the name is instead
5701 // considered to name the constructor
5702 //
5703 // We don't get here if naming the constructor would be valid, so we
5704 // just reject immediately and recover by treating the
5705 // injected-class-name as naming the template.
5706 Diag(Name.getBeginLoc(),
5707 diag::ext_out_of_line_qualified_id_type_names_constructor)
5708 << Name.Identifier
5709 << 0 /*injected-class-name used as template name*/
5710 << TemplateKWLoc.isValid();
5711 }
5712 return TNK;
5713 }
5714
5715 if (!MemberOfUnknownSpecialization) {
5716 // Didn't find a template name, and the lookup wasn't dependent.
5717 // Do the lookup again to determine if this is a "nothing found" case or
5718 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
5719 // need to do this.
5720 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
5721 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
5722 LookupOrdinaryName);
5723 bool MOUS;
5724 // Tell LookupTemplateName that we require a template so that it diagnoses
5725 // cases where it finds a non-template.
5726 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
5727 ? RequiredTemplateKind(TemplateKWLoc)
5728 : TemplateNameIsRequired;
5729 if (!LookupTemplateName(Found&: R, S, SS, ObjectType: ObjectType.get(), EnteringContext, MemberOfUnknownSpecialization&: MOUS,
5730 RequiredTemplate: RTK, ATK: nullptr, /*AllowTypoCorrection=*/false) &&
5731 !R.isAmbiguous()) {
5732 if (LookupCtx)
5733 Diag(Name.getBeginLoc(), diag::err_no_member)
5734 << DNI.getName() << LookupCtx << SS.getRange();
5735 else
5736 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
5737 << DNI.getName() << SS.getRange();
5738 }
5739 return TNK_Non_template;
5740 }
5741
5742 NestedNameSpecifier *Qualifier = SS.getScopeRep();
5743
5744 switch (Name.getKind()) {
5745 case UnqualifiedIdKind::IK_Identifier:
5746 Result = TemplateTy::make(
5747 P: Context.getDependentTemplateName(NNS: Qualifier, Name: Name.Identifier));
5748 return TNK_Dependent_template_name;
5749
5750 case UnqualifiedIdKind::IK_OperatorFunctionId:
5751 Result = TemplateTy::make(P: Context.getDependentTemplateName(
5752 NNS: Qualifier, Operator: Name.OperatorFunctionId.Operator));
5753 return TNK_Function_template;
5754
5755 case UnqualifiedIdKind::IK_LiteralOperatorId:
5756 // This is a kind of template name, but can never occur in a dependent
5757 // scope (literal operators can only be declared at namespace scope).
5758 break;
5759
5760 default:
5761 break;
5762 }
5763
5764 // This name cannot possibly name a dependent template. Diagnose this now
5765 // rather than building a dependent template name that can never be valid.
5766 Diag(Name.getBeginLoc(),
5767 diag::err_template_kw_refers_to_dependent_non_template)
5768 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5769 << TemplateKWLoc.isValid() << TemplateKWLoc;
5770 return TNK_Non_template;
5771}
5772
5773bool Sema::CheckTemplateTypeArgument(
5774 TemplateTypeParmDecl *Param, TemplateArgumentLoc &AL,
5775 SmallVectorImpl<TemplateArgument> &SugaredConverted,
5776 SmallVectorImpl<TemplateArgument> &CanonicalConverted) {
5777 const TemplateArgument &Arg = AL.getArgument();
5778 QualType ArgType;
5779 TypeSourceInfo *TSI = nullptr;
5780
5781 // Check template type parameter.
5782 switch(Arg.getKind()) {
5783 case TemplateArgument::Type:
5784 // C++ [temp.arg.type]p1:
5785 // A template-argument for a template-parameter which is a
5786 // type shall be a type-id.
5787 ArgType = Arg.getAsType();
5788 TSI = AL.getTypeSourceInfo();
5789 break;
5790 case TemplateArgument::Template:
5791 case TemplateArgument::TemplateExpansion: {
5792 // We have a template type parameter but the template argument
5793 // is a template without any arguments.
5794 SourceRange SR = AL.getSourceRange();
5795 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
5796 diagnoseMissingTemplateArguments(Name, Loc: SR.getEnd());
5797 return true;
5798 }
5799 case TemplateArgument::Expression: {
5800 // We have a template type parameter but the template argument is an
5801 // expression; see if maybe it is missing the "typename" keyword.
5802 CXXScopeSpec SS;
5803 DeclarationNameInfo NameInfo;
5804
5805 if (DependentScopeDeclRefExpr *ArgExpr =
5806 dyn_cast<DependentScopeDeclRefExpr>(Val: Arg.getAsExpr())) {
5807 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5808 NameInfo = ArgExpr->getNameInfo();
5809 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5810 dyn_cast<CXXDependentScopeMemberExpr>(Val: Arg.getAsExpr())) {
5811 if (ArgExpr->isImplicitAccess()) {
5812 SS.Adopt(Other: ArgExpr->getQualifierLoc());
5813 NameInfo = ArgExpr->getMemberNameInfo();
5814 }
5815 }
5816
5817 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5818 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5819 LookupParsedName(R&: Result, S: CurScope, SS: &SS);
5820
5821 if (Result.getAsSingle<TypeDecl>() ||
5822 Result.getResultKind() ==
5823 LookupResult::NotFoundInCurrentInstantiation) {
5824 assert(SS.getScopeRep() && "dependent scope expr must has a scope!");
5825 // Suggest that the user add 'typename' before the NNS.
5826 SourceLocation Loc = AL.getSourceRange().getBegin();
5827 Diag(Loc, getLangOpts().MSVCCompat
5828 ? diag::ext_ms_template_type_arg_missing_typename
5829 : diag::err_template_arg_must_be_type_suggest)
5830 << FixItHint::CreateInsertion(Loc, "typename ");
5831 NoteTemplateParameterLocation(*Param);
5832
5833 // Recover by synthesizing a type using the location information that we
5834 // already have.
5835 ArgType = Context.getDependentNameType(Keyword: ElaboratedTypeKeyword::Typename,
5836 NNS: SS.getScopeRep(), Name: II);
5837 TypeLocBuilder TLB;
5838 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: ArgType);
5839 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5840 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5841 TL.setNameLoc(NameInfo.getLoc());
5842 TSI = TLB.getTypeSourceInfo(Context, T: ArgType);
5843
5844 // Overwrite our input TemplateArgumentLoc so that we can recover
5845 // properly.
5846 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5847 TemplateArgumentLocInfo(TSI));
5848
5849 break;
5850 }
5851 }
5852 // fallthrough
5853 [[fallthrough]];
5854 }
5855 default: {
5856 // We allow instantiateing a template with template argument packs when
5857 // building deduction guides.
5858 if (Arg.getKind() == TemplateArgument::Pack &&
5859 CodeSynthesisContexts.back().Kind ==
5860 Sema::CodeSynthesisContext::BuildingDeductionGuides) {
5861 SugaredConverted.push_back(Elt: Arg);
5862 CanonicalConverted.push_back(Elt: Arg);
5863 return false;
5864 }
5865 // We have a template type parameter but the template argument
5866 // is not a type.
5867 SourceRange SR = AL.getSourceRange();
5868 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5869 NoteTemplateParameterLocation(*Param);
5870
5871 return true;
5872 }
5873 }
5874
5875 if (CheckTemplateArgument(Arg: TSI))
5876 return true;
5877
5878 // Objective-C ARC:
5879 // If an explicitly-specified template argument type is a lifetime type
5880 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5881 if (getLangOpts().ObjCAutoRefCount &&
5882 ArgType->isObjCLifetimeType() &&
5883 !ArgType.getObjCLifetime()) {
5884 Qualifiers Qs;
5885 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5886 ArgType = Context.getQualifiedType(T: ArgType, Qs);
5887 }
5888
5889 SugaredConverted.push_back(Elt: TemplateArgument(ArgType));
5890 CanonicalConverted.push_back(
5891 Elt: TemplateArgument(Context.getCanonicalType(T: ArgType)));
5892 return false;
5893}
5894
5895/// Substitute template arguments into the default template argument for
5896/// the given template type parameter.
5897///
5898/// \param SemaRef the semantic analysis object for which we are performing
5899/// the substitution.
5900///
5901/// \param Template the template that we are synthesizing template arguments
5902/// for.
5903///
5904/// \param TemplateLoc the location of the template name that started the
5905/// template-id we are checking.
5906///
5907/// \param RAngleLoc the location of the right angle bracket ('>') that
5908/// terminates the template-id.
5909///
5910/// \param Param the template template parameter whose default we are
5911/// substituting into.
5912///
5913/// \param Converted the list of template arguments provided for template
5914/// parameters that precede \p Param in the template parameter list.
5915/// \returns the substituted template argument, or NULL if an error occurred.
5916static TypeSourceInfo *SubstDefaultTemplateArgument(
5917 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5918 SourceLocation RAngleLoc, TemplateTypeParmDecl *Param,
5919 ArrayRef<TemplateArgument> SugaredConverted,
5920 ArrayRef<TemplateArgument> CanonicalConverted) {
5921 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
5922
5923 // If the argument type is dependent, instantiate it now based
5924 // on the previously-computed template arguments.
5925 if (ArgType->getType()->isInstantiationDependentType()) {
5926 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5927 SugaredConverted,
5928 SourceRange(TemplateLoc, RAngleLoc));
5929 if (Inst.isInvalid())
5930 return nullptr;
5931
5932 // Only substitute for the innermost template argument list.
5933 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5934 /*Final=*/true);
5935 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5936 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5937
5938 bool ForLambdaCallOperator = false;
5939 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5940 ForLambdaCallOperator = Rec->isLambda();
5941 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5942 !ForLambdaCallOperator);
5943 ArgType =
5944 SemaRef.SubstType(ArgType, TemplateArgLists,
5945 Param->getDefaultArgumentLoc(), Param->getDeclName());
5946 }
5947
5948 return ArgType;
5949}
5950
5951/// Substitute template arguments into the default template argument for
5952/// the given non-type template parameter.
5953///
5954/// \param SemaRef the semantic analysis object for which we are performing
5955/// the substitution.
5956///
5957/// \param Template the template that we are synthesizing template arguments
5958/// for.
5959///
5960/// \param TemplateLoc the location of the template name that started the
5961/// template-id we are checking.
5962///
5963/// \param RAngleLoc the location of the right angle bracket ('>') that
5964/// terminates the template-id.
5965///
5966/// \param Param the non-type template parameter whose default we are
5967/// substituting into.
5968///
5969/// \param Converted the list of template arguments provided for template
5970/// parameters that precede \p Param in the template parameter list.
5971///
5972/// \returns the substituted template argument, or NULL if an error occurred.
5973static ExprResult SubstDefaultTemplateArgument(
5974 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
5975 SourceLocation RAngleLoc, NonTypeTemplateParmDecl *Param,
5976 ArrayRef<TemplateArgument> SugaredConverted,
5977 ArrayRef<TemplateArgument> CanonicalConverted) {
5978 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc, Param, Template,
5979 SugaredConverted,
5980 SourceRange(TemplateLoc, RAngleLoc));
5981 if (Inst.isInvalid())
5982 return ExprError();
5983
5984 // Only substitute for the innermost template argument list.
5985 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
5986 /*Final=*/true);
5987 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5988 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
5989
5990 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5991 EnterExpressionEvaluationContext ConstantEvaluated(
5992 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5993 return SemaRef.SubstExpr(E: Param->getDefaultArgument(), TemplateArgs: TemplateArgLists);
5994}
5995
5996/// Substitute template arguments into the default template argument for
5997/// the given template template parameter.
5998///
5999/// \param SemaRef the semantic analysis object for which we are performing
6000/// the substitution.
6001///
6002/// \param Template the template that we are synthesizing template arguments
6003/// for.
6004///
6005/// \param TemplateLoc the location of the template name that started the
6006/// template-id we are checking.
6007///
6008/// \param RAngleLoc the location of the right angle bracket ('>') that
6009/// terminates the template-id.
6010///
6011/// \param Param the template template parameter whose default we are
6012/// substituting into.
6013///
6014/// \param Converted the list of template arguments provided for template
6015/// parameters that precede \p Param in the template parameter list.
6016///
6017/// \param QualifierLoc Will be set to the nested-name-specifier (with
6018/// source-location information) that precedes the template name.
6019///
6020/// \returns the substituted template argument, or NULL if an error occurred.
6021static TemplateName SubstDefaultTemplateArgument(
6022 Sema &SemaRef, TemplateDecl *Template, SourceLocation TemplateLoc,
6023 SourceLocation RAngleLoc, TemplateTemplateParmDecl *Param,
6024 ArrayRef<TemplateArgument> SugaredConverted,
6025 ArrayRef<TemplateArgument> CanonicalConverted,
6026 NestedNameSpecifierLoc &QualifierLoc) {
6027 Sema::InstantiatingTemplate Inst(
6028 SemaRef, TemplateLoc, TemplateParameter(Param), Template,
6029 SugaredConverted, SourceRange(TemplateLoc, RAngleLoc));
6030 if (Inst.isInvalid())
6031 return TemplateName();
6032
6033 // Only substitute for the innermost template argument list.
6034 MultiLevelTemplateArgumentList TemplateArgLists(Template, SugaredConverted,
6035 /*Final=*/true);
6036 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
6037 TemplateArgLists.addOuterTemplateArguments(std::nullopt);
6038
6039 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
6040 // Substitute into the nested-name-specifier first,
6041 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
6042 if (QualifierLoc) {
6043 QualifierLoc =
6044 SemaRef.SubstNestedNameSpecifierLoc(NNS: QualifierLoc, TemplateArgs: TemplateArgLists);
6045 if (!QualifierLoc)
6046 return TemplateName();
6047 }
6048
6049 return SemaRef.SubstTemplateName(
6050 QualifierLoc,
6051 Name: Param->getDefaultArgument().getArgument().getAsTemplate(),
6052 Loc: Param->getDefaultArgument().getTemplateNameLoc(),
6053 TemplateArgs: TemplateArgLists);
6054}
6055
6056/// If the given template parameter has a default template
6057/// argument, substitute into that default template argument and
6058/// return the corresponding template argument.
6059TemplateArgumentLoc Sema::SubstDefaultTemplateArgumentIfAvailable(
6060 TemplateDecl *Template, SourceLocation TemplateLoc,
6061 SourceLocation RAngleLoc, Decl *Param,
6062 ArrayRef<TemplateArgument> SugaredConverted,
6063 ArrayRef<TemplateArgument> CanonicalConverted, bool &HasDefaultArg) {
6064 HasDefaultArg = false;
6065
6066 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
6067 if (!hasReachableDefaultArgument(TypeParm))
6068 return TemplateArgumentLoc();
6069
6070 HasDefaultArg = true;
6071 TypeSourceInfo *DI = SubstDefaultTemplateArgument(
6072 SemaRef&: *this, Template, TemplateLoc, RAngleLoc, Param: TypeParm, SugaredConverted,
6073 CanonicalConverted);
6074 if (DI)
6075 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
6076
6077 return TemplateArgumentLoc();
6078 }
6079
6080 if (NonTypeTemplateParmDecl *NonTypeParm
6081 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
6082 if (!hasReachableDefaultArgument(NonTypeParm))
6083 return TemplateArgumentLoc();
6084
6085 HasDefaultArg = true;
6086 ExprResult Arg = SubstDefaultTemplateArgument(
6087 SemaRef&: *this, Template, TemplateLoc, RAngleLoc, Param: NonTypeParm, SugaredConverted,
6088 CanonicalConverted);
6089 if (Arg.isInvalid())
6090 return TemplateArgumentLoc();
6091
6092 Expr *ArgE = Arg.getAs<Expr>();
6093 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
6094 }
6095
6096 TemplateTemplateParmDecl *TempTempParm
6097 = cast<TemplateTemplateParmDecl>(Val: Param);
6098 if (!hasReachableDefaultArgument(TempTempParm))
6099 return TemplateArgumentLoc();
6100
6101 HasDefaultArg = true;
6102 NestedNameSpecifierLoc QualifierLoc;
6103 TemplateName TName = SubstDefaultTemplateArgument(
6104 SemaRef&: *this, Template, TemplateLoc, RAngleLoc, Param: TempTempParm, SugaredConverted,
6105 CanonicalConverted, QualifierLoc);
6106 if (TName.isNull())
6107 return TemplateArgumentLoc();
6108
6109 return TemplateArgumentLoc(
6110 Context, TemplateArgument(TName),
6111 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
6112 TempTempParm->getDefaultArgument().getTemplateNameLoc());
6113}
6114
6115/// Convert a template-argument that we parsed as a type into a template, if
6116/// possible. C++ permits injected-class-names to perform dual service as
6117/// template template arguments and as template type arguments.
6118static TemplateArgumentLoc
6119convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
6120 // Extract and step over any surrounding nested-name-specifier.
6121 NestedNameSpecifierLoc QualLoc;
6122 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
6123 if (ETLoc.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None)
6124 return TemplateArgumentLoc();
6125
6126 QualLoc = ETLoc.getQualifierLoc();
6127 TLoc = ETLoc.getNamedTypeLoc();
6128 }
6129 // If this type was written as an injected-class-name, it can be used as a
6130 // template template argument.
6131 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
6132 return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
6133 QualLoc, InjLoc.getNameLoc());
6134
6135 // If this type was written as an injected-class-name, it may have been
6136 // converted to a RecordType during instantiation. If the RecordType is
6137 // *not* wrapped in a TemplateSpecializationType and denotes a class
6138 // template specialization, it must have come from an injected-class-name.
6139 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
6140 if (auto *CTSD =
6141 dyn_cast<ClassTemplateSpecializationDecl>(Val: RecLoc.getDecl()))
6142 return TemplateArgumentLoc(Context,
6143 TemplateName(CTSD->getSpecializedTemplate()),
6144 QualLoc, RecLoc.getNameLoc());
6145
6146 return TemplateArgumentLoc();
6147}
6148
6149/// Check that the given template argument corresponds to the given
6150/// template parameter.
6151///
6152/// \param Param The template parameter against which the argument will be
6153/// checked.
6154///
6155/// \param Arg The template argument, which may be updated due to conversions.
6156///
6157/// \param Template The template in which the template argument resides.
6158///
6159/// \param TemplateLoc The location of the template name for the template
6160/// whose argument list we're matching.
6161///
6162/// \param RAngleLoc The location of the right angle bracket ('>') that closes
6163/// the template argument list.
6164///
6165/// \param ArgumentPackIndex The index into the argument pack where this
6166/// argument will be placed. Only valid if the parameter is a parameter pack.
6167///
6168/// \param Converted The checked, converted argument will be added to the
6169/// end of this small vector.
6170///
6171/// \param CTAK Describes how we arrived at this particular template argument:
6172/// explicitly written, deduced, etc.
6173///
6174/// \returns true on error, false otherwise.
6175bool Sema::CheckTemplateArgument(
6176 NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template,
6177 SourceLocation TemplateLoc, SourceLocation RAngleLoc,
6178 unsigned ArgumentPackIndex,
6179 SmallVectorImpl<TemplateArgument> &SugaredConverted,
6180 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
6181 CheckTemplateArgumentKind CTAK) {
6182 // Check template type parameters.
6183 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param))
6184 return CheckTemplateTypeArgument(Param: TTP, AL&: Arg, SugaredConverted,
6185 CanonicalConverted);
6186
6187 // Check non-type template parameters.
6188 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
6189 // Do substitution on the type of the non-type template parameter
6190 // with the template arguments we've seen thus far. But if the
6191 // template has a dependent context then we cannot substitute yet.
6192 QualType NTTPType = NTTP->getType();
6193 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
6194 NTTPType = NTTP->getExpansionType(I: ArgumentPackIndex);
6195
6196 if (NTTPType->isInstantiationDependentType() &&
6197 !isa<TemplateTemplateParmDecl>(Val: Template) &&
6198 !Template->getDeclContext()->isDependentContext()) {
6199 // Do substitution on the type of the non-type template parameter.
6200 InstantiatingTemplate Inst(*this, TemplateLoc, Template, NTTP,
6201 SugaredConverted,
6202 SourceRange(TemplateLoc, RAngleLoc));
6203 if (Inst.isInvalid())
6204 return true;
6205
6206 MultiLevelTemplateArgumentList MLTAL(Template, SugaredConverted,
6207 /*Final=*/true);
6208 // If the parameter is a pack expansion, expand this slice of the pack.
6209 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
6210 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
6211 ArgumentPackIndex);
6212 NTTPType = SubstType(PET->getPattern(), MLTAL, NTTP->getLocation(),
6213 NTTP->getDeclName());
6214 } else {
6215 NTTPType = SubstType(NTTPType, MLTAL, NTTP->getLocation(),
6216 NTTP->getDeclName());
6217 }
6218
6219 // If that worked, check the non-type template parameter type
6220 // for validity.
6221 if (!NTTPType.isNull())
6222 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
6223 NTTP->getLocation());
6224 if (NTTPType.isNull())
6225 return true;
6226 }
6227
6228 switch (Arg.getArgument().getKind()) {
6229 case TemplateArgument::Null:
6230 llvm_unreachable("Should never see a NULL template argument here");
6231
6232 case TemplateArgument::Expression: {
6233 Expr *E = Arg.getArgument().getAsExpr();
6234 TemplateArgument SugaredResult, CanonicalResult;
6235 unsigned CurSFINAEErrors = NumSFINAEErrors;
6236 ExprResult Res = CheckTemplateArgument(Param: NTTP, InstantiatedParamType: NTTPType, Arg: E, SugaredConverted&: SugaredResult,
6237 CanonicalConverted&: CanonicalResult, CTAK);
6238 if (Res.isInvalid())
6239 return true;
6240 // If the current template argument causes an error, give up now.
6241 if (CurSFINAEErrors < NumSFINAEErrors)
6242 return true;
6243
6244 // If the resulting expression is new, then use it in place of the
6245 // old expression in the template argument.
6246 if (Res.get() != E) {
6247 TemplateArgument TA(Res.get());
6248 Arg = TemplateArgumentLoc(TA, Res.get());
6249 }
6250
6251 SugaredConverted.push_back(Elt: SugaredResult);
6252 CanonicalConverted.push_back(Elt: CanonicalResult);
6253 break;
6254 }
6255
6256 case TemplateArgument::Declaration:
6257 case TemplateArgument::Integral:
6258 case TemplateArgument::StructuralValue:
6259 case TemplateArgument::NullPtr:
6260 // We've already checked this template argument, so just copy
6261 // it to the list of converted arguments.
6262 SugaredConverted.push_back(Elt: Arg.getArgument());
6263 CanonicalConverted.push_back(
6264 Elt: Context.getCanonicalTemplateArgument(Arg: Arg.getArgument()));
6265 break;
6266
6267 case TemplateArgument::Template:
6268 case TemplateArgument::TemplateExpansion:
6269 // We were given a template template argument. It may not be ill-formed;
6270 // see below.
6271 if (DependentTemplateName *DTN
6272 = Arg.getArgument().getAsTemplateOrTemplatePattern()
6273 .getAsDependentTemplateName()) {
6274 // We have a template argument such as \c T::template X, which we
6275 // parsed as a template template argument. However, since we now
6276 // know that we need a non-type template argument, convert this
6277 // template name into an expression.
6278
6279 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
6280 Arg.getTemplateNameLoc());
6281
6282 CXXScopeSpec SS;
6283 SS.Adopt(Other: Arg.getTemplateQualifierLoc());
6284 // FIXME: the template-template arg was a DependentTemplateName,
6285 // so it was provided with a template keyword. However, its source
6286 // location is not stored in the template argument structure.
6287 SourceLocation TemplateKWLoc;
6288 ExprResult E = DependentScopeDeclRefExpr::Create(
6289 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
6290 TemplateArgs: nullptr);
6291
6292 // If we parsed the template argument as a pack expansion, create a
6293 // pack expansion expression.
6294 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
6295 E = ActOnPackExpansion(Pattern: E.get(), EllipsisLoc: Arg.getTemplateEllipsisLoc());
6296 if (E.isInvalid())
6297 return true;
6298 }
6299
6300 TemplateArgument SugaredResult, CanonicalResult;
6301 E = CheckTemplateArgument(Param: NTTP, InstantiatedParamType: NTTPType, Arg: E.get(), SugaredConverted&: SugaredResult,
6302 CanonicalConverted&: CanonicalResult, CTAK: CTAK_Specified);
6303 if (E.isInvalid())
6304 return true;
6305
6306 SugaredConverted.push_back(Elt: SugaredResult);
6307 CanonicalConverted.push_back(Elt: CanonicalResult);
6308 break;
6309 }
6310
6311 // We have a template argument that actually does refer to a class
6312 // template, alias template, or template template parameter, and
6313 // therefore cannot be a non-type template argument.
6314 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
6315 << Arg.getSourceRange();
6316 NoteTemplateParameterLocation(Decl: *Param);
6317
6318 return true;
6319
6320 case TemplateArgument::Type: {
6321 // We have a non-type template parameter but the template
6322 // argument is a type.
6323
6324 // C++ [temp.arg]p2:
6325 // In a template-argument, an ambiguity between a type-id and
6326 // an expression is resolved to a type-id, regardless of the
6327 // form of the corresponding template-parameter.
6328 //
6329 // We warn specifically about this case, since it can be rather
6330 // confusing for users.
6331 QualType T = Arg.getArgument().getAsType();
6332 SourceRange SR = Arg.getSourceRange();
6333 if (T->isFunctionType())
6334 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
6335 else
6336 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
6337 NoteTemplateParameterLocation(Decl: *Param);
6338 return true;
6339 }
6340
6341 case TemplateArgument::Pack:
6342 llvm_unreachable("Caller must expand template argument packs");
6343 }
6344
6345 return false;
6346 }
6347
6348
6349 // Check template template parameters.
6350 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Val: Param);
6351
6352 TemplateParameterList *Params = TempParm->getTemplateParameters();
6353 if (TempParm->isExpandedParameterPack())
6354 Params = TempParm->getExpansionTemplateParameters(I: ArgumentPackIndex);
6355
6356 // Substitute into the template parameter list of the template
6357 // template parameter, since previously-supplied template arguments
6358 // may appear within the template template parameter.
6359 //
6360 // FIXME: Skip this if the parameters aren't instantiation-dependent.
6361 {
6362 // Set up a template instantiation context.
6363 LocalInstantiationScope Scope(*this);
6364 InstantiatingTemplate Inst(*this, TemplateLoc, Template, TempParm,
6365 SugaredConverted,
6366 SourceRange(TemplateLoc, RAngleLoc));
6367 if (Inst.isInvalid())
6368 return true;
6369
6370 Params =
6371 SubstTemplateParams(Params, Owner: CurContext,
6372 TemplateArgs: MultiLevelTemplateArgumentList(
6373 Template, SugaredConverted, /*Final=*/true),
6374 /*EvaluateConstraints=*/false);
6375 if (!Params)
6376 return true;
6377 }
6378
6379 // C++1z [temp.local]p1: (DR1004)
6380 // When [the injected-class-name] is used [...] as a template-argument for
6381 // a template template-parameter [...] it refers to the class template
6382 // itself.
6383 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
6384 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
6385 Context, TLoc: Arg.getTypeSourceInfo()->getTypeLoc());
6386 if (!ConvertedArg.getArgument().isNull())
6387 Arg = ConvertedArg;
6388 }
6389
6390 switch (Arg.getArgument().getKind()) {
6391 case TemplateArgument::Null:
6392 llvm_unreachable("Should never see a NULL template argument here");
6393
6394 case TemplateArgument::Template:
6395 case TemplateArgument::TemplateExpansion:
6396 if (CheckTemplateTemplateArgument(Param: TempParm, Params, Arg))
6397 return true;
6398
6399 SugaredConverted.push_back(Elt: Arg.getArgument());
6400 CanonicalConverted.push_back(
6401 Elt: Context.getCanonicalTemplateArgument(Arg: Arg.getArgument()));
6402 break;
6403
6404 case TemplateArgument::Expression:
6405 case TemplateArgument::Type:
6406 // We have a template template parameter but the template
6407 // argument does not refer to a template.
6408 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
6409 << getLangOpts().CPlusPlus11;
6410 return true;
6411
6412 case TemplateArgument::Declaration:
6413 case TemplateArgument::Integral:
6414 case TemplateArgument::StructuralValue:
6415 case TemplateArgument::NullPtr:
6416 llvm_unreachable("non-type argument with template template parameter");
6417
6418 case TemplateArgument::Pack:
6419 llvm_unreachable("Caller must expand template argument packs");
6420 }
6421
6422 return false;
6423}
6424
6425/// Diagnose a missing template argument.
6426template<typename TemplateParmDecl>
6427static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
6428 TemplateDecl *TD,
6429 const TemplateParmDecl *D,
6430 TemplateArgumentListInfo &Args) {
6431 // Dig out the most recent declaration of the template parameter; there may be
6432 // declarations of the template that are more recent than TD.
6433 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
6434 ->getTemplateParameters()
6435 ->getParam(D->getIndex()));
6436
6437 // If there's a default argument that's not reachable, diagnose that we're
6438 // missing a module import.
6439 llvm::SmallVector<Module*, 8> Modules;
6440 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, Modules: &Modules)) {
6441 S.diagnoseMissingImport(Loc, cast<NamedDecl>(Val: TD),
6442 D->getDefaultArgumentLoc(), Modules,
6443 Sema::MissingImportKind::DefaultArgument,
6444 /*Recover*/true);
6445 return true;
6446 }
6447
6448 // FIXME: If there's a more recent default argument that *is* visible,
6449 // diagnose that it was declared too late.
6450
6451 TemplateParameterList *Params = TD->getTemplateParameters();
6452
6453 S.Diag(Loc, diag::err_template_arg_list_different_arity)
6454 << /*not enough args*/0
6455 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
6456 << TD;
6457 S.NoteTemplateLocation(*TD, Params->getSourceRange());
6458 return true;
6459}
6460
6461/// Check that the given template argument list is well-formed
6462/// for specializing the given template.
6463bool Sema::CheckTemplateArgumentList(
6464 TemplateDecl *Template, SourceLocation TemplateLoc,
6465 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
6466 SmallVectorImpl<TemplateArgument> &SugaredConverted,
6467 SmallVectorImpl<TemplateArgument> &CanonicalConverted,
6468 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
6469
6470 if (ConstraintsNotSatisfied)
6471 *ConstraintsNotSatisfied = false;
6472
6473 // Make a copy of the template arguments for processing. Only make the
6474 // changes at the end when successful in matching the arguments to the
6475 // template.
6476 TemplateArgumentListInfo NewArgs = TemplateArgs;
6477
6478 TemplateParameterList *Params = GetTemplateParameterList(TD: Template);
6479
6480 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
6481
6482 // C++ [temp.arg]p1:
6483 // [...] The type and form of each template-argument specified in
6484 // a template-id shall match the type and form specified for the
6485 // corresponding parameter declared by the template in its
6486 // template-parameter-list.
6487 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Val: Template);
6488 SmallVector<TemplateArgument, 2> SugaredArgumentPack;
6489 SmallVector<TemplateArgument, 2> CanonicalArgumentPack;
6490 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
6491 LocalInstantiationScope InstScope(*this, true);
6492 for (TemplateParameterList::iterator Param = Params->begin(),
6493 ParamEnd = Params->end();
6494 Param != ParamEnd; /* increment in loop */) {
6495 // If we have an expanded parameter pack, make sure we don't have too
6496 // many arguments.
6497 if (std::optional<unsigned> Expansions = getExpandedPackSize(Param: *Param)) {
6498 if (*Expansions == SugaredArgumentPack.size()) {
6499 // We're done with this parameter pack. Pack up its arguments and add
6500 // them to the list.
6501 SugaredConverted.push_back(
6502 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6503 SugaredArgumentPack.clear();
6504
6505 CanonicalConverted.push_back(
6506 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6507 CanonicalArgumentPack.clear();
6508
6509 // This argument is assigned to the next parameter.
6510 ++Param;
6511 continue;
6512 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
6513 // Not enough arguments for this parameter pack.
6514 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6515 << /*not enough args*/0
6516 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
6517 << Template;
6518 NoteTemplateLocation(*Template, Params->getSourceRange());
6519 return true;
6520 }
6521 }
6522
6523 if (ArgIdx < NumArgs) {
6524 // Check the template argument we were given.
6525 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template, TemplateLoc,
6526 RAngleLoc, SugaredArgumentPack.size(),
6527 SugaredConverted, CanonicalConverted,
6528 CTAK_Specified))
6529 return true;
6530
6531 CanonicalConverted.back().setIsDefaulted(
6532 clang::isSubstitutedDefaultArgument(
6533 Ctx&: Context, Arg: NewArgs[ArgIdx].getArgument(), Param: *Param,
6534 Args: CanonicalConverted, Depth: Params->getDepth()));
6535
6536 bool PackExpansionIntoNonPack =
6537 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
6538 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(Param: *Param));
6539 if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Val: Template) ||
6540 isa<ConceptDecl>(Val: Template))) {
6541 // Core issue 1430: we have a pack expansion as an argument to an
6542 // alias template, and it's not part of a parameter pack. This
6543 // can't be canonicalized, so reject it now.
6544 // As for concepts - we cannot normalize constraints where this
6545 // situation exists.
6546 Diag(NewArgs[ArgIdx].getLocation(),
6547 diag::err_template_expansion_into_fixed_list)
6548 << (isa<ConceptDecl>(Template) ? 1 : 0)
6549 << NewArgs[ArgIdx].getSourceRange();
6550 NoteTemplateParameterLocation(Decl: **Param);
6551 return true;
6552 }
6553
6554 // We're now done with this argument.
6555 ++ArgIdx;
6556
6557 if ((*Param)->isTemplateParameterPack()) {
6558 // The template parameter was a template parameter pack, so take the
6559 // deduced argument and place it on the argument pack. Note that we
6560 // stay on the same template parameter so that we can deduce more
6561 // arguments.
6562 SugaredArgumentPack.push_back(Elt: SugaredConverted.pop_back_val());
6563 CanonicalArgumentPack.push_back(Elt: CanonicalConverted.pop_back_val());
6564 } else {
6565 // Move to the next template parameter.
6566 ++Param;
6567 }
6568
6569 // If we just saw a pack expansion into a non-pack, then directly convert
6570 // the remaining arguments, because we don't know what parameters they'll
6571 // match up with.
6572 if (PackExpansionIntoNonPack) {
6573 if (!SugaredArgumentPack.empty()) {
6574 // If we were part way through filling in an expanded parameter pack,
6575 // fall back to just producing individual arguments.
6576 SugaredConverted.insert(I: SugaredConverted.end(),
6577 From: SugaredArgumentPack.begin(),
6578 To: SugaredArgumentPack.end());
6579 SugaredArgumentPack.clear();
6580
6581 CanonicalConverted.insert(I: CanonicalConverted.end(),
6582 From: CanonicalArgumentPack.begin(),
6583 To: CanonicalArgumentPack.end());
6584 CanonicalArgumentPack.clear();
6585 }
6586
6587 while (ArgIdx < NumArgs) {
6588 const TemplateArgument &Arg = NewArgs[ArgIdx].getArgument();
6589 SugaredConverted.push_back(Elt: Arg);
6590 CanonicalConverted.push_back(
6591 Elt: Context.getCanonicalTemplateArgument(Arg));
6592 ++ArgIdx;
6593 }
6594
6595 return false;
6596 }
6597
6598 continue;
6599 }
6600
6601 // If we're checking a partial template argument list, we're done.
6602 if (PartialTemplateArgs) {
6603 if ((*Param)->isTemplateParameterPack() && !SugaredArgumentPack.empty()) {
6604 SugaredConverted.push_back(
6605 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6606 CanonicalConverted.push_back(
6607 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6608 }
6609 return false;
6610 }
6611
6612 // If we have a template parameter pack with no more corresponding
6613 // arguments, just break out now and we'll fill in the argument pack below.
6614 if ((*Param)->isTemplateParameterPack()) {
6615 assert(!getExpandedPackSize(*Param) &&
6616 "Should have dealt with this already");
6617
6618 // A non-expanded parameter pack before the end of the parameter list
6619 // only occurs for an ill-formed template parameter list, unless we've
6620 // got a partial argument list for a function template, so just bail out.
6621 if (Param + 1 != ParamEnd) {
6622 assert(
6623 (Template->getMostRecentDecl()->getKind() != Decl::Kind::Concept) &&
6624 "Concept templates must have parameter packs at the end.");
6625 return true;
6626 }
6627
6628 SugaredConverted.push_back(
6629 Elt: TemplateArgument::CreatePackCopy(Context, Args: SugaredArgumentPack));
6630 SugaredArgumentPack.clear();
6631
6632 CanonicalConverted.push_back(
6633 Elt: TemplateArgument::CreatePackCopy(Context, Args: CanonicalArgumentPack));
6634 CanonicalArgumentPack.clear();
6635
6636 ++Param;
6637 continue;
6638 }
6639
6640 // Check whether we have a default argument.
6641 TemplateArgumentLoc Arg;
6642
6643 // Retrieve the default template argument from the template
6644 // parameter. For each kind of template parameter, we substitute the
6645 // template arguments provided thus far and any "outer" template arguments
6646 // (when the template parameter was part of a nested template) into
6647 // the default argument.
6648 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: *Param)) {
6649 if (!hasReachableDefaultArgument(TTP))
6650 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: TTP,
6651 Args&: NewArgs);
6652
6653 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(
6654 SemaRef&: *this, Template, TemplateLoc, RAngleLoc, Param: TTP, SugaredConverted,
6655 CanonicalConverted);
6656 if (!ArgType)
6657 return true;
6658
6659 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
6660 ArgType);
6661 } else if (NonTypeTemplateParmDecl *NTTP
6662 = dyn_cast<NonTypeTemplateParmDecl>(Val: *Param)) {
6663 if (!hasReachableDefaultArgument(NTTP))
6664 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: NTTP,
6665 Args&: NewArgs);
6666
6667 ExprResult E = SubstDefaultTemplateArgument(
6668 SemaRef&: *this, Template, TemplateLoc, RAngleLoc, Param: NTTP, SugaredConverted,
6669 CanonicalConverted);
6670 if (E.isInvalid())
6671 return true;
6672
6673 Expr *Ex = E.getAs<Expr>();
6674 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
6675 } else {
6676 TemplateTemplateParmDecl *TempParm
6677 = cast<TemplateTemplateParmDecl>(Val: *Param);
6678
6679 if (!hasReachableDefaultArgument(TempParm))
6680 return diagnoseMissingArgument(S&: *this, Loc: TemplateLoc, TD: Template, D: TempParm,
6681 Args&: NewArgs);
6682
6683 NestedNameSpecifierLoc QualifierLoc;
6684 TemplateName Name = SubstDefaultTemplateArgument(
6685 SemaRef&: *this, Template, TemplateLoc, RAngleLoc, Param: TempParm, SugaredConverted,
6686 CanonicalConverted, QualifierLoc);
6687 if (Name.isNull())
6688 return true;
6689
6690 Arg = TemplateArgumentLoc(
6691 Context, TemplateArgument(Name), QualifierLoc,
6692 TempParm->getDefaultArgument().getTemplateNameLoc());
6693 }
6694
6695 // Introduce an instantiation record that describes where we are using
6696 // the default template argument. We're not actually instantiating a
6697 // template here, we just create this object to put a note into the
6698 // context stack.
6699 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param,
6700 SugaredConverted,
6701 SourceRange(TemplateLoc, RAngleLoc));
6702 if (Inst.isInvalid())
6703 return true;
6704
6705 // Check the default template argument.
6706 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc, RAngleLoc, 0,
6707 SugaredConverted, CanonicalConverted,
6708 CTAK_Specified))
6709 return true;
6710
6711 CanonicalConverted.back().setIsDefaulted(true);
6712
6713 // Core issue 150 (assumed resolution): if this is a template template
6714 // parameter, keep track of the default template arguments from the
6715 // template definition.
6716 if (isTemplateTemplateParameter)
6717 NewArgs.addArgument(Loc: Arg);
6718
6719 // Move to the next template parameter and argument.
6720 ++Param;
6721 ++ArgIdx;
6722 }
6723
6724 // If we're performing a partial argument substitution, allow any trailing
6725 // pack expansions; they might be empty. This can happen even if
6726 // PartialTemplateArgs is false (the list of arguments is complete but
6727 // still dependent).
6728 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
6729 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
6730 while (ArgIdx < NumArgs &&
6731 NewArgs[ArgIdx].getArgument().isPackExpansion()) {
6732 const TemplateArgument &Arg = NewArgs[ArgIdx++].getArgument();
6733 SugaredConverted.push_back(Elt: Arg);
6734 CanonicalConverted.push_back(Elt: Context.getCanonicalTemplateArgument(Arg));
6735 }
6736 }
6737
6738 // If we have any leftover arguments, then there were too many arguments.
6739 // Complain and fail.
6740 if (ArgIdx < NumArgs) {
6741 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
6742 << /*too many args*/1
6743 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
6744 << Template
6745 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
6746 NoteTemplateLocation(*Template, Params->getSourceRange());
6747 return true;
6748 }
6749
6750 // No problems found with the new argument list, propagate changes back
6751 // to caller.
6752 if (UpdateArgsWithConversions)
6753 TemplateArgs = std::move(NewArgs);
6754
6755 if (!PartialTemplateArgs) {
6756 // Setup the context/ThisScope for the case where we are needing to
6757 // re-instantiate constraints outside of normal instantiation.
6758 DeclContext *NewContext = Template->getDeclContext();
6759
6760 // If this template is in a template, make sure we extract the templated
6761 // decl.
6762 if (auto *TD = dyn_cast<TemplateDecl>(NewContext))
6763 NewContext = Decl::castToDeclContext(TD->getTemplatedDecl());
6764 auto *RD = dyn_cast<CXXRecordDecl>(Val: NewContext);
6765
6766 Qualifiers ThisQuals;
6767 if (const auto *Method =
6768 dyn_cast_or_null<CXXMethodDecl>(Val: Template->getTemplatedDecl()))
6769 ThisQuals = Method->getMethodQualifiers();
6770
6771 ContextRAII Context(*this, NewContext);
6772 CXXThisScopeRAII(*this, RD, ThisQuals, RD != nullptr);
6773
6774 MultiLevelTemplateArgumentList MLTAL = getTemplateInstantiationArgs(
6775 Template, NewContext, /*Final=*/false, CanonicalConverted,
6776 /*RelativeToPrimary=*/true,
6777 /*Pattern=*/nullptr,
6778 /*ForConceptInstantiation=*/true);
6779 if (EnsureTemplateArgumentListConstraints(
6780 Template, TemplateArgs: MLTAL,
6781 TemplateIDRange: SourceRange(TemplateLoc, TemplateArgs.getRAngleLoc()))) {
6782 if (ConstraintsNotSatisfied)
6783 *ConstraintsNotSatisfied = true;
6784 return true;
6785 }
6786 }
6787
6788 return false;
6789}
6790
6791namespace {
6792 class UnnamedLocalNoLinkageFinder
6793 : public TypeVisitor<UnnamedLocalNoLinkageFinder, bool>
6794 {
6795 Sema &S;
6796 SourceRange SR;
6797
6798 typedef TypeVisitor<UnnamedLocalNoLinkageFinder, bool> inherited;
6799
6800 public:
6801 UnnamedLocalNoLinkageFinder(Sema &S, SourceRange SR) : S(S), SR(SR) { }
6802
6803 bool Visit(QualType T) {
6804 return T.isNull() ? false : inherited::Visit(T: T.getTypePtr());
6805 }
6806
6807#define TYPE(Class, Parent) \
6808 bool Visit##Class##Type(const Class##Type *);
6809#define ABSTRACT_TYPE(Class, Parent) \
6810 bool Visit##Class##Type(const Class##Type *) { return false; }
6811#define NON_CANONICAL_TYPE(Class, Parent) \
6812 bool Visit##Class##Type(const Class##Type *) { return false; }
6813#include "clang/AST/TypeNodes.inc"
6814
6815 bool VisitTagDecl(const TagDecl *Tag);
6816 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS);
6817 };
6818} // end anonymous namespace
6819
6820bool UnnamedLocalNoLinkageFinder::VisitBuiltinType(const BuiltinType*) {
6821 return false;
6822}
6823
6824bool UnnamedLocalNoLinkageFinder::VisitComplexType(const ComplexType* T) {
6825 return Visit(T: T->getElementType());
6826}
6827
6828bool UnnamedLocalNoLinkageFinder::VisitPointerType(const PointerType* T) {
6829 return Visit(T: T->getPointeeType());
6830}
6831
6832bool UnnamedLocalNoLinkageFinder::VisitBlockPointerType(
6833 const BlockPointerType* T) {
6834 return Visit(T: T->getPointeeType());
6835}
6836
6837bool UnnamedLocalNoLinkageFinder::VisitLValueReferenceType(
6838 const LValueReferenceType* T) {
6839 return Visit(T: T->getPointeeType());
6840}
6841
6842bool UnnamedLocalNoLinkageFinder::VisitRValueReferenceType(
6843 const RValueReferenceType* T) {
6844 return Visit(T: T->getPointeeType());
6845}
6846
6847bool UnnamedLocalNoLinkageFinder::VisitMemberPointerType(
6848 const MemberPointerType* T) {
6849 return Visit(T: T->getPointeeType()) || Visit(T: QualType(T->getClass(), 0));
6850}
6851
6852bool UnnamedLocalNoLinkageFinder::VisitConstantArrayType(
6853 const ConstantArrayType* T) {
6854 return Visit(T: T->getElementType());
6855}
6856
6857bool UnnamedLocalNoLinkageFinder::VisitIncompleteArrayType(
6858 const IncompleteArrayType* T) {
6859 return Visit(T: T->getElementType());
6860}
6861
6862bool UnnamedLocalNoLinkageFinder::VisitVariableArrayType(
6863 const VariableArrayType* T) {
6864 return Visit(T: T->getElementType());
6865}
6866
6867bool UnnamedLocalNoLinkageFinder::VisitDependentSizedArrayType(
6868 const DependentSizedArrayType* T) {
6869 return Visit(T: T->getElementType());
6870}
6871
6872bool UnnamedLocalNoLinkageFinder::VisitDependentSizedExtVectorType(
6873 const DependentSizedExtVectorType* T) {
6874 return Visit(T: T->getElementType());
6875}
6876
6877bool UnnamedLocalNoLinkageFinder::VisitDependentSizedMatrixType(
6878 const DependentSizedMatrixType *T) {
6879 return Visit(T: T->getElementType());
6880}
6881
6882bool UnnamedLocalNoLinkageFinder::VisitDependentAddressSpaceType(
6883 const DependentAddressSpaceType *T) {
6884 return Visit(T: T->getPointeeType());
6885}
6886
6887bool UnnamedLocalNoLinkageFinder::VisitVectorType(const VectorType* T) {
6888 return Visit(T: T->getElementType());
6889}
6890
6891bool UnnamedLocalNoLinkageFinder::VisitDependentVectorType(
6892 const DependentVectorType *T) {
6893 return Visit(T: T->getElementType());
6894}
6895
6896bool UnnamedLocalNoLinkageFinder::VisitExtVectorType(const ExtVectorType* T) {
6897 return Visit(T: T->getElementType());
6898}
6899
6900bool UnnamedLocalNoLinkageFinder::VisitConstantMatrixType(
6901 const ConstantMatrixType *T) {
6902 return Visit(T: T->getElementType());
6903}
6904
6905bool UnnamedLocalNoLinkageFinder::VisitFunctionProtoType(
6906 const FunctionProtoType* T) {
6907 for (const auto &A : T->param_types()) {
6908 if (Visit(T: A))
6909 return true;
6910 }
6911
6912 return Visit(T: T->getReturnType());
6913}
6914
6915bool UnnamedLocalNoLinkageFinder::VisitFunctionNoProtoType(
6916 const FunctionNoProtoType* T) {
6917 return Visit(T: T->getReturnType());
6918}
6919
6920bool UnnamedLocalNoLinkageFinder::VisitUnresolvedUsingType(
6921 const UnresolvedUsingType*) {
6922 return false;
6923}
6924
6925bool UnnamedLocalNoLinkageFinder::VisitTypeOfExprType(const TypeOfExprType*) {
6926 return false;
6927}
6928
6929bool UnnamedLocalNoLinkageFinder::VisitTypeOfType(const TypeOfType* T) {
6930 return Visit(T: T->getUnmodifiedType());
6931}
6932
6933bool UnnamedLocalNoLinkageFinder::VisitDecltypeType(const DecltypeType*) {
6934 return false;
6935}
6936
6937bool UnnamedLocalNoLinkageFinder::VisitPackIndexingType(
6938 const PackIndexingType *) {
6939 return false;
6940}
6941
6942bool UnnamedLocalNoLinkageFinder::VisitUnaryTransformType(
6943 const UnaryTransformType*) {
6944 return false;
6945}
6946
6947bool UnnamedLocalNoLinkageFinder::VisitAutoType(const AutoType *T) {
6948 return Visit(T: T->getDeducedType());
6949}
6950
6951bool UnnamedLocalNoLinkageFinder::VisitDeducedTemplateSpecializationType(
6952 const DeducedTemplateSpecializationType *T) {
6953 return Visit(T: T->getDeducedType());
6954}
6955
6956bool UnnamedLocalNoLinkageFinder::VisitRecordType(const RecordType* T) {
6957 return VisitTagDecl(T->getDecl());
6958}
6959
6960bool UnnamedLocalNoLinkageFinder::VisitEnumType(const EnumType* T) {
6961 return VisitTagDecl(T->getDecl());
6962}
6963
6964bool UnnamedLocalNoLinkageFinder::VisitTemplateTypeParmType(
6965 const TemplateTypeParmType*) {
6966 return false;
6967}
6968
6969bool UnnamedLocalNoLinkageFinder::VisitSubstTemplateTypeParmPackType(
6970 const SubstTemplateTypeParmPackType *) {
6971 return false;
6972}
6973
6974bool UnnamedLocalNoLinkageFinder::VisitTemplateSpecializationType(
6975 const TemplateSpecializationType*) {
6976 return false;
6977}
6978
6979bool UnnamedLocalNoLinkageFinder::VisitInjectedClassNameType(
6980 const InjectedClassNameType* T) {
6981 return VisitTagDecl(T->getDecl());
6982}
6983
6984bool UnnamedLocalNoLinkageFinder::VisitDependentNameType(
6985 const DependentNameType* T) {
6986 return VisitNestedNameSpecifier(NNS: T->getQualifier());
6987}
6988
6989bool UnnamedLocalNoLinkageFinder::VisitDependentTemplateSpecializationType(
6990 const DependentTemplateSpecializationType* T) {
6991 if (auto *Q = T->getQualifier())
6992 return VisitNestedNameSpecifier(NNS: Q);
6993 return false;
6994}
6995
6996bool UnnamedLocalNoLinkageFinder::VisitPackExpansionType(
6997 const PackExpansionType* T) {
6998 return Visit(T: T->getPattern());
6999}
7000
7001bool UnnamedLocalNoLinkageFinder::VisitObjCObjectType(const ObjCObjectType *) {
7002 return false;
7003}
7004
7005bool UnnamedLocalNoLinkageFinder::VisitObjCInterfaceType(
7006 const ObjCInterfaceType *) {
7007 return false;
7008}
7009
7010bool UnnamedLocalNoLinkageFinder::VisitObjCObjectPointerType(
7011 const ObjCObjectPointerType *) {
7012 return false;
7013}
7014
7015bool UnnamedLocalNoLinkageFinder::VisitAtomicType(const AtomicType* T) {
7016 return Visit(T: T->getValueType());
7017}
7018
7019bool UnnamedLocalNoLinkageFinder::VisitPipeType(const PipeType* T) {
7020 return false;
7021}
7022
7023bool UnnamedLocalNoLinkageFinder::VisitBitIntType(const BitIntType *T) {
7024 return false;
7025}
7026
7027bool UnnamedLocalNoLinkageFinder::VisitArrayParameterType(
7028 const ArrayParameterType *T) {
7029 return VisitConstantArrayType(T);
7030}
7031
7032bool UnnamedLocalNoLinkageFinder::VisitDependentBitIntType(
7033 const DependentBitIntType *T) {
7034 return false;
7035}
7036
7037bool UnnamedLocalNoLinkageFinder::VisitTagDecl(const TagDecl *Tag) {
7038 if (Tag->getDeclContext()->isFunctionOrMethod()) {
7039 S.Diag(SR.getBegin(),
7040 S.getLangOpts().CPlusPlus11 ?
7041 diag::warn_cxx98_compat_template_arg_local_type :
7042 diag::ext_template_arg_local_type)
7043 << S.Context.getTypeDeclType(Tag) << SR;
7044 return true;
7045 }
7046
7047 if (!Tag->hasNameForLinkage()) {
7048 S.Diag(SR.getBegin(),
7049 S.getLangOpts().CPlusPlus11 ?
7050 diag::warn_cxx98_compat_template_arg_unnamed_type :
7051 diag::ext_template_arg_unnamed_type) << SR;
7052 S.Diag(Tag->getLocation(), diag::note_template_unnamed_type_here);
7053 return true;
7054 }
7055
7056 return false;
7057}
7058
7059bool UnnamedLocalNoLinkageFinder::VisitNestedNameSpecifier(
7060 NestedNameSpecifier *NNS) {
7061 assert(NNS);
7062 if (NNS->getPrefix() && VisitNestedNameSpecifier(NNS: NNS->getPrefix()))
7063 return true;
7064
7065 switch (NNS->getKind()) {
7066 case NestedNameSpecifier::Identifier:
7067 case NestedNameSpecifier::Namespace:
7068 case NestedNameSpecifier::NamespaceAlias:
7069 case NestedNameSpecifier::Global:
7070 case NestedNameSpecifier::Super:
7071 return false;
7072
7073 case NestedNameSpecifier::TypeSpec:
7074 case NestedNameSpecifier::TypeSpecWithTemplate:
7075 return Visit(T: QualType(NNS->getAsType(), 0));
7076 }
7077 llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
7078}
7079
7080/// Check a template argument against its corresponding
7081/// template type parameter.
7082///
7083/// This routine implements the semantics of C++ [temp.arg.type]. It
7084/// returns true if an error occurred, and false otherwise.
7085bool Sema::CheckTemplateArgument(TypeSourceInfo *ArgInfo) {
7086 assert(ArgInfo && "invalid TypeSourceInfo");
7087 QualType Arg = ArgInfo->getType();
7088 SourceRange SR = ArgInfo->getTypeLoc().getSourceRange();
7089 QualType CanonArg = Context.getCanonicalType(T: Arg);
7090
7091 if (CanonArg->isVariablyModifiedType()) {
7092 return Diag(SR.getBegin(), diag::err_variably_modified_template_arg) << Arg;
7093 } else if (Context.hasSameUnqualifiedType(T1: Arg, T2: Context.OverloadTy)) {
7094 return Diag(SR.getBegin(), diag::err_template_arg_overload_type) << SR;
7095 }
7096
7097 // C++03 [temp.arg.type]p2:
7098 // A local type, a type with no linkage, an unnamed type or a type
7099 // compounded from any of these types shall not be used as a
7100 // template-argument for a template type-parameter.
7101 //
7102 // C++11 allows these, and even in C++03 we allow them as an extension with
7103 // a warning.
7104 if (LangOpts.CPlusPlus11 || CanonArg->hasUnnamedOrLocalType()) {
7105 UnnamedLocalNoLinkageFinder Finder(*this, SR);
7106 (void)Finder.Visit(T: CanonArg);
7107 }
7108
7109 return false;
7110}
7111
7112enum NullPointerValueKind {
7113 NPV_NotNullPointer,
7114 NPV_NullPointer,
7115 NPV_Error
7116};
7117
7118/// Determine whether the given template argument is a null pointer
7119/// value of the appropriate type.
7120static NullPointerValueKind
7121isNullPointerValueTemplateArgument(Sema &S, NonTypeTemplateParmDecl *Param,
7122 QualType ParamType, Expr *Arg,
7123 Decl *Entity = nullptr) {
7124 if (Arg->isValueDependent() || Arg->isTypeDependent())
7125 return NPV_NotNullPointer;
7126
7127 // dllimport'd entities aren't constant but are available inside of template
7128 // arguments.
7129 if (Entity && Entity->hasAttr<DLLImportAttr>())
7130 return NPV_NotNullPointer;
7131
7132 if (!S.isCompleteType(Loc: Arg->getExprLoc(), T: ParamType))
7133 llvm_unreachable(
7134 "Incomplete parameter type in isNullPointerValueTemplateArgument!");
7135
7136 if (!S.getLangOpts().CPlusPlus11)
7137 return NPV_NotNullPointer;
7138
7139 // Determine whether we have a constant expression.
7140 ExprResult ArgRV = S.DefaultFunctionArrayConversion(E: Arg);
7141 if (ArgRV.isInvalid())
7142 return NPV_Error;
7143 Arg = ArgRV.get();
7144
7145 Expr::EvalResult EvalResult;
7146 SmallVector<PartialDiagnosticAt, 8> Notes;
7147 EvalResult.Diag = &Notes;
7148 if (!Arg->EvaluateAsRValue(Result&: EvalResult, Ctx: S.Context) ||
7149 EvalResult.HasSideEffects) {
7150 SourceLocation DiagLoc = Arg->getExprLoc();
7151
7152 // If our only note is the usual "invalid subexpression" note, just point
7153 // the caret at its location rather than producing an essentially
7154 // redundant note.
7155 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
7156 diag::note_invalid_subexpr_in_const_expr) {
7157 DiagLoc = Notes[0].first;
7158 Notes.clear();
7159 }
7160
7161 S.Diag(DiagLoc, diag::err_template_arg_not_address_constant)
7162 << Arg->getType() << Arg->getSourceRange();
7163 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
7164 S.Diag(Notes[I].first, Notes[I].second);
7165
7166 S.NoteTemplateParameterLocation(*Param);
7167 return NPV_Error;
7168 }
7169
7170 // C++11 [temp.arg.nontype]p1:
7171 // - an address constant expression of type std::nullptr_t
7172 if (Arg->getType()->isNullPtrType())
7173 return NPV_NullPointer;
7174
7175 // - a constant expression that evaluates to a null pointer value (4.10); or
7176 // - a constant expression that evaluates to a null member pointer value
7177 // (4.11); or
7178 if ((EvalResult.Val.isLValue() && EvalResult.Val.isNullPointer()) ||
7179 (EvalResult.Val.isMemberPointer() &&
7180 !EvalResult.Val.getMemberPointerDecl())) {
7181 // If our expression has an appropriate type, we've succeeded.
7182 bool ObjCLifetimeConversion;
7183 if (S.Context.hasSameUnqualifiedType(T1: Arg->getType(), T2: ParamType) ||
7184 S.IsQualificationConversion(FromType: Arg->getType(), ToType: ParamType, CStyle: false,
7185 ObjCLifetimeConversion))
7186 return NPV_NullPointer;
7187
7188 // The types didn't match, but we know we got a null pointer; complain,
7189 // then recover as if the types were correct.
7190 S.Diag(Arg->getExprLoc(), diag::err_template_arg_wrongtype_null_constant)
7191 << Arg->getType() << ParamType << Arg->getSourceRange();
7192 S.NoteTemplateParameterLocation(*Param);
7193 return NPV_NullPointer;
7194 }
7195
7196 if (EvalResult.Val.isLValue() && !EvalResult.Val.getLValueBase()) {
7197 // We found a pointer that isn't null, but doesn't refer to an object.
7198 // We could just return NPV_NotNullPointer, but we can print a better
7199 // message with the information we have here.
7200 S.Diag(Arg->getExprLoc(), diag::err_template_arg_invalid)
7201 << EvalResult.Val.getAsString(S.Context, ParamType);
7202 S.NoteTemplateParameterLocation(*Param);
7203 return NPV_Error;
7204 }
7205
7206 // If we don't have a null pointer value, but we do have a NULL pointer
7207 // constant, suggest a cast to the appropriate type.
7208 if (Arg->isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_NeverValueDependent)) {
7209 std::string Code = "static_cast<" + ParamType.getAsString() + ">(";
7210 S.Diag(Arg->getExprLoc(), diag::err_template_arg_untyped_null_constant)
7211 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), Code)
7212 << FixItHint::CreateInsertion(S.getLocForEndOfToken(Arg->getEndLoc()),
7213 ")");
7214 S.NoteTemplateParameterLocation(*Param);
7215 return NPV_NullPointer;
7216 }
7217
7218 // FIXME: If we ever want to support general, address-constant expressions
7219 // as non-type template arguments, we should return the ExprResult here to
7220 // be interpreted by the caller.
7221 return NPV_NotNullPointer;
7222}
7223
7224/// Checks whether the given template argument is compatible with its
7225/// template parameter.
7226static bool CheckTemplateArgumentIsCompatibleWithParameter(
7227 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
7228 Expr *Arg, QualType ArgType) {
7229 bool ObjCLifetimeConversion;
7230 if (ParamType->isPointerType() &&
7231 !ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType() &&
7232 S.IsQualificationConversion(FromType: ArgType, ToType: ParamType, CStyle: false,
7233 ObjCLifetimeConversion)) {
7234 // For pointer-to-object types, qualification conversions are
7235 // permitted.
7236 } else {
7237 if (const ReferenceType *ParamRef = ParamType->getAs<ReferenceType>()) {
7238 if (!ParamRef->getPointeeType()->isFunctionType()) {
7239 // C++ [temp.arg.nontype]p5b3:
7240 // For a non-type template-parameter of type reference to
7241 // object, no conversions apply. The type referred to by the
7242 // reference may be more cv-qualified than the (otherwise
7243 // identical) type of the template- argument. The
7244 // template-parameter is bound directly to the
7245 // template-argument, which shall be an lvalue.
7246
7247 // FIXME: Other qualifiers?
7248 unsigned ParamQuals = ParamRef->getPointeeType().getCVRQualifiers();
7249 unsigned ArgQuals = ArgType.getCVRQualifiers();
7250
7251 if ((ParamQuals | ArgQuals) != ParamQuals) {
7252 S.Diag(Arg->getBeginLoc(),
7253 diag::err_template_arg_ref_bind_ignores_quals)
7254 << ParamType << Arg->getType() << Arg->getSourceRange();
7255 S.NoteTemplateParameterLocation(*Param);
7256 return true;
7257 }
7258 }
7259 }
7260
7261 // At this point, the template argument refers to an object or
7262 // function with external linkage. We now need to check whether the
7263 // argument and parameter types are compatible.
7264 if (!S.Context.hasSameUnqualifiedType(T1: ArgType,
7265 T2: ParamType.getNonReferenceType())) {
7266 // We can't perform this conversion or binding.
7267 if (ParamType->isReferenceType())
7268 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_no_ref_bind)
7269 << ParamType << ArgIn->getType() << Arg->getSourceRange();
7270 else
7271 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
7272 << ArgIn->getType() << ParamType << Arg->getSourceRange();
7273 S.NoteTemplateParameterLocation(*Param);
7274 return true;
7275 }
7276 }
7277
7278 return false;
7279}
7280
7281/// Checks whether the given template argument is the address
7282/// of an object or function according to C++ [temp.arg.nontype]p1.
7283static bool CheckTemplateArgumentAddressOfObjectOrFunction(
7284 Sema &S, NonTypeTemplateParmDecl *Param, QualType ParamType, Expr *ArgIn,
7285 TemplateArgument &SugaredConverted, TemplateArgument &CanonicalConverted) {
7286 bool Invalid = false;
7287 Expr *Arg = ArgIn;
7288 QualType ArgType = Arg->getType();
7289
7290 bool AddressTaken = false;
7291 SourceLocation AddrOpLoc;
7292 if (S.getLangOpts().MicrosoftExt) {
7293 // Microsoft Visual C++ strips all casts, allows an arbitrary number of
7294 // dereference and address-of operators.
7295 Arg = Arg->IgnoreParenCasts();
7296
7297 bool ExtWarnMSTemplateArg = false;
7298 UnaryOperatorKind FirstOpKind;
7299 SourceLocation FirstOpLoc;
7300 while (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
7301 UnaryOperatorKind UnOpKind = UnOp->getOpcode();
7302 if (UnOpKind == UO_Deref)
7303 ExtWarnMSTemplateArg = true;
7304 if (UnOpKind == UO_AddrOf || UnOpKind == UO_Deref) {
7305 Arg = UnOp->getSubExpr()->IgnoreParenCasts();
7306 if (!AddrOpLoc.isValid()) {
7307 FirstOpKind = UnOpKind;
7308 FirstOpLoc = UnOp->getOperatorLoc();
7309 }
7310 } else
7311 break;
7312 }
7313 if (FirstOpLoc.isValid()) {
7314 if (ExtWarnMSTemplateArg)
7315 S.Diag(ArgIn->getBeginLoc(), diag::ext_ms_deref_template_argument)
7316 << ArgIn->getSourceRange();
7317
7318 if (FirstOpKind == UO_AddrOf)
7319 AddressTaken = true;
7320 else if (Arg->getType()->isPointerType()) {
7321 // We cannot let pointers get dereferenced here, that is obviously not a
7322 // constant expression.
7323 assert(FirstOpKind == UO_Deref);
7324 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7325 << Arg->getSourceRange();
7326 }
7327 }
7328 } else {
7329 // See through any implicit casts we added to fix the type.
7330 Arg = Arg->IgnoreImpCasts();
7331
7332 // C++ [temp.arg.nontype]p1:
7333 //
7334 // A template-argument for a non-type, non-template
7335 // template-parameter shall be one of: [...]
7336 //
7337 // -- the address of an object or function with external
7338 // linkage, including function templates and function
7339 // template-ids but excluding non-static class members,
7340 // expressed as & id-expression where the & is optional if
7341 // the name refers to a function or array, or if the
7342 // corresponding template-parameter is a reference; or
7343
7344 // In C++98/03 mode, give an extension warning on any extra parentheses.
7345 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7346 bool ExtraParens = false;
7347 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
7348 if (!Invalid && !ExtraParens) {
7349 S.Diag(Arg->getBeginLoc(),
7350 S.getLangOpts().CPlusPlus11
7351 ? diag::warn_cxx98_compat_template_arg_extra_parens
7352 : diag::ext_template_arg_extra_parens)
7353 << Arg->getSourceRange();
7354 ExtraParens = true;
7355 }
7356
7357 Arg = Parens->getSubExpr();
7358 }
7359
7360 while (SubstNonTypeTemplateParmExpr *subst =
7361 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
7362 Arg = subst->getReplacement()->IgnoreImpCasts();
7363
7364 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
7365 if (UnOp->getOpcode() == UO_AddrOf) {
7366 Arg = UnOp->getSubExpr();
7367 AddressTaken = true;
7368 AddrOpLoc = UnOp->getOperatorLoc();
7369 }
7370 }
7371
7372 while (SubstNonTypeTemplateParmExpr *subst =
7373 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
7374 Arg = subst->getReplacement()->IgnoreImpCasts();
7375 }
7376
7377 ValueDecl *Entity = nullptr;
7378 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg))
7379 Entity = DRE->getDecl();
7380 else if (CXXUuidofExpr *CUE = dyn_cast<CXXUuidofExpr>(Val: Arg))
7381 Entity = CUE->getGuidDecl();
7382
7383 // If our parameter has pointer type, check for a null template value.
7384 if (ParamType->isPointerType() || ParamType->isNullPtrType()) {
7385 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ArgIn,
7386 Entity)) {
7387 case NPV_NullPointer:
7388 S.Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7389 SugaredConverted = TemplateArgument(ParamType,
7390 /*isNullPtr=*/true);
7391 CanonicalConverted =
7392 TemplateArgument(S.Context.getCanonicalType(T: ParamType),
7393 /*isNullPtr=*/true);
7394 return false;
7395
7396 case NPV_Error:
7397 return true;
7398
7399 case NPV_NotNullPointer:
7400 break;
7401 }
7402 }
7403
7404 // Stop checking the precise nature of the argument if it is value dependent,
7405 // it should be checked when instantiated.
7406 if (Arg->isValueDependent()) {
7407 SugaredConverted = TemplateArgument(ArgIn);
7408 CanonicalConverted =
7409 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7410 return false;
7411 }
7412
7413 if (!Entity) {
7414 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7415 << Arg->getSourceRange();
7416 S.NoteTemplateParameterLocation(*Param);
7417 return true;
7418 }
7419
7420 // Cannot refer to non-static data members
7421 if (isa<FieldDecl>(Val: Entity) || isa<IndirectFieldDecl>(Val: Entity)) {
7422 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_field)
7423 << Entity << Arg->getSourceRange();
7424 S.NoteTemplateParameterLocation(*Param);
7425 return true;
7426 }
7427
7428 // Cannot refer to non-static member functions
7429 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Entity)) {
7430 if (!Method->isStatic()) {
7431 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_method)
7432 << Method << Arg->getSourceRange();
7433 S.NoteTemplateParameterLocation(*Param);
7434 return true;
7435 }
7436 }
7437
7438 FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: Entity);
7439 VarDecl *Var = dyn_cast<VarDecl>(Val: Entity);
7440 MSGuidDecl *Guid = dyn_cast<MSGuidDecl>(Val: Entity);
7441
7442 // A non-type template argument must refer to an object or function.
7443 if (!Func && !Var && !Guid) {
7444 // We found something, but we don't know specifically what it is.
7445 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_object_or_func)
7446 << Arg->getSourceRange();
7447 S.Diag(Entity->getLocation(), diag::note_template_arg_refers_here);
7448 return true;
7449 }
7450
7451 // Address / reference template args must have external linkage in C++98.
7452 if (Entity->getFormalLinkage() == Linkage::Internal) {
7453 S.Diag(Arg->getBeginLoc(),
7454 S.getLangOpts().CPlusPlus11
7455 ? diag::warn_cxx98_compat_template_arg_object_internal
7456 : diag::ext_template_arg_object_internal)
7457 << !Func << Entity << Arg->getSourceRange();
7458 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
7459 << !Func;
7460 } else if (!Entity->hasLinkage()) {
7461 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_object_no_linkage)
7462 << !Func << Entity << Arg->getSourceRange();
7463 S.Diag(Entity->getLocation(), diag::note_template_arg_internal_object)
7464 << !Func;
7465 return true;
7466 }
7467
7468 if (Var) {
7469 // A value of reference type is not an object.
7470 if (Var->getType()->isReferenceType()) {
7471 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_reference_var)
7472 << Var->getType() << Arg->getSourceRange();
7473 S.NoteTemplateParameterLocation(*Param);
7474 return true;
7475 }
7476
7477 // A template argument must have static storage duration.
7478 if (Var->getTLSKind()) {
7479 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_thread_local)
7480 << Arg->getSourceRange();
7481 S.Diag(Var->getLocation(), diag::note_template_arg_refers_here);
7482 return true;
7483 }
7484 }
7485
7486 if (AddressTaken && ParamType->isReferenceType()) {
7487 // If we originally had an address-of operator, but the
7488 // parameter has reference type, complain and (if things look
7489 // like they will work) drop the address-of operator.
7490 if (!S.Context.hasSameUnqualifiedType(T1: Entity->getType(),
7491 T2: ParamType.getNonReferenceType())) {
7492 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
7493 << ParamType;
7494 S.NoteTemplateParameterLocation(*Param);
7495 return true;
7496 }
7497
7498 S.Diag(AddrOpLoc, diag::err_template_arg_address_of_non_pointer)
7499 << ParamType
7500 << FixItHint::CreateRemoval(AddrOpLoc);
7501 S.NoteTemplateParameterLocation(*Param);
7502
7503 ArgType = Entity->getType();
7504 }
7505
7506 // If the template parameter has pointer type, either we must have taken the
7507 // address or the argument must decay to a pointer.
7508 if (!AddressTaken && ParamType->isPointerType()) {
7509 if (Func) {
7510 // Function-to-pointer decay.
7511 ArgType = S.Context.getPointerType(Func->getType());
7512 } else if (Entity->getType()->isArrayType()) {
7513 // Array-to-pointer decay.
7514 ArgType = S.Context.getArrayDecayedType(T: Entity->getType());
7515 } else {
7516 // If the template parameter has pointer type but the address of
7517 // this object was not taken, complain and (possibly) recover by
7518 // taking the address of the entity.
7519 ArgType = S.Context.getPointerType(T: Entity->getType());
7520 if (!S.Context.hasSameUnqualifiedType(T1: ArgType, T2: ParamType)) {
7521 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7522 << ParamType;
7523 S.NoteTemplateParameterLocation(*Param);
7524 return true;
7525 }
7526
7527 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_address_of)
7528 << ParamType << FixItHint::CreateInsertion(Arg->getBeginLoc(), "&");
7529
7530 S.NoteTemplateParameterLocation(*Param);
7531 }
7532 }
7533
7534 if (CheckTemplateArgumentIsCompatibleWithParameter(S, Param, ParamType, ArgIn,
7535 Arg, ArgType))
7536 return true;
7537
7538 // Create the template argument.
7539 SugaredConverted = TemplateArgument(Entity, ParamType);
7540 CanonicalConverted =
7541 TemplateArgument(cast<ValueDecl>(Entity->getCanonicalDecl()),
7542 S.Context.getCanonicalType(T: ParamType));
7543 S.MarkAnyDeclReferenced(Loc: Arg->getBeginLoc(), D: Entity, MightBeOdrUse: false);
7544 return false;
7545}
7546
7547/// Checks whether the given template argument is a pointer to
7548/// member constant according to C++ [temp.arg.nontype]p1.
7549static bool
7550CheckTemplateArgumentPointerToMember(Sema &S, NonTypeTemplateParmDecl *Param,
7551 QualType ParamType, Expr *&ResultArg,
7552 TemplateArgument &SugaredConverted,
7553 TemplateArgument &CanonicalConverted) {
7554 bool Invalid = false;
7555
7556 Expr *Arg = ResultArg;
7557 bool ObjCLifetimeConversion;
7558
7559 // C++ [temp.arg.nontype]p1:
7560 //
7561 // A template-argument for a non-type, non-template
7562 // template-parameter shall be one of: [...]
7563 //
7564 // -- a pointer to member expressed as described in 5.3.1.
7565 DeclRefExpr *DRE = nullptr;
7566
7567 // In C++98/03 mode, give an extension warning on any extra parentheses.
7568 // See http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#773
7569 bool ExtraParens = false;
7570 while (ParenExpr *Parens = dyn_cast<ParenExpr>(Val: Arg)) {
7571 if (!Invalid && !ExtraParens) {
7572 S.Diag(Arg->getBeginLoc(),
7573 S.getLangOpts().CPlusPlus11
7574 ? diag::warn_cxx98_compat_template_arg_extra_parens
7575 : diag::ext_template_arg_extra_parens)
7576 << Arg->getSourceRange();
7577 ExtraParens = true;
7578 }
7579
7580 Arg = Parens->getSubExpr();
7581 }
7582
7583 while (SubstNonTypeTemplateParmExpr *subst =
7584 dyn_cast<SubstNonTypeTemplateParmExpr>(Val: Arg))
7585 Arg = subst->getReplacement()->IgnoreImpCasts();
7586
7587 // A pointer-to-member constant written &Class::member.
7588 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(Val: Arg)) {
7589 if (UnOp->getOpcode() == UO_AddrOf) {
7590 DRE = dyn_cast<DeclRefExpr>(Val: UnOp->getSubExpr());
7591 if (DRE && !DRE->getQualifier())
7592 DRE = nullptr;
7593 }
7594 }
7595 // A constant of pointer-to-member type.
7596 else if ((DRE = dyn_cast<DeclRefExpr>(Val: Arg))) {
7597 ValueDecl *VD = DRE->getDecl();
7598 if (VD->getType()->isMemberPointerType()) {
7599 if (isa<NonTypeTemplateParmDecl>(Val: VD)) {
7600 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7601 SugaredConverted = TemplateArgument(Arg);
7602 CanonicalConverted =
7603 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7604 } else {
7605 SugaredConverted = TemplateArgument(VD, ParamType);
7606 CanonicalConverted =
7607 TemplateArgument(cast<ValueDecl>(VD->getCanonicalDecl()),
7608 S.Context.getCanonicalType(T: ParamType));
7609 }
7610 return Invalid;
7611 }
7612 }
7613
7614 DRE = nullptr;
7615 }
7616
7617 ValueDecl *Entity = DRE ? DRE->getDecl() : nullptr;
7618
7619 // Check for a null pointer value.
7620 switch (isNullPointerValueTemplateArgument(S, Param, ParamType, ResultArg,
7621 Entity)) {
7622 case NPV_Error:
7623 return true;
7624 case NPV_NullPointer:
7625 S.Diag(ResultArg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
7626 SugaredConverted = TemplateArgument(ParamType,
7627 /*isNullPtr*/ true);
7628 CanonicalConverted = TemplateArgument(S.Context.getCanonicalType(T: ParamType),
7629 /*isNullPtr*/ true);
7630 return false;
7631 case NPV_NotNullPointer:
7632 break;
7633 }
7634
7635 if (S.IsQualificationConversion(FromType: ResultArg->getType(),
7636 ToType: ParamType.getNonReferenceType(), CStyle: false,
7637 ObjCLifetimeConversion)) {
7638 ResultArg = S.ImpCastExprToType(E: ResultArg, Type: ParamType, CK: CK_NoOp,
7639 VK: ResultArg->getValueKind())
7640 .get();
7641 } else if (!S.Context.hasSameUnqualifiedType(
7642 T1: ResultArg->getType(), T2: ParamType.getNonReferenceType())) {
7643 // We can't perform this conversion.
7644 S.Diag(ResultArg->getBeginLoc(), diag::err_template_arg_not_convertible)
7645 << ResultArg->getType() << ParamType << ResultArg->getSourceRange();
7646 S.NoteTemplateParameterLocation(*Param);
7647 return true;
7648 }
7649
7650 if (!DRE)
7651 return S.Diag(Arg->getBeginLoc(),
7652 diag::err_template_arg_not_pointer_to_member_form)
7653 << Arg->getSourceRange();
7654
7655 if (isa<FieldDecl>(Val: DRE->getDecl()) ||
7656 isa<IndirectFieldDecl>(Val: DRE->getDecl()) ||
7657 isa<CXXMethodDecl>(Val: DRE->getDecl())) {
7658 assert((isa<FieldDecl>(DRE->getDecl()) ||
7659 isa<IndirectFieldDecl>(DRE->getDecl()) ||
7660 cast<CXXMethodDecl>(DRE->getDecl())
7661 ->isImplicitObjectMemberFunction()) &&
7662 "Only non-static member pointers can make it here");
7663
7664 // Okay: this is the address of a non-static member, and therefore
7665 // a member pointer constant.
7666 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
7667 SugaredConverted = TemplateArgument(Arg);
7668 CanonicalConverted =
7669 S.Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7670 } else {
7671 ValueDecl *D = DRE->getDecl();
7672 SugaredConverted = TemplateArgument(D, ParamType);
7673 CanonicalConverted =
7674 TemplateArgument(cast<ValueDecl>(D->getCanonicalDecl()),
7675 S.Context.getCanonicalType(T: ParamType));
7676 }
7677 return Invalid;
7678 }
7679
7680 // We found something else, but we don't know specifically what it is.
7681 S.Diag(Arg->getBeginLoc(), diag::err_template_arg_not_pointer_to_member_form)
7682 << Arg->getSourceRange();
7683 S.Diag(DRE->getDecl()->getLocation(), diag::note_template_arg_refers_here);
7684 return true;
7685}
7686
7687/// Check a template argument against its corresponding
7688/// non-type template parameter.
7689///
7690/// This routine implements the semantics of C++ [temp.arg.nontype].
7691/// If an error occurred, it returns ExprError(); otherwise, it
7692/// returns the converted template argument. \p ParamType is the
7693/// type of the non-type template parameter after it has been instantiated.
7694ExprResult Sema::CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
7695 QualType ParamType, Expr *Arg,
7696 TemplateArgument &SugaredConverted,
7697 TemplateArgument &CanonicalConverted,
7698 CheckTemplateArgumentKind CTAK) {
7699 SourceLocation StartLoc = Arg->getBeginLoc();
7700
7701 // If the parameter type somehow involves auto, deduce the type now.
7702 DeducedType *DeducedT = ParamType->getContainedDeducedType();
7703 if (getLangOpts().CPlusPlus17 && DeducedT && !DeducedT->isDeduced()) {
7704 // During template argument deduction, we allow 'decltype(auto)' to
7705 // match an arbitrary dependent argument.
7706 // FIXME: The language rules don't say what happens in this case.
7707 // FIXME: We get an opaque dependent type out of decltype(auto) if the
7708 // expression is merely instantiation-dependent; is this enough?
7709 if (CTAK == CTAK_Deduced && Arg->isTypeDependent()) {
7710 auto *AT = dyn_cast<AutoType>(Val: DeducedT);
7711 if (AT && AT->isDecltypeAuto()) {
7712 SugaredConverted = TemplateArgument(Arg);
7713 CanonicalConverted = TemplateArgument(
7714 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7715 return Arg;
7716 }
7717 }
7718
7719 // When checking a deduced template argument, deduce from its type even if
7720 // the type is dependent, in order to check the types of non-type template
7721 // arguments line up properly in partial ordering.
7722 Expr *DeductionArg = Arg;
7723 if (auto *PE = dyn_cast<PackExpansionExpr>(Val: DeductionArg))
7724 DeductionArg = PE->getPattern();
7725 TypeSourceInfo *TSI =
7726 Context.getTrivialTypeSourceInfo(T: ParamType, Loc: Param->getLocation());
7727 if (isa<DeducedTemplateSpecializationType>(Val: DeducedT)) {
7728 InitializedEntity Entity =
7729 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7730 InitializationKind Kind = InitializationKind::CreateForInit(
7731 Loc: DeductionArg->getBeginLoc(), /*DirectInit*/false, Init: DeductionArg);
7732 Expr *Inits[1] = {DeductionArg};
7733 ParamType =
7734 DeduceTemplateSpecializationFromInitializer(TInfo: TSI, Entity, Kind, Init: Inits);
7735 if (ParamType.isNull())
7736 return ExprError();
7737 } else {
7738 TemplateDeductionInfo Info(DeductionArg->getExprLoc(),
7739 Param->getDepth() + 1);
7740 ParamType = QualType();
7741 TemplateDeductionResult Result =
7742 DeduceAutoType(AutoTypeLoc: TSI->getTypeLoc(), Initializer: DeductionArg, Result&: ParamType, Info,
7743 /*DependentDeduction=*/true,
7744 // We do not check constraints right now because the
7745 // immediately-declared constraint of the auto type is
7746 // also an associated constraint, and will be checked
7747 // along with the other associated constraints after
7748 // checking the template argument list.
7749 /*IgnoreConstraints=*/true);
7750 if (Result == TemplateDeductionResult::AlreadyDiagnosed) {
7751 if (ParamType.isNull())
7752 return ExprError();
7753 } else if (Result != TemplateDeductionResult::Success) {
7754 Diag(Arg->getExprLoc(),
7755 diag::err_non_type_template_parm_type_deduction_failure)
7756 << Param->getDeclName() << Param->getType() << Arg->getType()
7757 << Arg->getSourceRange();
7758 NoteTemplateParameterLocation(*Param);
7759 return ExprError();
7760 }
7761 }
7762 // CheckNonTypeTemplateParameterType will produce a diagnostic if there's
7763 // an error. The error message normally references the parameter
7764 // declaration, but here we'll pass the argument location because that's
7765 // where the parameter type is deduced.
7766 ParamType = CheckNonTypeTemplateParameterType(T: ParamType, Loc: Arg->getExprLoc());
7767 if (ParamType.isNull()) {
7768 NoteTemplateParameterLocation(*Param);
7769 return ExprError();
7770 }
7771 }
7772
7773 // We should have already dropped all cv-qualifiers by now.
7774 assert(!ParamType.hasQualifiers() &&
7775 "non-type template parameter type cannot be qualified");
7776
7777 // FIXME: When Param is a reference, should we check that Arg is an lvalue?
7778 if (CTAK == CTAK_Deduced &&
7779 (ParamType->isReferenceType()
7780 ? !Context.hasSameType(T1: ParamType.getNonReferenceType(),
7781 T2: Arg->getType())
7782 : !Context.hasSameUnqualifiedType(T1: ParamType, T2: Arg->getType()))) {
7783 // FIXME: If either type is dependent, we skip the check. This isn't
7784 // correct, since during deduction we're supposed to have replaced each
7785 // template parameter with some unique (non-dependent) placeholder.
7786 // FIXME: If the argument type contains 'auto', we carry on and fail the
7787 // type check in order to force specific types to be more specialized than
7788 // 'auto'. It's not clear how partial ordering with 'auto' is supposed to
7789 // work. Similarly for CTAD, when comparing 'A<x>' against 'A'.
7790 if ((ParamType->isDependentType() || Arg->isTypeDependent()) &&
7791 !Arg->getType()->getContainedDeducedType()) {
7792 SugaredConverted = TemplateArgument(Arg);
7793 CanonicalConverted = TemplateArgument(
7794 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7795 return Arg;
7796 }
7797 // FIXME: This attempts to implement C++ [temp.deduct.type]p17. Per DR1770,
7798 // we should actually be checking the type of the template argument in P,
7799 // not the type of the template argument deduced from A, against the
7800 // template parameter type.
7801 Diag(StartLoc, diag::err_deduced_non_type_template_arg_type_mismatch)
7802 << Arg->getType()
7803 << ParamType.getUnqualifiedType();
7804 NoteTemplateParameterLocation(*Param);
7805 return ExprError();
7806 }
7807
7808 // If either the parameter has a dependent type or the argument is
7809 // type-dependent, there's nothing we can check now.
7810 if (ParamType->isDependentType() || Arg->isTypeDependent()) {
7811 // Force the argument to the type of the parameter to maintain invariants.
7812 auto *PE = dyn_cast<PackExpansionExpr>(Val: Arg);
7813 if (PE)
7814 Arg = PE->getPattern();
7815 ExprResult E = ImpCastExprToType(
7816 E: Arg, Type: ParamType.getNonLValueExprType(Context), CK: CK_Dependent,
7817 VK: ParamType->isLValueReferenceType() ? VK_LValue
7818 : ParamType->isRValueReferenceType() ? VK_XValue
7819 : VK_PRValue);
7820 if (E.isInvalid())
7821 return ExprError();
7822 if (PE) {
7823 // Recreate a pack expansion if we unwrapped one.
7824 E = new (Context)
7825 PackExpansionExpr(E.get()->getType(), E.get(), PE->getEllipsisLoc(),
7826 PE->getNumExpansions());
7827 }
7828 SugaredConverted = TemplateArgument(E.get());
7829 CanonicalConverted = TemplateArgument(
7830 Context.getCanonicalTemplateArgument(Arg: SugaredConverted));
7831 return E;
7832 }
7833
7834 QualType CanonParamType = Context.getCanonicalType(T: ParamType);
7835 // Avoid making a copy when initializing a template parameter of class type
7836 // from a template parameter object of the same type. This is going beyond
7837 // the standard, but is required for soundness: in
7838 // template<A a> struct X { X *p; X<a> *q; };
7839 // ... we need p and q to have the same type.
7840 //
7841 // Similarly, don't inject a call to a copy constructor when initializing
7842 // from a template parameter of the same type.
7843 Expr *InnerArg = Arg->IgnoreParenImpCasts();
7844 if (ParamType->isRecordType() && isa<DeclRefExpr>(Val: InnerArg) &&
7845 Context.hasSameUnqualifiedType(T1: ParamType, T2: InnerArg->getType())) {
7846 NamedDecl *ND = cast<DeclRefExpr>(Val: InnerArg)->getDecl();
7847 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
7848
7849 SugaredConverted = TemplateArgument(TPO, ParamType);
7850 CanonicalConverted =
7851 TemplateArgument(TPO->getCanonicalDecl(), CanonParamType);
7852 return Arg;
7853 }
7854 if (isa<NonTypeTemplateParmDecl>(Val: ND)) {
7855 SugaredConverted = TemplateArgument(Arg);
7856 CanonicalConverted =
7857 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7858 return Arg;
7859 }
7860 }
7861
7862 // The initialization of the parameter from the argument is
7863 // a constant-evaluated context.
7864 EnterExpressionEvaluationContext ConstantEvaluated(
7865 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7866
7867 bool IsConvertedConstantExpression = true;
7868 if (isa<InitListExpr>(Val: Arg) || ParamType->isRecordType()) {
7869 InitializationKind Kind = InitializationKind::CreateForInit(
7870 Loc: Arg->getBeginLoc(), /*DirectInit=*/false, Init: Arg);
7871 Expr *Inits[1] = {Arg};
7872 InitializedEntity Entity =
7873 InitializedEntity::InitializeTemplateParameter(T: ParamType, Param);
7874 InitializationSequence InitSeq(*this, Entity, Kind, Inits);
7875 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Inits);
7876 if (Result.isInvalid() || !Result.get())
7877 return ExprError();
7878 Result = ActOnConstantExpression(Res: Result.get());
7879 if (Result.isInvalid() || !Result.get())
7880 return ExprError();
7881 Arg = ActOnFinishFullExpr(Result.get(), Arg->getBeginLoc(),
7882 /*DiscardedValue=*/false,
7883 /*IsConstexpr=*/true, /*IsTemplateArgument=*/true)
7884 .get();
7885 IsConvertedConstantExpression = false;
7886 }
7887
7888 if (getLangOpts().CPlusPlus17) {
7889 // C++17 [temp.arg.nontype]p1:
7890 // A template-argument for a non-type template parameter shall be
7891 // a converted constant expression of the type of the template-parameter.
7892 APValue Value;
7893 ExprResult ArgResult;
7894 if (IsConvertedConstantExpression) {
7895 ArgResult = BuildConvertedConstantExpression(Arg, ParamType,
7896 CCEK_TemplateArg, Param);
7897 if (ArgResult.isInvalid())
7898 return ExprError();
7899 } else {
7900 ArgResult = Arg;
7901 }
7902
7903 // For a value-dependent argument, CheckConvertedConstantExpression is
7904 // permitted (and expected) to be unable to determine a value.
7905 if (ArgResult.get()->isValueDependent()) {
7906 SugaredConverted = TemplateArgument(ArgResult.get());
7907 CanonicalConverted =
7908 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
7909 return ArgResult;
7910 }
7911
7912 APValue PreNarrowingValue;
7913 ArgResult = EvaluateConvertedConstantExpression(
7914 E: ArgResult.get(), T: ParamType, Value, CCE: CCEK_TemplateArg, /*RequireInt=*/
7915 false, PreNarrowingValue);
7916 if (ArgResult.isInvalid())
7917 return ExprError();
7918
7919 if (Value.isLValue()) {
7920 APValue::LValueBase Base = Value.getLValueBase();
7921 auto *VD = const_cast<ValueDecl *>(Base.dyn_cast<const ValueDecl *>());
7922 // For a non-type template-parameter of pointer or reference type,
7923 // the value of the constant expression shall not refer to
7924 assert(ParamType->isPointerType() || ParamType->isReferenceType() ||
7925 ParamType->isNullPtrType());
7926 // -- a temporary object
7927 // -- a string literal
7928 // -- the result of a typeid expression, or
7929 // -- a predefined __func__ variable
7930 if (Base &&
7931 (!VD ||
7932 isa<LifetimeExtendedTemporaryDecl, UnnamedGlobalConstantDecl>(Val: VD))) {
7933 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_decl_ref)
7934 << Arg->getSourceRange();
7935 return ExprError();
7936 }
7937
7938 if (Value.hasLValuePath() && Value.getLValuePath().size() == 1 && VD &&
7939 VD->getType()->isArrayType() &&
7940 Value.getLValuePath()[0].getAsArrayIndex() == 0 &&
7941 !Value.isLValueOnePastTheEnd() && ParamType->isPointerType()) {
7942 SugaredConverted = TemplateArgument(VD, ParamType);
7943 CanonicalConverted = TemplateArgument(
7944 cast<ValueDecl>(VD->getCanonicalDecl()), CanonParamType);
7945 return ArgResult.get();
7946 }
7947
7948 // -- a subobject [until C++20]
7949 if (!getLangOpts().CPlusPlus20) {
7950 if (!Value.hasLValuePath() || Value.getLValuePath().size() ||
7951 Value.isLValueOnePastTheEnd()) {
7952 Diag(StartLoc, diag::err_non_type_template_arg_subobject)
7953 << Value.getAsString(Context, ParamType);
7954 return ExprError();
7955 }
7956 assert((VD || !ParamType->isReferenceType()) &&
7957 "null reference should not be a constant expression");
7958 assert((!VD || !ParamType->isNullPtrType()) &&
7959 "non-null value of type nullptr_t?");
7960 }
7961 }
7962
7963 if (Value.isAddrLabelDiff())
7964 return Diag(StartLoc, diag::err_non_type_template_arg_addr_label_diff);
7965
7966 SugaredConverted = TemplateArgument(Context, ParamType, Value);
7967 CanonicalConverted = TemplateArgument(Context, CanonParamType, Value);
7968 return ArgResult.get();
7969 }
7970
7971 // C++ [temp.arg.nontype]p5:
7972 // The following conversions are performed on each expression used
7973 // as a non-type template-argument. If a non-type
7974 // template-argument cannot be converted to the type of the
7975 // corresponding template-parameter then the program is
7976 // ill-formed.
7977 if (ParamType->isIntegralOrEnumerationType()) {
7978 // C++11:
7979 // -- for a non-type template-parameter of integral or
7980 // enumeration type, conversions permitted in a converted
7981 // constant expression are applied.
7982 //
7983 // C++98:
7984 // -- for a non-type template-parameter of integral or
7985 // enumeration type, integral promotions (4.5) and integral
7986 // conversions (4.7) are applied.
7987
7988 if (getLangOpts().CPlusPlus11) {
7989 // C++ [temp.arg.nontype]p1:
7990 // A template-argument for a non-type, non-template template-parameter
7991 // shall be one of:
7992 //
7993 // -- for a non-type template-parameter of integral or enumeration
7994 // type, a converted constant expression of the type of the
7995 // template-parameter; or
7996 llvm::APSInt Value;
7997 ExprResult ArgResult =
7998 CheckConvertedConstantExpression(From: Arg, T: ParamType, Value,
7999 CCE: CCEK_TemplateArg);
8000 if (ArgResult.isInvalid())
8001 return ExprError();
8002
8003 // We can't check arbitrary value-dependent arguments.
8004 if (ArgResult.get()->isValueDependent()) {
8005 SugaredConverted = TemplateArgument(ArgResult.get());
8006 CanonicalConverted =
8007 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
8008 return ArgResult;
8009 }
8010
8011 // Widen the argument value to sizeof(parameter type). This is almost
8012 // always a no-op, except when the parameter type is bool. In
8013 // that case, this may extend the argument from 1 bit to 8 bits.
8014 QualType IntegerType = ParamType;
8015 if (const EnumType *Enum = IntegerType->getAs<EnumType>())
8016 IntegerType = Enum->getDecl()->getIntegerType();
8017 Value = Value.extOrTrunc(width: IntegerType->isBitIntType()
8018 ? Context.getIntWidth(T: IntegerType)
8019 : Context.getTypeSize(T: IntegerType));
8020
8021 SugaredConverted = TemplateArgument(Context, Value, ParamType);
8022 CanonicalConverted =
8023 TemplateArgument(Context, Value, Context.getCanonicalType(T: ParamType));
8024 return ArgResult;
8025 }
8026
8027 ExprResult ArgResult = DefaultLvalueConversion(E: Arg);
8028 if (ArgResult.isInvalid())
8029 return ExprError();
8030 Arg = ArgResult.get();
8031
8032 QualType ArgType = Arg->getType();
8033
8034 // C++ [temp.arg.nontype]p1:
8035 // A template-argument for a non-type, non-template
8036 // template-parameter shall be one of:
8037 //
8038 // -- an integral constant-expression of integral or enumeration
8039 // type; or
8040 // -- the name of a non-type template-parameter; or
8041 llvm::APSInt Value;
8042 if (!ArgType->isIntegralOrEnumerationType()) {
8043 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_integral_or_enumeral)
8044 << ArgType << Arg->getSourceRange();
8045 NoteTemplateParameterLocation(*Param);
8046 return ExprError();
8047 } else if (!Arg->isValueDependent()) {
8048 class TmplArgICEDiagnoser : public VerifyICEDiagnoser {
8049 QualType T;
8050
8051 public:
8052 TmplArgICEDiagnoser(QualType T) : T(T) { }
8053
8054 SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
8055 SourceLocation Loc) override {
8056 return S.Diag(Loc, diag::err_template_arg_not_ice) << T;
8057 }
8058 } Diagnoser(ArgType);
8059
8060 Arg = VerifyIntegerConstantExpression(Arg, &Value, Diagnoser).get();
8061 if (!Arg)
8062 return ExprError();
8063 }
8064
8065 // From here on out, all we care about is the unqualified form
8066 // of the argument type.
8067 ArgType = ArgType.getUnqualifiedType();
8068
8069 // Try to convert the argument to the parameter's type.
8070 if (Context.hasSameType(T1: ParamType, T2: ArgType)) {
8071 // Okay: no conversion necessary
8072 } else if (ParamType->isBooleanType()) {
8073 // This is an integral-to-boolean conversion.
8074 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralToBoolean).get();
8075 } else if (IsIntegralPromotion(From: Arg, FromType: ArgType, ToType: ParamType) ||
8076 !ParamType->isEnumeralType()) {
8077 // This is an integral promotion or conversion.
8078 Arg = ImpCastExprToType(E: Arg, Type: ParamType, CK: CK_IntegralCast).get();
8079 } else {
8080 // We can't perform this conversion.
8081 Diag(Arg->getBeginLoc(), diag::err_template_arg_not_convertible)
8082 << Arg->getType() << ParamType << Arg->getSourceRange();
8083 NoteTemplateParameterLocation(*Param);
8084 return ExprError();
8085 }
8086
8087 // Add the value of this argument to the list of converted
8088 // arguments. We use the bitwidth and signedness of the template
8089 // parameter.
8090 if (Arg->isValueDependent()) {
8091 // The argument is value-dependent. Create a new
8092 // TemplateArgument with the converted expression.
8093 SugaredConverted = TemplateArgument(Arg);
8094 CanonicalConverted =
8095 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
8096 return Arg;
8097 }
8098
8099 QualType IntegerType = ParamType;
8100 if (const EnumType *Enum = IntegerType->getAs<EnumType>()) {
8101 IntegerType = Enum->getDecl()->getIntegerType();
8102 }
8103
8104 if (ParamType->isBooleanType()) {
8105 // Value must be zero or one.
8106 Value = Value != 0;
8107 unsigned AllowedBits = Context.getTypeSize(T: IntegerType);
8108 if (Value.getBitWidth() != AllowedBits)
8109 Value = Value.extOrTrunc(width: AllowedBits);
8110 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
8111 } else {
8112 llvm::APSInt OldValue = Value;
8113
8114 // Coerce the template argument's value to the value it will have
8115 // based on the template parameter's type.
8116 unsigned AllowedBits = IntegerType->isBitIntType()
8117 ? Context.getIntWidth(T: IntegerType)
8118 : Context.getTypeSize(T: IntegerType);
8119 if (Value.getBitWidth() != AllowedBits)
8120 Value = Value.extOrTrunc(width: AllowedBits);
8121 Value.setIsSigned(IntegerType->isSignedIntegerOrEnumerationType());
8122
8123 // Complain if an unsigned parameter received a negative value.
8124 if (IntegerType->isUnsignedIntegerOrEnumerationType() &&
8125 (OldValue.isSigned() && OldValue.isNegative())) {
8126 Diag(Arg->getBeginLoc(), diag::warn_template_arg_negative)
8127 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
8128 << Arg->getSourceRange();
8129 NoteTemplateParameterLocation(*Param);
8130 }
8131
8132 // Complain if we overflowed the template parameter's type.
8133 unsigned RequiredBits;
8134 if (IntegerType->isUnsignedIntegerOrEnumerationType())
8135 RequiredBits = OldValue.getActiveBits();
8136 else if (OldValue.isUnsigned())
8137 RequiredBits = OldValue.getActiveBits() + 1;
8138 else
8139 RequiredBits = OldValue.getSignificantBits();
8140 if (RequiredBits > AllowedBits) {
8141 Diag(Arg->getBeginLoc(), diag::warn_template_arg_too_large)
8142 << toString(OldValue, 10) << toString(Value, 10) << Param->getType()
8143 << Arg->getSourceRange();
8144 NoteTemplateParameterLocation(*Param);
8145 }
8146 }
8147
8148 QualType T = ParamType->isEnumeralType() ? ParamType : IntegerType;
8149 SugaredConverted = TemplateArgument(Context, Value, T);
8150 CanonicalConverted =
8151 TemplateArgument(Context, Value, Context.getCanonicalType(T));
8152 return Arg;
8153 }
8154
8155 QualType ArgType = Arg->getType();
8156 DeclAccessPair FoundResult; // temporary for ResolveOverloadedFunction
8157
8158 // Handle pointer-to-function, reference-to-function, and
8159 // pointer-to-member-function all in (roughly) the same way.
8160 if (// -- For a non-type template-parameter of type pointer to
8161 // function, only the function-to-pointer conversion (4.3) is
8162 // applied. If the template-argument represents a set of
8163 // overloaded functions (or a pointer to such), the matching
8164 // function is selected from the set (13.4).
8165 (ParamType->isPointerType() &&
8166 ParamType->castAs<PointerType>()->getPointeeType()->isFunctionType()) ||
8167 // -- For a non-type template-parameter of type reference to
8168 // function, no conversions apply. If the template-argument
8169 // represents a set of overloaded functions, the matching
8170 // function is selected from the set (13.4).
8171 (ParamType->isReferenceType() &&
8172 ParamType->castAs<ReferenceType>()->getPointeeType()->isFunctionType()) ||
8173 // -- For a non-type template-parameter of type pointer to
8174 // member function, no conversions apply. If the
8175 // template-argument represents a set of overloaded member
8176 // functions, the matching member function is selected from
8177 // the set (13.4).
8178 (ParamType->isMemberPointerType() &&
8179 ParamType->castAs<MemberPointerType>()->getPointeeType()
8180 ->isFunctionType())) {
8181
8182 if (Arg->getType() == Context.OverloadTy) {
8183 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg, TargetType: ParamType,
8184 Complain: true,
8185 Found&: FoundResult)) {
8186 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
8187 return ExprError();
8188
8189 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
8190 if (Res.isInvalid())
8191 return ExprError();
8192 Arg = Res.get();
8193 ArgType = Arg->getType();
8194 } else
8195 return ExprError();
8196 }
8197
8198 if (!ParamType->isMemberPointerType()) {
8199 if (CheckTemplateArgumentAddressOfObjectOrFunction(
8200 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted,
8201 CanonicalConverted))
8202 return ExprError();
8203 return Arg;
8204 }
8205
8206 if (CheckTemplateArgumentPointerToMember(
8207 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
8208 return ExprError();
8209 return Arg;
8210 }
8211
8212 if (ParamType->isPointerType()) {
8213 // -- for a non-type template-parameter of type pointer to
8214 // object, qualification conversions (4.4) and the
8215 // array-to-pointer conversion (4.2) are applied.
8216 // C++0x also allows a value of std::nullptr_t.
8217 assert(ParamType->getPointeeType()->isIncompleteOrObjectType() &&
8218 "Only object pointers allowed here");
8219
8220 if (CheckTemplateArgumentAddressOfObjectOrFunction(
8221 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted, CanonicalConverted))
8222 return ExprError();
8223 return Arg;
8224 }
8225
8226 if (const ReferenceType *ParamRefType = ParamType->getAs<ReferenceType>()) {
8227 // -- For a non-type template-parameter of type reference to
8228 // object, no conversions apply. The type referred to by the
8229 // reference may be more cv-qualified than the (otherwise
8230 // identical) type of the template-argument. The
8231 // template-parameter is bound directly to the
8232 // template-argument, which must be an lvalue.
8233 assert(ParamRefType->getPointeeType()->isIncompleteOrObjectType() &&
8234 "Only object references allowed here");
8235
8236 if (Arg->getType() == Context.OverloadTy) {
8237 if (FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(AddressOfExpr: Arg,
8238 TargetType: ParamRefType->getPointeeType(),
8239 Complain: true,
8240 Found&: FoundResult)) {
8241 if (DiagnoseUseOfDecl(D: Fn, Locs: Arg->getBeginLoc()))
8242 return ExprError();
8243 ExprResult Res = FixOverloadedFunctionReference(E: Arg, FoundDecl: FoundResult, Fn);
8244 if (Res.isInvalid())
8245 return ExprError();
8246 Arg = Res.get();
8247 ArgType = Arg->getType();
8248 } else
8249 return ExprError();
8250 }
8251
8252 if (CheckTemplateArgumentAddressOfObjectOrFunction(
8253 S&: *this, Param, ParamType, ArgIn: Arg, SugaredConverted, CanonicalConverted))
8254 return ExprError();
8255 return Arg;
8256 }
8257
8258 // Deal with parameters of type std::nullptr_t.
8259 if (ParamType->isNullPtrType()) {
8260 if (Arg->isTypeDependent() || Arg->isValueDependent()) {
8261 SugaredConverted = TemplateArgument(Arg);
8262 CanonicalConverted =
8263 Context.getCanonicalTemplateArgument(Arg: SugaredConverted);
8264 return Arg;
8265 }
8266
8267 switch (isNullPointerValueTemplateArgument(S&: *this, Param, ParamType, Arg)) {
8268 case NPV_NotNullPointer:
8269 Diag(Arg->getExprLoc(), diag::err_template_arg_not_convertible)
8270 << Arg->getType() << ParamType;
8271 NoteTemplateParameterLocation(*Param);
8272 return ExprError();
8273
8274 case NPV_Error:
8275 return ExprError();
8276
8277 case NPV_NullPointer:
8278 Diag(Arg->getExprLoc(), diag::warn_cxx98_compat_template_arg_null);
8279 SugaredConverted = TemplateArgument(ParamType,
8280 /*isNullPtr=*/true);
8281 CanonicalConverted = TemplateArgument(Context.getCanonicalType(T: ParamType),
8282 /*isNullPtr=*/true);
8283 return Arg;
8284 }
8285 }
8286
8287 // -- For a non-type template-parameter of type pointer to data
8288 // member, qualification conversions (4.4) are applied.
8289 assert(ParamType->isMemberPointerType() && "Only pointers to members remain");
8290
8291 if (CheckTemplateArgumentPointerToMember(
8292 S&: *this, Param, ParamType, ResultArg&: Arg, SugaredConverted, CanonicalConverted))
8293 return ExprError();
8294 return Arg;
8295}
8296
8297static void DiagnoseTemplateParameterListArityMismatch(
8298 Sema &S, TemplateParameterList *New, TemplateParameterList *Old,
8299 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc);
8300
8301/// Check a template argument against its corresponding
8302/// template template parameter.
8303///
8304/// This routine implements the semantics of C++ [temp.arg.template].
8305/// It returns true if an error occurred, and false otherwise.
8306bool Sema::CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
8307 TemplateParameterList *Params,
8308 TemplateArgumentLoc &Arg) {
8309 TemplateName Name = Arg.getArgument().getAsTemplateOrTemplatePattern();
8310 TemplateDecl *Template = Name.getAsTemplateDecl();
8311 if (!Template) {
8312 // Any dependent template name is fine.
8313 assert(Name.isDependent() && "Non-dependent template isn't a declaration?");
8314 return false;
8315 }
8316
8317 if (Template->isInvalidDecl())
8318 return true;
8319
8320 // C++0x [temp.arg.template]p1:
8321 // A template-argument for a template template-parameter shall be
8322 // the name of a class template or an alias template, expressed as an
8323 // id-expression. When the template-argument names a class template, only
8324 // primary class templates are considered when matching the
8325 // template template argument with the corresponding parameter;
8326 // partial specializations are not considered even if their
8327 // parameter lists match that of the template template parameter.
8328 //
8329 // Note that we also allow template template parameters here, which
8330 // will happen when we are dealing with, e.g., class template
8331 // partial specializations.
8332 if (!isa<ClassTemplateDecl>(Val: Template) &&
8333 !isa<TemplateTemplateParmDecl>(Val: Template) &&
8334 !isa<TypeAliasTemplateDecl>(Val: Template) &&
8335 !isa<BuiltinTemplateDecl>(Val: Template)) {
8336 assert(isa<FunctionTemplateDecl>(Template) &&
8337 "Only function templates are possible here");
8338 Diag(Arg.getLocation(), diag::err_template_arg_not_valid_template);
8339 Diag(Template->getLocation(), diag::note_template_arg_refers_here_func)
8340 << Template;
8341 }
8342
8343 // C++1z [temp.arg.template]p3: (DR 150)
8344 // A template-argument matches a template template-parameter P when P
8345 // is at least as specialized as the template-argument A.
8346 // FIXME: We should enable RelaxedTemplateTemplateArgs by default as it is a
8347 // defect report resolution from C++17 and shouldn't be introduced by
8348 // concepts.
8349 if (getLangOpts().RelaxedTemplateTemplateArgs) {
8350 // Quick check for the common case:
8351 // If P contains a parameter pack, then A [...] matches P if each of A's
8352 // template parameters matches the corresponding template parameter in
8353 // the template-parameter-list of P.
8354 if (TemplateParameterListsAreEqual(
8355 New: Template->getTemplateParameters(), Old: Params, Complain: false,
8356 Kind: TPL_TemplateTemplateArgumentMatch, TemplateArgLoc: Arg.getLocation()) &&
8357 // If the argument has no associated constraints, then the parameter is
8358 // definitely at least as specialized as the argument.
8359 // Otherwise - we need a more thorough check.
8360 !Template->hasAssociatedConstraints())
8361 return false;
8362
8363 if (isTemplateTemplateParameterAtLeastAsSpecializedAs(PParam: Params, AArg: Template,
8364 Loc: Arg.getLocation())) {
8365 // P2113
8366 // C++20[temp.func.order]p2
8367 // [...] If both deductions succeed, the partial ordering selects the
8368 // more constrained template (if one exists) as determined below.
8369 SmallVector<const Expr *, 3> ParamsAC, TemplateAC;
8370 Params->getAssociatedConstraints(AC&: ParamsAC);
8371 // C++2a[temp.arg.template]p3
8372 // [...] In this comparison, if P is unconstrained, the constraints on A
8373 // are not considered.
8374 if (ParamsAC.empty())
8375 return false;
8376
8377 Template->getAssociatedConstraints(AC&: TemplateAC);
8378
8379 bool IsParamAtLeastAsConstrained;
8380 if (IsAtLeastAsConstrained(Param, ParamsAC, Template, TemplateAC,
8381 IsParamAtLeastAsConstrained))
8382 return true;
8383 if (!IsParamAtLeastAsConstrained) {
8384 Diag(Arg.getLocation(),
8385 diag::err_template_template_parameter_not_at_least_as_constrained)
8386 << Template << Param << Arg.getSourceRange();
8387 Diag(Param->getLocation(), diag::note_entity_declared_at) << Param;
8388 Diag(Template->getLocation(), diag::note_entity_declared_at)
8389 << Template;
8390 MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Param, ParamsAC, Template,
8391 TemplateAC);
8392 return true;
8393 }
8394 return false;
8395 }
8396 // FIXME: Produce better diagnostics for deduction failures.
8397 }
8398
8399 return !TemplateParameterListsAreEqual(New: Template->getTemplateParameters(),
8400 Old: Params,
8401 Complain: true,
8402 Kind: TPL_TemplateTemplateArgumentMatch,
8403 TemplateArgLoc: Arg.getLocation());
8404}
8405
8406static Sema::SemaDiagnosticBuilder noteLocation(Sema &S, const NamedDecl &Decl,
8407 unsigned HereDiagID,
8408 unsigned ExternalDiagID) {
8409 if (Decl.getLocation().isValid())
8410 return S.Diag(Decl.getLocation(), HereDiagID);
8411
8412 SmallString<128> Str;
8413 llvm::raw_svector_ostream Out(Str);
8414 PrintingPolicy PP = S.getPrintingPolicy();
8415 PP.TerseOutput = 1;
8416 Decl.print(Out, PP);
8417 return S.Diag(Decl.getLocation(), ExternalDiagID) << Out.str();
8418}
8419
8420void Sema::NoteTemplateLocation(const NamedDecl &Decl,
8421 std::optional<SourceRange> ParamRange) {
8422 SemaDiagnosticBuilder DB =
8423 noteLocation(*this, Decl, diag::note_template_decl_here,
8424 diag::note_template_decl_external);
8425 if (ParamRange && ParamRange->isValid()) {
8426 assert(Decl.getLocation().isValid() &&
8427 "Parameter range has location when Decl does not");
8428 DB << *ParamRange;
8429 }
8430}
8431
8432void Sema::NoteTemplateParameterLocation(const NamedDecl &Decl) {
8433 noteLocation(*this, Decl, diag::note_template_param_here,
8434 diag::note_template_param_external);
8435}
8436
8437/// Given a non-type template argument that refers to a
8438/// declaration and the type of its corresponding non-type template
8439/// parameter, produce an expression that properly refers to that
8440/// declaration.
8441ExprResult
8442Sema::BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
8443 QualType ParamType,
8444 SourceLocation Loc) {
8445 // C++ [temp.param]p8:
8446 //
8447 // A non-type template-parameter of type "array of T" or
8448 // "function returning T" is adjusted to be of type "pointer to
8449 // T" or "pointer to function returning T", respectively.
8450 if (ParamType->isArrayType())
8451 ParamType = Context.getArrayDecayedType(T: ParamType);
8452 else if (ParamType->isFunctionType())
8453 ParamType = Context.getPointerType(T: ParamType);
8454
8455 // For a NULL non-type template argument, return nullptr casted to the
8456 // parameter's type.
8457 if (Arg.getKind() == TemplateArgument::NullPtr) {
8458 return ImpCastExprToType(
8459 new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc),
8460 ParamType,
8461 ParamType->getAs<MemberPointerType>()
8462 ? CK_NullToMemberPointer
8463 : CK_NullToPointer);
8464 }
8465 assert(Arg.getKind() == TemplateArgument::Declaration &&
8466 "Only declaration template arguments permitted here");
8467
8468 ValueDecl *VD = Arg.getAsDecl();
8469
8470 CXXScopeSpec SS;
8471 if (ParamType->isMemberPointerType()) {
8472 // If this is a pointer to member, we need to use a qualified name to
8473 // form a suitable pointer-to-member constant.
8474 assert(VD->getDeclContext()->isRecord() &&
8475 (isa<CXXMethodDecl>(VD) || isa<FieldDecl>(VD) ||
8476 isa<IndirectFieldDecl>(VD)));
8477 QualType ClassType
8478 = Context.getTypeDeclType(Decl: cast<RecordDecl>(VD->getDeclContext()));
8479 NestedNameSpecifier *Qualifier
8480 = NestedNameSpecifier::Create(Context, Prefix: nullptr, Template: false,
8481 T: ClassType.getTypePtr());
8482 SS.MakeTrivial(Context, Qualifier, R: Loc);
8483 }
8484
8485 ExprResult RefExpr = BuildDeclarationNameExpr(
8486 SS, DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8487 if (RefExpr.isInvalid())
8488 return ExprError();
8489
8490 // For a pointer, the argument declaration is the pointee. Take its address.
8491 QualType ElemT(RefExpr.get()->getType()->getArrayElementTypeNoTypeQual(), 0);
8492 if (ParamType->isPointerType() && !ElemT.isNull() &&
8493 Context.hasSimilarType(T1: ElemT, T2: ParamType->getPointeeType())) {
8494 // Decay an array argument if we want a pointer to its first element.
8495 RefExpr = DefaultFunctionArrayConversion(E: RefExpr.get());
8496 if (RefExpr.isInvalid())
8497 return ExprError();
8498 } else if (ParamType->isPointerType() || ParamType->isMemberPointerType()) {
8499 // For any other pointer, take the address (or form a pointer-to-member).
8500 RefExpr = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_AddrOf, InputExpr: RefExpr.get());
8501 if (RefExpr.isInvalid())
8502 return ExprError();
8503 } else if (ParamType->isRecordType()) {
8504 assert(isa<TemplateParamObjectDecl>(VD) &&
8505 "arg for class template param not a template parameter object");
8506 // No conversions apply in this case.
8507 return RefExpr;
8508 } else {
8509 assert(ParamType->isReferenceType() &&
8510 "unexpected type for decl template argument");
8511 }
8512
8513 // At this point we should have the right value category.
8514 assert(ParamType->isReferenceType() == RefExpr.get()->isLValue() &&
8515 "value kind mismatch for non-type template argument");
8516
8517 // The type of the template parameter can differ from the type of the
8518 // argument in various ways; convert it now if necessary.
8519 QualType DestExprType = ParamType.getNonLValueExprType(Context);
8520 if (!Context.hasSameType(T1: RefExpr.get()->getType(), T2: DestExprType)) {
8521 CastKind CK;
8522 QualType Ignored;
8523 if (Context.hasSimilarType(T1: RefExpr.get()->getType(), T2: DestExprType) ||
8524 IsFunctionConversion(FromType: RefExpr.get()->getType(), ToType: DestExprType, ResultTy&: Ignored)) {
8525 CK = CK_NoOp;
8526 } else if (ParamType->isVoidPointerType() &&
8527 RefExpr.get()->getType()->isPointerType()) {
8528 CK = CK_BitCast;
8529 } else {
8530 // FIXME: Pointers to members can need conversion derived-to-base or
8531 // base-to-derived conversions. We currently don't retain enough
8532 // information to convert properly (we need to track a cast path or
8533 // subobject number in the template argument).
8534 llvm_unreachable(
8535 "unexpected conversion required for non-type template argument");
8536 }
8537 RefExpr = ImpCastExprToType(E: RefExpr.get(), Type: DestExprType, CK,
8538 VK: RefExpr.get()->getValueKind());
8539 }
8540
8541 return RefExpr;
8542}
8543
8544/// Construct a new expression that refers to the given
8545/// integral template argument with the given source-location
8546/// information.
8547///
8548/// This routine takes care of the mapping from an integral template
8549/// argument (which may have any integral type) to the appropriate
8550/// literal value.
8551static Expr *BuildExpressionFromIntegralTemplateArgumentValue(
8552 Sema &S, QualType OrigT, const llvm::APSInt &Int, SourceLocation Loc) {
8553 assert(OrigT->isIntegralOrEnumerationType());
8554
8555 // If this is an enum type that we're instantiating, we need to use an integer
8556 // type the same size as the enumerator. We don't want to build an
8557 // IntegerLiteral with enum type. The integer type of an enum type can be of
8558 // any integral type with C++11 enum classes, make sure we create the right
8559 // type of literal for it.
8560 QualType T = OrigT;
8561 if (const EnumType *ET = OrigT->getAs<EnumType>())
8562 T = ET->getDecl()->getIntegerType();
8563
8564 Expr *E;
8565 if (T->isAnyCharacterType()) {
8566 CharacterLiteralKind Kind;
8567 if (T->isWideCharType())
8568 Kind = CharacterLiteralKind::Wide;
8569 else if (T->isChar8Type() && S.getLangOpts().Char8)
8570 Kind = CharacterLiteralKind::UTF8;
8571 else if (T->isChar16Type())
8572 Kind = CharacterLiteralKind::UTF16;
8573 else if (T->isChar32Type())
8574 Kind = CharacterLiteralKind::UTF32;
8575 else
8576 Kind = CharacterLiteralKind::Ascii;
8577
8578 E = new (S.Context) CharacterLiteral(Int.getZExtValue(), Kind, T, Loc);
8579 } else if (T->isBooleanType()) {
8580 E = CXXBoolLiteralExpr::Create(C: S.Context, Val: Int.getBoolValue(), Ty: T, Loc);
8581 } else {
8582 E = IntegerLiteral::Create(C: S.Context, V: Int, type: T, l: Loc);
8583 }
8584
8585 if (OrigT->isEnumeralType()) {
8586 // FIXME: This is a hack. We need a better way to handle substituted
8587 // non-type template parameters.
8588 E = CStyleCastExpr::Create(Context: S.Context, T: OrigT, VK: VK_PRValue, K: CK_IntegralCast, Op: E,
8589 BasePath: nullptr, FPO: S.CurFPFeatureOverrides(),
8590 WrittenTy: S.Context.getTrivialTypeSourceInfo(T: OrigT, Loc),
8591 L: Loc, R: Loc);
8592 }
8593
8594 return E;
8595}
8596
8597static Expr *BuildExpressionFromNonTypeTemplateArgumentValue(
8598 Sema &S, QualType T, const APValue &Val, SourceLocation Loc) {
8599 auto MakeInitList = [&](ArrayRef<Expr *> Elts) -> Expr * {
8600 auto *ILE = new (S.Context) InitListExpr(S.Context, Loc, Elts, Loc);
8601 ILE->setType(T);
8602 return ILE;
8603 };
8604
8605 switch (Val.getKind()) {
8606 case APValue::AddrLabelDiff:
8607 // This cannot occur in a template argument at all.
8608 case APValue::Array:
8609 case APValue::Struct:
8610 case APValue::Union:
8611 // These can only occur within a template parameter object, which is
8612 // represented as a TemplateArgument::Declaration.
8613 llvm_unreachable("unexpected template argument value");
8614
8615 case APValue::Int:
8616 return BuildExpressionFromIntegralTemplateArgumentValue(S, OrigT: T, Int: Val.getInt(),
8617 Loc);
8618
8619 case APValue::Float:
8620 return FloatingLiteral::Create(C: S.Context, V: Val.getFloat(), /*IsExact=*/isexact: true,
8621 Type: T, L: Loc);
8622
8623 case APValue::FixedPoint:
8624 return FixedPointLiteral::CreateFromRawInt(
8625 C: S.Context, V: Val.getFixedPoint().getValue(), type: T, l: Loc,
8626 Scale: Val.getFixedPoint().getScale());
8627
8628 case APValue::ComplexInt: {
8629 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8630 return MakeInitList({BuildExpressionFromIntegralTemplateArgumentValue(
8631 S, OrigT: ElemT, Int: Val.getComplexIntReal(), Loc),
8632 BuildExpressionFromIntegralTemplateArgumentValue(
8633 S, OrigT: ElemT, Int: Val.getComplexIntImag(), Loc)});
8634 }
8635
8636 case APValue::ComplexFloat: {
8637 QualType ElemT = T->castAs<ComplexType>()->getElementType();
8638 return MakeInitList(
8639 {FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatReal(), isexact: true,
8640 Type: ElemT, L: Loc),
8641 FloatingLiteral::Create(C: S.Context, V: Val.getComplexFloatImag(), isexact: true,
8642 Type: ElemT, L: Loc)});
8643 }
8644
8645 case APValue::Vector: {
8646 QualType ElemT = T->castAs<VectorType>()->getElementType();
8647 llvm::SmallVector<Expr *, 8> Elts;
8648 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I)
8649 Elts.push_back(Elt: BuildExpressionFromNonTypeTemplateArgumentValue(
8650 S, T: ElemT, Val: Val.getVectorElt(I), Loc));
8651 return MakeInitList(Elts);
8652 }
8653
8654 case APValue::None:
8655 case APValue::Indeterminate:
8656 llvm_unreachable("Unexpected APValue kind.");
8657 case APValue::LValue:
8658 case APValue::MemberPointer:
8659 // There isn't necessarily a valid equivalent source-level syntax for
8660 // these; in particular, a naive lowering might violate access control.
8661 // So for now we lower to a ConstantExpr holding the value, wrapped around
8662 // an OpaqueValueExpr.
8663 // FIXME: We should have a better representation for this.
8664 ExprValueKind VK = VK_PRValue;
8665 if (T->isReferenceType()) {
8666 T = T->getPointeeType();
8667 VK = VK_LValue;
8668 }
8669 auto *OVE = new (S.Context) OpaqueValueExpr(Loc, T, VK);
8670 return ConstantExpr::Create(S.Context, OVE, Val);
8671 }
8672 llvm_unreachable("Unhandled APValue::ValueKind enum");
8673}
8674
8675ExprResult
8676Sema::BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg,
8677 SourceLocation Loc) {
8678 switch (Arg.getKind()) {
8679 case TemplateArgument::Null:
8680 case TemplateArgument::Type:
8681 case TemplateArgument::Template:
8682 case TemplateArgument::TemplateExpansion:
8683 case TemplateArgument::Pack:
8684 llvm_unreachable("not a non-type template argument");
8685
8686 case TemplateArgument::Expression:
8687 return Arg.getAsExpr();
8688
8689 case TemplateArgument::NullPtr:
8690 case TemplateArgument::Declaration:
8691 return BuildExpressionFromDeclTemplateArgument(
8692 Arg, ParamType: Arg.getNonTypeTemplateArgumentType(), Loc);
8693
8694 case TemplateArgument::Integral:
8695 return BuildExpressionFromIntegralTemplateArgumentValue(
8696 S&: *this, OrigT: Arg.getIntegralType(), Int: Arg.getAsIntegral(), Loc);
8697
8698 case TemplateArgument::StructuralValue:
8699 return BuildExpressionFromNonTypeTemplateArgumentValue(
8700 S&: *this, T: Arg.getStructuralValueType(), Val: Arg.getAsStructuralValue(), Loc);
8701 }
8702 llvm_unreachable("Unhandled TemplateArgument::ArgKind enum");
8703}
8704
8705/// Match two template parameters within template parameter lists.
8706static bool MatchTemplateParameterKind(
8707 Sema &S, NamedDecl *New,
8708 const Sema::TemplateCompareNewDeclInfo &NewInstFrom, NamedDecl *Old,
8709 const NamedDecl *OldInstFrom, bool Complain,
8710 Sema::TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8711 // Check the actual kind (type, non-type, template).
8712 if (Old->getKind() != New->getKind()) {
8713 if (Complain) {
8714 unsigned NextDiag = diag::err_template_param_different_kind;
8715 if (TemplateArgLoc.isValid()) {
8716 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8717 NextDiag = diag::note_template_param_different_kind;
8718 }
8719 S.Diag(New->getLocation(), NextDiag)
8720 << (Kind != Sema::TPL_TemplateMatch);
8721 S.Diag(Old->getLocation(), diag::note_template_prev_declaration)
8722 << (Kind != Sema::TPL_TemplateMatch);
8723 }
8724
8725 return false;
8726 }
8727
8728 // Check that both are parameter packs or neither are parameter packs.
8729 // However, if we are matching a template template argument to a
8730 // template template parameter, the template template parameter can have
8731 // a parameter pack where the template template argument does not.
8732 if (Old->isTemplateParameterPack() != New->isTemplateParameterPack() &&
8733 !(Kind == Sema::TPL_TemplateTemplateArgumentMatch &&
8734 Old->isTemplateParameterPack())) {
8735 if (Complain) {
8736 unsigned NextDiag = diag::err_template_parameter_pack_non_pack;
8737 if (TemplateArgLoc.isValid()) {
8738 S.Diag(TemplateArgLoc,
8739 diag::err_template_arg_template_params_mismatch);
8740 NextDiag = diag::note_template_parameter_pack_non_pack;
8741 }
8742
8743 unsigned ParamKind = isa<TemplateTypeParmDecl>(Val: New)? 0
8744 : isa<NonTypeTemplateParmDecl>(Val: New)? 1
8745 : 2;
8746 S.Diag(New->getLocation(), NextDiag)
8747 << ParamKind << New->isParameterPack();
8748 S.Diag(Old->getLocation(), diag::note_template_parameter_pack_here)
8749 << ParamKind << Old->isParameterPack();
8750 }
8751
8752 return false;
8753 }
8754
8755 // For non-type template parameters, check the type of the parameter.
8756 if (NonTypeTemplateParmDecl *OldNTTP
8757 = dyn_cast<NonTypeTemplateParmDecl>(Val: Old)) {
8758 NonTypeTemplateParmDecl *NewNTTP = cast<NonTypeTemplateParmDecl>(Val: New);
8759
8760 // If we are matching a template template argument to a template
8761 // template parameter and one of the non-type template parameter types
8762 // is dependent, then we must wait until template instantiation time
8763 // to actually compare the arguments.
8764 if (Kind != Sema::TPL_TemplateTemplateArgumentMatch ||
8765 (!OldNTTP->getType()->isDependentType() &&
8766 !NewNTTP->getType()->isDependentType())) {
8767 // C++20 [temp.over.link]p6:
8768 // Two [non-type] template-parameters are equivalent [if] they have
8769 // equivalent types ignoring the use of type-constraints for
8770 // placeholder types
8771 QualType OldType = S.Context.getUnconstrainedType(T: OldNTTP->getType());
8772 QualType NewType = S.Context.getUnconstrainedType(T: NewNTTP->getType());
8773 if (!S.Context.hasSameType(T1: OldType, T2: NewType)) {
8774 if (Complain) {
8775 unsigned NextDiag = diag::err_template_nontype_parm_different_type;
8776 if (TemplateArgLoc.isValid()) {
8777 S.Diag(TemplateArgLoc,
8778 diag::err_template_arg_template_params_mismatch);
8779 NextDiag = diag::note_template_nontype_parm_different_type;
8780 }
8781 S.Diag(NewNTTP->getLocation(), NextDiag)
8782 << NewNTTP->getType()
8783 << (Kind != Sema::TPL_TemplateMatch);
8784 S.Diag(OldNTTP->getLocation(),
8785 diag::note_template_nontype_parm_prev_declaration)
8786 << OldNTTP->getType();
8787 }
8788
8789 return false;
8790 }
8791 }
8792 }
8793 // For template template parameters, check the template parameter types.
8794 // The template parameter lists of template template
8795 // parameters must agree.
8796 else if (TemplateTemplateParmDecl *OldTTP =
8797 dyn_cast<TemplateTemplateParmDecl>(Val: Old)) {
8798 TemplateTemplateParmDecl *NewTTP = cast<TemplateTemplateParmDecl>(Val: New);
8799 if (!S.TemplateParameterListsAreEqual(
8800 NewInstFrom, NewTTP->getTemplateParameters(), OldInstFrom,
8801 OldTTP->getTemplateParameters(), Complain,
8802 (Kind == Sema::TPL_TemplateMatch
8803 ? Sema::TPL_TemplateTemplateParmMatch
8804 : Kind),
8805 TemplateArgLoc))
8806 return false;
8807 }
8808
8809 if (Kind != Sema::TPL_TemplateParamsEquivalent &&
8810 Kind != Sema::TPL_TemplateTemplateArgumentMatch &&
8811 !isa<TemplateTemplateParmDecl>(Val: Old)) {
8812 const Expr *NewC = nullptr, *OldC = nullptr;
8813
8814 if (isa<TemplateTypeParmDecl>(Val: New)) {
8815 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: New)->getTypeConstraint())
8816 NewC = TC->getImmediatelyDeclaredConstraint();
8817 if (const auto *TC = cast<TemplateTypeParmDecl>(Val: Old)->getTypeConstraint())
8818 OldC = TC->getImmediatelyDeclaredConstraint();
8819 } else if (isa<NonTypeTemplateParmDecl>(Val: New)) {
8820 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: New)
8821 ->getPlaceholderTypeConstraint())
8822 NewC = E;
8823 if (const Expr *E = cast<NonTypeTemplateParmDecl>(Val: Old)
8824 ->getPlaceholderTypeConstraint())
8825 OldC = E;
8826 } else
8827 llvm_unreachable("unexpected template parameter type");
8828
8829 auto Diagnose = [&] {
8830 S.Diag(NewC ? NewC->getBeginLoc() : New->getBeginLoc(),
8831 diag::err_template_different_type_constraint);
8832 S.Diag(OldC ? OldC->getBeginLoc() : Old->getBeginLoc(),
8833 diag::note_template_prev_declaration) << /*declaration*/0;
8834 };
8835
8836 if (!NewC != !OldC) {
8837 if (Complain)
8838 Diagnose();
8839 return false;
8840 }
8841
8842 if (NewC) {
8843 if (!S.AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldC, New: NewInstFrom,
8844 NewConstr: NewC)) {
8845 if (Complain)
8846 Diagnose();
8847 return false;
8848 }
8849 }
8850 }
8851
8852 return true;
8853}
8854
8855/// Diagnose a known arity mismatch when comparing template argument
8856/// lists.
8857static
8858void DiagnoseTemplateParameterListArityMismatch(Sema &S,
8859 TemplateParameterList *New,
8860 TemplateParameterList *Old,
8861 Sema::TemplateParameterListEqualKind Kind,
8862 SourceLocation TemplateArgLoc) {
8863 unsigned NextDiag = diag::err_template_param_list_different_arity;
8864 if (TemplateArgLoc.isValid()) {
8865 S.Diag(TemplateArgLoc, diag::err_template_arg_template_params_mismatch);
8866 NextDiag = diag::note_template_param_list_different_arity;
8867 }
8868 S.Diag(New->getTemplateLoc(), NextDiag)
8869 << (New->size() > Old->size())
8870 << (Kind != Sema::TPL_TemplateMatch)
8871 << SourceRange(New->getTemplateLoc(), New->getRAngleLoc());
8872 S.Diag(Old->getTemplateLoc(), diag::note_template_prev_declaration)
8873 << (Kind != Sema::TPL_TemplateMatch)
8874 << SourceRange(Old->getTemplateLoc(), Old->getRAngleLoc());
8875}
8876
8877/// Determine whether the given template parameter lists are
8878/// equivalent.
8879///
8880/// \param New The new template parameter list, typically written in the
8881/// source code as part of a new template declaration.
8882///
8883/// \param Old The old template parameter list, typically found via
8884/// name lookup of the template declared with this template parameter
8885/// list.
8886///
8887/// \param Complain If true, this routine will produce a diagnostic if
8888/// the template parameter lists are not equivalent.
8889///
8890/// \param Kind describes how we are to match the template parameter lists.
8891///
8892/// \param TemplateArgLoc If this source location is valid, then we
8893/// are actually checking the template parameter list of a template
8894/// argument (New) against the template parameter list of its
8895/// corresponding template template parameter (Old). We produce
8896/// slightly different diagnostics in this scenario.
8897///
8898/// \returns True if the template parameter lists are equal, false
8899/// otherwise.
8900bool Sema::TemplateParameterListsAreEqual(
8901 const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New,
8902 const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain,
8903 TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc) {
8904 if (Old->size() != New->size() && Kind != TPL_TemplateTemplateArgumentMatch) {
8905 if (Complain)
8906 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8907 TemplateArgLoc);
8908
8909 return false;
8910 }
8911
8912 // C++0x [temp.arg.template]p3:
8913 // A template-argument matches a template template-parameter (call it P)
8914 // when each of the template parameters in the template-parameter-list of
8915 // the template-argument's corresponding class template or alias template
8916 // (call it A) matches the corresponding template parameter in the
8917 // template-parameter-list of P. [...]
8918 TemplateParameterList::iterator NewParm = New->begin();
8919 TemplateParameterList::iterator NewParmEnd = New->end();
8920 for (TemplateParameterList::iterator OldParm = Old->begin(),
8921 OldParmEnd = Old->end();
8922 OldParm != OldParmEnd; ++OldParm) {
8923 if (Kind != TPL_TemplateTemplateArgumentMatch ||
8924 !(*OldParm)->isTemplateParameterPack()) {
8925 if (NewParm == NewParmEnd) {
8926 if (Complain)
8927 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8928 TemplateArgLoc);
8929
8930 return false;
8931 }
8932
8933 if (!MatchTemplateParameterKind(S&: *this, New: *NewParm, NewInstFrom, Old: *OldParm,
8934 OldInstFrom, Complain, Kind,
8935 TemplateArgLoc))
8936 return false;
8937
8938 ++NewParm;
8939 continue;
8940 }
8941
8942 // C++0x [temp.arg.template]p3:
8943 // [...] When P's template- parameter-list contains a template parameter
8944 // pack (14.5.3), the template parameter pack will match zero or more
8945 // template parameters or template parameter packs in the
8946 // template-parameter-list of A with the same type and form as the
8947 // template parameter pack in P (ignoring whether those template
8948 // parameters are template parameter packs).
8949 for (; NewParm != NewParmEnd; ++NewParm) {
8950 if (!MatchTemplateParameterKind(S&: *this, New: *NewParm, NewInstFrom, Old: *OldParm,
8951 OldInstFrom, Complain, Kind,
8952 TemplateArgLoc))
8953 return false;
8954 }
8955 }
8956
8957 // Make sure we exhausted all of the arguments.
8958 if (NewParm != NewParmEnd) {
8959 if (Complain)
8960 DiagnoseTemplateParameterListArityMismatch(S&: *this, New, Old, Kind,
8961 TemplateArgLoc);
8962
8963 return false;
8964 }
8965
8966 if (Kind != TPL_TemplateTemplateArgumentMatch &&
8967 Kind != TPL_TemplateParamsEquivalent) {
8968 const Expr *NewRC = New->getRequiresClause();
8969 const Expr *OldRC = Old->getRequiresClause();
8970
8971 auto Diagnose = [&] {
8972 Diag(NewRC ? NewRC->getBeginLoc() : New->getTemplateLoc(),
8973 diag::err_template_different_requires_clause);
8974 Diag(OldRC ? OldRC->getBeginLoc() : Old->getTemplateLoc(),
8975 diag::note_template_prev_declaration) << /*declaration*/0;
8976 };
8977
8978 if (!NewRC != !OldRC) {
8979 if (Complain)
8980 Diagnose();
8981 return false;
8982 }
8983
8984 if (NewRC) {
8985 if (!AreConstraintExpressionsEqual(Old: OldInstFrom, OldConstr: OldRC, New: NewInstFrom,
8986 NewConstr: NewRC)) {
8987 if (Complain)
8988 Diagnose();
8989 return false;
8990 }
8991 }
8992 }
8993
8994 return true;
8995}
8996
8997/// Check whether a template can be declared within this scope.
8998///
8999/// If the template declaration is valid in this scope, returns
9000/// false. Otherwise, issues a diagnostic and returns true.
9001bool
9002Sema::CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams) {
9003 if (!S)
9004 return false;
9005
9006 // Find the nearest enclosing declaration scope.
9007 S = S->getDeclParent();
9008
9009 // C++ [temp.pre]p6: [P2096]
9010 // A template, explicit specialization, or partial specialization shall not
9011 // have C linkage.
9012 DeclContext *Ctx = S->getEntity();
9013 if (Ctx && Ctx->isExternCContext()) {
9014 Diag(TemplateParams->getTemplateLoc(), diag::err_template_linkage)
9015 << TemplateParams->getSourceRange();
9016 if (const LinkageSpecDecl *LSD = Ctx->getExternCContext())
9017 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
9018 return true;
9019 }
9020 Ctx = Ctx ? Ctx->getRedeclContext() : nullptr;
9021
9022 // C++ [temp]p2:
9023 // A template-declaration can appear only as a namespace scope or
9024 // class scope declaration.
9025 // C++ [temp.expl.spec]p3:
9026 // An explicit specialization may be declared in any scope in which the
9027 // corresponding primary template may be defined.
9028 // C++ [temp.class.spec]p6: [P2096]
9029 // A partial specialization may be declared in any scope in which the
9030 // corresponding primary template may be defined.
9031 if (Ctx) {
9032 if (Ctx->isFileContext())
9033 return false;
9034 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: Ctx)) {
9035 // C++ [temp.mem]p2:
9036 // A local class shall not have member templates.
9037 if (RD->isLocalClass())
9038 return Diag(TemplateParams->getTemplateLoc(),
9039 diag::err_template_inside_local_class)
9040 << TemplateParams->getSourceRange();
9041 else
9042 return false;
9043 }
9044 }
9045
9046 return Diag(TemplateParams->getTemplateLoc(),
9047 diag::err_template_outside_namespace_or_class_scope)
9048 << TemplateParams->getSourceRange();
9049}
9050
9051/// Determine what kind of template specialization the given declaration
9052/// is.
9053static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D) {
9054 if (!D)
9055 return TSK_Undeclared;
9056
9057 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D))
9058 return Record->getTemplateSpecializationKind();
9059 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D))
9060 return Function->getTemplateSpecializationKind();
9061 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D))
9062 return Var->getTemplateSpecializationKind();
9063
9064 return TSK_Undeclared;
9065}
9066
9067/// Check whether a specialization is well-formed in the current
9068/// context.
9069///
9070/// This routine determines whether a template specialization can be declared
9071/// in the current context (C++ [temp.expl.spec]p2).
9072///
9073/// \param S the semantic analysis object for which this check is being
9074/// performed.
9075///
9076/// \param Specialized the entity being specialized or instantiated, which
9077/// may be a kind of template (class template, function template, etc.) or
9078/// a member of a class template (member function, static data member,
9079/// member class).
9080///
9081/// \param PrevDecl the previous declaration of this entity, if any.
9082///
9083/// \param Loc the location of the explicit specialization or instantiation of
9084/// this entity.
9085///
9086/// \param IsPartialSpecialization whether this is a partial specialization of
9087/// a class template.
9088///
9089/// \returns true if there was an error that we cannot recover from, false
9090/// otherwise.
9091static bool CheckTemplateSpecializationScope(Sema &S,
9092 NamedDecl *Specialized,
9093 NamedDecl *PrevDecl,
9094 SourceLocation Loc,
9095 bool IsPartialSpecialization) {
9096 // Keep these "kind" numbers in sync with the %select statements in the
9097 // various diagnostics emitted by this routine.
9098 int EntityKind = 0;
9099 if (isa<ClassTemplateDecl>(Val: Specialized))
9100 EntityKind = IsPartialSpecialization? 1 : 0;
9101 else if (isa<VarTemplateDecl>(Val: Specialized))
9102 EntityKind = IsPartialSpecialization ? 3 : 2;
9103 else if (isa<FunctionTemplateDecl>(Val: Specialized))
9104 EntityKind = 4;
9105 else if (isa<CXXMethodDecl>(Val: Specialized))
9106 EntityKind = 5;
9107 else if (isa<VarDecl>(Val: Specialized))
9108 EntityKind = 6;
9109 else if (isa<RecordDecl>(Val: Specialized))
9110 EntityKind = 7;
9111 else if (isa<EnumDecl>(Val: Specialized) && S.getLangOpts().CPlusPlus11)
9112 EntityKind = 8;
9113 else {
9114 S.Diag(Loc, diag::err_template_spec_unknown_kind)
9115 << S.getLangOpts().CPlusPlus11;
9116 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
9117 return true;
9118 }
9119
9120 // C++ [temp.expl.spec]p2:
9121 // An explicit specialization may be declared in any scope in which
9122 // the corresponding primary template may be defined.
9123 if (S.CurContext->getRedeclContext()->isFunctionOrMethod()) {
9124 S.Diag(Loc, diag::err_template_spec_decl_function_scope)
9125 << Specialized;
9126 return true;
9127 }
9128
9129 // C++ [temp.class.spec]p6:
9130 // A class template partial specialization may be declared in any
9131 // scope in which the primary template may be defined.
9132 DeclContext *SpecializedContext =
9133 Specialized->getDeclContext()->getRedeclContext();
9134 DeclContext *DC = S.CurContext->getRedeclContext();
9135
9136 // Make sure that this redeclaration (or definition) occurs in the same
9137 // scope or an enclosing namespace.
9138 if (!(DC->isFileContext() ? DC->Encloses(DC: SpecializedContext)
9139 : DC->Equals(DC: SpecializedContext))) {
9140 if (isa<TranslationUnitDecl>(Val: SpecializedContext))
9141 S.Diag(Loc, diag::err_template_spec_redecl_global_scope)
9142 << EntityKind << Specialized;
9143 else {
9144 auto *ND = cast<NamedDecl>(Val: SpecializedContext);
9145 int Diag = diag::err_template_spec_redecl_out_of_scope;
9146 if (S.getLangOpts().MicrosoftExt && !DC->isRecord())
9147 Diag = diag::ext_ms_template_spec_redecl_out_of_scope;
9148 S.Diag(Loc, Diag) << EntityKind << Specialized
9149 << ND << isa<CXXRecordDecl>(ND);
9150 }
9151
9152 S.Diag(Specialized->getLocation(), diag::note_specialized_entity);
9153
9154 // Don't allow specializing in the wrong class during error recovery.
9155 // Otherwise, things can go horribly wrong.
9156 if (DC->isRecord())
9157 return true;
9158 }
9159
9160 return false;
9161}
9162
9163static SourceRange findTemplateParameterInType(unsigned Depth, Expr *E) {
9164 if (!E->isTypeDependent())
9165 return SourceLocation();
9166 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
9167 Checker.TraverseStmt(E);
9168 if (Checker.MatchLoc.isInvalid())
9169 return E->getSourceRange();
9170 return Checker.MatchLoc;
9171}
9172
9173static SourceRange findTemplateParameter(unsigned Depth, TypeLoc TL) {
9174 if (!TL.getType()->isDependentType())
9175 return SourceLocation();
9176 DependencyChecker Checker(Depth, /*IgnoreNonTypeDependent*/true);
9177 Checker.TraverseTypeLoc(TL);
9178 if (Checker.MatchLoc.isInvalid())
9179 return TL.getSourceRange();
9180 return Checker.MatchLoc;
9181}
9182
9183/// Subroutine of Sema::CheckTemplatePartialSpecializationArgs
9184/// that checks non-type template partial specialization arguments.
9185static bool CheckNonTypeTemplatePartialSpecializationArgs(
9186 Sema &S, SourceLocation TemplateNameLoc, NonTypeTemplateParmDecl *Param,
9187 const TemplateArgument *Args, unsigned NumArgs, bool IsDefaultArgument) {
9188 for (unsigned I = 0; I != NumArgs; ++I) {
9189 if (Args[I].getKind() == TemplateArgument::Pack) {
9190 if (CheckNonTypeTemplatePartialSpecializationArgs(
9191 S, TemplateNameLoc, Param, Args: Args[I].pack_begin(),
9192 NumArgs: Args[I].pack_size(), IsDefaultArgument))
9193 return true;
9194
9195 continue;
9196 }
9197
9198 if (Args[I].getKind() != TemplateArgument::Expression)
9199 continue;
9200
9201 Expr *ArgExpr = Args[I].getAsExpr();
9202
9203 // We can have a pack expansion of any of the bullets below.
9204 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Val: ArgExpr))
9205 ArgExpr = Expansion->getPattern();
9206
9207 // Strip off any implicit casts we added as part of type checking.
9208 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
9209 ArgExpr = ICE->getSubExpr();
9210
9211 // C++ [temp.class.spec]p8:
9212 // A non-type argument is non-specialized if it is the name of a
9213 // non-type parameter. All other non-type arguments are
9214 // specialized.
9215 //
9216 // Below, we check the two conditions that only apply to
9217 // specialized non-type arguments, so skip any non-specialized
9218 // arguments.
9219 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: ArgExpr))
9220 if (isa<NonTypeTemplateParmDecl>(Val: DRE->getDecl()))
9221 continue;
9222
9223 // C++ [temp.class.spec]p9:
9224 // Within the argument list of a class template partial
9225 // specialization, the following restrictions apply:
9226 // -- A partially specialized non-type argument expression
9227 // shall not involve a template parameter of the partial
9228 // specialization except when the argument expression is a
9229 // simple identifier.
9230 // -- The type of a template parameter corresponding to a
9231 // specialized non-type argument shall not be dependent on a
9232 // parameter of the specialization.
9233 // DR1315 removes the first bullet, leaving an incoherent set of rules.
9234 // We implement a compromise between the original rules and DR1315:
9235 // -- A specialized non-type template argument shall not be
9236 // type-dependent and the corresponding template parameter
9237 // shall have a non-dependent type.
9238 SourceRange ParamUseRange =
9239 findTemplateParameterInType(Param->getDepth(), ArgExpr);
9240 if (ParamUseRange.isValid()) {
9241 if (IsDefaultArgument) {
9242 S.Diag(TemplateNameLoc,
9243 diag::err_dependent_non_type_arg_in_partial_spec);
9244 S.Diag(ParamUseRange.getBegin(),
9245 diag::note_dependent_non_type_default_arg_in_partial_spec)
9246 << ParamUseRange;
9247 } else {
9248 S.Diag(ParamUseRange.getBegin(),
9249 diag::err_dependent_non_type_arg_in_partial_spec)
9250 << ParamUseRange;
9251 }
9252 return true;
9253 }
9254
9255 ParamUseRange = findTemplateParameter(
9256 Param->getDepth(), Param->getTypeSourceInfo()->getTypeLoc());
9257 if (ParamUseRange.isValid()) {
9258 S.Diag(IsDefaultArgument ? TemplateNameLoc : ArgExpr->getBeginLoc(),
9259 diag::err_dependent_typed_non_type_arg_in_partial_spec)
9260 << Param->getType();
9261 S.NoteTemplateParameterLocation(*Param);
9262 return true;
9263 }
9264 }
9265
9266 return false;
9267}
9268
9269/// Check the non-type template arguments of a class template
9270/// partial specialization according to C++ [temp.class.spec]p9.
9271///
9272/// \param TemplateNameLoc the location of the template name.
9273/// \param PrimaryTemplate the template parameters of the primary class
9274/// template.
9275/// \param NumExplicit the number of explicitly-specified template arguments.
9276/// \param TemplateArgs the template arguments of the class template
9277/// partial specialization.
9278///
9279/// \returns \c true if there was an error, \c false otherwise.
9280bool Sema::CheckTemplatePartialSpecializationArgs(
9281 SourceLocation TemplateNameLoc, TemplateDecl *PrimaryTemplate,
9282 unsigned NumExplicit, ArrayRef<TemplateArgument> TemplateArgs) {
9283 // We have to be conservative when checking a template in a dependent
9284 // context.
9285 if (PrimaryTemplate->getDeclContext()->isDependentContext())
9286 return false;
9287
9288 TemplateParameterList *TemplateParams =
9289 PrimaryTemplate->getTemplateParameters();
9290 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
9291 NonTypeTemplateParmDecl *Param
9292 = dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: I));
9293 if (!Param)
9294 continue;
9295
9296 if (CheckNonTypeTemplatePartialSpecializationArgs(S&: *this, TemplateNameLoc,
9297 Param, Args: &TemplateArgs[I],
9298 NumArgs: 1, IsDefaultArgument: I >= NumExplicit))
9299 return true;
9300 }
9301
9302 return false;
9303}
9304
9305DeclResult Sema::ActOnClassTemplateSpecialization(
9306 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
9307 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
9308 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
9309 MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody) {
9310 assert(TUK != TUK_Reference && "References are not specializations");
9311
9312 // NOTE: KWLoc is the location of the tag keyword. This will instead
9313 // store the location of the outermost template keyword in the declaration.
9314 SourceLocation TemplateKWLoc = TemplateParameterLists.size() > 0
9315 ? TemplateParameterLists[0]->getTemplateLoc() : KWLoc;
9316 SourceLocation TemplateNameLoc = TemplateId.TemplateNameLoc;
9317 SourceLocation LAngleLoc = TemplateId.LAngleLoc;
9318 SourceLocation RAngleLoc = TemplateId.RAngleLoc;
9319
9320 // Find the class template we're specializing
9321 TemplateName Name = TemplateId.Template.get();
9322 ClassTemplateDecl *ClassTemplate
9323 = dyn_cast_or_null<ClassTemplateDecl>(Val: Name.getAsTemplateDecl());
9324
9325 if (!ClassTemplate) {
9326 Diag(TemplateNameLoc, diag::err_not_class_template_specialization)
9327 << (Name.getAsTemplateDecl() &&
9328 isa<TemplateTemplateParmDecl>(Name.getAsTemplateDecl()));
9329 return true;
9330 }
9331
9332 bool isMemberSpecialization = false;
9333 bool isPartialSpecialization = false;
9334
9335 if (SS.isSet()) {
9336 if (TUK != TUK_Reference && TUK != TUK_Friend &&
9337 diagnoseQualifiedDeclaration(SS, DC: ClassTemplate->getDeclContext(),
9338 Name: ClassTemplate->getDeclName(),
9339 Loc: TemplateNameLoc, TemplateId: &TemplateId,
9340 /*IsMemberSpecialization=*/false))
9341 return true;
9342 }
9343
9344 // Check the validity of the template headers that introduce this
9345 // template.
9346 // FIXME: We probably shouldn't complain about these headers for
9347 // friend declarations.
9348 bool Invalid = false;
9349 TemplateParameterList *TemplateParams =
9350 MatchTemplateParametersToScopeSpecifier(
9351 DeclStartLoc: KWLoc, DeclLoc: TemplateNameLoc, SS, TemplateId: &TemplateId,
9352 ParamLists: TemplateParameterLists, IsFriend: TUK == TUK_Friend, IsMemberSpecialization&: isMemberSpecialization,
9353 Invalid);
9354 if (Invalid)
9355 return true;
9356
9357 // Check that we can declare a template specialization here.
9358 if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
9359 return true;
9360
9361 if (TemplateParams && TemplateParams->size() > 0) {
9362 isPartialSpecialization = true;
9363
9364 if (TUK == TUK_Friend) {
9365 Diag(KWLoc, diag::err_partial_specialization_friend)
9366 << SourceRange(LAngleLoc, RAngleLoc);
9367 return true;
9368 }
9369
9370 // C++ [temp.class.spec]p10:
9371 // The template parameter list of a specialization shall not
9372 // contain default template argument values.
9373 for (unsigned I = 0, N = TemplateParams->size(); I != N; ++I) {
9374 Decl *Param = TemplateParams->getParam(Idx: I);
9375 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Val: Param)) {
9376 if (TTP->hasDefaultArgument()) {
9377 Diag(TTP->getDefaultArgumentLoc(),
9378 diag::err_default_arg_in_partial_spec);
9379 TTP->removeDefaultArgument();
9380 }
9381 } else if (NonTypeTemplateParmDecl *NTTP
9382 = dyn_cast<NonTypeTemplateParmDecl>(Val: Param)) {
9383 if (Expr *DefArg = NTTP->getDefaultArgument()) {
9384 Diag(NTTP->getDefaultArgumentLoc(),
9385 diag::err_default_arg_in_partial_spec)
9386 << DefArg->getSourceRange();
9387 NTTP->removeDefaultArgument();
9388 }
9389 } else {
9390 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(Val: Param);
9391 if (TTP->hasDefaultArgument()) {
9392 Diag(TTP->getDefaultArgument().getLocation(),
9393 diag::err_default_arg_in_partial_spec)
9394 << TTP->getDefaultArgument().getSourceRange();
9395 TTP->removeDefaultArgument();
9396 }
9397 }
9398 }
9399 } else if (TemplateParams) {
9400 if (TUK == TUK_Friend)
9401 Diag(KWLoc, diag::err_template_spec_friend)
9402 << FixItHint::CreateRemoval(
9403 SourceRange(TemplateParams->getTemplateLoc(),
9404 TemplateParams->getRAngleLoc()))
9405 << SourceRange(LAngleLoc, RAngleLoc);
9406 } else {
9407 assert(TUK == TUK_Friend && "should have a 'template<>' for this decl");
9408 }
9409
9410 // Check that the specialization uses the same tag kind as the
9411 // original template.
9412 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
9413 assert(Kind != TagTypeKind::Enum &&
9414 "Invalid enum tag in class template spec!");
9415 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(),
9416 NewTag: Kind, isDefinition: TUK == TUK_Definition, NewTagLoc: KWLoc,
9417 Name: ClassTemplate->getIdentifier())) {
9418 Diag(KWLoc, diag::err_use_with_wrong_tag)
9419 << ClassTemplate
9420 << FixItHint::CreateReplacement(KWLoc,
9421 ClassTemplate->getTemplatedDecl()->getKindName());
9422 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
9423 diag::note_previous_use);
9424 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
9425 }
9426
9427 // Translate the parser's template argument list in our AST format.
9428 TemplateArgumentListInfo TemplateArgs =
9429 makeTemplateArgumentListInfo(S&: *this, TemplateId);
9430
9431 // Check for unexpanded parameter packs in any of the template arguments.
9432 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
9433 if (DiagnoseUnexpandedParameterPack(Arg: TemplateArgs[I],
9434 UPPC: isPartialSpecialization
9435 ? UPPC_PartialSpecialization
9436 : UPPC_ExplicitSpecialization))
9437 return true;
9438
9439 // Check that the template argument list is well-formed for this
9440 // template.
9441 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
9442 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
9443 false, SugaredConverted, CanonicalConverted,
9444 /*UpdateArgsWithConversions=*/true))
9445 return true;
9446
9447 // Find the class template (partial) specialization declaration that
9448 // corresponds to these arguments.
9449 if (isPartialSpecialization) {
9450 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, ClassTemplate,
9451 TemplateArgs.size(),
9452 CanonicalConverted))
9453 return true;
9454
9455 // FIXME: Move this to CheckTemplatePartialSpecializationArgs so we
9456 // also do it during instantiation.
9457 if (!Name.isDependent() &&
9458 !TemplateSpecializationType::anyDependentTemplateArguments(
9459 TemplateArgs, Converted: CanonicalConverted)) {
9460 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
9461 << ClassTemplate->getDeclName();
9462 isPartialSpecialization = false;
9463 Invalid = true;
9464 }
9465 }
9466
9467 void *InsertPos = nullptr;
9468 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
9469
9470 if (isPartialSpecialization)
9471 PrevDecl = ClassTemplate->findPartialSpecialization(
9472 Args: CanonicalConverted, TPL: TemplateParams, InsertPos);
9473 else
9474 PrevDecl = ClassTemplate->findSpecialization(Args: CanonicalConverted, InsertPos);
9475
9476 ClassTemplateSpecializationDecl *Specialization = nullptr;
9477
9478 // Check whether we can declare a class template specialization in
9479 // the current scope.
9480 if (TUK != TUK_Friend &&
9481 CheckTemplateSpecializationScope(*this, ClassTemplate, PrevDecl,
9482 TemplateNameLoc,
9483 isPartialSpecialization))
9484 return true;
9485
9486 // The canonical type
9487 QualType CanonType;
9488 if (isPartialSpecialization) {
9489 // Build the canonical type that describes the converted template
9490 // arguments of the class template partial specialization.
9491 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
9492 CanonType = Context.getTemplateSpecializationType(T: CanonTemplate,
9493 Args: CanonicalConverted);
9494
9495 if (Context.hasSameType(T1: CanonType,
9496 T2: ClassTemplate->getInjectedClassNameSpecialization()) &&
9497 (!Context.getLangOpts().CPlusPlus20 ||
9498 !TemplateParams->hasAssociatedConstraints())) {
9499 // C++ [temp.class.spec]p9b3:
9500 //
9501 // -- The argument list of the specialization shall not be identical
9502 // to the implicit argument list of the primary template.
9503 //
9504 // This rule has since been removed, because it's redundant given DR1495,
9505 // but we keep it because it produces better diagnostics and recovery.
9506 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
9507 << /*class template*/0 << (TUK == TUK_Definition)
9508 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
9509 return CheckClassTemplate(S, TagSpec, TUK, KWLoc, SS,
9510 Name: ClassTemplate->getIdentifier(),
9511 NameLoc: TemplateNameLoc,
9512 Attr,
9513 TemplateParams,
9514 AS: AS_none, /*ModulePrivateLoc=*/SourceLocation(),
9515 /*FriendLoc*/SourceLocation(),
9516 NumOuterTemplateParamLists: TemplateParameterLists.size() - 1,
9517 OuterTemplateParamLists: TemplateParameterLists.data());
9518 }
9519
9520 // Create a new class template partial specialization declaration node.
9521 ClassTemplatePartialSpecializationDecl *PrevPartial
9522 = cast_or_null<ClassTemplatePartialSpecializationDecl>(Val: PrevDecl);
9523 ClassTemplatePartialSpecializationDecl *Partial =
9524 ClassTemplatePartialSpecializationDecl::Create(
9525 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc,
9526 IdLoc: TemplateNameLoc, Params: TemplateParams, SpecializedTemplate: ClassTemplate, Args: CanonicalConverted,
9527 ArgInfos: TemplateArgs, CanonInjectedType: CanonType, PrevDecl: PrevPartial);
9528 SetNestedNameSpecifier(*this, Partial, SS);
9529 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
9530 Partial->setTemplateParameterListsInfo(
9531 Context, TemplateParameterLists.drop_back(N: 1));
9532 }
9533
9534 if (!PrevPartial)
9535 ClassTemplate->AddPartialSpecialization(D: Partial, InsertPos);
9536 Specialization = Partial;
9537
9538 // If we are providing an explicit specialization of a member class
9539 // template specialization, make a note of that.
9540 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
9541 PrevPartial->setMemberSpecialization();
9542
9543 CheckTemplatePartialSpecialization(Partial);
9544 } else {
9545 // Create a new class template specialization declaration node for
9546 // this explicit specialization or friend declaration.
9547 Specialization = ClassTemplateSpecializationDecl::Create(
9548 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
9549 SpecializedTemplate: ClassTemplate, Args: CanonicalConverted, PrevDecl);
9550 SetNestedNameSpecifier(*this, Specialization, SS);
9551 if (TemplateParameterLists.size() > 0) {
9552 Specialization->setTemplateParameterListsInfo(Context,
9553 TemplateParameterLists);
9554 }
9555
9556 if (!PrevDecl)
9557 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
9558
9559 if (CurContext->isDependentContext()) {
9560 TemplateName CanonTemplate = Context.getCanonicalTemplateName(Name);
9561 CanonType = Context.getTemplateSpecializationType(T: CanonTemplate,
9562 Args: CanonicalConverted);
9563 } else {
9564 CanonType = Context.getTypeDeclType(Specialization);
9565 }
9566 }
9567
9568 // C++ [temp.expl.spec]p6:
9569 // If a template, a member template or the member of a class template is
9570 // explicitly specialized then that specialization shall be declared
9571 // before the first use of that specialization that would cause an implicit
9572 // instantiation to take place, in every translation unit in which such a
9573 // use occurs; no diagnostic is required.
9574 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
9575 bool Okay = false;
9576 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9577 // Is there any previous explicit specialization declaration?
9578 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9579 Okay = true;
9580 break;
9581 }
9582 }
9583
9584 if (!Okay) {
9585 SourceRange Range(TemplateNameLoc, RAngleLoc);
9586 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
9587 << Context.getTypeDeclType(Specialization) << Range;
9588
9589 Diag(PrevDecl->getPointOfInstantiation(),
9590 diag::note_instantiation_required_here)
9591 << (PrevDecl->getTemplateSpecializationKind()
9592 != TSK_ImplicitInstantiation);
9593 return true;
9594 }
9595 }
9596
9597 // If this is not a friend, note that this is an explicit specialization.
9598 if (TUK != TUK_Friend)
9599 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
9600
9601 // Check that this isn't a redefinition of this specialization.
9602 if (TUK == TUK_Definition) {
9603 RecordDecl *Def = Specialization->getDefinition();
9604 NamedDecl *Hidden = nullptr;
9605 if (Def && SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
9606 SkipBody->ShouldSkip = true;
9607 SkipBody->Previous = Def;
9608 makeMergedDefinitionVisible(ND: Hidden);
9609 } else if (Def) {
9610 SourceRange Range(TemplateNameLoc, RAngleLoc);
9611 Diag(TemplateNameLoc, diag::err_redefinition) << Specialization << Range;
9612 Diag(Def->getLocation(), diag::note_previous_definition);
9613 Specialization->setInvalidDecl();
9614 return true;
9615 }
9616 }
9617
9618 ProcessDeclAttributeList(S, Specialization, Attr);
9619 ProcessAPINotes(Specialization);
9620
9621 // Add alignment attributes if necessary; these attributes are checked when
9622 // the ASTContext lays out the structure.
9623 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
9624 AddAlignmentAttributesForRecord(Specialization);
9625 AddMsStructLayoutForRecord(Specialization);
9626 }
9627
9628 if (ModulePrivateLoc.isValid())
9629 Diag(Specialization->getLocation(), diag::err_module_private_specialization)
9630 << (isPartialSpecialization? 1 : 0)
9631 << FixItHint::CreateRemoval(ModulePrivateLoc);
9632
9633 // Build the fully-sugared type for this class template
9634 // specialization as the user wrote in the specialization
9635 // itself. This means that we'll pretty-print the type retrieved
9636 // from the specialization's declaration the way that the user
9637 // actually wrote the specialization, rather than formatting the
9638 // name based on the "canonical" representation used to store the
9639 // template arguments in the specialization.
9640 TypeSourceInfo *WrittenTy
9641 = Context.getTemplateSpecializationTypeInfo(T: Name, TLoc: TemplateNameLoc,
9642 Args: TemplateArgs, Canon: CanonType);
9643 if (TUK != TUK_Friend) {
9644 Specialization->setTypeAsWritten(WrittenTy);
9645 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
9646 }
9647
9648 // C++ [temp.expl.spec]p9:
9649 // A template explicit specialization is in the scope of the
9650 // namespace in which the template was defined.
9651 //
9652 // We actually implement this paragraph where we set the semantic
9653 // context (in the creation of the ClassTemplateSpecializationDecl),
9654 // but we also maintain the lexical context where the actual
9655 // definition occurs.
9656 Specialization->setLexicalDeclContext(CurContext);
9657
9658 // We may be starting the definition of this specialization.
9659 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
9660 Specialization->startDefinition();
9661
9662 if (TUK == TUK_Friend) {
9663 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext,
9664 L: TemplateNameLoc,
9665 Friend_: WrittenTy,
9666 /*FIXME:*/FriendL: KWLoc);
9667 Friend->setAccess(AS_public);
9668 CurContext->addDecl(Friend);
9669 } else {
9670 // Add the specialization into its lexical context, so that it can
9671 // be seen when iterating through the list of declarations in that
9672 // context. However, specializations are not found by name lookup.
9673 CurContext->addDecl(Specialization);
9674 }
9675
9676 if (SkipBody && SkipBody->ShouldSkip)
9677 return SkipBody->Previous;
9678
9679 Specialization->setInvalidDecl(Invalid);
9680 return Specialization;
9681}
9682
9683Decl *Sema::ActOnTemplateDeclarator(Scope *S,
9684 MultiTemplateParamsArg TemplateParameterLists,
9685 Declarator &D) {
9686 Decl *NewDecl = HandleDeclarator(S, D, TemplateParameterLists);
9687 ActOnDocumentableDecl(D: NewDecl);
9688 return NewDecl;
9689}
9690
9691Decl *Sema::ActOnConceptDefinition(
9692 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
9693 const IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr) {
9694 DeclContext *DC = CurContext;
9695
9696 if (!DC->getRedeclContext()->isFileContext()) {
9697 Diag(NameLoc,
9698 diag::err_concept_decls_may_only_appear_in_global_namespace_scope);
9699 return nullptr;
9700 }
9701
9702 if (TemplateParameterLists.size() > 1) {
9703 Diag(NameLoc, diag::err_concept_extra_headers);
9704 return nullptr;
9705 }
9706
9707 TemplateParameterList *Params = TemplateParameterLists.front();
9708
9709 if (Params->size() == 0) {
9710 Diag(NameLoc, diag::err_concept_no_parameters);
9711 return nullptr;
9712 }
9713
9714 // Ensure that the parameter pack, if present, is the last parameter in the
9715 // template.
9716 for (TemplateParameterList::const_iterator ParamIt = Params->begin(),
9717 ParamEnd = Params->end();
9718 ParamIt != ParamEnd; ++ParamIt) {
9719 Decl const *Param = *ParamIt;
9720 if (Param->isParameterPack()) {
9721 if (++ParamIt == ParamEnd)
9722 break;
9723 Diag(Param->getLocation(),
9724 diag::err_template_param_pack_must_be_last_template_parameter);
9725 return nullptr;
9726 }
9727 }
9728
9729 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr))
9730 return nullptr;
9731
9732 ConceptDecl *NewDecl =
9733 ConceptDecl::Create(C&: Context, DC, L: NameLoc, Name, Params, ConstraintExpr);
9734
9735 if (NewDecl->hasAssociatedConstraints()) {
9736 // C++2a [temp.concept]p4:
9737 // A concept shall not have associated constraints.
9738 Diag(NameLoc, diag::err_concept_no_associated_constraints);
9739 NewDecl->setInvalidDecl();
9740 }
9741
9742 // Check for conflicting previous declaration.
9743 DeclarationNameInfo NameInfo(NewDecl->getDeclName(), NameLoc);
9744 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
9745 forRedeclarationInCurContext());
9746 LookupName(R&: Previous, S);
9747 FilterLookupForScope(R&: Previous, Ctx: DC, S, /*ConsiderLinkage=*/false,
9748 /*AllowInlineNamespace*/false);
9749 bool AddToScope = true;
9750 CheckConceptRedefinition(NewDecl, Previous, AddToScope);
9751
9752 ActOnDocumentableDecl(NewDecl);
9753 if (AddToScope)
9754 PushOnScopeChains(NewDecl, S);
9755 return NewDecl;
9756}
9757
9758void Sema::CheckConceptRedefinition(ConceptDecl *NewDecl,
9759 LookupResult &Previous, bool &AddToScope) {
9760 AddToScope = true;
9761
9762 if (Previous.empty())
9763 return;
9764
9765 auto *OldConcept = dyn_cast<ConceptDecl>(Val: Previous.getRepresentativeDecl()->getUnderlyingDecl());
9766 if (!OldConcept) {
9767 auto *Old = Previous.getRepresentativeDecl();
9768 Diag(NewDecl->getLocation(), diag::err_redefinition_different_kind)
9769 << NewDecl->getDeclName();
9770 notePreviousDefinition(Old, New: NewDecl->getLocation());
9771 AddToScope = false;
9772 return;
9773 }
9774 // Check if we can merge with a concept declaration.
9775 bool IsSame = Context.isSameEntity(NewDecl, OldConcept);
9776 if (!IsSame) {
9777 Diag(NewDecl->getLocation(), diag::err_redefinition_different_concept)
9778 << NewDecl->getDeclName();
9779 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9780 AddToScope = false;
9781 return;
9782 }
9783 if (hasReachableDefinition(OldConcept) &&
9784 IsRedefinitionInModule(NewDecl, OldConcept)) {
9785 Diag(NewDecl->getLocation(), diag::err_redefinition)
9786 << NewDecl->getDeclName();
9787 notePreviousDefinition(Old: OldConcept, New: NewDecl->getLocation());
9788 AddToScope = false;
9789 return;
9790 }
9791 if (!Previous.isSingleResult()) {
9792 // FIXME: we should produce an error in case of ambig and failed lookups.
9793 // Other decls (e.g. namespaces) also have this shortcoming.
9794 return;
9795 }
9796 // We unwrap canonical decl late to check for module visibility.
9797 Context.setPrimaryMergedDecl(NewDecl, OldConcept->getCanonicalDecl());
9798}
9799
9800/// \brief Strips various properties off an implicit instantiation
9801/// that has just been explicitly specialized.
9802static void StripImplicitInstantiation(NamedDecl *D, bool MinGW) {
9803 if (MinGW || (isa<FunctionDecl>(D) &&
9804 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()))
9805 D->dropAttrs<DLLImportAttr, DLLExportAttr>();
9806
9807 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D))
9808 FD->setInlineSpecified(false);
9809}
9810
9811/// Compute the diagnostic location for an explicit instantiation
9812// declaration or definition.
9813static SourceLocation DiagLocForExplicitInstantiation(
9814 NamedDecl* D, SourceLocation PointOfInstantiation) {
9815 // Explicit instantiations following a specialization have no effect and
9816 // hence no PointOfInstantiation. In that case, walk decl backwards
9817 // until a valid name loc is found.
9818 SourceLocation PrevDiagLoc = PointOfInstantiation;
9819 for (Decl *Prev = D; Prev && !PrevDiagLoc.isValid();
9820 Prev = Prev->getPreviousDecl()) {
9821 PrevDiagLoc = Prev->getLocation();
9822 }
9823 assert(PrevDiagLoc.isValid() &&
9824 "Explicit instantiation without point of instantiation?");
9825 return PrevDiagLoc;
9826}
9827
9828/// Diagnose cases where we have an explicit template specialization
9829/// before/after an explicit template instantiation, producing diagnostics
9830/// for those cases where they are required and determining whether the
9831/// new specialization/instantiation will have any effect.
9832///
9833/// \param NewLoc the location of the new explicit specialization or
9834/// instantiation.
9835///
9836/// \param NewTSK the kind of the new explicit specialization or instantiation.
9837///
9838/// \param PrevDecl the previous declaration of the entity.
9839///
9840/// \param PrevTSK the kind of the old explicit specialization or instantiatin.
9841///
9842/// \param PrevPointOfInstantiation if valid, indicates where the previous
9843/// declaration was instantiated (either implicitly or explicitly).
9844///
9845/// \param HasNoEffect will be set to true to indicate that the new
9846/// specialization or instantiation has no effect and should be ignored.
9847///
9848/// \returns true if there was an error that should prevent the introduction of
9849/// the new declaration into the AST, false otherwise.
9850bool
9851Sema::CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
9852 TemplateSpecializationKind NewTSK,
9853 NamedDecl *PrevDecl,
9854 TemplateSpecializationKind PrevTSK,
9855 SourceLocation PrevPointOfInstantiation,
9856 bool &HasNoEffect) {
9857 HasNoEffect = false;
9858
9859 switch (NewTSK) {
9860 case TSK_Undeclared:
9861 case TSK_ImplicitInstantiation:
9862 assert(
9863 (PrevTSK == TSK_Undeclared || PrevTSK == TSK_ImplicitInstantiation) &&
9864 "previous declaration must be implicit!");
9865 return false;
9866
9867 case TSK_ExplicitSpecialization:
9868 switch (PrevTSK) {
9869 case TSK_Undeclared:
9870 case TSK_ExplicitSpecialization:
9871 // Okay, we're just specializing something that is either already
9872 // explicitly specialized or has merely been mentioned without any
9873 // instantiation.
9874 return false;
9875
9876 case TSK_ImplicitInstantiation:
9877 if (PrevPointOfInstantiation.isInvalid()) {
9878 // The declaration itself has not actually been instantiated, so it is
9879 // still okay to specialize it.
9880 StripImplicitInstantiation(
9881 D: PrevDecl,
9882 MinGW: Context.getTargetInfo().getTriple().isWindowsGNUEnvironment());
9883 return false;
9884 }
9885 // Fall through
9886 [[fallthrough]];
9887
9888 case TSK_ExplicitInstantiationDeclaration:
9889 case TSK_ExplicitInstantiationDefinition:
9890 assert((PrevTSK == TSK_ImplicitInstantiation ||
9891 PrevPointOfInstantiation.isValid()) &&
9892 "Explicit instantiation without point of instantiation?");
9893
9894 // C++ [temp.expl.spec]p6:
9895 // If a template, a member template or the member of a class template
9896 // is explicitly specialized then that specialization shall be declared
9897 // before the first use of that specialization that would cause an
9898 // implicit instantiation to take place, in every translation unit in
9899 // which such a use occurs; no diagnostic is required.
9900 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9901 // Is there any previous explicit specialization declaration?
9902 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization)
9903 return false;
9904 }
9905
9906 Diag(NewLoc, diag::err_specialization_after_instantiation)
9907 << PrevDecl;
9908 Diag(PrevPointOfInstantiation, diag::note_instantiation_required_here)
9909 << (PrevTSK != TSK_ImplicitInstantiation);
9910
9911 return true;
9912 }
9913 llvm_unreachable("The switch over PrevTSK must be exhaustive.");
9914
9915 case TSK_ExplicitInstantiationDeclaration:
9916 switch (PrevTSK) {
9917 case TSK_ExplicitInstantiationDeclaration:
9918 // This explicit instantiation declaration is redundant (that's okay).
9919 HasNoEffect = true;
9920 return false;
9921
9922 case TSK_Undeclared:
9923 case TSK_ImplicitInstantiation:
9924 // We're explicitly instantiating something that may have already been
9925 // implicitly instantiated; that's fine.
9926 return false;
9927
9928 case TSK_ExplicitSpecialization:
9929 // C++0x [temp.explicit]p4:
9930 // For a given set of template parameters, if an explicit instantiation
9931 // of a template appears after a declaration of an explicit
9932 // specialization for that template, the explicit instantiation has no
9933 // effect.
9934 HasNoEffect = true;
9935 return false;
9936
9937 case TSK_ExplicitInstantiationDefinition:
9938 // C++0x [temp.explicit]p10:
9939 // If an entity is the subject of both an explicit instantiation
9940 // declaration and an explicit instantiation definition in the same
9941 // translation unit, the definition shall follow the declaration.
9942 Diag(NewLoc,
9943 diag::err_explicit_instantiation_declaration_after_definition);
9944
9945 // Explicit instantiations following a specialization have no effect and
9946 // hence no PrevPointOfInstantiation. In that case, walk decl backwards
9947 // until a valid name loc is found.
9948 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
9949 diag::note_explicit_instantiation_definition_here);
9950 HasNoEffect = true;
9951 return false;
9952 }
9953 llvm_unreachable("Unexpected TemplateSpecializationKind!");
9954
9955 case TSK_ExplicitInstantiationDefinition:
9956 switch (PrevTSK) {
9957 case TSK_Undeclared:
9958 case TSK_ImplicitInstantiation:
9959 // We're explicitly instantiating something that may have already been
9960 // implicitly instantiated; that's fine.
9961 return false;
9962
9963 case TSK_ExplicitSpecialization:
9964 // C++ DR 259, C++0x [temp.explicit]p4:
9965 // For a given set of template parameters, if an explicit
9966 // instantiation of a template appears after a declaration of
9967 // an explicit specialization for that template, the explicit
9968 // instantiation has no effect.
9969 Diag(NewLoc, diag::warn_explicit_instantiation_after_specialization)
9970 << PrevDecl;
9971 Diag(PrevDecl->getLocation(),
9972 diag::note_previous_template_specialization);
9973 HasNoEffect = true;
9974 return false;
9975
9976 case TSK_ExplicitInstantiationDeclaration:
9977 // We're explicitly instantiating a definition for something for which we
9978 // were previously asked to suppress instantiations. That's fine.
9979
9980 // C++0x [temp.explicit]p4:
9981 // For a given set of template parameters, if an explicit instantiation
9982 // of a template appears after a declaration of an explicit
9983 // specialization for that template, the explicit instantiation has no
9984 // effect.
9985 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
9986 // Is there any previous explicit specialization declaration?
9987 if (getTemplateSpecializationKind(D: Prev) == TSK_ExplicitSpecialization) {
9988 HasNoEffect = true;
9989 break;
9990 }
9991 }
9992
9993 return false;
9994
9995 case TSK_ExplicitInstantiationDefinition:
9996 // C++0x [temp.spec]p5:
9997 // For a given template and a given set of template-arguments,
9998 // - an explicit instantiation definition shall appear at most once
9999 // in a program,
10000
10001 // MSVCCompat: MSVC silently ignores duplicate explicit instantiations.
10002 Diag(NewLoc, (getLangOpts().MSVCCompat)
10003 ? diag::ext_explicit_instantiation_duplicate
10004 : diag::err_explicit_instantiation_duplicate)
10005 << PrevDecl;
10006 Diag(DiagLocForExplicitInstantiation(PrevDecl, PrevPointOfInstantiation),
10007 diag::note_previous_explicit_instantiation);
10008 HasNoEffect = true;
10009 return false;
10010 }
10011 }
10012
10013 llvm_unreachable("Missing specialization/instantiation case?");
10014}
10015
10016/// Perform semantic analysis for the given dependent function
10017/// template specialization.
10018///
10019/// The only possible way to get a dependent function template specialization
10020/// is with a friend declaration, like so:
10021///
10022/// \code
10023/// template \<class T> void foo(T);
10024/// template \<class T> class A {
10025/// friend void foo<>(T);
10026/// };
10027/// \endcode
10028///
10029/// There really isn't any useful analysis we can do here, so we
10030/// just store the information.
10031bool Sema::CheckDependentFunctionTemplateSpecialization(
10032 FunctionDecl *FD, const TemplateArgumentListInfo *ExplicitTemplateArgs,
10033 LookupResult &Previous) {
10034 // Remove anything from Previous that isn't a function template in
10035 // the correct context.
10036 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
10037 LookupResult::Filter F = Previous.makeFilter();
10038 enum DiscardReason { NotAFunctionTemplate, NotAMemberOfEnclosing };
10039 SmallVector<std::pair<DiscardReason, Decl *>, 8> DiscardedCandidates;
10040 while (F.hasNext()) {
10041 NamedDecl *D = F.next()->getUnderlyingDecl();
10042 if (!isa<FunctionTemplateDecl>(Val: D)) {
10043 F.erase();
10044 DiscardedCandidates.push_back(std::make_pair(x: NotAFunctionTemplate, y&: D));
10045 continue;
10046 }
10047
10048 if (!FDLookupContext->InEnclosingNamespaceSetOf(
10049 NS: D->getDeclContext()->getRedeclContext())) {
10050 F.erase();
10051 DiscardedCandidates.push_back(std::make_pair(x: NotAMemberOfEnclosing, y&: D));
10052 continue;
10053 }
10054 }
10055 F.done();
10056
10057 bool IsFriend = FD->getFriendObjectKind() != Decl::FOK_None;
10058 if (Previous.empty()) {
10059 Diag(FD->getLocation(), diag::err_dependent_function_template_spec_no_match)
10060 << IsFriend;
10061 for (auto &P : DiscardedCandidates)
10062 Diag(P.second->getLocation(),
10063 diag::note_dependent_function_template_spec_discard_reason)
10064 << P.first << IsFriend;
10065 return true;
10066 }
10067
10068 FD->setDependentTemplateSpecialization(Context, Templates: Previous.asUnresolvedSet(),
10069 TemplateArgs: ExplicitTemplateArgs);
10070 return false;
10071}
10072
10073/// Perform semantic analysis for the given function template
10074/// specialization.
10075///
10076/// This routine performs all of the semantic analysis required for an
10077/// explicit function template specialization. On successful completion,
10078/// the function declaration \p FD will become a function template
10079/// specialization.
10080///
10081/// \param FD the function declaration, which will be updated to become a
10082/// function template specialization.
10083///
10084/// \param ExplicitTemplateArgs the explicitly-provided template arguments,
10085/// if any. Note that this may be valid info even when 0 arguments are
10086/// explicitly provided as in, e.g., \c void sort<>(char*, char*);
10087/// as it anyway contains info on the angle brackets locations.
10088///
10089/// \param Previous the set of declarations that may be specialized by
10090/// this function specialization.
10091///
10092/// \param QualifiedFriend whether this is a lookup for a qualified friend
10093/// declaration with no explicit template argument list that might be
10094/// befriending a function template specialization.
10095bool Sema::CheckFunctionTemplateSpecialization(
10096 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
10097 LookupResult &Previous, bool QualifiedFriend) {
10098 // The set of function template specializations that could match this
10099 // explicit function template specialization.
10100 UnresolvedSet<8> Candidates;
10101 TemplateSpecCandidateSet FailedCandidates(FD->getLocation(),
10102 /*ForTakingAddress=*/false);
10103
10104 llvm::SmallDenseMap<FunctionDecl *, TemplateArgumentListInfo, 8>
10105 ConvertedTemplateArgs;
10106
10107 DeclContext *FDLookupContext = FD->getDeclContext()->getRedeclContext();
10108 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
10109 I != E; ++I) {
10110 NamedDecl *Ovl = (*I)->getUnderlyingDecl();
10111 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Ovl)) {
10112 // Only consider templates found within the same semantic lookup scope as
10113 // FD.
10114 if (!FDLookupContext->InEnclosingNamespaceSetOf(
10115 NS: Ovl->getDeclContext()->getRedeclContext()))
10116 continue;
10117
10118 // When matching a constexpr member function template specialization
10119 // against the primary template, we don't yet know whether the
10120 // specialization has an implicit 'const' (because we don't know whether
10121 // it will be a static member function until we know which template it
10122 // specializes), so adjust it now assuming it specializes this template.
10123 QualType FT = FD->getType();
10124 if (FD->isConstexpr()) {
10125 CXXMethodDecl *OldMD =
10126 dyn_cast<CXXMethodDecl>(Val: FunTmpl->getTemplatedDecl());
10127 if (OldMD && OldMD->isConst()) {
10128 const FunctionProtoType *FPT = FT->castAs<FunctionProtoType>();
10129 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10130 EPI.TypeQuals.addConst();
10131 FT = Context.getFunctionType(ResultTy: FPT->getReturnType(),
10132 Args: FPT->getParamTypes(), EPI);
10133 }
10134 }
10135
10136 TemplateArgumentListInfo Args;
10137 if (ExplicitTemplateArgs)
10138 Args = *ExplicitTemplateArgs;
10139
10140 // C++ [temp.expl.spec]p11:
10141 // A trailing template-argument can be left unspecified in the
10142 // template-id naming an explicit function template specialization
10143 // provided it can be deduced from the function argument type.
10144 // Perform template argument deduction to determine whether we may be
10145 // specializing this template.
10146 // FIXME: It is somewhat wasteful to build
10147 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10148 FunctionDecl *Specialization = nullptr;
10149 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
10150 cast<FunctionTemplateDecl>(FunTmpl->getFirstDecl()),
10151 ExplicitTemplateArgs ? &Args : nullptr, FT, Specialization, Info);
10152 TDK != TemplateDeductionResult::Success) {
10153 // Template argument deduction failed; record why it failed, so
10154 // that we can provide nifty diagnostics.
10155 FailedCandidates.addCandidate().set(
10156 I.getPair(), FunTmpl->getTemplatedDecl(),
10157 MakeDeductionFailureInfo(Context, TDK, Info));
10158 (void)TDK;
10159 continue;
10160 }
10161
10162 // Target attributes are part of the cuda function signature, so
10163 // the deduced template's cuda target must match that of the
10164 // specialization. Given that C++ template deduction does not
10165 // take target attributes into account, we reject candidates
10166 // here that have a different target.
10167 if (LangOpts.CUDA &&
10168 CUDA().IdentifyTarget(D: Specialization,
10169 /* IgnoreImplicitHDAttr = */ true) !=
10170 CUDA().IdentifyTarget(D: FD, /* IgnoreImplicitHDAttr = */ true)) {
10171 FailedCandidates.addCandidate().set(
10172 I.getPair(), FunTmpl->getTemplatedDecl(),
10173 MakeDeductionFailureInfo(
10174 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
10175 continue;
10176 }
10177
10178 // Record this candidate.
10179 if (ExplicitTemplateArgs)
10180 ConvertedTemplateArgs[Specialization] = std::move(Args);
10181 Candidates.addDecl(Specialization, I.getAccess());
10182 }
10183 }
10184
10185 // For a qualified friend declaration (with no explicit marker to indicate
10186 // that a template specialization was intended), note all (template and
10187 // non-template) candidates.
10188 if (QualifiedFriend && Candidates.empty()) {
10189 Diag(FD->getLocation(), diag::err_qualified_friend_no_match)
10190 << FD->getDeclName() << FDLookupContext;
10191 // FIXME: We should form a single candidate list and diagnose all
10192 // candidates at once, to get proper sorting and limiting.
10193 for (auto *OldND : Previous) {
10194 if (auto *OldFD = dyn_cast<FunctionDecl>(Val: OldND->getUnderlyingDecl()))
10195 NoteOverloadCandidate(Found: OldND, Fn: OldFD, RewriteKind: CRK_None, DestType: FD->getType(), TakingAddress: false);
10196 }
10197 FailedCandidates.NoteCandidates(*this, FD->getLocation());
10198 return true;
10199 }
10200
10201 // Find the most specialized function template.
10202 UnresolvedSetIterator Result = getMostSpecialized(
10203 Candidates.begin(), Candidates.end(), FailedCandidates, FD->getLocation(),
10204 PDiag(diag::err_function_template_spec_no_match) << FD->getDeclName(),
10205 PDiag(diag::err_function_template_spec_ambiguous)
10206 << FD->getDeclName() << (ExplicitTemplateArgs != nullptr),
10207 PDiag(diag::note_function_template_spec_matched));
10208
10209 if (Result == Candidates.end())
10210 return true;
10211
10212 // Ignore access information; it doesn't figure into redeclaration checking.
10213 FunctionDecl *Specialization = cast<FunctionDecl>(Val: *Result);
10214
10215 // C++23 [except.spec]p13:
10216 // An exception specification is considered to be needed when:
10217 // - [...]
10218 // - the exception specification is compared to that of another declaration
10219 // (e.g., an explicit specialization or an overriding virtual function);
10220 // - [...]
10221 //
10222 // The exception specification of a defaulted function is evaluated as
10223 // described above only when needed; similarly, the noexcept-specifier of a
10224 // specialization of a function template or member function of a class
10225 // template is instantiated only when needed.
10226 //
10227 // The standard doesn't specify what the "comparison with another declaration"
10228 // entails, nor the exact circumstances in which it occurs. Moreover, it does
10229 // not state which properties of an explicit specialization must match the
10230 // primary template.
10231 //
10232 // We assume that an explicit specialization must correspond with (per
10233 // [basic.scope.scope]p4) and declare the same entity as (per [basic.link]p8)
10234 // the declaration produced by substitution into the function template.
10235 //
10236 // Since the determination whether two function declarations correspond does
10237 // not consider exception specification, we only need to instantiate it once
10238 // we determine the primary template when comparing types per
10239 // [basic.link]p11.1.
10240 auto *SpecializationFPT =
10241 Specialization->getType()->castAs<FunctionProtoType>();
10242 // If the function has a dependent exception specification, resolve it after
10243 // we have selected the primary template so we can check whether it matches.
10244 if (getLangOpts().CPlusPlus17 &&
10245 isUnresolvedExceptionSpec(SpecializationFPT->getExceptionSpecType()) &&
10246 !ResolveExceptionSpec(Loc: FD->getLocation(), FPT: SpecializationFPT))
10247 return true;
10248
10249 FunctionTemplateSpecializationInfo *SpecInfo
10250 = Specialization->getTemplateSpecializationInfo();
10251 assert(SpecInfo && "Function template specialization info missing?");
10252
10253 // Note: do not overwrite location info if previous template
10254 // specialization kind was explicit.
10255 TemplateSpecializationKind TSK = SpecInfo->getTemplateSpecializationKind();
10256 if (TSK == TSK_Undeclared || TSK == TSK_ImplicitInstantiation) {
10257 Specialization->setLocation(FD->getLocation());
10258 Specialization->setLexicalDeclContext(FD->getLexicalDeclContext());
10259 // C++11 [dcl.constexpr]p1: An explicit specialization of a constexpr
10260 // function can differ from the template declaration with respect to
10261 // the constexpr specifier.
10262 // FIXME: We need an update record for this AST mutation.
10263 // FIXME: What if there are multiple such prior declarations (for instance,
10264 // from different modules)?
10265 Specialization->setConstexprKind(FD->getConstexprKind());
10266 }
10267
10268 // FIXME: Check if the prior specialization has a point of instantiation.
10269 // If so, we have run afoul of .
10270
10271 // If this is a friend declaration, then we're not really declaring
10272 // an explicit specialization.
10273 bool isFriend = (FD->getFriendObjectKind() != Decl::FOK_None);
10274
10275 // Check the scope of this explicit specialization.
10276 if (!isFriend &&
10277 CheckTemplateSpecializationScope(*this,
10278 Specialization->getPrimaryTemplate(),
10279 Specialization, FD->getLocation(),
10280 false))
10281 return true;
10282
10283 // C++ [temp.expl.spec]p6:
10284 // If a template, a member template or the member of a class template is
10285 // explicitly specialized then that specialization shall be declared
10286 // before the first use of that specialization that would cause an implicit
10287 // instantiation to take place, in every translation unit in which such a
10288 // use occurs; no diagnostic is required.
10289 bool HasNoEffect = false;
10290 if (!isFriend &&
10291 CheckSpecializationInstantiationRedecl(NewLoc: FD->getLocation(),
10292 NewTSK: TSK_ExplicitSpecialization,
10293 PrevDecl: Specialization,
10294 PrevTSK: SpecInfo->getTemplateSpecializationKind(),
10295 PrevPointOfInstantiation: SpecInfo->getPointOfInstantiation(),
10296 HasNoEffect))
10297 return true;
10298
10299 // Mark the prior declaration as an explicit specialization, so that later
10300 // clients know that this is an explicit specialization.
10301 if (!isFriend) {
10302 // Since explicit specializations do not inherit '=delete' from their
10303 // primary function template - check if the 'specialization' that was
10304 // implicitly generated (during template argument deduction for partial
10305 // ordering) from the most specialized of all the function templates that
10306 // 'FD' could have been specializing, has a 'deleted' definition. If so,
10307 // first check that it was implicitly generated during template argument
10308 // deduction by making sure it wasn't referenced, and then reset the deleted
10309 // flag to not-deleted, so that we can inherit that information from 'FD'.
10310 if (Specialization->isDeleted() && !SpecInfo->isExplicitSpecialization() &&
10311 !Specialization->getCanonicalDecl()->isReferenced()) {
10312 // FIXME: This assert will not hold in the presence of modules.
10313 assert(
10314 Specialization->getCanonicalDecl() == Specialization &&
10315 "This must be the only existing declaration of this specialization");
10316 // FIXME: We need an update record for this AST mutation.
10317 Specialization->setDeletedAsWritten(D: false);
10318 }
10319 // FIXME: We need an update record for this AST mutation.
10320 SpecInfo->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10321 MarkUnusedFileScopedDecl(Specialization);
10322 }
10323
10324 // Turn the given function declaration into a function template
10325 // specialization, with the template arguments from the previous
10326 // specialization.
10327 // Take copies of (semantic and syntactic) template argument lists.
10328 const TemplateArgumentList *TemplArgs = TemplateArgumentList::CreateCopy(
10329 Context, Args: Specialization->getTemplateSpecializationArgs()->asArray());
10330 FD->setFunctionTemplateSpecialization(
10331 Template: Specialization->getPrimaryTemplate(), TemplateArgs: TemplArgs, /*InsertPos=*/nullptr,
10332 TSK: SpecInfo->getTemplateSpecializationKind(),
10333 TemplateArgsAsWritten: ExplicitTemplateArgs ? &ConvertedTemplateArgs[Specialization] : nullptr);
10334
10335 // A function template specialization inherits the target attributes
10336 // of its template. (We require the attributes explicitly in the
10337 // code to match, but a template may have implicit attributes by
10338 // virtue e.g. of being constexpr, and it passes these implicit
10339 // attributes on to its specializations.)
10340 if (LangOpts.CUDA)
10341 CUDA().inheritTargetAttrs(FD, TD: *Specialization->getPrimaryTemplate());
10342
10343 // The "previous declaration" for this function template specialization is
10344 // the prior function template specialization.
10345 Previous.clear();
10346 Previous.addDecl(Specialization);
10347 return false;
10348}
10349
10350/// Perform semantic analysis for the given non-template member
10351/// specialization.
10352///
10353/// This routine performs all of the semantic analysis required for an
10354/// explicit member function specialization. On successful completion,
10355/// the function declaration \p FD will become a member function
10356/// specialization.
10357///
10358/// \param Member the member declaration, which will be updated to become a
10359/// specialization.
10360///
10361/// \param Previous the set of declarations, one of which may be specialized
10362/// by this function specialization; the set will be modified to contain the
10363/// redeclared member.
10364bool
10365Sema::CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous) {
10366 assert(!isa<TemplateDecl>(Member) && "Only for non-template members");
10367
10368 // Try to find the member we are instantiating.
10369 NamedDecl *FoundInstantiation = nullptr;
10370 NamedDecl *Instantiation = nullptr;
10371 NamedDecl *InstantiatedFrom = nullptr;
10372 MemberSpecializationInfo *MSInfo = nullptr;
10373
10374 if (Previous.empty()) {
10375 // Nowhere to look anyway.
10376 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Member)) {
10377 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
10378 I != E; ++I) {
10379 NamedDecl *D = (*I)->getUnderlyingDecl();
10380 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
10381 QualType Adjusted = Function->getType();
10382 if (!hasExplicitCallingConv(T: Adjusted))
10383 Adjusted = adjustCCAndNoReturn(ArgFunctionType: Adjusted, FunctionType: Method->getType());
10384 // This doesn't handle deduced return types, but both function
10385 // declarations should be undeduced at this point.
10386 if (Context.hasSameType(Adjusted, Method->getType())) {
10387 FoundInstantiation = *I;
10388 Instantiation = Method;
10389 InstantiatedFrom = Method->getInstantiatedFromMemberFunction();
10390 MSInfo = Method->getMemberSpecializationInfo();
10391 break;
10392 }
10393 }
10394 }
10395 } else if (isa<VarDecl>(Val: Member)) {
10396 VarDecl *PrevVar;
10397 if (Previous.isSingleResult() &&
10398 (PrevVar = dyn_cast<VarDecl>(Val: Previous.getFoundDecl())))
10399 if (PrevVar->isStaticDataMember()) {
10400 FoundInstantiation = Previous.getRepresentativeDecl();
10401 Instantiation = PrevVar;
10402 InstantiatedFrom = PrevVar->getInstantiatedFromStaticDataMember();
10403 MSInfo = PrevVar->getMemberSpecializationInfo();
10404 }
10405 } else if (isa<RecordDecl>(Val: Member)) {
10406 CXXRecordDecl *PrevRecord;
10407 if (Previous.isSingleResult() &&
10408 (PrevRecord = dyn_cast<CXXRecordDecl>(Val: Previous.getFoundDecl()))) {
10409 FoundInstantiation = Previous.getRepresentativeDecl();
10410 Instantiation = PrevRecord;
10411 InstantiatedFrom = PrevRecord->getInstantiatedFromMemberClass();
10412 MSInfo = PrevRecord->getMemberSpecializationInfo();
10413 }
10414 } else if (isa<EnumDecl>(Val: Member)) {
10415 EnumDecl *PrevEnum;
10416 if (Previous.isSingleResult() &&
10417 (PrevEnum = dyn_cast<EnumDecl>(Val: Previous.getFoundDecl()))) {
10418 FoundInstantiation = Previous.getRepresentativeDecl();
10419 Instantiation = PrevEnum;
10420 InstantiatedFrom = PrevEnum->getInstantiatedFromMemberEnum();
10421 MSInfo = PrevEnum->getMemberSpecializationInfo();
10422 }
10423 }
10424
10425 if (!Instantiation) {
10426 // There is no previous declaration that matches. Since member
10427 // specializations are always out-of-line, the caller will complain about
10428 // this mismatch later.
10429 return false;
10430 }
10431
10432 // A member specialization in a friend declaration isn't really declaring
10433 // an explicit specialization, just identifying a specific (possibly implicit)
10434 // specialization. Don't change the template specialization kind.
10435 //
10436 // FIXME: Is this really valid? Other compilers reject.
10437 if (Member->getFriendObjectKind() != Decl::FOK_None) {
10438 // Preserve instantiation information.
10439 if (InstantiatedFrom && isa<CXXMethodDecl>(Val: Member)) {
10440 cast<CXXMethodDecl>(Val: Member)->setInstantiationOfMemberFunction(
10441 cast<CXXMethodDecl>(Val: InstantiatedFrom),
10442 cast<CXXMethodDecl>(Val: Instantiation)->getTemplateSpecializationKind());
10443 } else if (InstantiatedFrom && isa<CXXRecordDecl>(Val: Member)) {
10444 cast<CXXRecordDecl>(Val: Member)->setInstantiationOfMemberClass(
10445 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom),
10446 TSK: cast<CXXRecordDecl>(Val: Instantiation)->getTemplateSpecializationKind());
10447 }
10448
10449 Previous.clear();
10450 Previous.addDecl(D: FoundInstantiation);
10451 return false;
10452 }
10453
10454 // Make sure that this is a specialization of a member.
10455 if (!InstantiatedFrom) {
10456 Diag(Member->getLocation(), diag::err_spec_member_not_instantiated)
10457 << Member;
10458 Diag(Instantiation->getLocation(), diag::note_specialized_decl);
10459 return true;
10460 }
10461
10462 // C++ [temp.expl.spec]p6:
10463 // If a template, a member template or the member of a class template is
10464 // explicitly specialized then that specialization shall be declared
10465 // before the first use of that specialization that would cause an implicit
10466 // instantiation to take place, in every translation unit in which such a
10467 // use occurs; no diagnostic is required.
10468 assert(MSInfo && "Member specialization info missing?");
10469
10470 bool HasNoEffect = false;
10471 if (CheckSpecializationInstantiationRedecl(NewLoc: Member->getLocation(),
10472 NewTSK: TSK_ExplicitSpecialization,
10473 PrevDecl: Instantiation,
10474 PrevTSK: MSInfo->getTemplateSpecializationKind(),
10475 PrevPointOfInstantiation: MSInfo->getPointOfInstantiation(),
10476 HasNoEffect))
10477 return true;
10478
10479 // Check the scope of this explicit specialization.
10480 if (CheckTemplateSpecializationScope(*this,
10481 InstantiatedFrom,
10482 Instantiation, Member->getLocation(),
10483 false))
10484 return true;
10485
10486 // Note that this member specialization is an "instantiation of" the
10487 // corresponding member of the original template.
10488 if (auto *MemberFunction = dyn_cast<FunctionDecl>(Val: Member)) {
10489 FunctionDecl *InstantiationFunction = cast<FunctionDecl>(Val: Instantiation);
10490 if (InstantiationFunction->getTemplateSpecializationKind() ==
10491 TSK_ImplicitInstantiation) {
10492 // Explicit specializations of member functions of class templates do not
10493 // inherit '=delete' from the member function they are specializing.
10494 if (InstantiationFunction->isDeleted()) {
10495 // FIXME: This assert will not hold in the presence of modules.
10496 assert(InstantiationFunction->getCanonicalDecl() ==
10497 InstantiationFunction);
10498 // FIXME: We need an update record for this AST mutation.
10499 InstantiationFunction->setDeletedAsWritten(D: false);
10500 }
10501 }
10502
10503 MemberFunction->setInstantiationOfMemberFunction(
10504 cast<CXXMethodDecl>(Val: InstantiatedFrom), TSK_ExplicitSpecialization);
10505 } else if (auto *MemberVar = dyn_cast<VarDecl>(Val: Member)) {
10506 MemberVar->setInstantiationOfStaticDataMember(
10507 VD: cast<VarDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10508 } else if (auto *MemberClass = dyn_cast<CXXRecordDecl>(Val: Member)) {
10509 MemberClass->setInstantiationOfMemberClass(
10510 RD: cast<CXXRecordDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10511 } else if (auto *MemberEnum = dyn_cast<EnumDecl>(Val: Member)) {
10512 MemberEnum->setInstantiationOfMemberEnum(
10513 ED: cast<EnumDecl>(Val: InstantiatedFrom), TSK: TSK_ExplicitSpecialization);
10514 } else {
10515 llvm_unreachable("unknown member specialization kind");
10516 }
10517
10518 // Save the caller the trouble of having to figure out which declaration
10519 // this specialization matches.
10520 Previous.clear();
10521 Previous.addDecl(D: FoundInstantiation);
10522 return false;
10523}
10524
10525/// Complete the explicit specialization of a member of a class template by
10526/// updating the instantiated member to be marked as an explicit specialization.
10527///
10528/// \param OrigD The member declaration instantiated from the template.
10529/// \param Loc The location of the explicit specialization of the member.
10530template<typename DeclT>
10531static void completeMemberSpecializationImpl(Sema &S, DeclT *OrigD,
10532 SourceLocation Loc) {
10533 if (OrigD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
10534 return;
10535
10536 // FIXME: Inform AST mutation listeners of this AST mutation.
10537 // FIXME: If there are multiple in-class declarations of the member (from
10538 // multiple modules, or a declaration and later definition of a member type),
10539 // should we update all of them?
10540 OrigD->setTemplateSpecializationKind(TSK_ExplicitSpecialization);
10541 OrigD->setLocation(Loc);
10542}
10543
10544void Sema::CompleteMemberSpecialization(NamedDecl *Member,
10545 LookupResult &Previous) {
10546 NamedDecl *Instantiation = cast<NamedDecl>(Member->getCanonicalDecl());
10547 if (Instantiation == Member)
10548 return;
10549
10550 if (auto *Function = dyn_cast<CXXMethodDecl>(Instantiation))
10551 completeMemberSpecializationImpl(*this, Function, Member->getLocation());
10552 else if (auto *Var = dyn_cast<VarDecl>(Instantiation))
10553 completeMemberSpecializationImpl(*this, Var, Member->getLocation());
10554 else if (auto *Record = dyn_cast<CXXRecordDecl>(Instantiation))
10555 completeMemberSpecializationImpl(*this, Record, Member->getLocation());
10556 else if (auto *Enum = dyn_cast<EnumDecl>(Instantiation))
10557 completeMemberSpecializationImpl(*this, Enum, Member->getLocation());
10558 else
10559 llvm_unreachable("unknown member specialization kind");
10560}
10561
10562/// Check the scope of an explicit instantiation.
10563///
10564/// \returns true if a serious error occurs, false otherwise.
10565static bool CheckExplicitInstantiationScope(Sema &S, NamedDecl *D,
10566 SourceLocation InstLoc,
10567 bool WasQualifiedName) {
10568 DeclContext *OrigContext= D->getDeclContext()->getEnclosingNamespaceContext();
10569 DeclContext *CurContext = S.CurContext->getRedeclContext();
10570
10571 if (CurContext->isRecord()) {
10572 S.Diag(InstLoc, diag::err_explicit_instantiation_in_class)
10573 << D;
10574 return true;
10575 }
10576
10577 // C++11 [temp.explicit]p3:
10578 // An explicit instantiation shall appear in an enclosing namespace of its
10579 // template. If the name declared in the explicit instantiation is an
10580 // unqualified name, the explicit instantiation shall appear in the
10581 // namespace where its template is declared or, if that namespace is inline
10582 // (7.3.1), any namespace from its enclosing namespace set.
10583 //
10584 // This is DR275, which we do not retroactively apply to C++98/03.
10585 if (WasQualifiedName) {
10586 if (CurContext->Encloses(DC: OrigContext))
10587 return false;
10588 } else {
10589 if (CurContext->InEnclosingNamespaceSetOf(NS: OrigContext))
10590 return false;
10591 }
10592
10593 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Val: OrigContext)) {
10594 if (WasQualifiedName)
10595 S.Diag(InstLoc,
10596 S.getLangOpts().CPlusPlus11?
10597 diag::err_explicit_instantiation_out_of_scope :
10598 diag::warn_explicit_instantiation_out_of_scope_0x)
10599 << D << NS;
10600 else
10601 S.Diag(InstLoc,
10602 S.getLangOpts().CPlusPlus11?
10603 diag::err_explicit_instantiation_unqualified_wrong_namespace :
10604 diag::warn_explicit_instantiation_unqualified_wrong_namespace_0x)
10605 << D << NS;
10606 } else
10607 S.Diag(InstLoc,
10608 S.getLangOpts().CPlusPlus11?
10609 diag::err_explicit_instantiation_must_be_global :
10610 diag::warn_explicit_instantiation_must_be_global_0x)
10611 << D;
10612 S.Diag(D->getLocation(), diag::note_explicit_instantiation_here);
10613 return false;
10614}
10615
10616/// Common checks for whether an explicit instantiation of \p D is valid.
10617static bool CheckExplicitInstantiation(Sema &S, NamedDecl *D,
10618 SourceLocation InstLoc,
10619 bool WasQualifiedName,
10620 TemplateSpecializationKind TSK) {
10621 // C++ [temp.explicit]p13:
10622 // An explicit instantiation declaration shall not name a specialization of
10623 // a template with internal linkage.
10624 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10625 D->getFormalLinkage() == Linkage::Internal) {
10626 S.Diag(InstLoc, diag::err_explicit_instantiation_internal_linkage) << D;
10627 return true;
10628 }
10629
10630 // C++11 [temp.explicit]p3: [DR 275]
10631 // An explicit instantiation shall appear in an enclosing namespace of its
10632 // template.
10633 if (CheckExplicitInstantiationScope(S, D, InstLoc, WasQualifiedName))
10634 return true;
10635
10636 return false;
10637}
10638
10639/// Determine whether the given scope specifier has a template-id in it.
10640static bool ScopeSpecifierHasTemplateId(const CXXScopeSpec &SS) {
10641 if (!SS.isSet())
10642 return false;
10643
10644 // C++11 [temp.explicit]p3:
10645 // If the explicit instantiation is for a member function, a member class
10646 // or a static data member of a class template specialization, the name of
10647 // the class template specialization in the qualified-id for the member
10648 // name shall be a simple-template-id.
10649 //
10650 // C++98 has the same restriction, just worded differently.
10651 for (NestedNameSpecifier *NNS = SS.getScopeRep(); NNS;
10652 NNS = NNS->getPrefix())
10653 if (const Type *T = NNS->getAsType())
10654 if (isa<TemplateSpecializationType>(Val: T))
10655 return true;
10656
10657 return false;
10658}
10659
10660/// Make a dllexport or dllimport attr on a class template specialization take
10661/// effect.
10662static void dllExportImportClassTemplateSpecialization(
10663 Sema &S, ClassTemplateSpecializationDecl *Def) {
10664 auto *A = cast_or_null<InheritableAttr>(Val: getDLLAttr(Def));
10665 assert(A && "dllExportImportClassTemplateSpecialization called "
10666 "on Def without dllexport or dllimport");
10667
10668 // We reject explicit instantiations in class scope, so there should
10669 // never be any delayed exported classes to worry about.
10670 assert(S.DelayedDllExportClasses.empty() &&
10671 "delayed exports present at explicit instantiation");
10672 S.checkClassLevelDLLAttribute(Def);
10673
10674 // Propagate attribute to base class templates.
10675 for (auto &B : Def->bases()) {
10676 if (auto *BT = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
10677 B.getType()->getAsCXXRecordDecl()))
10678 S.propagateDLLAttrToBaseClassTemplate(Def, A, BT, B.getBeginLoc());
10679 }
10680
10681 S.referenceDLLExportedClassMethods();
10682}
10683
10684// Explicit instantiation of a class template specialization
10685DeclResult Sema::ActOnExplicitInstantiation(
10686 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
10687 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
10688 TemplateTy TemplateD, SourceLocation TemplateNameLoc,
10689 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn,
10690 SourceLocation RAngleLoc, const ParsedAttributesView &Attr) {
10691 // Find the class template we're specializing
10692 TemplateName Name = TemplateD.get();
10693 TemplateDecl *TD = Name.getAsTemplateDecl();
10694 // Check that the specialization uses the same tag kind as the
10695 // original template.
10696 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
10697 assert(Kind != TagTypeKind::Enum &&
10698 "Invalid enum tag in class template explicit instantiation!");
10699
10700 ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(Val: TD);
10701
10702 if (!ClassTemplate) {
10703 NonTagKind NTK = getNonTagTypeDeclKind(TD, Kind);
10704 Diag(TemplateNameLoc, diag::err_tag_reference_non_tag)
10705 << TD << NTK << llvm::to_underlying(Kind);
10706 Diag(TD->getLocation(), diag::note_previous_use);
10707 return true;
10708 }
10709
10710 if (!isAcceptableTagRedeclaration(Previous: ClassTemplate->getTemplatedDecl(),
10711 NewTag: Kind, /*isDefinition*/false, NewTagLoc: KWLoc,
10712 Name: ClassTemplate->getIdentifier())) {
10713 Diag(KWLoc, diag::err_use_with_wrong_tag)
10714 << ClassTemplate
10715 << FixItHint::CreateReplacement(KWLoc,
10716 ClassTemplate->getTemplatedDecl()->getKindName());
10717 Diag(ClassTemplate->getTemplatedDecl()->getLocation(),
10718 diag::note_previous_use);
10719 Kind = ClassTemplate->getTemplatedDecl()->getTagKind();
10720 }
10721
10722 // C++0x [temp.explicit]p2:
10723 // There are two forms of explicit instantiation: an explicit instantiation
10724 // definition and an explicit instantiation declaration. An explicit
10725 // instantiation declaration begins with the extern keyword. [...]
10726 TemplateSpecializationKind TSK = ExternLoc.isInvalid()
10727 ? TSK_ExplicitInstantiationDefinition
10728 : TSK_ExplicitInstantiationDeclaration;
10729
10730 if (TSK == TSK_ExplicitInstantiationDeclaration &&
10731 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
10732 // Check for dllexport class template instantiation declarations,
10733 // except for MinGW mode.
10734 for (const ParsedAttr &AL : Attr) {
10735 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10736 Diag(ExternLoc,
10737 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10738 Diag(AL.getLoc(), diag::note_attribute);
10739 break;
10740 }
10741 }
10742
10743 if (auto *A = ClassTemplate->getTemplatedDecl()->getAttr<DLLExportAttr>()) {
10744 Diag(ExternLoc,
10745 diag::warn_attribute_dllexport_explicit_instantiation_decl);
10746 Diag(A->getLocation(), diag::note_attribute);
10747 }
10748 }
10749
10750 // In MSVC mode, dllimported explicit instantiation definitions are treated as
10751 // instantiation declarations for most purposes.
10752 bool DLLImportExplicitInstantiationDef = false;
10753 if (TSK == TSK_ExplicitInstantiationDefinition &&
10754 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10755 // Check for dllimport class template instantiation definitions.
10756 bool DLLImport =
10757 ClassTemplate->getTemplatedDecl()->getAttr<DLLImportAttr>();
10758 for (const ParsedAttr &AL : Attr) {
10759 if (AL.getKind() == ParsedAttr::AT_DLLImport)
10760 DLLImport = true;
10761 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10762 // dllexport trumps dllimport here.
10763 DLLImport = false;
10764 break;
10765 }
10766 }
10767 if (DLLImport) {
10768 TSK = TSK_ExplicitInstantiationDeclaration;
10769 DLLImportExplicitInstantiationDef = true;
10770 }
10771 }
10772
10773 // Translate the parser's template argument list in our AST format.
10774 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
10775 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
10776
10777 // Check that the template argument list is well-formed for this
10778 // template.
10779 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
10780 if (CheckTemplateArgumentList(ClassTemplate, TemplateNameLoc, TemplateArgs,
10781 false, SugaredConverted, CanonicalConverted,
10782 /*UpdateArgsWithConversions=*/true))
10783 return true;
10784
10785 // Find the class template specialization declaration that
10786 // corresponds to these arguments.
10787 void *InsertPos = nullptr;
10788 ClassTemplateSpecializationDecl *PrevDecl =
10789 ClassTemplate->findSpecialization(Args: CanonicalConverted, InsertPos);
10790
10791 TemplateSpecializationKind PrevDecl_TSK
10792 = PrevDecl ? PrevDecl->getTemplateSpecializationKind() : TSK_Undeclared;
10793
10794 if (TSK == TSK_ExplicitInstantiationDefinition && PrevDecl != nullptr &&
10795 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
10796 // Check for dllexport class template instantiation definitions in MinGW
10797 // mode, if a previous declaration of the instantiation was seen.
10798 for (const ParsedAttr &AL : Attr) {
10799 if (AL.getKind() == ParsedAttr::AT_DLLExport) {
10800 Diag(AL.getLoc(),
10801 diag::warn_attribute_dllexport_explicit_instantiation_def);
10802 break;
10803 }
10804 }
10805 }
10806
10807 if (CheckExplicitInstantiation(*this, ClassTemplate, TemplateNameLoc,
10808 SS.isSet(), TSK))
10809 return true;
10810
10811 ClassTemplateSpecializationDecl *Specialization = nullptr;
10812
10813 bool HasNoEffect = false;
10814 if (PrevDecl) {
10815 if (CheckSpecializationInstantiationRedecl(TemplateNameLoc, TSK,
10816 PrevDecl, PrevDecl_TSK,
10817 PrevDecl->getPointOfInstantiation(),
10818 HasNoEffect))
10819 return PrevDecl;
10820
10821 // Even though HasNoEffect == true means that this explicit instantiation
10822 // has no effect on semantics, we go on to put its syntax in the AST.
10823
10824 if (PrevDecl_TSK == TSK_ImplicitInstantiation ||
10825 PrevDecl_TSK == TSK_Undeclared) {
10826 // Since the only prior class template specialization with these
10827 // arguments was referenced but not declared, reuse that
10828 // declaration node as our own, updating the source location
10829 // for the template name to reflect our new declaration.
10830 // (Other source locations will be updated later.)
10831 Specialization = PrevDecl;
10832 Specialization->setLocation(TemplateNameLoc);
10833 PrevDecl = nullptr;
10834 }
10835
10836 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10837 DLLImportExplicitInstantiationDef) {
10838 // The new specialization might add a dllimport attribute.
10839 HasNoEffect = false;
10840 }
10841 }
10842
10843 if (!Specialization) {
10844 // Create a new class template specialization declaration node for
10845 // this explicit specialization.
10846 Specialization = ClassTemplateSpecializationDecl::Create(
10847 Context, TK: Kind, DC: ClassTemplate->getDeclContext(), StartLoc: KWLoc, IdLoc: TemplateNameLoc,
10848 SpecializedTemplate: ClassTemplate, Args: CanonicalConverted, PrevDecl);
10849 SetNestedNameSpecifier(*this, Specialization, SS);
10850
10851 // A MSInheritanceAttr attached to the previous declaration must be
10852 // propagated to the new node prior to instantiation.
10853 if (PrevDecl) {
10854 if (const auto *A = PrevDecl->getAttr<MSInheritanceAttr>()) {
10855 auto *Clone = A->clone(getASTContext());
10856 Clone->setInherited(true);
10857 Specialization->addAttr(A: Clone);
10858 Consumer.AssignInheritanceModel(Specialization);
10859 }
10860 }
10861
10862 if (!HasNoEffect && !PrevDecl) {
10863 // Insert the new specialization.
10864 ClassTemplate->AddSpecialization(D: Specialization, InsertPos);
10865 }
10866 }
10867
10868 // Build the fully-sugared type for this explicit instantiation as
10869 // the user wrote in the explicit instantiation itself. This means
10870 // that we'll pretty-print the type retrieved from the
10871 // specialization's declaration the way that the user actually wrote
10872 // the explicit instantiation, rather than formatting the name based
10873 // on the "canonical" representation used to store the template
10874 // arguments in the specialization.
10875 TypeSourceInfo *WrittenTy
10876 = Context.getTemplateSpecializationTypeInfo(T: Name, TLoc: TemplateNameLoc,
10877 Args: TemplateArgs,
10878 Canon: Context.getTypeDeclType(Specialization));
10879 Specialization->setTypeAsWritten(WrittenTy);
10880
10881 // Set source locations for keywords.
10882 Specialization->setExternLoc(ExternLoc);
10883 Specialization->setTemplateKeywordLoc(TemplateLoc);
10884 Specialization->setBraceRange(SourceRange());
10885
10886 bool PreviouslyDLLExported = Specialization->hasAttr<DLLExportAttr>();
10887 ProcessDeclAttributeList(S, Specialization, Attr);
10888 ProcessAPINotes(Specialization);
10889
10890 // Add the explicit instantiation into its lexical context. However,
10891 // since explicit instantiations are never found by name lookup, we
10892 // just put it into the declaration context directly.
10893 Specialization->setLexicalDeclContext(CurContext);
10894 CurContext->addDecl(Specialization);
10895
10896 // Syntax is now OK, so return if it has no other effect on semantics.
10897 if (HasNoEffect) {
10898 // Set the template specialization kind.
10899 Specialization->setTemplateSpecializationKind(TSK);
10900 return Specialization;
10901 }
10902
10903 // C++ [temp.explicit]p3:
10904 // A definition of a class template or class member template
10905 // shall be in scope at the point of the explicit instantiation of
10906 // the class template or class member template.
10907 //
10908 // This check comes when we actually try to perform the
10909 // instantiation.
10910 ClassTemplateSpecializationDecl *Def
10911 = cast_or_null<ClassTemplateSpecializationDecl>(
10912 Specialization->getDefinition());
10913 if (!Def)
10914 InstantiateClassTemplateSpecialization(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Specialization, TSK);
10915 else if (TSK == TSK_ExplicitInstantiationDefinition) {
10916 MarkVTableUsed(TemplateNameLoc, Specialization, true);
10917 Specialization->setPointOfInstantiation(Def->getPointOfInstantiation());
10918 }
10919
10920 // Instantiate the members of this class template specialization.
10921 Def = cast_or_null<ClassTemplateSpecializationDecl>(
10922 Specialization->getDefinition());
10923 if (Def) {
10924 TemplateSpecializationKind Old_TSK = Def->getTemplateSpecializationKind();
10925 // Fix a TSK_ExplicitInstantiationDeclaration followed by a
10926 // TSK_ExplicitInstantiationDefinition
10927 if (Old_TSK == TSK_ExplicitInstantiationDeclaration &&
10928 (TSK == TSK_ExplicitInstantiationDefinition ||
10929 DLLImportExplicitInstantiationDef)) {
10930 // FIXME: Need to notify the ASTMutationListener that we did this.
10931 Def->setTemplateSpecializationKind(TSK);
10932
10933 if (!getDLLAttr(Def) && getDLLAttr(Specialization) &&
10934 (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
10935 !Context.getTargetInfo().getTriple().isPS())) {
10936 // An explicit instantiation definition can add a dll attribute to a
10937 // template with a previous instantiation declaration. MinGW doesn't
10938 // allow this.
10939 auto *A = cast<InheritableAttr>(
10940 Val: getDLLAttr(Specialization)->clone(C&: getASTContext()));
10941 A->setInherited(true);
10942 Def->addAttr(A: A);
10943 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10944 }
10945 }
10946
10947 // Fix a TSK_ImplicitInstantiation followed by a
10948 // TSK_ExplicitInstantiationDefinition
10949 bool NewlyDLLExported =
10950 !PreviouslyDLLExported && Specialization->hasAttr<DLLExportAttr>();
10951 if (Old_TSK == TSK_ImplicitInstantiation && NewlyDLLExported &&
10952 (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
10953 !Context.getTargetInfo().getTriple().isPS())) {
10954 // An explicit instantiation definition can add a dll attribute to a
10955 // template with a previous implicit instantiation. MinGW doesn't allow
10956 // this. We limit clang to only adding dllexport, to avoid potentially
10957 // strange codegen behavior. For example, if we extend this conditional
10958 // to dllimport, and we have a source file calling a method on an
10959 // implicitly instantiated template class instance and then declaring a
10960 // dllimport explicit instantiation definition for the same template
10961 // class, the codegen for the method call will not respect the dllimport,
10962 // while it will with cl. The Def will already have the DLL attribute,
10963 // since the Def and Specialization will be the same in the case of
10964 // Old_TSK == TSK_ImplicitInstantiation, and we already added the
10965 // attribute to the Specialization; we just need to make it take effect.
10966 assert(Def == Specialization &&
10967 "Def and Specialization should match for implicit instantiation");
10968 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10969 }
10970
10971 // In MinGW mode, export the template instantiation if the declaration
10972 // was marked dllexport.
10973 if (PrevDecl_TSK == TSK_ExplicitInstantiationDeclaration &&
10974 Context.getTargetInfo().getTriple().isWindowsGNUEnvironment() &&
10975 PrevDecl->hasAttr<DLLExportAttr>()) {
10976 dllExportImportClassTemplateSpecialization(S&: *this, Def);
10977 }
10978
10979 // Set the template specialization kind. Make sure it is set before
10980 // instantiating the members which will trigger ASTConsumer callbacks.
10981 Specialization->setTemplateSpecializationKind(TSK);
10982 InstantiateClassTemplateSpecializationMembers(PointOfInstantiation: TemplateNameLoc, ClassTemplateSpec: Def, TSK);
10983 } else {
10984
10985 // Set the template specialization kind.
10986 Specialization->setTemplateSpecializationKind(TSK);
10987 }
10988
10989 return Specialization;
10990}
10991
10992// Explicit instantiation of a member class of a class template.
10993DeclResult
10994Sema::ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
10995 SourceLocation TemplateLoc, unsigned TagSpec,
10996 SourceLocation KWLoc, CXXScopeSpec &SS,
10997 IdentifierInfo *Name, SourceLocation NameLoc,
10998 const ParsedAttributesView &Attr) {
10999
11000 bool Owned = false;
11001 bool IsDependent = false;
11002 Decl *TagD = ActOnTag(S, TagSpec, TUK: Sema::TUK_Reference, KWLoc, SS, Name,
11003 NameLoc, Attr, AS: AS_none, /*ModulePrivateLoc=*/SourceLocation(),
11004 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent, ScopedEnumKWLoc: SourceLocation(),
11005 ScopedEnumUsesClassTag: false, UnderlyingType: TypeResult(), /*IsTypeSpecifier*/ false,
11006 /*IsTemplateParamOrArg*/ false, /*OOK=*/OOK_Outside).get();
11007 assert(!IsDependent && "explicit instantiation of dependent name not yet handled");
11008
11009 if (!TagD)
11010 return true;
11011
11012 TagDecl *Tag = cast<TagDecl>(Val: TagD);
11013 assert(!Tag->isEnum() && "shouldn't see enumerations here");
11014
11015 if (Tag->isInvalidDecl())
11016 return true;
11017
11018 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: Tag);
11019 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
11020 if (!Pattern) {
11021 Diag(TemplateLoc, diag::err_explicit_instantiation_nontemplate_type)
11022 << Context.getTypeDeclType(Record);
11023 Diag(Record->getLocation(), diag::note_nontemplate_decl_here);
11024 return true;
11025 }
11026
11027 // C++0x [temp.explicit]p2:
11028 // If the explicit instantiation is for a class or member class, the
11029 // elaborated-type-specifier in the declaration shall include a
11030 // simple-template-id.
11031 //
11032 // C++98 has the same restriction, just worded differently.
11033 if (!ScopeSpecifierHasTemplateId(SS))
11034 Diag(TemplateLoc, diag::ext_explicit_instantiation_without_qualified_id)
11035 << Record << SS.getRange();
11036
11037 // C++0x [temp.explicit]p2:
11038 // There are two forms of explicit instantiation: an explicit instantiation
11039 // definition and an explicit instantiation declaration. An explicit
11040 // instantiation declaration begins with the extern keyword. [...]
11041 TemplateSpecializationKind TSK
11042 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
11043 : TSK_ExplicitInstantiationDeclaration;
11044
11045 CheckExplicitInstantiation(*this, Record, NameLoc, true, TSK);
11046
11047 // Verify that it is okay to explicitly instantiate here.
11048 CXXRecordDecl *PrevDecl
11049 = cast_or_null<CXXRecordDecl>(Val: Record->getPreviousDecl());
11050 if (!PrevDecl && Record->getDefinition())
11051 PrevDecl = Record;
11052 if (PrevDecl) {
11053 MemberSpecializationInfo *MSInfo = PrevDecl->getMemberSpecializationInfo();
11054 bool HasNoEffect = false;
11055 assert(MSInfo && "No member specialization information?");
11056 if (CheckSpecializationInstantiationRedecl(TemplateLoc, TSK,
11057 PrevDecl,
11058 MSInfo->getTemplateSpecializationKind(),
11059 MSInfo->getPointOfInstantiation(),
11060 HasNoEffect))
11061 return true;
11062 if (HasNoEffect)
11063 return TagD;
11064 }
11065
11066 CXXRecordDecl *RecordDef
11067 = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
11068 if (!RecordDef) {
11069 // C++ [temp.explicit]p3:
11070 // A definition of a member class of a class template shall be in scope
11071 // at the point of an explicit instantiation of the member class.
11072 CXXRecordDecl *Def
11073 = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition());
11074 if (!Def) {
11075 Diag(TemplateLoc, diag::err_explicit_instantiation_undefined_member)
11076 << 0 << Record->getDeclName() << Record->getDeclContext();
11077 Diag(Pattern->getLocation(), diag::note_forward_declaration)
11078 << Pattern;
11079 return true;
11080 } else {
11081 if (InstantiateClass(PointOfInstantiation: NameLoc, Instantiation: Record, Pattern: Def,
11082 TemplateArgs: getTemplateInstantiationArgs(Record),
11083 TSK))
11084 return true;
11085
11086 RecordDef = cast_or_null<CXXRecordDecl>(Val: Record->getDefinition());
11087 if (!RecordDef)
11088 return true;
11089 }
11090 }
11091
11092 // Instantiate all of the members of the class.
11093 InstantiateClassMembers(PointOfInstantiation: NameLoc, Instantiation: RecordDef,
11094 TemplateArgs: getTemplateInstantiationArgs(Record), TSK);
11095
11096 if (TSK == TSK_ExplicitInstantiationDefinition)
11097 MarkVTableUsed(Loc: NameLoc, Class: RecordDef, DefinitionRequired: true);
11098
11099 // FIXME: We don't have any representation for explicit instantiations of
11100 // member classes. Such a representation is not needed for compilation, but it
11101 // should be available for clients that want to see all of the declarations in
11102 // the source code.
11103 return TagD;
11104}
11105
11106DeclResult Sema::ActOnExplicitInstantiation(Scope *S,
11107 SourceLocation ExternLoc,
11108 SourceLocation TemplateLoc,
11109 Declarator &D) {
11110 // Explicit instantiations always require a name.
11111 // TODO: check if/when DNInfo should replace Name.
11112 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
11113 DeclarationName Name = NameInfo.getName();
11114 if (!Name) {
11115 if (!D.isInvalidType())
11116 Diag(D.getDeclSpec().getBeginLoc(),
11117 diag::err_explicit_instantiation_requires_name)
11118 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
11119
11120 return true;
11121 }
11122
11123 // Get the innermost enclosing declaration scope.
11124 S = S->getDeclParent();
11125
11126 // Determine the type of the declaration.
11127 TypeSourceInfo *T = GetTypeForDeclarator(D);
11128 QualType R = T->getType();
11129 if (R.isNull())
11130 return true;
11131
11132 // C++ [dcl.stc]p1:
11133 // A storage-class-specifier shall not be specified in [...] an explicit
11134 // instantiation (14.7.2) directive.
11135 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
11136 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_of_typedef)
11137 << Name;
11138 return true;
11139 } else if (D.getDeclSpec().getStorageClassSpec()
11140 != DeclSpec::SCS_unspecified) {
11141 // Complain about then remove the storage class specifier.
11142 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_storage_class)
11143 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
11144
11145 D.getMutableDeclSpec().ClearStorageClassSpecs();
11146 }
11147
11148 // C++0x [temp.explicit]p1:
11149 // [...] An explicit instantiation of a function template shall not use the
11150 // inline or constexpr specifiers.
11151 // Presumably, this also applies to member functions of class templates as
11152 // well.
11153 if (D.getDeclSpec().isInlineSpecified())
11154 Diag(D.getDeclSpec().getInlineSpecLoc(),
11155 getLangOpts().CPlusPlus11 ?
11156 diag::err_explicit_instantiation_inline :
11157 diag::warn_explicit_instantiation_inline_0x)
11158 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
11159 if (D.getDeclSpec().hasConstexprSpecifier() && R->isFunctionType())
11160 // FIXME: Add a fix-it to remove the 'constexpr' and add a 'const' if one is
11161 // not already specified.
11162 Diag(D.getDeclSpec().getConstexprSpecLoc(),
11163 diag::err_explicit_instantiation_constexpr);
11164
11165 // A deduction guide is not on the list of entities that can be explicitly
11166 // instantiated.
11167 if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
11168 Diag(D.getDeclSpec().getBeginLoc(), diag::err_deduction_guide_specialized)
11169 << /*explicit instantiation*/ 0;
11170 return true;
11171 }
11172
11173 // C++0x [temp.explicit]p2:
11174 // There are two forms of explicit instantiation: an explicit instantiation
11175 // definition and an explicit instantiation declaration. An explicit
11176 // instantiation declaration begins with the extern keyword. [...]
11177 TemplateSpecializationKind TSK
11178 = ExternLoc.isInvalid()? TSK_ExplicitInstantiationDefinition
11179 : TSK_ExplicitInstantiationDeclaration;
11180
11181 LookupResult Previous(*this, NameInfo, LookupOrdinaryName);
11182 LookupParsedName(R&: Previous, S, SS: &D.getCXXScopeSpec());
11183
11184 if (!R->isFunctionType()) {
11185 // C++ [temp.explicit]p1:
11186 // A [...] static data member of a class template can be explicitly
11187 // instantiated from the member definition associated with its class
11188 // template.
11189 // C++1y [temp.explicit]p1:
11190 // A [...] variable [...] template specialization can be explicitly
11191 // instantiated from its template.
11192 if (Previous.isAmbiguous())
11193 return true;
11194
11195 VarDecl *Prev = Previous.getAsSingle<VarDecl>();
11196 VarTemplateDecl *PrevTemplate = Previous.getAsSingle<VarTemplateDecl>();
11197
11198 if (!PrevTemplate) {
11199 if (!Prev || !Prev->isStaticDataMember()) {
11200 // We expect to see a static data member here.
11201 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_not_known)
11202 << Name;
11203 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
11204 P != PEnd; ++P)
11205 Diag((*P)->getLocation(), diag::note_explicit_instantiation_here);
11206 return true;
11207 }
11208
11209 if (!Prev->getInstantiatedFromStaticDataMember()) {
11210 // FIXME: Check for explicit specialization?
11211 Diag(D.getIdentifierLoc(),
11212 diag::err_explicit_instantiation_data_member_not_instantiated)
11213 << Prev;
11214 Diag(Prev->getLocation(), diag::note_explicit_instantiation_here);
11215 // FIXME: Can we provide a note showing where this was declared?
11216 return true;
11217 }
11218 } else {
11219 // Explicitly instantiate a variable template.
11220
11221 // C++1y [dcl.spec.auto]p6:
11222 // ... A program that uses auto or decltype(auto) in a context not
11223 // explicitly allowed in this section is ill-formed.
11224 //
11225 // This includes auto-typed variable template instantiations.
11226 if (R->isUndeducedType()) {
11227 Diag(T->getTypeLoc().getBeginLoc(),
11228 diag::err_auto_not_allowed_var_inst);
11229 return true;
11230 }
11231
11232 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
11233 // C++1y [temp.explicit]p3:
11234 // If the explicit instantiation is for a variable, the unqualified-id
11235 // in the declaration shall be a template-id.
11236 Diag(D.getIdentifierLoc(),
11237 diag::err_explicit_instantiation_without_template_id)
11238 << PrevTemplate;
11239 Diag(PrevTemplate->getLocation(),
11240 diag::note_explicit_instantiation_here);
11241 return true;
11242 }
11243
11244 // Translate the parser's template argument list into our AST format.
11245 TemplateArgumentListInfo TemplateArgs =
11246 makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
11247
11248 DeclResult Res = CheckVarTemplateId(Template: PrevTemplate, TemplateLoc,
11249 TemplateNameLoc: D.getIdentifierLoc(), TemplateArgs);
11250 if (Res.isInvalid())
11251 return true;
11252
11253 if (!Res.isUsable()) {
11254 // We somehow specified dependent template arguments in an explicit
11255 // instantiation. This should probably only happen during error
11256 // recovery.
11257 Diag(D.getIdentifierLoc(), diag::err_explicit_instantiation_dependent);
11258 return true;
11259 }
11260
11261 // Ignore access control bits, we don't need them for redeclaration
11262 // checking.
11263 Prev = cast<VarDecl>(Val: Res.get());
11264 }
11265
11266 // C++0x [temp.explicit]p2:
11267 // If the explicit instantiation is for a member function, a member class
11268 // or a static data member of a class template specialization, the name of
11269 // the class template specialization in the qualified-id for the member
11270 // name shall be a simple-template-id.
11271 //
11272 // C++98 has the same restriction, just worded differently.
11273 //
11274 // This does not apply to variable template specializations, where the
11275 // template-id is in the unqualified-id instead.
11276 if (!ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()) && !PrevTemplate)
11277 Diag(D.getIdentifierLoc(),
11278 diag::ext_explicit_instantiation_without_qualified_id)
11279 << Prev << D.getCXXScopeSpec().getRange();
11280
11281 CheckExplicitInstantiation(*this, Prev, D.getIdentifierLoc(), true, TSK);
11282
11283 // Verify that it is okay to explicitly instantiate here.
11284 TemplateSpecializationKind PrevTSK = Prev->getTemplateSpecializationKind();
11285 SourceLocation POI = Prev->getPointOfInstantiation();
11286 bool HasNoEffect = false;
11287 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK, Prev,
11288 PrevTSK, POI, HasNoEffect))
11289 return true;
11290
11291 if (!HasNoEffect) {
11292 // Instantiate static data member or variable template.
11293 Prev->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
11294 // Merge attributes.
11295 ProcessDeclAttributeList(S, Prev, D.getDeclSpec().getAttributes());
11296 if (PrevTemplate)
11297 ProcessAPINotes(Prev);
11298
11299 if (TSK == TSK_ExplicitInstantiationDefinition)
11300 InstantiateVariableDefinition(PointOfInstantiation: D.getIdentifierLoc(), Var: Prev);
11301 }
11302
11303 // Check the new variable specialization against the parsed input.
11304 if (PrevTemplate && !Context.hasSameType(Prev->getType(), R)) {
11305 Diag(T->getTypeLoc().getBeginLoc(),
11306 diag::err_invalid_var_template_spec_type)
11307 << 0 << PrevTemplate << R << Prev->getType();
11308 Diag(PrevTemplate->getLocation(), diag::note_template_declared_here)
11309 << 2 << PrevTemplate->getDeclName();
11310 return true;
11311 }
11312
11313 // FIXME: Create an ExplicitInstantiation node?
11314 return (Decl*) nullptr;
11315 }
11316
11317 // If the declarator is a template-id, translate the parser's template
11318 // argument list into our AST format.
11319 bool HasExplicitTemplateArgs = false;
11320 TemplateArgumentListInfo TemplateArgs;
11321 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
11322 TemplateArgs = makeTemplateArgumentListInfo(S&: *this, TemplateId&: *D.getName().TemplateId);
11323 HasExplicitTemplateArgs = true;
11324 }
11325
11326 // C++ [temp.explicit]p1:
11327 // A [...] function [...] can be explicitly instantiated from its template.
11328 // A member function [...] of a class template can be explicitly
11329 // instantiated from the member definition associated with its class
11330 // template.
11331 UnresolvedSet<8> TemplateMatches;
11332 FunctionDecl *NonTemplateMatch = nullptr;
11333 TemplateSpecCandidateSet FailedCandidates(D.getIdentifierLoc());
11334 for (LookupResult::iterator P = Previous.begin(), PEnd = Previous.end();
11335 P != PEnd; ++P) {
11336 NamedDecl *Prev = *P;
11337 if (!HasExplicitTemplateArgs) {
11338 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Prev)) {
11339 QualType Adjusted = adjustCCAndNoReturn(ArgFunctionType: R, FunctionType: Method->getType(),
11340 /*AdjustExceptionSpec*/true);
11341 if (Context.hasSameUnqualifiedType(T1: Method->getType(), T2: Adjusted)) {
11342 if (Method->getPrimaryTemplate()) {
11343 TemplateMatches.addDecl(Method, P.getAccess());
11344 } else {
11345 // FIXME: Can this assert ever happen? Needs a test.
11346 assert(!NonTemplateMatch && "Multiple NonTemplateMatches");
11347 NonTemplateMatch = Method;
11348 }
11349 }
11350 }
11351 }
11352
11353 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Prev);
11354 if (!FunTmpl)
11355 continue;
11356
11357 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11358 FunctionDecl *Specialization = nullptr;
11359 if (TemplateDeductionResult TDK = DeduceTemplateArguments(
11360 FunctionTemplate: FunTmpl, ExplicitTemplateArgs: (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), ArgFunctionType: R,
11361 Specialization, Info);
11362 TDK != TemplateDeductionResult::Success) {
11363 // Keep track of almost-matches.
11364 FailedCandidates.addCandidate()
11365 .set(P.getPair(), FunTmpl->getTemplatedDecl(),
11366 MakeDeductionFailureInfo(Context, TDK, Info));
11367 (void)TDK;
11368 continue;
11369 }
11370
11371 // Target attributes are part of the cuda function signature, so
11372 // the cuda target of the instantiated function must match that of its
11373 // template. Given that C++ template deduction does not take
11374 // target attributes into account, we reject candidates here that
11375 // have a different target.
11376 if (LangOpts.CUDA &&
11377 CUDA().IdentifyTarget(D: Specialization,
11378 /* IgnoreImplicitHDAttr = */ true) !=
11379 CUDA().IdentifyTarget(Attrs: D.getDeclSpec().getAttributes())) {
11380 FailedCandidates.addCandidate().set(
11381 P.getPair(), FunTmpl->getTemplatedDecl(),
11382 MakeDeductionFailureInfo(
11383 Context, TDK: TemplateDeductionResult::CUDATargetMismatch, Info));
11384 continue;
11385 }
11386
11387 TemplateMatches.addDecl(Specialization, P.getAccess());
11388 }
11389
11390 FunctionDecl *Specialization = NonTemplateMatch;
11391 if (!Specialization) {
11392 // Find the most specialized function template specialization.
11393 UnresolvedSetIterator Result = getMostSpecialized(
11394 TemplateMatches.begin(), TemplateMatches.end(), FailedCandidates,
11395 D.getIdentifierLoc(),
11396 PDiag(diag::err_explicit_instantiation_not_known) << Name,
11397 PDiag(diag::err_explicit_instantiation_ambiguous) << Name,
11398 PDiag(diag::note_explicit_instantiation_candidate));
11399
11400 if (Result == TemplateMatches.end())
11401 return true;
11402
11403 // Ignore access control bits, we don't need them for redeclaration checking.
11404 Specialization = cast<FunctionDecl>(Val: *Result);
11405 }
11406
11407 // C++11 [except.spec]p4
11408 // In an explicit instantiation an exception-specification may be specified,
11409 // but is not required.
11410 // If an exception-specification is specified in an explicit instantiation
11411 // directive, it shall be compatible with the exception-specifications of
11412 // other declarations of that function.
11413 if (auto *FPT = R->getAs<FunctionProtoType>())
11414 if (FPT->hasExceptionSpec()) {
11415 unsigned DiagID =
11416 diag::err_mismatched_exception_spec_explicit_instantiation;
11417 if (getLangOpts().MicrosoftExt)
11418 DiagID = diag::ext_mismatched_exception_spec_explicit_instantiation;
11419 bool Result = CheckEquivalentExceptionSpec(
11420 PDiag(DiagID) << Specialization->getType(),
11421 PDiag(diag::note_explicit_instantiation_here),
11422 Specialization->getType()->getAs<FunctionProtoType>(),
11423 Specialization->getLocation(), FPT, D.getBeginLoc());
11424 // In Microsoft mode, mismatching exception specifications just cause a
11425 // warning.
11426 if (!getLangOpts().MicrosoftExt && Result)
11427 return true;
11428 }
11429
11430 if (Specialization->getTemplateSpecializationKind() == TSK_Undeclared) {
11431 Diag(D.getIdentifierLoc(),
11432 diag::err_explicit_instantiation_member_function_not_instantiated)
11433 << Specialization
11434 << (Specialization->getTemplateSpecializationKind() ==
11435 TSK_ExplicitSpecialization);
11436 Diag(Specialization->getLocation(), diag::note_explicit_instantiation_here);
11437 return true;
11438 }
11439
11440 FunctionDecl *PrevDecl = Specialization->getPreviousDecl();
11441 if (!PrevDecl && Specialization->isThisDeclarationADefinition())
11442 PrevDecl = Specialization;
11443
11444 if (PrevDecl) {
11445 bool HasNoEffect = false;
11446 if (CheckSpecializationInstantiationRedecl(D.getIdentifierLoc(), TSK,
11447 PrevDecl,
11448 PrevDecl->getTemplateSpecializationKind(),
11449 PrevDecl->getPointOfInstantiation(),
11450 HasNoEffect))
11451 return true;
11452
11453 // FIXME: We may still want to build some representation of this
11454 // explicit specialization.
11455 if (HasNoEffect)
11456 return (Decl*) nullptr;
11457 }
11458
11459 // HACK: libc++ has a bug where it attempts to explicitly instantiate the
11460 // functions
11461 // valarray<size_t>::valarray(size_t) and
11462 // valarray<size_t>::~valarray()
11463 // that it declared to have internal linkage with the internal_linkage
11464 // attribute. Ignore the explicit instantiation declaration in this case.
11465 if (Specialization->hasAttr<InternalLinkageAttr>() &&
11466 TSK == TSK_ExplicitInstantiationDeclaration) {
11467 if (auto *RD = dyn_cast<CXXRecordDecl>(Specialization->getDeclContext()))
11468 if (RD->getIdentifier() && RD->getIdentifier()->isStr("valarray") &&
11469 RD->isInStdNamespace())
11470 return (Decl*) nullptr;
11471 }
11472
11473 ProcessDeclAttributeList(S, Specialization, D.getDeclSpec().getAttributes());
11474 ProcessAPINotes(Specialization);
11475
11476 // In MSVC mode, dllimported explicit instantiation definitions are treated as
11477 // instantiation declarations.
11478 if (TSK == TSK_ExplicitInstantiationDefinition &&
11479 Specialization->hasAttr<DLLImportAttr>() &&
11480 Context.getTargetInfo().getCXXABI().isMicrosoft())
11481 TSK = TSK_ExplicitInstantiationDeclaration;
11482
11483 Specialization->setTemplateSpecializationKind(TSK, PointOfInstantiation: D.getIdentifierLoc());
11484
11485 if (Specialization->isDefined()) {
11486 // Let the ASTConsumer know that this function has been explicitly
11487 // instantiated now, and its linkage might have changed.
11488 Consumer.HandleTopLevelDecl(D: DeclGroupRef(Specialization));
11489 } else if (TSK == TSK_ExplicitInstantiationDefinition)
11490 InstantiateFunctionDefinition(PointOfInstantiation: D.getIdentifierLoc(), Function: Specialization);
11491
11492 // C++0x [temp.explicit]p2:
11493 // If the explicit instantiation is for a member function, a member class
11494 // or a static data member of a class template specialization, the name of
11495 // the class template specialization in the qualified-id for the member
11496 // name shall be a simple-template-id.
11497 //
11498 // C++98 has the same restriction, just worded differently.
11499 FunctionTemplateDecl *FunTmpl = Specialization->getPrimaryTemplate();
11500 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId && !FunTmpl &&
11501 D.getCXXScopeSpec().isSet() &&
11502 !ScopeSpecifierHasTemplateId(D.getCXXScopeSpec()))
11503 Diag(D.getIdentifierLoc(),
11504 diag::ext_explicit_instantiation_without_qualified_id)
11505 << Specialization << D.getCXXScopeSpec().getRange();
11506
11507 CheckExplicitInstantiation(
11508 *this,
11509 FunTmpl ? (NamedDecl *)FunTmpl
11510 : Specialization->getInstantiatedFromMemberFunction(),
11511 D.getIdentifierLoc(), D.getCXXScopeSpec().isSet(), TSK);
11512
11513 // FIXME: Create some kind of ExplicitInstantiationDecl here.
11514 return (Decl*) nullptr;
11515}
11516
11517TypeResult Sema::ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11518 const CXXScopeSpec &SS,
11519 const IdentifierInfo *Name,
11520 SourceLocation TagLoc,
11521 SourceLocation NameLoc) {
11522 // This has to hold, because SS is expected to be defined.
11523 assert(Name && "Expected a name in a dependent tag");
11524
11525 NestedNameSpecifier *NNS = SS.getScopeRep();
11526 if (!NNS)
11527 return true;
11528
11529 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
11530
11531 if (TUK == TUK_Declaration || TUK == TUK_Definition) {
11532 Diag(NameLoc, diag::err_dependent_tag_decl)
11533 << (TUK == TUK_Definition) << llvm::to_underlying(Kind)
11534 << SS.getRange();
11535 return true;
11536 }
11537
11538 // Create the resulting type.
11539 ElaboratedTypeKeyword Kwd = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
11540 QualType Result = Context.getDependentNameType(Keyword: Kwd, NNS, Name);
11541
11542 // Create type-source location information for this type.
11543 TypeLocBuilder TLB;
11544 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(T: Result);
11545 TL.setElaboratedKeywordLoc(TagLoc);
11546 TL.setQualifierLoc(SS.getWithLocInContext(Context));
11547 TL.setNameLoc(NameLoc);
11548 return CreateParsedType(T: Result, TInfo: TLB.getTypeSourceInfo(Context, T: Result));
11549}
11550
11551TypeResult Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11552 const CXXScopeSpec &SS,
11553 const IdentifierInfo &II,
11554 SourceLocation IdLoc,
11555 ImplicitTypenameContext IsImplicitTypename) {
11556 if (SS.isInvalid())
11557 return true;
11558
11559 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11560 Diag(TypenameLoc,
11561 getLangOpts().CPlusPlus11 ?
11562 diag::warn_cxx98_compat_typename_outside_of_template :
11563 diag::ext_typename_outside_of_template)
11564 << FixItHint::CreateRemoval(TypenameLoc);
11565
11566 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
11567 TypeSourceInfo *TSI = nullptr;
11568 QualType T =
11569 CheckTypenameType(Keyword: (TypenameLoc.isValid() ||
11570 IsImplicitTypename == ImplicitTypenameContext::Yes)
11571 ? ElaboratedTypeKeyword::Typename
11572 : ElaboratedTypeKeyword::None,
11573 KeywordLoc: TypenameLoc, QualifierLoc, II, IILoc: IdLoc, TSI: &TSI,
11574 /*DeducedTSTContext=*/true);
11575 if (T.isNull())
11576 return true;
11577 return CreateParsedType(T, TInfo: TSI);
11578}
11579
11580TypeResult
11581Sema::ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
11582 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
11583 TemplateTy TemplateIn, const IdentifierInfo *TemplateII,
11584 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
11585 ASTTemplateArgsPtr TemplateArgsIn,
11586 SourceLocation RAngleLoc) {
11587 if (TypenameLoc.isValid() && S && !S->getTemplateParamParent())
11588 Diag(TypenameLoc,
11589 getLangOpts().CPlusPlus11 ?
11590 diag::warn_cxx98_compat_typename_outside_of_template :
11591 diag::ext_typename_outside_of_template)
11592 << FixItHint::CreateRemoval(TypenameLoc);
11593
11594 // Strangely, non-type results are not ignored by this lookup, so the
11595 // program is ill-formed if it finds an injected-class-name.
11596 if (TypenameLoc.isValid()) {
11597 auto *LookupRD =
11598 dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS, EnteringContext: false));
11599 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
11600 Diag(TemplateIILoc,
11601 diag::ext_out_of_line_qualified_id_type_names_constructor)
11602 << TemplateII << 0 /*injected-class-name used as template name*/
11603 << (TemplateKWLoc.isValid() ? 1 : 0 /*'template'/'typename' keyword*/);
11604 }
11605 }
11606
11607 // Translate the parser's template argument list in our AST format.
11608 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
11609 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
11610
11611 TemplateName Template = TemplateIn.get();
11612 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
11613 // Construct a dependent template specialization type.
11614 assert(DTN && "dependent template has non-dependent name?");
11615 assert(DTN->getQualifier() == SS.getScopeRep());
11616 QualType T = Context.getDependentTemplateSpecializationType(
11617 Keyword: ElaboratedTypeKeyword::Typename, NNS: DTN->getQualifier(),
11618 Name: DTN->getIdentifier(), Args: TemplateArgs.arguments());
11619
11620 // Create source-location information for this type.
11621 TypeLocBuilder Builder;
11622 DependentTemplateSpecializationTypeLoc SpecTL
11623 = Builder.push<DependentTemplateSpecializationTypeLoc>(T);
11624 SpecTL.setElaboratedKeywordLoc(TypenameLoc);
11625 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
11626 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
11627 SpecTL.setTemplateNameLoc(TemplateIILoc);
11628 SpecTL.setLAngleLoc(LAngleLoc);
11629 SpecTL.setRAngleLoc(RAngleLoc);
11630 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
11631 SpecTL.setArgLocInfo(i: I, AI: TemplateArgs[I].getLocInfo());
11632 return CreateParsedType(T, TInfo: Builder.getTypeSourceInfo(Context, T));
11633 }
11634
11635 QualType T = CheckTemplateIdType(Name: Template, TemplateLoc: TemplateIILoc, TemplateArgs);
11636 if (T.isNull())
11637 return true;
11638
11639 // Provide source-location information for the template specialization type.
11640 TypeLocBuilder Builder;
11641 TemplateSpecializationTypeLoc SpecTL
11642 = Builder.push<TemplateSpecializationTypeLoc>(T);
11643 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
11644 SpecTL.setTemplateNameLoc(TemplateIILoc);
11645 SpecTL.setLAngleLoc(LAngleLoc);
11646 SpecTL.setRAngleLoc(RAngleLoc);
11647 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
11648 SpecTL.setArgLocInfo(i: I, AI: TemplateArgs[I].getLocInfo());
11649
11650 T = Context.getElaboratedType(Keyword: ElaboratedTypeKeyword::Typename,
11651 NNS: SS.getScopeRep(), NamedType: T);
11652 ElaboratedTypeLoc TL = Builder.push<ElaboratedTypeLoc>(T);
11653 TL.setElaboratedKeywordLoc(TypenameLoc);
11654 TL.setQualifierLoc(SS.getWithLocInContext(Context));
11655
11656 TypeSourceInfo *TSI = Builder.getTypeSourceInfo(Context, T);
11657 return CreateParsedType(T, TInfo: TSI);
11658}
11659
11660/// Determine whether this failed name lookup should be treated as being
11661/// disabled by a usage of std::enable_if.
11662static bool isEnableIf(NestedNameSpecifierLoc NNS, const IdentifierInfo &II,
11663 SourceRange &CondRange, Expr *&Cond) {
11664 // We must be looking for a ::type...
11665 if (!II.isStr(Str: "type"))
11666 return false;
11667
11668 // ... within an explicitly-written template specialization...
11669 if (!NNS || !NNS.getNestedNameSpecifier()->getAsType())
11670 return false;
11671 TypeLoc EnableIfTy = NNS.getTypeLoc();
11672 TemplateSpecializationTypeLoc EnableIfTSTLoc =
11673 EnableIfTy.getAs<TemplateSpecializationTypeLoc>();
11674 if (!EnableIfTSTLoc || EnableIfTSTLoc.getNumArgs() == 0)
11675 return false;
11676 const TemplateSpecializationType *EnableIfTST = EnableIfTSTLoc.getTypePtr();
11677
11678 // ... which names a complete class template declaration...
11679 const TemplateDecl *EnableIfDecl =
11680 EnableIfTST->getTemplateName().getAsTemplateDecl();
11681 if (!EnableIfDecl || EnableIfTST->isIncompleteType())
11682 return false;
11683
11684 // ... called "enable_if".
11685 const IdentifierInfo *EnableIfII =
11686 EnableIfDecl->getDeclName().getAsIdentifierInfo();
11687 if (!EnableIfII || !EnableIfII->isStr(Str: "enable_if"))
11688 return false;
11689
11690 // Assume the first template argument is the condition.
11691 CondRange = EnableIfTSTLoc.getArgLoc(i: 0).getSourceRange();
11692
11693 // Dig out the condition.
11694 Cond = nullptr;
11695 if (EnableIfTSTLoc.getArgLoc(i: 0).getArgument().getKind()
11696 != TemplateArgument::Expression)
11697 return true;
11698
11699 Cond = EnableIfTSTLoc.getArgLoc(i: 0).getSourceExpression();
11700
11701 // Ignore Boolean literals; they add no value.
11702 if (isa<CXXBoolLiteralExpr>(Val: Cond->IgnoreParenCasts()))
11703 Cond = nullptr;
11704
11705 return true;
11706}
11707
11708QualType
11709Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11710 SourceLocation KeywordLoc,
11711 NestedNameSpecifierLoc QualifierLoc,
11712 const IdentifierInfo &II,
11713 SourceLocation IILoc,
11714 TypeSourceInfo **TSI,
11715 bool DeducedTSTContext) {
11716 QualType T = CheckTypenameType(Keyword, KeywordLoc, QualifierLoc, II, IILoc,
11717 DeducedTSTContext);
11718 if (T.isNull())
11719 return QualType();
11720
11721 *TSI = Context.CreateTypeSourceInfo(T);
11722 if (isa<DependentNameType>(Val: T)) {
11723 DependentNameTypeLoc TL =
11724 (*TSI)->getTypeLoc().castAs<DependentNameTypeLoc>();
11725 TL.setElaboratedKeywordLoc(KeywordLoc);
11726 TL.setQualifierLoc(QualifierLoc);
11727 TL.setNameLoc(IILoc);
11728 } else {
11729 ElaboratedTypeLoc TL = (*TSI)->getTypeLoc().castAs<ElaboratedTypeLoc>();
11730 TL.setElaboratedKeywordLoc(KeywordLoc);
11731 TL.setQualifierLoc(QualifierLoc);
11732 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IILoc);
11733 }
11734 return T;
11735}
11736
11737/// Build the type that describes a C++ typename specifier,
11738/// e.g., "typename T::type".
11739QualType
11740Sema::CheckTypenameType(ElaboratedTypeKeyword Keyword,
11741 SourceLocation KeywordLoc,
11742 NestedNameSpecifierLoc QualifierLoc,
11743 const IdentifierInfo &II,
11744 SourceLocation IILoc, bool DeducedTSTContext) {
11745 CXXScopeSpec SS;
11746 SS.Adopt(Other: QualifierLoc);
11747
11748 DeclContext *Ctx = nullptr;
11749 if (QualifierLoc) {
11750 Ctx = computeDeclContext(SS);
11751 if (!Ctx) {
11752 // If the nested-name-specifier is dependent and couldn't be
11753 // resolved to a type, build a typename type.
11754 assert(QualifierLoc.getNestedNameSpecifier()->isDependent());
11755 return Context.getDependentNameType(Keyword,
11756 NNS: QualifierLoc.getNestedNameSpecifier(),
11757 Name: &II);
11758 }
11759
11760 // If the nested-name-specifier refers to the current instantiation,
11761 // the "typename" keyword itself is superfluous. In C++03, the
11762 // program is actually ill-formed. However, DR 382 (in C++0x CD1)
11763 // allows such extraneous "typename" keywords, and we retroactively
11764 // apply this DR to C++03 code with only a warning. In any case we continue.
11765
11766 if (RequireCompleteDeclContext(SS, DC: Ctx))
11767 return QualType();
11768 }
11769
11770 DeclarationName Name(&II);
11771 LookupResult Result(*this, Name, IILoc, LookupOrdinaryName);
11772 if (Ctx)
11773 LookupQualifiedName(R&: Result, LookupCtx: Ctx, SS);
11774 else
11775 LookupName(R&: Result, S: CurScope);
11776 unsigned DiagID = 0;
11777 Decl *Referenced = nullptr;
11778 switch (Result.getResultKind()) {
11779 case LookupResult::NotFound: {
11780 // If we're looking up 'type' within a template named 'enable_if', produce
11781 // a more specific diagnostic.
11782 SourceRange CondRange;
11783 Expr *Cond = nullptr;
11784 if (Ctx && isEnableIf(NNS: QualifierLoc, II, CondRange, Cond)) {
11785 // If we have a condition, narrow it down to the specific failed
11786 // condition.
11787 if (Cond) {
11788 Expr *FailedCond;
11789 std::string FailedDescription;
11790 std::tie(args&: FailedCond, args&: FailedDescription) =
11791 findFailedBooleanCondition(Cond);
11792
11793 Diag(FailedCond->getExprLoc(),
11794 diag::err_typename_nested_not_found_requirement)
11795 << FailedDescription
11796 << FailedCond->getSourceRange();
11797 return QualType();
11798 }
11799
11800 Diag(CondRange.getBegin(),
11801 diag::err_typename_nested_not_found_enable_if)
11802 << Ctx << CondRange;
11803 return QualType();
11804 }
11805
11806 DiagID = Ctx ? diag::err_typename_nested_not_found
11807 : diag::err_unknown_typename;
11808 break;
11809 }
11810
11811 case LookupResult::FoundUnresolvedValue: {
11812 // We found a using declaration that is a value. Most likely, the using
11813 // declaration itself is meant to have the 'typename' keyword.
11814 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11815 IILoc);
11816 Diag(IILoc, diag::err_typename_refers_to_using_value_decl)
11817 << Name << Ctx << FullRange;
11818 if (UnresolvedUsingValueDecl *Using
11819 = dyn_cast<UnresolvedUsingValueDecl>(Val: Result.getRepresentativeDecl())){
11820 SourceLocation Loc = Using->getQualifierLoc().getBeginLoc();
11821 Diag(Loc, diag::note_using_value_decl_missing_typename)
11822 << FixItHint::CreateInsertion(Loc, "typename ");
11823 }
11824 }
11825 // Fall through to create a dependent typename type, from which we can recover
11826 // better.
11827 [[fallthrough]];
11828
11829 case LookupResult::NotFoundInCurrentInstantiation:
11830 // Okay, it's a member of an unknown instantiation.
11831 return Context.getDependentNameType(Keyword,
11832 NNS: QualifierLoc.getNestedNameSpecifier(),
11833 Name: &II);
11834
11835 case LookupResult::Found:
11836 if (TypeDecl *Type = dyn_cast<TypeDecl>(Val: Result.getFoundDecl())) {
11837 // C++ [class.qual]p2:
11838 // In a lookup in which function names are not ignored and the
11839 // nested-name-specifier nominates a class C, if the name specified
11840 // after the nested-name-specifier, when looked up in C, is the
11841 // injected-class-name of C [...] then the name is instead considered
11842 // to name the constructor of class C.
11843 //
11844 // Unlike in an elaborated-type-specifier, function names are not ignored
11845 // in typename-specifier lookup. However, they are ignored in all the
11846 // contexts where we form a typename type with no keyword (that is, in
11847 // mem-initializer-ids, base-specifiers, and elaborated-type-specifiers).
11848 //
11849 // FIXME: That's not strictly true: mem-initializer-id lookup does not
11850 // ignore functions, but that appears to be an oversight.
11851 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(Val: Ctx);
11852 auto *FoundRD = dyn_cast<CXXRecordDecl>(Val: Type);
11853 if (Keyword == ElaboratedTypeKeyword::Typename && LookupRD && FoundRD &&
11854 FoundRD->isInjectedClassName() &&
11855 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
11856 Diag(IILoc, diag::ext_out_of_line_qualified_id_type_names_constructor)
11857 << &II << 1 << 0 /*'typename' keyword used*/;
11858
11859 // We found a type. Build an ElaboratedType, since the
11860 // typename-specifier was just sugar.
11861 MarkAnyDeclReferenced(Loc: Type->getLocation(), D: Type, /*OdrUse=*/MightBeOdrUse: false);
11862 return Context.getElaboratedType(Keyword,
11863 NNS: QualifierLoc.getNestedNameSpecifier(),
11864 NamedType: Context.getTypeDeclType(Decl: Type));
11865 }
11866
11867 // C++ [dcl.type.simple]p2:
11868 // A type-specifier of the form
11869 // typename[opt] nested-name-specifier[opt] template-name
11870 // is a placeholder for a deduced class type [...].
11871 if (getLangOpts().CPlusPlus17) {
11872 if (auto *TD = getAsTypeTemplateDecl(Result.getFoundDecl())) {
11873 if (!DeducedTSTContext) {
11874 QualType T(QualifierLoc
11875 ? QualifierLoc.getNestedNameSpecifier()->getAsType()
11876 : nullptr, 0);
11877 if (!T.isNull())
11878 Diag(IILoc, diag::err_dependent_deduced_tst)
11879 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD)) << T;
11880 else
11881 Diag(IILoc, diag::err_deduced_tst)
11882 << (int)getTemplateNameKindForDiagnostics(TemplateName(TD));
11883 NoteTemplateLocation(Decl: *TD);
11884 return QualType();
11885 }
11886 return Context.getElaboratedType(
11887 Keyword, NNS: QualifierLoc.getNestedNameSpecifier(),
11888 NamedType: Context.getDeducedTemplateSpecializationType(Template: TemplateName(TD),
11889 DeducedType: QualType(), IsDependent: false));
11890 }
11891 }
11892
11893 DiagID = Ctx ? diag::err_typename_nested_not_type
11894 : diag::err_typename_not_type;
11895 Referenced = Result.getFoundDecl();
11896 break;
11897
11898 case LookupResult::FoundOverloaded:
11899 DiagID = Ctx ? diag::err_typename_nested_not_type
11900 : diag::err_typename_not_type;
11901 Referenced = *Result.begin();
11902 break;
11903
11904 case LookupResult::Ambiguous:
11905 return QualType();
11906 }
11907
11908 // If we get here, it's because name lookup did not find a
11909 // type. Emit an appropriate diagnostic and return an error.
11910 SourceRange FullRange(KeywordLoc.isValid() ? KeywordLoc : SS.getBeginLoc(),
11911 IILoc);
11912 if (Ctx)
11913 Diag(IILoc, DiagID) << FullRange << Name << Ctx;
11914 else
11915 Diag(IILoc, DiagID) << FullRange << Name;
11916 if (Referenced)
11917 Diag(Referenced->getLocation(),
11918 Ctx ? diag::note_typename_member_refers_here
11919 : diag::note_typename_refers_here)
11920 << Name;
11921 return QualType();
11922}
11923
11924namespace {
11925 // See Sema::RebuildTypeInCurrentInstantiation
11926 class CurrentInstantiationRebuilder
11927 : public TreeTransform<CurrentInstantiationRebuilder> {
11928 SourceLocation Loc;
11929 DeclarationName Entity;
11930
11931 public:
11932 typedef TreeTransform<CurrentInstantiationRebuilder> inherited;
11933
11934 CurrentInstantiationRebuilder(Sema &SemaRef,
11935 SourceLocation Loc,
11936 DeclarationName Entity)
11937 : TreeTransform<CurrentInstantiationRebuilder>(SemaRef),
11938 Loc(Loc), Entity(Entity) { }
11939
11940 /// Determine whether the given type \p T has already been
11941 /// transformed.
11942 ///
11943 /// For the purposes of type reconstruction, a type has already been
11944 /// transformed if it is NULL or if it is not dependent.
11945 bool AlreadyTransformed(QualType T) {
11946 return T.isNull() || !T->isInstantiationDependentType();
11947 }
11948
11949 /// Returns the location of the entity whose type is being
11950 /// rebuilt.
11951 SourceLocation getBaseLocation() { return Loc; }
11952
11953 /// Returns the name of the entity whose type is being rebuilt.
11954 DeclarationName getBaseEntity() { return Entity; }
11955
11956 /// Sets the "base" location and entity when that
11957 /// information is known based on another transformation.
11958 void setBase(SourceLocation Loc, DeclarationName Entity) {
11959 this->Loc = Loc;
11960 this->Entity = Entity;
11961 }
11962
11963 ExprResult TransformLambdaExpr(LambdaExpr *E) {
11964 // Lambdas never need to be transformed.
11965 return E;
11966 }
11967 };
11968} // end anonymous namespace
11969
11970/// Rebuilds a type within the context of the current instantiation.
11971///
11972/// The type \p T is part of the type of an out-of-line member definition of
11973/// a class template (or class template partial specialization) that was parsed
11974/// and constructed before we entered the scope of the class template (or
11975/// partial specialization thereof). This routine will rebuild that type now
11976/// that we have entered the declarator's scope, which may produce different
11977/// canonical types, e.g.,
11978///
11979/// \code
11980/// template<typename T>
11981/// struct X {
11982/// typedef T* pointer;
11983/// pointer data();
11984/// };
11985///
11986/// template<typename T>
11987/// typename X<T>::pointer X<T>::data() { ... }
11988/// \endcode
11989///
11990/// Here, the type "typename X<T>::pointer" will be created as a DependentNameType,
11991/// since we do not know that we can look into X<T> when we parsed the type.
11992/// This function will rebuild the type, performing the lookup of "pointer"
11993/// in X<T> and returning an ElaboratedType whose canonical type is the same
11994/// as the canonical type of T*, allowing the return types of the out-of-line
11995/// definition and the declaration to match.
11996TypeSourceInfo *Sema::RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
11997 SourceLocation Loc,
11998 DeclarationName Name) {
11999 if (!T || !T->getType()->isInstantiationDependentType())
12000 return T;
12001
12002 CurrentInstantiationRebuilder Rebuilder(*this, Loc, Name);
12003 return Rebuilder.TransformType(T);
12004}
12005
12006ExprResult Sema::RebuildExprInCurrentInstantiation(Expr *E) {
12007 CurrentInstantiationRebuilder Rebuilder(*this, E->getExprLoc(),
12008 DeclarationName());
12009 return Rebuilder.TransformExpr(E);
12010}
12011
12012bool Sema::RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS) {
12013 if (SS.isInvalid())
12014 return true;
12015
12016 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12017 CurrentInstantiationRebuilder Rebuilder(*this, SS.getRange().getBegin(),
12018 DeclarationName());
12019 NestedNameSpecifierLoc Rebuilt
12020 = Rebuilder.TransformNestedNameSpecifierLoc(QualifierLoc);
12021 if (!Rebuilt)
12022 return true;
12023
12024 SS.Adopt(Other: Rebuilt);
12025 return false;
12026}
12027
12028/// Rebuild the template parameters now that we know we're in a current
12029/// instantiation.
12030bool Sema::RebuildTemplateParamsInCurrentInstantiation(
12031 TemplateParameterList *Params) {
12032 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
12033 Decl *Param = Params->getParam(Idx: I);
12034
12035 // There is nothing to rebuild in a type parameter.
12036 if (isa<TemplateTypeParmDecl>(Val: Param))
12037 continue;
12038
12039 // Rebuild the template parameter list of a template template parameter.
12040 if (TemplateTemplateParmDecl *TTP
12041 = dyn_cast<TemplateTemplateParmDecl>(Val: Param)) {
12042 if (RebuildTemplateParamsInCurrentInstantiation(
12043 Params: TTP->getTemplateParameters()))
12044 return true;
12045
12046 continue;
12047 }
12048
12049 // Rebuild the type of a non-type template parameter.
12050 NonTypeTemplateParmDecl *NTTP = cast<NonTypeTemplateParmDecl>(Val: Param);
12051 TypeSourceInfo *NewTSI
12052 = RebuildTypeInCurrentInstantiation(T: NTTP->getTypeSourceInfo(),
12053 Loc: NTTP->getLocation(),
12054 Name: NTTP->getDeclName());
12055 if (!NewTSI)
12056 return true;
12057
12058 if (NewTSI->getType()->isUndeducedType()) {
12059 // C++17 [temp.dep.expr]p3:
12060 // An id-expression is type-dependent if it contains
12061 // - an identifier associated by name lookup with a non-type
12062 // template-parameter declared with a type that contains a
12063 // placeholder type (7.1.7.4),
12064 NewTSI = SubstAutoTypeSourceInfoDependent(TypeWithAuto: NewTSI);
12065 }
12066
12067 if (NewTSI != NTTP->getTypeSourceInfo()) {
12068 NTTP->setTypeSourceInfo(NewTSI);
12069 NTTP->setType(NewTSI->getType());
12070 }
12071 }
12072
12073 return false;
12074}
12075
12076/// Produces a formatted string that describes the binding of
12077/// template parameters to template arguments.
12078std::string
12079Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12080 const TemplateArgumentList &Args) {
12081 return getTemplateArgumentBindingsText(Params, Args: Args.data(), NumArgs: Args.size());
12082}
12083
12084std::string
12085Sema::getTemplateArgumentBindingsText(const TemplateParameterList *Params,
12086 const TemplateArgument *Args,
12087 unsigned NumArgs) {
12088 SmallString<128> Str;
12089 llvm::raw_svector_ostream Out(Str);
12090
12091 if (!Params || Params->size() == 0 || NumArgs == 0)
12092 return std::string();
12093
12094 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
12095 if (I >= NumArgs)
12096 break;
12097
12098 if (I == 0)
12099 Out << "[with ";
12100 else
12101 Out << ", ";
12102
12103 if (const IdentifierInfo *Id = Params->getParam(Idx: I)->getIdentifier()) {
12104 Out << Id->getName();
12105 } else {
12106 Out << '$' << I;
12107 }
12108
12109 Out << " = ";
12110 Args[I].print(Policy: getPrintingPolicy(), Out,
12111 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
12112 Policy: getPrintingPolicy(), TPL: Params, Idx: I));
12113 }
12114
12115 Out << ']';
12116 return std::string(Out.str());
12117}
12118
12119void Sema::MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
12120 CachedTokens &Toks) {
12121 if (!FD)
12122 return;
12123
12124 auto LPT = std::make_unique<LateParsedTemplate>();
12125
12126 // Take tokens to avoid allocations
12127 LPT->Toks.swap(RHS&: Toks);
12128 LPT->D = FnD;
12129 LPT->FPO = getCurFPFeatures();
12130 LateParsedTemplateMap.insert(KV: std::make_pair(x&: FD, y: std::move(LPT)));
12131
12132 FD->setLateTemplateParsed(true);
12133}
12134
12135void Sema::UnmarkAsLateParsedTemplate(FunctionDecl *FD) {
12136 if (!FD)
12137 return;
12138 FD->setLateTemplateParsed(false);
12139}
12140
12141bool Sema::IsInsideALocalClassWithinATemplateFunction() {
12142 DeclContext *DC = CurContext;
12143
12144 while (DC) {
12145 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
12146 const FunctionDecl *FD = RD->isLocalClass();
12147 return (FD && FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate);
12148 } else if (DC->isTranslationUnit() || DC->isNamespace())
12149 return false;
12150
12151 DC = DC->getParent();
12152 }
12153 return false;
12154}
12155
12156namespace {
12157/// Walk the path from which a declaration was instantiated, and check
12158/// that every explicit specialization along that path is visible. This enforces
12159/// C++ [temp.expl.spec]/6:
12160///
12161/// If a template, a member template or a member of a class template is
12162/// explicitly specialized then that specialization shall be declared before
12163/// the first use of that specialization that would cause an implicit
12164/// instantiation to take place, in every translation unit in which such a
12165/// use occurs; no diagnostic is required.
12166///
12167/// and also C++ [temp.class.spec]/1:
12168///
12169/// A partial specialization shall be declared before the first use of a
12170/// class template specialization that would make use of the partial
12171/// specialization as the result of an implicit or explicit instantiation
12172/// in every translation unit in which such a use occurs; no diagnostic is
12173/// required.
12174class ExplicitSpecializationVisibilityChecker {
12175 Sema &S;
12176 SourceLocation Loc;
12177 llvm::SmallVector<Module *, 8> Modules;
12178 Sema::AcceptableKind Kind;
12179
12180public:
12181 ExplicitSpecializationVisibilityChecker(Sema &S, SourceLocation Loc,
12182 Sema::AcceptableKind Kind)
12183 : S(S), Loc(Loc), Kind(Kind) {}
12184
12185 void check(NamedDecl *ND) {
12186 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
12187 return checkImpl(Spec: FD);
12188 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: ND))
12189 return checkImpl(Spec: RD);
12190 if (auto *VD = dyn_cast<VarDecl>(Val: ND))
12191 return checkImpl(Spec: VD);
12192 if (auto *ED = dyn_cast<EnumDecl>(Val: ND))
12193 return checkImpl(Spec: ED);
12194 }
12195
12196private:
12197 void diagnose(NamedDecl *D, bool IsPartialSpec) {
12198 auto Kind = IsPartialSpec ? Sema::MissingImportKind::PartialSpecialization
12199 : Sema::MissingImportKind::ExplicitSpecialization;
12200 const bool Recover = true;
12201
12202 // If we got a custom set of modules (because only a subset of the
12203 // declarations are interesting), use them, otherwise let
12204 // diagnoseMissingImport intelligently pick some.
12205 if (Modules.empty())
12206 S.diagnoseMissingImport(Loc, Decl: D, MIK: Kind, Recover);
12207 else
12208 S.diagnoseMissingImport(Loc, D, D->getLocation(), Modules, Kind, Recover);
12209 }
12210
12211 bool CheckMemberSpecialization(const NamedDecl *D) {
12212 return Kind == Sema::AcceptableKind::Visible
12213 ? S.hasVisibleMemberSpecialization(D)
12214 : S.hasReachableMemberSpecialization(D);
12215 }
12216
12217 bool CheckExplicitSpecialization(const NamedDecl *D) {
12218 return Kind == Sema::AcceptableKind::Visible
12219 ? S.hasVisibleExplicitSpecialization(D)
12220 : S.hasReachableExplicitSpecialization(D);
12221 }
12222
12223 bool CheckDeclaration(const NamedDecl *D) {
12224 return Kind == Sema::AcceptableKind::Visible ? S.hasVisibleDeclaration(D)
12225 : S.hasReachableDeclaration(D);
12226 }
12227
12228 // Check a specific declaration. There are three problematic cases:
12229 //
12230 // 1) The declaration is an explicit specialization of a template
12231 // specialization.
12232 // 2) The declaration is an explicit specialization of a member of an
12233 // templated class.
12234 // 3) The declaration is an instantiation of a template, and that template
12235 // is an explicit specialization of a member of a templated class.
12236 //
12237 // We don't need to go any deeper than that, as the instantiation of the
12238 // surrounding class / etc is not triggered by whatever triggered this
12239 // instantiation, and thus should be checked elsewhere.
12240 template<typename SpecDecl>
12241 void checkImpl(SpecDecl *Spec) {
12242 bool IsHiddenExplicitSpecialization = false;
12243 if (Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
12244 IsHiddenExplicitSpecialization = Spec->getMemberSpecializationInfo()
12245 ? !CheckMemberSpecialization(D: Spec)
12246 : !CheckExplicitSpecialization(D: Spec);
12247 } else {
12248 checkInstantiated(Spec);
12249 }
12250
12251 if (IsHiddenExplicitSpecialization)
12252 diagnose(D: Spec->getMostRecentDecl(), IsPartialSpec: false);
12253 }
12254
12255 void checkInstantiated(FunctionDecl *FD) {
12256 if (auto *TD = FD->getPrimaryTemplate())
12257 checkTemplate(TD);
12258 }
12259
12260 void checkInstantiated(CXXRecordDecl *RD) {
12261 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: RD);
12262 if (!SD)
12263 return;
12264
12265 auto From = SD->getSpecializedTemplateOrPartial();
12266 if (auto *TD = From.dyn_cast<ClassTemplateDecl *>())
12267 checkTemplate(TD);
12268 else if (auto *TD =
12269 From.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
12270 if (!CheckDeclaration(TD))
12271 diagnose(TD, true);
12272 checkTemplate(TD);
12273 }
12274 }
12275
12276 void checkInstantiated(VarDecl *RD) {
12277 auto *SD = dyn_cast<VarTemplateSpecializationDecl>(Val: RD);
12278 if (!SD)
12279 return;
12280
12281 auto From = SD->getSpecializedTemplateOrPartial();
12282 if (auto *TD = From.dyn_cast<VarTemplateDecl *>())
12283 checkTemplate(TD);
12284 else if (auto *TD =
12285 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
12286 if (!CheckDeclaration(TD))
12287 diagnose(TD, true);
12288 checkTemplate(TD);
12289 }
12290 }
12291
12292 void checkInstantiated(EnumDecl *FD) {}
12293
12294 template<typename TemplDecl>
12295 void checkTemplate(TemplDecl *TD) {
12296 if (TD->isMemberSpecialization()) {
12297 if (!CheckMemberSpecialization(D: TD))
12298 diagnose(D: TD->getMostRecentDecl(), IsPartialSpec: false);
12299 }
12300 }
12301};
12302} // end anonymous namespace
12303
12304void Sema::checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec) {
12305 if (!getLangOpts().Modules)
12306 return;
12307
12308 ExplicitSpecializationVisibilityChecker(*this, Loc,
12309 Sema::AcceptableKind::Visible)
12310 .check(ND: Spec);
12311}
12312
12313void Sema::checkSpecializationReachability(SourceLocation Loc,
12314 NamedDecl *Spec) {
12315 if (!getLangOpts().CPlusPlusModules)
12316 return checkSpecializationVisibility(Loc, Spec);
12317
12318 ExplicitSpecializationVisibilityChecker(*this, Loc,
12319 Sema::AcceptableKind::Reachable)
12320 .check(ND: Spec);
12321}
12322
12323/// Returns the top most location responsible for the definition of \p N.
12324/// If \p N is a a template specialization, this is the location
12325/// of the top of the instantiation stack.
12326/// Otherwise, the location of \p N is returned.
12327SourceLocation Sema::getTopMostPointOfInstantiation(const NamedDecl *N) const {
12328 if (!getLangOpts().CPlusPlus || CodeSynthesisContexts.empty())
12329 return N->getLocation();
12330 if (const auto *FD = dyn_cast<FunctionDecl>(Val: N)) {
12331 if (!FD->isFunctionTemplateSpecialization())
12332 return FD->getLocation();
12333 } else if (!isa<ClassTemplateSpecializationDecl,
12334 VarTemplateSpecializationDecl>(Val: N)) {
12335 return N->getLocation();
12336 }
12337 for (const CodeSynthesisContext &CSC : CodeSynthesisContexts) {
12338 if (!CSC.isInstantiationRecord() || CSC.PointOfInstantiation.isInvalid())
12339 continue;
12340 return CSC.PointOfInstantiation;
12341 }
12342 return N->getLocation();
12343}
12344

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