clang 19.0.0git
SemaTemplate.cpp
Go to the documentation of this file.
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"
14#include "clang/AST/Decl.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
27#include "clang/Basic/Stack.h"
29#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Overload.h"
35#include "clang/Sema/Scope.h"
37#include "clang/Sema/Template.h"
39#include "llvm/ADT/SmallBitVector.h"
40#include "llvm/ADT/SmallString.h"
41#include "llvm/ADT/StringExtras.h"
42
43#include <iterator>
44#include <optional>
45using namespace clang;
46using namespace sema;
47
48// Exported for use by Parser.
51 unsigned N) {
52 if (!N) return SourceRange();
53 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
54}
55
56unsigned Sema::getTemplateDepth(Scope *S) const {
57 unsigned Depth = 0;
58
59 // Each template parameter scope represents one level of template parameter
60 // depth.
61 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
62 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
63 ++Depth;
64 }
65
66 // Note that there are template parameters with the given depth.
67 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
68
69 // Look for parameters of an enclosing generic lambda. We don't create a
70 // template parameter scope for these.
72 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
73 if (!LSI->TemplateParams.empty()) {
74 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
75 break;
76 }
77 if (LSI->GLTemplateParameterList) {
78 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
79 break;
80 }
81 }
82 }
83
84 // Look for parameters of an enclosing terse function template. We don't
85 // create a template parameter scope for these either.
86 for (const InventedTemplateParameterInfo &Info :
88 if (!Info.TemplateParams.empty()) {
89 ParamsAtDepth(Info.AutoTemplateParameterDepth);
90 break;
91 }
92 }
93
94 return Depth;
95}
96
97/// \brief Determine whether the declaration found is acceptable as the name
98/// of a template and, if so, return that template declaration. Otherwise,
99/// returns null.
100///
101/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
102/// is true. In all other cases it will return a TemplateDecl (or null).
104 bool AllowFunctionTemplates,
105 bool AllowDependent) {
106 D = D->getUnderlyingDecl();
107
108 if (isa<TemplateDecl>(D)) {
109 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
110 return nullptr;
111
112 return D;
113 }
114
115 if (const auto *Record = dyn_cast<CXXRecordDecl>(D)) {
116 // C++ [temp.local]p1:
117 // Like normal (non-template) classes, class templates have an
118 // injected-class-name (Clause 9). The injected-class-name
119 // can be used with or without a template-argument-list. When
120 // it is used without a template-argument-list, it is
121 // equivalent to the injected-class-name followed by the
122 // template-parameters of the class template enclosed in
123 // <>. When it is used with a template-argument-list, it
124 // refers to the specified class template specialization,
125 // which could be the current specialization or another
126 // specialization.
127 if (Record->isInjectedClassName()) {
128 Record = cast<CXXRecordDecl>(Record->getDeclContext());
129 if (Record->getDescribedClassTemplate())
130 return Record->getDescribedClassTemplate();
131
132 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Record))
133 return Spec->getSpecializedTemplate();
134 }
135
136 return nullptr;
137 }
138
139 // 'using Dependent::foo;' can resolve to a template name.
140 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
141 // injected-class-name).
142 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
143 return D;
144
145 return nullptr;
146}
147
149 bool AllowFunctionTemplates,
150 bool AllowDependent) {
151 LookupResult::Filter filter = R.makeFilter();
152 while (filter.hasNext()) {
153 NamedDecl *Orig = filter.next();
154 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
155 filter.erase();
156 }
157 filter.done();
158}
159
161 bool AllowFunctionTemplates,
162 bool AllowDependent,
163 bool AllowNonTemplateFunctions) {
164 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
165 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
166 return true;
167 if (AllowNonTemplateFunctions &&
168 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
169 return true;
170 }
171
172 return false;
173}
174
176 CXXScopeSpec &SS,
177 bool hasTemplateKeyword,
178 const UnqualifiedId &Name,
179 ParsedType ObjectTypePtr,
180 bool EnteringContext,
181 TemplateTy &TemplateResult,
182 bool &MemberOfUnknownSpecialization,
183 bool Disambiguation) {
184 assert(getLangOpts().CPlusPlus && "No template names in C!");
185
186 DeclarationName TName;
187 MemberOfUnknownSpecialization = false;
188
189 switch (Name.getKind()) {
191 TName = DeclarationName(Name.Identifier);
192 break;
193
196 Name.OperatorFunctionId.Operator);
197 break;
198
200 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
201 break;
202
203 default:
204 return TNK_Non_template;
205 }
206
207 QualType ObjectType = ObjectTypePtr.get();
208
209 AssumedTemplateKind AssumedTemplate;
210 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
211 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
212 MemberOfUnknownSpecialization, SourceLocation(),
213 &AssumedTemplate,
214 /*AllowTypoCorrection=*/!Disambiguation))
215 return TNK_Non_template;
216
217 if (AssumedTemplate != AssumedTemplateKind::None) {
218 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
219 // Let the parser know whether we found nothing or found functions; if we
220 // found nothing, we want to more carefully check whether this is actually
221 // a function template name versus some other kind of undeclared identifier.
222 return AssumedTemplate == AssumedTemplateKind::FoundNothing
225 }
226
227 if (R.empty())
228 return TNK_Non_template;
229
230 NamedDecl *D = nullptr;
231 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
232 if (R.isAmbiguous()) {
233 // If we got an ambiguity involving a non-function template, treat this
234 // as a template name, and pick an arbitrary template for error recovery.
235 bool AnyFunctionTemplates = false;
236 for (NamedDecl *FoundD : R) {
237 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
238 if (isa<FunctionTemplateDecl>(FoundTemplate))
239 AnyFunctionTemplates = true;
240 else {
241 D = FoundTemplate;
242 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
243 break;
244 }
245 }
246 }
247
248 // If we didn't find any templates at all, this isn't a template name.
249 // Leave the ambiguity for a later lookup to diagnose.
250 if (!D && !AnyFunctionTemplates) {
251 R.suppressDiagnostics();
252 return TNK_Non_template;
253 }
254
255 // If the only templates were function templates, filter out the rest.
256 // We'll diagnose the ambiguity later.
257 if (!D)
259 }
260
261 // At this point, we have either picked a single template name declaration D
262 // or we have a non-empty set of results R containing either one template name
263 // declaration or a set of function templates.
264
265 TemplateName Template;
266 TemplateNameKind TemplateKind;
267
268 unsigned ResultCount = R.end() - R.begin();
269 if (!D && ResultCount > 1) {
270 // We assume that we'll preserve the qualifier from a function
271 // template name in other ways.
272 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
273 TemplateKind = TNK_Function_template;
274
275 // We'll do this lookup again later.
277 } else {
278 if (!D) {
280 assert(D && "unambiguous result is not a template name");
281 }
282
283 if (isa<UnresolvedUsingValueDecl>(D)) {
284 // We don't yet know whether this is a template-name or not.
285 MemberOfUnknownSpecialization = true;
286 return TNK_Non_template;
287 }
288
289 TemplateDecl *TD = cast<TemplateDecl>(D);
290 Template =
291 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
292 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD);
293 if (SS.isSet() && !SS.isInvalid()) {
294 NestedNameSpecifier *Qualifier = SS.getScopeRep();
295 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
296 Template);
297 }
298
299 if (isa<FunctionTemplateDecl>(TD)) {
300 TemplateKind = TNK_Function_template;
301
302 // We'll do this lookup again later.
304 } else {
305 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||
306 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||
307 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD));
308 TemplateKind =
309 isa<VarTemplateDecl>(TD) ? TNK_Var_template :
310 isa<ConceptDecl>(TD) ? TNK_Concept_template :
312 }
313 }
314
315 TemplateResult = TemplateTy::make(Template);
316 return TemplateKind;
317}
318
320 SourceLocation NameLoc, CXXScopeSpec &SS,
321 ParsedTemplateTy *Template /*=nullptr*/) {
322 bool MemberOfUnknownSpecialization = false;
323
324 // We could use redeclaration lookup here, but we don't need to: the
325 // syntactic form of a deduction guide is enough to identify it even
326 // if we can't look up the template name at all.
327 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
328 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
329 /*EnteringContext*/ false,
330 MemberOfUnknownSpecialization))
331 return false;
332
333 if (R.empty()) return false;
334 if (R.isAmbiguous()) {
335 // FIXME: Diagnose an ambiguity if we find at least one template.
337 return false;
338 }
339
340 // We only treat template-names that name type templates as valid deduction
341 // guide names.
343 if (!TD || !getAsTypeTemplateDecl(TD))
344 return false;
345
346 if (Template)
347 *Template = TemplateTy::make(TemplateName(TD));
348 return true;
349}
350
352 SourceLocation IILoc,
353 Scope *S,
354 const CXXScopeSpec *SS,
355 TemplateTy &SuggestedTemplate,
356 TemplateNameKind &SuggestedKind) {
357 // We can't recover unless there's a dependent scope specifier preceding the
358 // template name.
359 // FIXME: Typo correction?
360 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
362 return false;
363
364 // The code is missing a 'template' keyword prior to the dependent template
365 // name.
367 Diag(IILoc, diag::err_template_kw_missing)
368 << Qualifier << II.getName()
369 << FixItHint::CreateInsertion(IILoc, "template ");
370 SuggestedTemplate
372 SuggestedKind = TNK_Dependent_template_name;
373 return true;
374}
375
377 Scope *S, CXXScopeSpec &SS,
378 QualType ObjectType,
379 bool EnteringContext,
380 bool &MemberOfUnknownSpecialization,
381 RequiredTemplateKind RequiredTemplate,
383 bool AllowTypoCorrection) {
384 if (ATK)
386
387 if (SS.isInvalid())
388 return true;
389
390 Found.setTemplateNameLookup(true);
391
392 // Determine where to perform name lookup
393 MemberOfUnknownSpecialization = false;
394 DeclContext *LookupCtx = nullptr;
395 bool IsDependent = false;
396 if (!ObjectType.isNull()) {
397 // This nested-name-specifier occurs in a member access expression, e.g.,
398 // x->B::f, and we are looking into the type of the object.
399 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist");
400 LookupCtx = computeDeclContext(ObjectType);
401 IsDependent = !LookupCtx && ObjectType->isDependentType();
402 assert((IsDependent || !ObjectType->isIncompleteType() ||
403 !ObjectType->getAs<TagType>() ||
404 ObjectType->castAs<TagType>()->isBeingDefined()) &&
405 "Caller should have completed object type");
406
407 // Template names cannot appear inside an Objective-C class or object type
408 // or a vector type.
409 //
410 // FIXME: This is wrong. For example:
411 //
412 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
413 // Vec<int> vi;
414 // vi.Vec<int>::~Vec<int>();
415 //
416 // ... should be accepted but we will not treat 'Vec' as a template name
417 // here. The right thing to do would be to check if the name is a valid
418 // vector component name, and look up a template name if not. And similarly
419 // for lookups into Objective-C class and object types, where the same
420 // problem can arise.
421 if (ObjectType->isObjCObjectOrInterfaceType() ||
422 ObjectType->isVectorType()) {
423 Found.clear();
424 return false;
425 }
426 } else if (SS.isNotEmpty()) {
427 // This nested-name-specifier occurs after another nested-name-specifier,
428 // so long into the context associated with the prior nested-name-specifier.
429 LookupCtx = computeDeclContext(SS, EnteringContext);
430 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
431
432 // The declaration context must be complete.
433 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
434 return true;
435 }
436
437 bool ObjectTypeSearchedInScope = false;
438 bool AllowFunctionTemplatesInLookup = true;
439 if (LookupCtx) {
440 // Perform "qualified" name lookup into the declaration context we
441 // computed, which is either the type of the base of a member access
442 // expression or the declaration context associated with a prior
443 // nested-name-specifier.
444 LookupQualifiedName(Found, LookupCtx);
445
446 // FIXME: The C++ standard does not clearly specify what happens in the
447 // case where the object type is dependent, and implementations vary. In
448 // Clang, we treat a name after a . or -> as a template-name if lookup
449 // finds a non-dependent member or member of the current instantiation that
450 // is a type template, or finds no such members and lookup in the context
451 // of the postfix-expression finds a type template. In the latter case, the
452 // name is nonetheless dependent, and we may resolve it to a member of an
453 // unknown specialization when we come to instantiate the template.
454 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
455 }
456
457 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
458 // C++ [basic.lookup.classref]p1:
459 // In a class member access expression (5.2.5), if the . or -> token is
460 // immediately followed by an identifier followed by a <, the
461 // identifier must be looked up to determine whether the < is the
462 // beginning of a template argument list (14.2) or a less-than operator.
463 // The identifier is first looked up in the class of the object
464 // expression. If the identifier is not found, it is then looked up in
465 // the context of the entire postfix-expression and shall name a class
466 // template.
467 if (S)
468 LookupName(Found, S);
469
470 if (!ObjectType.isNull()) {
471 // FIXME: We should filter out all non-type templates here, particularly
472 // variable templates and concepts. But the exclusion of alias templates
473 // and template template parameters is a wording defect.
474 AllowFunctionTemplatesInLookup = false;
475 ObjectTypeSearchedInScope = true;
476 }
477
478 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
479 }
480
481 if (Found.isAmbiguous())
482 return false;
483
484 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
485 !RequiredTemplate.hasTemplateKeyword()) {
486 // C++2a [temp.names]p2:
487 // A name is also considered to refer to a template if it is an
488 // unqualified-id followed by a < and name lookup finds either one or more
489 // functions or finds nothing.
490 //
491 // To keep our behavior consistent, we apply the "finds nothing" part in
492 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
493 // successfully form a call to an undeclared template-id.
494 bool AllFunctions =
495 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
496 return isa<FunctionDecl>(ND->getUnderlyingDecl());
497 });
498 if (AllFunctions || (Found.empty() && !IsDependent)) {
499 // If lookup found any functions, or if this is a name that can only be
500 // used for a function, then strongly assume this is a function
501 // template-id.
502 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
505 Found.clear();
506 return false;
507 }
508 }
509
510 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
511 // If we did not find any names, and this is not a disambiguation, attempt
512 // to correct any typos.
513 DeclarationName Name = Found.getLookupName();
514 Found.clear();
515 // Simple filter callback that, for keywords, only accepts the C++ *_cast
516 DefaultFilterCCC FilterCCC{};
517 FilterCCC.WantTypeSpecifiers = false;
518 FilterCCC.WantExpressionKeywords = false;
519 FilterCCC.WantRemainingKeywords = false;
520 FilterCCC.WantCXXNamedCasts = true;
521 if (TypoCorrection Corrected =
522 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
523 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
524 if (auto *ND = Corrected.getFoundDecl())
525 Found.addDecl(ND);
527 if (Found.isAmbiguous()) {
528 Found.clear();
529 } else if (!Found.empty()) {
530 Found.setLookupName(Corrected.getCorrection());
531 if (LookupCtx) {
532 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
533 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
534 Name.getAsString() == CorrectedStr;
535 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
536 << Name << LookupCtx << DroppedSpecifier
537 << SS.getRange());
538 } else {
539 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
540 }
541 }
542 }
543 }
544
545 NamedDecl *ExampleLookupResult =
546 Found.empty() ? nullptr : Found.getRepresentativeDecl();
547 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
548 if (Found.empty()) {
549 if (IsDependent) {
550 MemberOfUnknownSpecialization = true;
551 return false;
552 }
553
554 // If a 'template' keyword was used, a lookup that finds only non-template
555 // names is an error.
556 if (ExampleLookupResult && RequiredTemplate) {
557 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
558 << Found.getLookupName() << SS.getRange()
559 << RequiredTemplate.hasTemplateKeyword()
560 << RequiredTemplate.getTemplateKeywordLoc();
561 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
562 diag::note_template_kw_refers_to_non_template)
563 << Found.getLookupName();
564 return true;
565 }
566
567 return false;
568 }
569
570 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
572 // C++03 [basic.lookup.classref]p1:
573 // [...] If the lookup in the class of the object expression finds a
574 // template, the name is also looked up in the context of the entire
575 // postfix-expression and [...]
576 //
577 // Note: C++11 does not perform this second lookup.
578 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
580 FoundOuter.setTemplateNameLookup(true);
581 LookupName(FoundOuter, S);
582 // FIXME: We silently accept an ambiguous lookup here, in violation of
583 // [basic.lookup]/1.
584 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
585
586 NamedDecl *OuterTemplate;
587 if (FoundOuter.empty()) {
588 // - if the name is not found, the name found in the class of the
589 // object expression is used, otherwise
590 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
591 !(OuterTemplate =
592 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
593 // - if the name is found in the context of the entire
594 // postfix-expression and does not name a class template, the name
595 // found in the class of the object expression is used, otherwise
596 FoundOuter.clear();
597 } else if (!Found.isSuppressingAmbiguousDiagnostics()) {
598 // - if the name found is a class template, it must refer to the same
599 // entity as the one found in the class of the object expression,
600 // otherwise the program is ill-formed.
601 if (!Found.isSingleResult() ||
603 OuterTemplate->getCanonicalDecl()) {
604 Diag(Found.getNameLoc(),
605 diag::ext_nested_name_member_ref_lookup_ambiguous)
606 << Found.getLookupName()
607 << ObjectType;
609 diag::note_ambig_member_ref_object_type)
610 << ObjectType;
611 Diag(FoundOuter.getFoundDecl()->getLocation(),
612 diag::note_ambig_member_ref_scope);
613
614 // Recover by taking the template that we found in the object
615 // expression's type.
616 }
617 }
618 }
619
620 return false;
621}
622
626 if (TemplateName.isInvalid())
627 return;
628
629 DeclarationNameInfo NameInfo;
630 CXXScopeSpec SS;
631 LookupNameKind LookupKind;
632
633 DeclContext *LookupCtx = nullptr;
634 NamedDecl *Found = nullptr;
635 bool MissingTemplateKeyword = false;
636
637 // Figure out what name we looked up.
638 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
639 NameInfo = DRE->getNameInfo();
640 SS.Adopt(DRE->getQualifierLoc());
641 LookupKind = LookupOrdinaryName;
642 Found = DRE->getFoundDecl();
643 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
644 NameInfo = ME->getMemberNameInfo();
645 SS.Adopt(ME->getQualifierLoc());
646 LookupKind = LookupMemberName;
647 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
648 Found = ME->getMemberDecl();
649 } else if (auto *DSDRE =
650 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
651 NameInfo = DSDRE->getNameInfo();
652 SS.Adopt(DSDRE->getQualifierLoc());
653 MissingTemplateKeyword = true;
654 } else if (auto *DSME =
655 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
656 NameInfo = DSME->getMemberNameInfo();
657 SS.Adopt(DSME->getQualifierLoc());
658 MissingTemplateKeyword = true;
659 } else {
660 llvm_unreachable("unexpected kind of potential template name");
661 }
662
663 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
664 // was missing.
665 if (MissingTemplateKeyword) {
666 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
667 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
668 return;
669 }
670
671 // Try to correct the name by looking for templates and C++ named casts.
672 struct TemplateCandidateFilter : CorrectionCandidateCallback {
673 Sema &S;
674 TemplateCandidateFilter(Sema &S) : S(S) {
675 WantTypeSpecifiers = false;
676 WantExpressionKeywords = false;
677 WantRemainingKeywords = false;
678 WantCXXNamedCasts = true;
679 };
680 bool ValidateCandidate(const TypoCorrection &Candidate) override {
681 if (auto *ND = Candidate.getCorrectionDecl())
682 return S.getAsTemplateNameDecl(ND);
683 return Candidate.isKeyword();
684 }
685
686 std::unique_ptr<CorrectionCandidateCallback> clone() override {
687 return std::make_unique<TemplateCandidateFilter>(*this);
688 }
689 };
690
691 DeclarationName Name = NameInfo.getName();
692 TemplateCandidateFilter CCC(*this);
693 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
694 CTK_ErrorRecovery, LookupCtx)) {
695 auto *ND = Corrected.getFoundDecl();
696 if (ND)
697 ND = getAsTemplateNameDecl(ND);
698 if (ND || Corrected.isKeyword()) {
699 if (LookupCtx) {
700 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
701 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
702 Name.getAsString() == CorrectedStr;
703 diagnoseTypo(Corrected,
704 PDiag(diag::err_non_template_in_member_template_id_suggest)
705 << Name << LookupCtx << DroppedSpecifier
706 << SS.getRange(), false);
707 } else {
708 diagnoseTypo(Corrected,
709 PDiag(diag::err_non_template_in_template_id_suggest)
710 << Name, false);
711 }
712 if (Found)
713 Diag(Found->getLocation(),
714 diag::note_non_template_in_template_id_found);
715 return;
716 }
717 }
718
719 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
720 << Name << SourceRange(Less, Greater);
721 if (Found)
722 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
723}
724
725/// ActOnDependentIdExpression - Handle a dependent id-expression that
726/// was just parsed. This is only possible with an explicit scope
727/// specifier naming a dependent type.
730 SourceLocation TemplateKWLoc,
731 const DeclarationNameInfo &NameInfo,
732 bool isAddressOfOperand,
733 const TemplateArgumentListInfo *TemplateArgs) {
735
736 // C++11 [expr.prim.general]p12:
737 // An id-expression that denotes a non-static data member or non-static
738 // member function of a class can only be used:
739 // (...)
740 // - if that id-expression denotes a non-static data member and it
741 // appears in an unevaluated operand.
742 //
743 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
744 // CXXDependentScopeMemberExpr. The former can instantiate to either
745 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
746 // always a MemberExpr.
747 bool MightBeCxx11UnevalField =
748 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
749
750 // Check if the nested name specifier is an enum type.
751 bool IsEnum = false;
752 if (NestedNameSpecifier *NNS = SS.getScopeRep())
753 IsEnum = isa_and_nonnull<EnumType>(NNS->getAsType());
754
755 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
756 isa<CXXMethodDecl>(DC) &&
757 cast<CXXMethodDecl>(DC)->isImplicitObjectMemberFunction()) {
758 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType().getNonReferenceType();
759
760 // Since the 'this' expression is synthesized, we don't need to
761 // perform the double-lookup check.
762 NamedDecl *FirstQualifierInScope = nullptr;
763
765 Context, /*This=*/nullptr, ThisType,
766 /*IsArrow=*/!Context.getLangOpts().HLSL,
767 /*Op=*/SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
768 FirstQualifierInScope, NameInfo, TemplateArgs);
769 }
770
771 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
772}
773
776 SourceLocation TemplateKWLoc,
777 const DeclarationNameInfo &NameInfo,
778 const TemplateArgumentListInfo *TemplateArgs) {
779 // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
781 if (!QualifierLoc)
782 return ExprError();
783
785 Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
786}
787
788
789/// Determine whether we would be unable to instantiate this template (because
790/// it either has no definition, or is in the process of being instantiated).
792 NamedDecl *Instantiation,
793 bool InstantiatedFromMember,
794 const NamedDecl *Pattern,
795 const NamedDecl *PatternDef,
797 bool Complain /*= true*/) {
798 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||
799 isa<VarDecl>(Instantiation));
800
801 bool IsEntityBeingDefined = false;
802 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
803 IsEntityBeingDefined = TD->isBeingDefined();
804
805 if (PatternDef && !IsEntityBeingDefined) {
806 NamedDecl *SuggestedDef = nullptr;
807 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
808 &SuggestedDef,
809 /*OnlyNeedComplete*/ false)) {
810 // If we're allowed to diagnose this and recover, do so.
811 bool Recover = Complain && !isSFINAEContext();
812 if (Complain)
813 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
815 return !Recover;
816 }
817 return false;
818 }
819
820 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
821 return true;
822
823 QualType InstantiationTy;
824 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
825 InstantiationTy = Context.getTypeDeclType(TD);
826 if (PatternDef) {
827 Diag(PointOfInstantiation,
828 diag::err_template_instantiate_within_definition)
829 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
830 << InstantiationTy;
831 // Not much point in noting the template declaration here, since
832 // we're lexically inside it.
833 Instantiation->setInvalidDecl();
834 } else if (InstantiatedFromMember) {
835 if (isa<FunctionDecl>(Instantiation)) {
836 Diag(PointOfInstantiation,
837 diag::err_explicit_instantiation_undefined_member)
838 << /*member function*/ 1 << Instantiation->getDeclName()
839 << Instantiation->getDeclContext();
840 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
841 } else {
842 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!");
843 Diag(PointOfInstantiation,
844 diag::err_implicit_instantiate_member_undefined)
845 << InstantiationTy;
846 Diag(Pattern->getLocation(), diag::note_member_declared_at);
847 }
848 } else {
849 if (isa<FunctionDecl>(Instantiation)) {
850 Diag(PointOfInstantiation,
851 diag::err_explicit_instantiation_undefined_func_template)
852 << Pattern;
853 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
854 } else if (isa<TagDecl>(Instantiation)) {
855 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
856 << (TSK != TSK_ImplicitInstantiation)
857 << InstantiationTy;
858 NoteTemplateLocation(*Pattern);
859 } else {
860 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!");
861 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
862 Diag(PointOfInstantiation,
863 diag::err_explicit_instantiation_undefined_var_template)
864 << Instantiation;
865 Instantiation->setInvalidDecl();
866 } else
867 Diag(PointOfInstantiation,
868 diag::err_explicit_instantiation_undefined_member)
869 << /*static data member*/ 2 << Instantiation->getDeclName()
870 << Instantiation->getDeclContext();
871 Diag(Pattern->getLocation(), diag::note_explicit_instantiation_here);
872 }
873 }
874
875 // In general, Instantiation isn't marked invalid to get more than one
876 // error for multiple undefined instantiations. But the code that does
877 // explicit declaration -> explicit definition conversion can't handle
878 // invalid declarations, so mark as invalid in that case.
880 Instantiation->setInvalidDecl();
881 return true;
882}
883
884/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
885/// that the template parameter 'PrevDecl' is being shadowed by a new
886/// declaration at location Loc. Returns true to indicate that this is
887/// an error, and false otherwise.
889 assert(PrevDecl->isTemplateParameter() && "Not a template parameter");
890
891 // C++ [temp.local]p4:
892 // A template-parameter shall not be redeclared within its
893 // scope (including nested scopes).
894 //
895 // Make this a warning when MSVC compatibility is requested.
896 unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
897 : diag::err_template_param_shadow;
898 const auto *ND = cast<NamedDecl>(PrevDecl);
899 Diag(Loc, DiagId) << ND->getDeclName();
901}
902
903/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
904/// the parameter D to reference the templated declaration and return a pointer
905/// to the template declaration. Otherwise, do nothing to D and return null.
907 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
908 D = Temp->getTemplatedDecl();
909 return Temp;
910 }
911 return nullptr;
912}
913
915 SourceLocation EllipsisLoc) const {
916 assert(Kind == Template &&
917 "Only template template arguments can be pack expansions here");
918 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&
919 "Template template argument pack expansion without packs");
921 Result.EllipsisLoc = EllipsisLoc;
922 return Result;
923}
924
926 const ParsedTemplateArgument &Arg) {
927
928 switch (Arg.getKind()) {
930 TypeSourceInfo *DI;
931 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
932 if (!DI)
933 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
935 }
936
938 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
940 }
941
943 TemplateName Template = Arg.getAsTemplate().get();
944 TemplateArgument TArg;
945 if (Arg.getEllipsisLoc().isValid())
946 TArg = TemplateArgument(Template, std::optional<unsigned int>());
947 else
948 TArg = Template;
949 return TemplateArgumentLoc(
950 SemaRef.Context, TArg,
952 Arg.getLocation(), Arg.getEllipsisLoc());
953 }
954 }
955
956 llvm_unreachable("Unhandled parsed template argument");
957}
958
959/// Translates template arguments as provided by the parser
960/// into template arguments used by semantic analysis.
962 TemplateArgumentListInfo &TemplateArgs) {
963 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
964 TemplateArgs.addArgument(translateTemplateArgument(*this,
965 TemplateArgsIn[I]));
966}
967
969 SourceLocation Loc,
970 IdentifierInfo *Name) {
971 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
973 if (PrevDecl && PrevDecl->isTemplateParameter())
974 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
975}
976
977/// Convert a parsed type into a parsed template argument. This is mostly
978/// trivial, except that we may have parsed a C++17 deduced class template
979/// specialization type, in which case we should form a template template
980/// argument instead of a type template argument.
982 TypeSourceInfo *TInfo;
984 if (T.isNull())
985 return ParsedTemplateArgument();
986 assert(TInfo && "template argument with no location");
987
988 // If we might have formed a deduced template specialization type, convert
989 // it to a template template argument.
990 if (getLangOpts().CPlusPlus17) {
991 TypeLoc TL = TInfo->getTypeLoc();
992 SourceLocation EllipsisLoc;
993 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
994 EllipsisLoc = PET.getEllipsisLoc();
995 TL = PET.getPatternLoc();
996 }
997
998 CXXScopeSpec SS;
999 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
1000 SS.Adopt(ET.getQualifierLoc());
1001 TL = ET.getNamedTypeLoc();
1002 }
1003
1004 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1005 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1006 if (SS.isSet())
1008 /*HasTemplateKeyword=*/false,
1009 Name);
1011 DTST.getTemplateNameLoc());
1012 if (EllipsisLoc.isValid())
1013 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1014 return Result;
1015 }
1016 }
1017
1018 // This is a normal type template argument. Note, if the type template
1019 // argument is an injected-class-name for a template, it has a dual nature
1020 // and can be used as either a type or a template. We handle that in
1021 // convertTypeTemplateArgumentToTemplate.
1024 TInfo->getTypeLoc().getBeginLoc());
1025}
1026
1027/// ActOnTypeParameter - Called when a C++ template type parameter
1028/// (e.g., "typename T") has been parsed. Typename specifies whether
1029/// the keyword "typename" was used to declare the type parameter
1030/// (otherwise, "class" was used), and KeyLoc is the location of the
1031/// "class" or "typename" keyword. ParamName is the name of the
1032/// parameter (NULL indicates an unnamed template parameter) and
1033/// ParamNameLoc is the location of the parameter name (if any).
1034/// If the type parameter has a default argument, it will be added
1035/// later via ActOnTypeParameterDefault.
1037 SourceLocation EllipsisLoc,
1038 SourceLocation KeyLoc,
1039 IdentifierInfo *ParamName,
1040 SourceLocation ParamNameLoc,
1041 unsigned Depth, unsigned Position,
1042 SourceLocation EqualLoc,
1043 ParsedType DefaultArg,
1044 bool HasTypeConstraint) {
1045 assert(S->isTemplateParamScope() &&
1046 "Template type parameter not in template parameter scope!");
1047
1048 bool IsParameterPack = EllipsisLoc.isValid();
1051 KeyLoc, ParamNameLoc, Depth, Position,
1052 ParamName, Typename, IsParameterPack,
1053 HasTypeConstraint);
1054 Param->setAccess(AS_public);
1055
1056 if (Param->isParameterPack())
1057 if (auto *LSI = getEnclosingLambda())
1058 LSI->LocalPacks.push_back(Param);
1059
1060 if (ParamName) {
1061 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1062
1063 // Add the template parameter into the current scope.
1064 S->AddDecl(Param);
1065 IdResolver.AddDecl(Param);
1066 }
1067
1068 // C++0x [temp.param]p9:
1069 // A default template-argument may be specified for any kind of
1070 // template-parameter that is not a template parameter pack.
1071 if (DefaultArg && IsParameterPack) {
1072 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1073 DefaultArg = nullptr;
1074 }
1075
1076 // Handle the default argument, if provided.
1077 if (DefaultArg) {
1078 TypeSourceInfo *DefaultTInfo;
1079 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1080
1081 assert(DefaultTInfo && "expected source information for type");
1082
1083 // Check for unexpanded parameter packs.
1084 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1086 return Param;
1087
1088 // Check the template argument itself.
1089 if (CheckTemplateArgument(DefaultTInfo)) {
1090 Param->setInvalidDecl();
1091 return Param;
1092 }
1093
1094 Param->setDefaultArgument(DefaultTInfo);
1095 }
1096
1097 return Param;
1098}
1099
1100/// Convert the parser's template argument list representation into our form.
1103 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1104 TemplateId.RAngleLoc);
1105 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1106 TemplateId.NumArgs);
1107 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1108 return TemplateArgs;
1109}
1110
1112
1113 TemplateName TN = TypeConstr->Template.get();
1114 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1115
1116 // C++2a [temp.param]p4:
1117 // [...] The concept designated by a type-constraint shall be a type
1118 // concept ([temp.concept]).
1119 if (!CD->isTypeConcept()) {
1120 Diag(TypeConstr->TemplateNameLoc,
1121 diag::err_type_constraint_non_type_concept);
1122 return true;
1123 }
1124
1125 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1126
1127 if (!WereArgsSpecified &&
1129 Diag(TypeConstr->TemplateNameLoc,
1130 diag::err_type_constraint_missing_arguments)
1131 << CD;
1132 return true;
1133 }
1134 return false;
1135}
1136
1138 TemplateIdAnnotation *TypeConstr,
1139 TemplateTypeParmDecl *ConstrainedParameter,
1140 SourceLocation EllipsisLoc) {
1141 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1142 false);
1143}
1144
1146 TemplateIdAnnotation *TypeConstr,
1147 TemplateTypeParmDecl *ConstrainedParameter,
1148 SourceLocation EllipsisLoc,
1149 bool AllowUnexpandedPack) {
1150
1151 if (CheckTypeConstraint(TypeConstr))
1152 return true;
1153
1154 TemplateName TN = TypeConstr->Template.get();
1155 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1156
1157 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1158 TypeConstr->TemplateNameLoc);
1159
1160 TemplateArgumentListInfo TemplateArgs;
1161 if (TypeConstr->LAngleLoc.isValid()) {
1162 TemplateArgs =
1163 makeTemplateArgumentListInfo(*this, *TypeConstr);
1164
1165 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1166 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1168 return true;
1169 }
1170 }
1171 }
1172 return AttachTypeConstraint(
1174 ConceptName, CD,
1175 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1176 ConstrainedParameter, EllipsisLoc);
1177}
1178
1179template<typename ArgumentLocAppender>
1182 ConceptDecl *NamedConcept, SourceLocation LAngleLoc,
1183 SourceLocation RAngleLoc, QualType ConstrainedType,
1184 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1185 SourceLocation EllipsisLoc) {
1186
1187 TemplateArgumentListInfo ConstraintArgs;
1188 ConstraintArgs.addArgument(
1190 /*NTTPType=*/QualType(), ParamNameLoc));
1191
1192 ConstraintArgs.setRAngleLoc(RAngleLoc);
1193 ConstraintArgs.setLAngleLoc(LAngleLoc);
1194 Appender(ConstraintArgs);
1195
1196 // C++2a [temp.param]p4:
1197 // [...] This constraint-expression E is called the immediately-declared
1198 // constraint of T. [...]
1199 CXXScopeSpec SS;
1200 SS.Adopt(NS);
1201 ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1202 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1203 /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs);
1204 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1205 return ImmediatelyDeclaredConstraint;
1206
1207 // C++2a [temp.param]p4:
1208 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1209 //
1210 // We have the following case:
1211 //
1212 // template<typename T> concept C1 = true;
1213 // template<C1... T> struct s1;
1214 //
1215 // The constraint: (C1<T> && ...)
1216 //
1217 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1218 // any unqualified lookups for 'operator&&' here.
1219 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1220 /*LParenLoc=*/SourceLocation(),
1221 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1222 EllipsisLoc, /*RHS=*/nullptr,
1223 /*RParenLoc=*/SourceLocation(),
1224 /*NumExpansions=*/std::nullopt);
1225}
1226
1227/// Attach a type-constraint to a template parameter.
1228/// \returns true if an error occurred. This can happen if the
1229/// immediately-declared constraint could not be formed (e.g. incorrect number
1230/// of arguments for the named concept).
1232 DeclarationNameInfo NameInfo,
1233 ConceptDecl *NamedConcept,
1234 const TemplateArgumentListInfo *TemplateArgs,
1235 TemplateTypeParmDecl *ConstrainedParameter,
1236 SourceLocation EllipsisLoc) {
1237 // C++2a [temp.param]p4:
1238 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1239 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1240 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1242 *TemplateArgs) : nullptr;
1243
1244 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1245
1246 ExprResult ImmediatelyDeclaredConstraint =
1248 *this, NS, NameInfo, NamedConcept,
1249 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1250 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1251 ParamAsArgument, ConstrainedParameter->getLocation(),
1252 [&] (TemplateArgumentListInfo &ConstraintArgs) {
1253 if (TemplateArgs)
1254 for (const auto &ArgLoc : TemplateArgs->arguments())
1255 ConstraintArgs.addArgument(ArgLoc);
1256 }, EllipsisLoc);
1257 if (ImmediatelyDeclaredConstraint.isInvalid())
1258 return true;
1259
1260 auto *CL = ConceptReference::Create(Context, /*NNS=*/NS,
1261 /*TemplateKWLoc=*/SourceLocation{},
1262 /*ConceptNameInfo=*/NameInfo,
1263 /*FoundDecl=*/NamedConcept,
1264 /*NamedConcept=*/NamedConcept,
1265 /*ArgsWritten=*/ArgsAsWritten);
1266 ConstrainedParameter->setTypeConstraint(CL,
1267 ImmediatelyDeclaredConstraint.get());
1268 return false;
1269}
1270
1272 NonTypeTemplateParmDecl *NewConstrainedParm,
1273 NonTypeTemplateParmDecl *OrigConstrainedParm,
1274 SourceLocation EllipsisLoc) {
1275 if (NewConstrainedParm->getType() != TL.getType() ||
1277 Diag(NewConstrainedParm->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1278 diag::err_unsupported_placeholder_constraint)
1279 << NewConstrainedParm->getTypeSourceInfo()
1280 ->getTypeLoc()
1281 .getSourceRange();
1282 return true;
1283 }
1284 // FIXME: Concepts: This should be the type of the placeholder, but this is
1285 // unclear in the wording right now.
1286 DeclRefExpr *Ref =
1287 BuildDeclRefExpr(OrigConstrainedParm, OrigConstrainedParm->getType(),
1288 VK_PRValue, OrigConstrainedParm->getLocation());
1289 if (!Ref)
1290 return true;
1291 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1293 TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(),
1294 BuildDecltypeType(Ref), OrigConstrainedParm->getLocation(),
1295 [&](TemplateArgumentListInfo &ConstraintArgs) {
1296 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1297 ConstraintArgs.addArgument(TL.getArgLoc(I));
1298 },
1299 EllipsisLoc);
1300 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1301 !ImmediatelyDeclaredConstraint.isUsable())
1302 return true;
1303
1304 NewConstrainedParm->setPlaceholderTypeConstraint(
1305 ImmediatelyDeclaredConstraint.get());
1306 return false;
1307}
1308
1309/// Check that the type of a non-type template parameter is
1310/// well-formed.
1311///
1312/// \returns the (possibly-promoted) parameter type if valid;
1313/// otherwise, produces a diagnostic and returns a NULL type.
1315 SourceLocation Loc) {
1316 if (TSI->getType()->isUndeducedType()) {
1317 // C++17 [temp.dep.expr]p3:
1318 // An id-expression is type-dependent if it contains
1319 // - an identifier associated by name lookup with a non-type
1320 // template-parameter declared with a type that contains a
1321 // placeholder type (7.1.7.4),
1323 }
1324
1325 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1326}
1327
1328/// Require the given type to be a structural type, and diagnose if it is not.
1329///
1330/// \return \c true if an error was produced.
1332 if (T->isDependentType())
1333 return false;
1334
1335 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1336 return true;
1337
1338 if (T->isStructuralType())
1339 return false;
1340
1341 // Structural types are required to be object types or lvalue references.
1342 if (T->isRValueReferenceType()) {
1343 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1344 return true;
1345 }
1346
1347 // Don't mention structural types in our diagnostic prior to C++20. Also,
1348 // there's not much more we can say about non-scalar non-class types --
1349 // because we can't see functions or arrays here, those can only be language
1350 // extensions.
1351 if (!getLangOpts().CPlusPlus20 ||
1352 (!T->isScalarType() && !T->isRecordType())) {
1353 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1354 return true;
1355 }
1356
1357 // Structural types are required to be literal types.
1358 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1359 return true;
1360
1361 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1362
1363 // Drill down into the reason why the class is non-structural.
1364 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1365 // All members are required to be public and non-mutable, and can't be of
1366 // rvalue reference type. Check these conditions first to prefer a "local"
1367 // reason over a more distant one.
1368 for (const FieldDecl *FD : RD->fields()) {
1369 if (FD->getAccess() != AS_public) {
1370 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1371 return true;
1372 }
1373 if (FD->isMutable()) {
1374 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1375 return true;
1376 }
1377 if (FD->getType()->isRValueReferenceType()) {
1378 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1379 << T;
1380 return true;
1381 }
1382 }
1383
1384 // All bases are required to be public.
1385 for (const auto &BaseSpec : RD->bases()) {
1386 if (BaseSpec.getAccessSpecifier() != AS_public) {
1387 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1388 << T << 1;
1389 return true;
1390 }
1391 }
1392
1393 // All subobjects are required to be of structural types.
1394 SourceLocation SubLoc;
1395 QualType SubType;
1396 int Kind = -1;
1397
1398 for (const FieldDecl *FD : RD->fields()) {
1399 QualType T = Context.getBaseElementType(FD->getType());
1400 if (!T->isStructuralType()) {
1401 SubLoc = FD->getLocation();
1402 SubType = T;
1403 Kind = 0;
1404 break;
1405 }
1406 }
1407
1408 if (Kind == -1) {
1409 for (const auto &BaseSpec : RD->bases()) {
1410 QualType T = BaseSpec.getType();
1411 if (!T->isStructuralType()) {
1412 SubLoc = BaseSpec.getBaseTypeLoc();
1413 SubType = T;
1414 Kind = 1;
1415 break;
1416 }
1417 }
1418 }
1419
1420 assert(Kind != -1 && "couldn't find reason why type is not structural");
1421 Diag(SubLoc, diag::note_not_structural_subobject)
1422 << T << Kind << SubType;
1423 T = SubType;
1424 RD = T->getAsCXXRecordDecl();
1425 }
1426
1427 return true;
1428}
1429
1431 SourceLocation Loc) {
1432 // We don't allow variably-modified types as the type of non-type template
1433 // parameters.
1434 if (T->isVariablyModifiedType()) {
1435 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1436 << T;
1437 return QualType();
1438 }
1439
1440 // C++ [temp.param]p4:
1441 //
1442 // A non-type template-parameter shall have one of the following
1443 // (optionally cv-qualified) types:
1444 //
1445 // -- integral or enumeration type,
1446 if (T->isIntegralOrEnumerationType() ||
1447 // -- pointer to object or pointer to function,
1448 T->isPointerType() ||
1449 // -- lvalue reference to object or lvalue reference to function,
1450 T->isLValueReferenceType() ||
1451 // -- pointer to member,
1452 T->isMemberPointerType() ||
1453 // -- std::nullptr_t, or
1454 T->isNullPtrType() ||
1455 // -- a type that contains a placeholder type.
1456 T->isUndeducedType()) {
1457 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1458 // are ignored when determining its type.
1459 return T.getUnqualifiedType();
1460 }
1461
1462 // C++ [temp.param]p8:
1463 //
1464 // A non-type template-parameter of type "array of T" or
1465 // "function returning T" is adjusted to be of type "pointer to
1466 // T" or "pointer to function returning T", respectively.
1467 if (T->isArrayType() || T->isFunctionType())
1468 return Context.getDecayedType(T);
1469
1470 // If T is a dependent type, we can't do the check now, so we
1471 // assume that it is well-formed. Note that stripping off the
1472 // qualifiers here is not really correct if T turns out to be
1473 // an array type, but we'll recompute the type everywhere it's
1474 // used during instantiation, so that should be OK. (Using the
1475 // qualified type is equally wrong.)
1476 if (T->isDependentType())
1477 return T.getUnqualifiedType();
1478
1479 // C++20 [temp.param]p6:
1480 // -- a structural type
1481 if (RequireStructuralType(T, Loc))
1482 return QualType();
1483
1484 if (!getLangOpts().CPlusPlus20) {
1485 // FIXME: Consider allowing structural types as an extension in C++17. (In
1486 // earlier language modes, the template argument evaluation rules are too
1487 // inflexible.)
1488 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1489 return QualType();
1490 }
1491
1492 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1493 return T.getUnqualifiedType();
1494}
1495
1497 unsigned Depth,
1498 unsigned Position,
1499 SourceLocation EqualLoc,
1500 Expr *Default) {
1502
1503 // Check that we have valid decl-specifiers specified.
1504 auto CheckValidDeclSpecifiers = [this, &D] {
1505 // C++ [temp.param]
1506 // p1
1507 // template-parameter:
1508 // ...
1509 // parameter-declaration
1510 // p2
1511 // ... A storage class shall not be specified in a template-parameter
1512 // declaration.
1513 // [dcl.typedef]p1:
1514 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1515 // of a parameter-declaration
1516 const DeclSpec &DS = D.getDeclSpec();
1517 auto EmitDiag = [this](SourceLocation Loc) {
1518 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1520 };
1522 EmitDiag(DS.getStorageClassSpecLoc());
1523
1525 EmitDiag(DS.getThreadStorageClassSpecLoc());
1526
1527 // [dcl.inline]p1:
1528 // The inline specifier can be applied only to the declaration or
1529 // definition of a variable or function.
1530
1531 if (DS.isInlineSpecified())
1532 EmitDiag(DS.getInlineSpecLoc());
1533
1534 // [dcl.constexpr]p1:
1535 // The constexpr specifier shall be applied only to the definition of a
1536 // variable or variable template or the declaration of a function or
1537 // function template.
1538
1539 if (DS.hasConstexprSpecifier())
1540 EmitDiag(DS.getConstexprSpecLoc());
1541
1542 // [dcl.fct.spec]p1:
1543 // Function-specifiers can be used only in function declarations.
1544
1545 if (DS.isVirtualSpecified())
1546 EmitDiag(DS.getVirtualSpecLoc());
1547
1548 if (DS.hasExplicitSpecifier())
1549 EmitDiag(DS.getExplicitSpecLoc());
1550
1551 if (DS.isNoreturnSpecified())
1552 EmitDiag(DS.getNoreturnSpecLoc());
1553 };
1554
1555 CheckValidDeclSpecifiers();
1556
1557 if (const auto *T = TInfo->getType()->getContainedDeducedType())
1558 if (isa<AutoType>(T))
1560 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1561 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1562
1563 assert(S->isTemplateParamScope() &&
1564 "Non-type template parameter not in template parameter scope!");
1565 bool Invalid = false;
1566
1568 if (T.isNull()) {
1569 T = Context.IntTy; // Recover with an 'int' type.
1570 Invalid = true;
1571 }
1572
1574
1575 IdentifierInfo *ParamName = D.getIdentifier();
1576 bool IsParameterPack = D.hasEllipsis();
1579 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1580 TInfo);
1581 Param->setAccess(AS_public);
1582
1584 if (TL.isConstrained())
1585 if (AttachTypeConstraint(TL, Param, Param, D.getEllipsisLoc()))
1586 Invalid = true;
1587
1588 if (Invalid)
1589 Param->setInvalidDecl();
1590
1591 if (Param->isParameterPack())
1592 if (auto *LSI = getEnclosingLambda())
1593 LSI->LocalPacks.push_back(Param);
1594
1595 if (ParamName) {
1597 ParamName);
1598
1599 // Add the template parameter into the current scope.
1600 S->AddDecl(Param);
1601 IdResolver.AddDecl(Param);
1602 }
1603
1604 // C++0x [temp.param]p9:
1605 // A default template-argument may be specified for any kind of
1606 // template-parameter that is not a template parameter pack.
1607 if (Default && IsParameterPack) {
1608 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1609 Default = nullptr;
1610 }
1611
1612 // Check the well-formedness of the default template argument, if provided.
1613 if (Default) {
1614 // Check for unexpanded parameter packs.
1616 return Param;
1617
1619 }
1620
1621 return Param;
1622}
1623
1624/// ActOnTemplateTemplateParameter - Called when a C++ template template
1625/// parameter (e.g. T in template <template <typename> class T> class array)
1626/// has been parsed. S is the current scope.
1628 SourceLocation TmpLoc,
1629 TemplateParameterList *Params,
1630 SourceLocation EllipsisLoc,
1631 IdentifierInfo *Name,
1632 SourceLocation NameLoc,
1633 unsigned Depth,
1634 unsigned Position,
1635 SourceLocation EqualLoc,
1637 assert(S->isTemplateParamScope() &&
1638 "Template template parameter not in template parameter scope!");
1639
1640 // Construct the parameter object.
1641 bool IsParameterPack = EllipsisLoc.isValid();
1644 NameLoc.isInvalid()? TmpLoc : NameLoc,
1645 Depth, Position, IsParameterPack,
1646 Name, Params);
1647 Param->setAccess(AS_public);
1648
1649 if (Param->isParameterPack())
1650 if (auto *LSI = getEnclosingLambda())
1651 LSI->LocalPacks.push_back(Param);
1652
1653 // If the template template parameter has a name, then link the identifier
1654 // into the scope and lookup mechanisms.
1655 if (Name) {
1656 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1657
1658 S->AddDecl(Param);
1659 IdResolver.AddDecl(Param);
1660 }
1661
1662 if (Params->size() == 0) {
1663 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1664 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1665 Param->setInvalidDecl();
1666 }
1667
1668 // C++0x [temp.param]p9:
1669 // A default template-argument may be specified for any kind of
1670 // template-parameter that is not a template parameter pack.
1671 if (IsParameterPack && !Default.isInvalid()) {
1672 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1674 }
1675
1676 if (!Default.isInvalid()) {
1677 // Check only that we have a template template argument. We don't want to
1678 // try to check well-formedness now, because our template template parameter
1679 // might have dependent types in its template parameters, which we wouldn't
1680 // be able to match now.
1681 //
1682 // If none of the template template parameter's template arguments mention
1683 // other template parameters, we could actually perform more checking here.
1684 // However, it isn't worth doing.
1686 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1687 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1688 << DefaultArg.getSourceRange();
1689 return Param;
1690 }
1691
1692 // Check for unexpanded parameter packs.
1694 DefaultArg.getArgument().getAsTemplate(),
1696 return Param;
1697
1698 Param->setDefaultArgument(Context, DefaultArg);
1699 }
1700
1701 return Param;
1702}
1703
1704namespace {
1705class ConstraintRefersToContainingTemplateChecker
1706 : public TreeTransform<ConstraintRefersToContainingTemplateChecker> {
1707 bool Result = false;
1708 const FunctionDecl *Friend = nullptr;
1709 unsigned TemplateDepth = 0;
1710
1711 // Check a record-decl that we've seen to see if it is a lexical parent of the
1712 // Friend, likely because it was referred to without its template arguments.
1713 void CheckIfContainingRecord(const CXXRecordDecl *CheckingRD) {
1714 CheckingRD = CheckingRD->getMostRecentDecl();
1715 if (!CheckingRD->isTemplated())
1716 return;
1717
1718 for (const DeclContext *DC = Friend->getLexicalDeclContext();
1719 DC && !DC->isFileContext(); DC = DC->getParent())
1720 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
1721 if (CheckingRD == RD->getMostRecentDecl())
1722 Result = true;
1723 }
1724
1725 void CheckNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1726 assert(D->getDepth() <= TemplateDepth &&
1727 "Nothing should reference a value below the actual template depth, "
1728 "depth is likely wrong");
1729 if (D->getDepth() != TemplateDepth)
1730 Result = true;
1731
1732 // Necessary because the type of the NTTP might be what refers to the parent
1733 // constriant.
1734 TransformType(D->getType());
1735 }
1736
1737public:
1739
1740 ConstraintRefersToContainingTemplateChecker(Sema &SemaRef,
1741 const FunctionDecl *Friend,
1742 unsigned TemplateDepth)
1743 : inherited(SemaRef), Friend(Friend), TemplateDepth(TemplateDepth) {}
1744 bool getResult() const { return Result; }
1745
1746 // This should be the only template parm type that we have to deal with.
1747 // SubstTempalteTypeParmPack, SubstNonTypeTemplateParmPack, and
1748 // FunctionParmPackExpr are all partially substituted, which cannot happen
1749 // with concepts at this point in translation.
1750 using inherited::TransformTemplateTypeParmType;
1751 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1752 TemplateTypeParmTypeLoc TL, bool) {
1753 assert(TL.getDecl()->getDepth() <= TemplateDepth &&
1754 "Nothing should reference a value below the actual template depth, "
1755 "depth is likely wrong");
1756 if (TL.getDecl()->getDepth() != TemplateDepth)
1757 Result = true;
1758 return inherited::TransformTemplateTypeParmType(
1759 TLB, TL,
1760 /*SuppressObjCLifetime=*/false);
1761 }
1762
1763 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
1764 if (!D)
1765 return D;
1766 // FIXME : This is possibly an incomplete list, but it is unclear what other
1767 // Decl kinds could be used to refer to the template parameters. This is a
1768 // best guess so far based on examples currently available, but the
1769 // unreachable should catch future instances/cases.
1770 if (auto *TD = dyn_cast<TypedefNameDecl>(D))
1771 TransformType(TD->getUnderlyingType());
1772 else if (auto *NTTPD = dyn_cast<NonTypeTemplateParmDecl>(D))
1773 CheckNonTypeTemplateParmDecl(NTTPD);
1774 else if (auto *VD = dyn_cast<ValueDecl>(D))
1775 TransformType(VD->getType());
1776 else if (auto *TD = dyn_cast<TemplateDecl>(D))
1777 TransformTemplateParameterList(TD->getTemplateParameters());
1778 else if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1779 CheckIfContainingRecord(RD);
1780 else if (isa<NamedDecl>(D)) {
1781 // No direct types to visit here I believe.
1782 } else
1783 llvm_unreachable("Don't know how to handle this declaration type yet");
1784 return D;
1785 }
1786};
1787} // namespace
1788
1790 const FunctionDecl *Friend, unsigned TemplateDepth,
1791 const Expr *Constraint) {
1792 assert(Friend->getFriendObjectKind() && "Only works on a friend");
1793 ConstraintRefersToContainingTemplateChecker Checker(*this, Friend,
1794 TemplateDepth);
1795 Checker.TransformExpr(const_cast<Expr *>(Constraint));
1796 return Checker.getResult();
1797}
1798
1799/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1800/// constrained by RequiresClause, that contains the template parameters in
1801/// Params.
1804 SourceLocation ExportLoc,
1805 SourceLocation TemplateLoc,
1806 SourceLocation LAngleLoc,
1807 ArrayRef<NamedDecl *> Params,
1808 SourceLocation RAngleLoc,
1809 Expr *RequiresClause) {
1810 if (ExportLoc.isValid())
1811 Diag(ExportLoc, diag::warn_template_export_unsupported);
1812
1813 for (NamedDecl *P : Params)
1815
1817 Context, TemplateLoc, LAngleLoc,
1818 llvm::ArrayRef(Params.data(), Params.size()), RAngleLoc, RequiresClause);
1819}
1820
1822 const CXXScopeSpec &SS) {
1823 if (SS.isSet())
1825}
1826
1827// Returns the template parameter list with all default template argument
1828// information.
1830 // Make sure we get the template parameter list from the most
1831 // recent declaration, since that is the only one that is guaranteed to
1832 // have all the default template argument information.
1833 return cast<TemplateDecl>(TD->getMostRecentDecl())->getTemplateParameters();
1834}
1835
1837 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1838 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1839 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1840 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1841 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1842 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1843 assert(TemplateParams && TemplateParams->size() > 0 &&
1844 "No template parameters");
1845 assert(TUK != TUK_Reference && "Can only declare or define class templates");
1846 bool Invalid = false;
1847
1848 // Check that we can declare a template here.
1849 if (CheckTemplateDeclScope(S, TemplateParams))
1850 return true;
1851
1853 assert(Kind != TagTypeKind::Enum &&
1854 "can't build template of enumerated type");
1855
1856 // There is no such thing as an unnamed class template.
1857 if (!Name) {
1858 Diag(KWLoc, diag::err_template_unnamed_class);
1859 return true;
1860 }
1861
1862 // Find any previous declaration with this name. For a friend with no
1863 // scope explicitly specified, we only look for tag declarations (per
1864 // C++11 [basic.lookup.elab]p2).
1865 DeclContext *SemanticContext;
1866 LookupResult Previous(*this, Name, NameLoc,
1867 (SS.isEmpty() && TUK == TUK_Friend)
1870 if (SS.isNotEmpty() && !SS.isInvalid()) {
1871 SemanticContext = computeDeclContext(SS, true);
1872 if (!SemanticContext) {
1873 // FIXME: Horrible, horrible hack! We can't currently represent this
1874 // in the AST, and historically we have just ignored such friend
1875 // class templates, so don't complain here.
1876 Diag(NameLoc, TUK == TUK_Friend
1877 ? diag::warn_template_qualified_friend_ignored
1878 : diag::err_template_qualified_declarator_no_match)
1879 << SS.getScopeRep() << SS.getRange();
1880 return TUK != TUK_Friend;
1881 }
1882
1883 if (RequireCompleteDeclContext(SS, SemanticContext))
1884 return true;
1885
1886 // If we're adding a template to a dependent context, we may need to
1887 // rebuilding some of the types used within the template parameter list,
1888 // now that we know what the current instantiation is.
1889 if (SemanticContext->isDependentContext()) {
1890 ContextRAII SavedContext(*this, SemanticContext);
1892 Invalid = true;
1893 }
1894
1895 if (TUK != TUK_Friend && TUK != TUK_Reference)
1896 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc,
1897 /*TemplateId-*/ nullptr,
1898 /*IsMemberSpecialization*/ false);
1899
1900 LookupQualifiedName(Previous, SemanticContext);
1901 } else {
1902 SemanticContext = CurContext;
1903
1904 // C++14 [class.mem]p14:
1905 // If T is the name of a class, then each of the following shall have a
1906 // name different from T:
1907 // -- every member template of class T
1908 if (TUK != TUK_Friend &&
1909 DiagnoseClassNameShadow(SemanticContext,
1910 DeclarationNameInfo(Name, NameLoc)))
1911 return true;
1912
1913 LookupName(Previous, S);
1914 }
1915
1916 if (Previous.isAmbiguous())
1917 return true;
1918
1919 NamedDecl *PrevDecl = nullptr;
1920 if (Previous.begin() != Previous.end())
1921 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1922
1923 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1924 // Maybe we will complain about the shadowed template parameter.
1925 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1926 // Just pretend that we didn't see the previous declaration.
1927 PrevDecl = nullptr;
1928 }
1929
1930 // If there is a previous declaration with the same name, check
1931 // whether this is a valid redeclaration.
1932 ClassTemplateDecl *PrevClassTemplate =
1933 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1934
1935 // We may have found the injected-class-name of a class template,
1936 // class template partial specialization, or class template specialization.
1937 // In these cases, grab the template that is being defined or specialized.
1938 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1939 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1940 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1941 PrevClassTemplate
1942 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1943 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1944 PrevClassTemplate
1945 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1946 ->getSpecializedTemplate();
1947 }
1948 }
1949
1950 if (TUK == TUK_Friend) {
1951 // C++ [namespace.memdef]p3:
1952 // [...] When looking for a prior declaration of a class or a function
1953 // declared as a friend, and when the name of the friend class or
1954 // function is neither a qualified name nor a template-id, scopes outside
1955 // the innermost enclosing namespace scope are not considered.
1956 if (!SS.isSet()) {
1957 DeclContext *OutermostContext = CurContext;
1958 while (!OutermostContext->isFileContext())
1959 OutermostContext = OutermostContext->getLookupParent();
1960
1961 if (PrevDecl &&
1962 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1963 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1964 SemanticContext = PrevDecl->getDeclContext();
1965 } else {
1966 // Declarations in outer scopes don't matter. However, the outermost
1967 // context we computed is the semantic context for our new
1968 // declaration.
1969 PrevDecl = PrevClassTemplate = nullptr;
1970 SemanticContext = OutermostContext;
1971
1972 // Check that the chosen semantic context doesn't already contain a
1973 // declaration of this name as a non-tag type.
1975 DeclContext *LookupContext = SemanticContext;
1976 while (LookupContext->isTransparentContext())
1977 LookupContext = LookupContext->getLookupParent();
1978 LookupQualifiedName(Previous, LookupContext);
1979
1980 if (Previous.isAmbiguous())
1981 return true;
1982
1983 if (Previous.begin() != Previous.end())
1984 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1985 }
1986 }
1987 } else if (PrevDecl &&
1988 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1989 S, SS.isValid()))
1990 PrevDecl = PrevClassTemplate = nullptr;
1991
1992 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1993 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1994 if (SS.isEmpty() &&
1995 !(PrevClassTemplate &&
1996 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1997 SemanticContext->getRedeclContext()))) {
1998 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1999 Diag(Shadow->getTargetDecl()->getLocation(),
2000 diag::note_using_decl_target);
2001 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
2002 // Recover by ignoring the old declaration.
2003 PrevDecl = PrevClassTemplate = nullptr;
2004 }
2005 }
2006
2007 if (PrevClassTemplate) {
2008 // Ensure that the template parameter lists are compatible. Skip this check
2009 // for a friend in a dependent context: the template parameter list itself
2010 // could be dependent.
2011 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
2013 TemplateCompareNewDeclInfo(SemanticContext ? SemanticContext
2014 : CurContext,
2015 CurContext, KWLoc),
2016 TemplateParams, PrevClassTemplate,
2017 PrevClassTemplate->getTemplateParameters(), /*Complain=*/true,
2019 return true;
2020
2021 // C++ [temp.class]p4:
2022 // In a redeclaration, partial specialization, explicit
2023 // specialization or explicit instantiation of a class template,
2024 // the class-key shall agree in kind with the original class
2025 // template declaration (7.1.5.3).
2026 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
2027 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
2028 TUK == TUK_Definition, KWLoc, Name)) {
2029 Diag(KWLoc, diag::err_use_with_wrong_tag)
2030 << Name
2031 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
2032 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
2033 Kind = PrevRecordDecl->getTagKind();
2034 }
2035
2036 // Check for redefinition of this class template.
2037 if (TUK == TUK_Definition) {
2038 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
2039 // If we have a prior definition that is not visible, treat this as
2040 // simply making that previous definition visible.
2041 NamedDecl *Hidden = nullptr;
2042 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
2043 SkipBody->ShouldSkip = true;
2044 SkipBody->Previous = Def;
2045 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
2046 assert(Tmpl && "original definition of a class template is not a "
2047 "class template?");
2050 } else {
2051 Diag(NameLoc, diag::err_redefinition) << Name;
2052 Diag(Def->getLocation(), diag::note_previous_definition);
2053 // FIXME: Would it make sense to try to "forget" the previous
2054 // definition, as part of error recovery?
2055 return true;
2056 }
2057 }
2058 }
2059 } else if (PrevDecl) {
2060 // C++ [temp]p5:
2061 // A class template shall not have the same name as any other
2062 // template, class, function, object, enumeration, enumerator,
2063 // namespace, or type in the same scope (3.3), except as specified
2064 // in (14.5.4).
2065 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
2066 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2067 return true;
2068 }
2069
2070 // Check the template parameter list of this declaration, possibly
2071 // merging in the template parameter list from the previous class
2072 // template declaration. Skip this check for a friend in a dependent
2073 // context, because the template parameter list might be dependent.
2074 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
2076 TemplateParams,
2077 PrevClassTemplate ? GetTemplateParameterList(PrevClassTemplate)
2078 : nullptr,
2079 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
2080 SemanticContext->isDependentContext())
2084 SkipBody))
2085 Invalid = true;
2086
2087 if (SS.isSet()) {
2088 // If the name of the template was qualified, we must be defining the
2089 // template out-of-line.
2090 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
2091 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
2092 : diag::err_member_decl_does_not_match)
2093 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
2094 Invalid = true;
2095 }
2096 }
2097
2098 // If this is a templated friend in a dependent context we should not put it
2099 // on the redecl chain. In some cases, the templated friend can be the most
2100 // recent declaration tricking the template instantiator to make substitutions
2101 // there.
2102 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
2103 bool ShouldAddRedecl
2104 = !(TUK == TUK_Friend && CurContext->isDependentContext());
2105
2106 CXXRecordDecl *NewClass =
2107 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
2108 PrevClassTemplate && ShouldAddRedecl ?
2109 PrevClassTemplate->getTemplatedDecl() : nullptr,
2110 /*DelayTypeCreation=*/true);
2111 SetNestedNameSpecifier(*this, NewClass, SS);
2112 if (NumOuterTemplateParamLists > 0)
2114 Context,
2115 llvm::ArrayRef(OuterTemplateParamLists, NumOuterTemplateParamLists));
2116
2117 // Add alignment attributes if necessary; these attributes are checked when
2118 // the ASTContext lays out the structure.
2119 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
2122 }
2123
2124 ClassTemplateDecl *NewTemplate
2125 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2126 DeclarationName(Name), TemplateParams,
2127 NewClass);
2128
2129 if (ShouldAddRedecl)
2130 NewTemplate->setPreviousDecl(PrevClassTemplate);
2131
2132 NewClass->setDescribedClassTemplate(NewTemplate);
2133
2134 if (ModulePrivateLoc.isValid())
2135 NewTemplate->setModulePrivate();
2136
2137 // Build the type for the class template declaration now.
2139 T = Context.getInjectedClassNameType(NewClass, T);
2140 assert(T->isDependentType() && "Class template type is not dependent?");
2141 (void)T;
2142
2143 // If we are providing an explicit specialization of a member that is a
2144 // class template, make a note of that.
2145 if (PrevClassTemplate &&
2146 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2147 PrevClassTemplate->setMemberSpecialization();
2148
2149 // Set the access specifier.
2150 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
2151 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2152
2153 // Set the lexical context of these templates
2155 NewTemplate->setLexicalDeclContext(CurContext);
2156
2157 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
2158 NewClass->startDefinition();
2159
2160 ProcessDeclAttributeList(S, NewClass, Attr);
2161 ProcessAPINotes(NewClass);
2162
2163 if (PrevClassTemplate)
2164 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2165
2168
2169 if (TUK != TUK_Friend) {
2170 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2171 Scope *Outer = S;
2172 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2173 Outer = Outer->getParent();
2174 PushOnScopeChains(NewTemplate, Outer);
2175 } else {
2176 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2177 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2178 NewClass->setAccess(PrevClassTemplate->getAccess());
2179 }
2180
2181 NewTemplate->setObjectOfFriendDecl();
2182
2183 // Friend templates are visible in fairly strange ways.
2185 DeclContext *DC = SemanticContext->getRedeclContext();
2186 DC->makeDeclVisibleInContext(NewTemplate);
2187 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2188 PushOnScopeChains(NewTemplate, EnclosingScope,
2189 /* AddToContext = */ false);
2190 }
2191
2193 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2194 Friend->setAccess(AS_public);
2195 CurContext->addDecl(Friend);
2196 }
2197
2198 if (PrevClassTemplate)
2199 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2200
2201 if (Invalid) {
2202 NewTemplate->setInvalidDecl();
2203 NewClass->setInvalidDecl();
2204 }
2205
2206 ActOnDocumentableDecl(NewTemplate);
2207
2208 if (SkipBody && SkipBody->ShouldSkip)
2209 return SkipBody->Previous;
2210
2211 return NewTemplate;
2212}
2213
2214namespace {
2215/// Tree transform to "extract" a transformed type from a class template's
2216/// constructor to a deduction guide.
2217class ExtractTypeForDeductionGuide
2218 : public TreeTransform<ExtractTypeForDeductionGuide> {
2219 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
2220
2221public:
2223 ExtractTypeForDeductionGuide(
2224 Sema &SemaRef,
2225 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs)
2226 : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {}
2227
2228 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
2229
2230 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
2231 ASTContext &Context = SemaRef.getASTContext();
2232 TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
2233 TypedefNameDecl *Decl = OrigDecl;
2234 // Transform the underlying type of the typedef and clone the Decl only if
2235 // the typedef has a dependent context.
2236 if (OrigDecl->getDeclContext()->isDependentContext()) {
2237 TypeLocBuilder InnerTLB;
2238 QualType Transformed =
2239 TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
2240 TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed);
2241 if (isa<TypeAliasDecl>(OrigDecl))
2243 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2244 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2245 else {
2246 assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef");
2248 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2249 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2250 }
2251 MaterializedTypedefs.push_back(Decl);
2252 }
2253
2254 QualType TDTy = Context.getTypedefType(Decl);
2255 TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy);
2256 TypedefTL.setNameLoc(TL.getNameLoc());
2257
2258 return TDTy;
2259 }
2260};
2261
2262/// Transform to convert portions of a constructor declaration into the
2263/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
2264struct ConvertConstructorToDeductionGuideTransform {
2265 ConvertConstructorToDeductionGuideTransform(Sema &S,
2266 ClassTemplateDecl *Template)
2267 : SemaRef(S), Template(Template) {
2268 // If the template is nested, then we need to use the original
2269 // pattern to iterate over the constructors.
2270 ClassTemplateDecl *Pattern = Template;
2271 while (Pattern->getInstantiatedFromMemberTemplate()) {
2272 if (Pattern->isMemberSpecialization())
2273 break;
2274 Pattern = Pattern->getInstantiatedFromMemberTemplate();
2275 NestedPattern = Pattern;
2276 }
2277
2278 if (NestedPattern)
2279 OuterInstantiationArgs = SemaRef.getTemplateInstantiationArgs(Template);
2280 }
2281
2282 Sema &SemaRef;
2283 ClassTemplateDecl *Template;
2284 ClassTemplateDecl *NestedPattern = nullptr;
2285
2286 DeclContext *DC = Template->getDeclContext();
2287 CXXRecordDecl *Primary = Template->getTemplatedDecl();
2288 DeclarationName DeductionGuideName =
2290
2291 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
2292
2293 // Index adjustment to apply to convert depth-1 template parameters into
2294 // depth-0 template parameters.
2295 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
2296
2297 // Instantiation arguments for the outermost depth-1 templates
2298 // when the template is nested
2299 MultiLevelTemplateArgumentList OuterInstantiationArgs;
2300
2301 /// Transform a constructor declaration into a deduction guide.
2302 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
2303 CXXConstructorDecl *CD) {
2305
2307
2308 // C++ [over.match.class.deduct]p1:
2309 // -- For each constructor of the class template designated by the
2310 // template-name, a function template with the following properties:
2311
2312 // -- The template parameters are the template parameters of the class
2313 // template followed by the template parameters (including default
2314 // template arguments) of the constructor, if any.
2315 TemplateParameterList *TemplateParams = GetTemplateParameterList(Template);
2316 if (FTD) {
2317 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
2320 AllParams.reserve(TemplateParams->size() + InnerParams->size());
2321 AllParams.insert(AllParams.begin(),
2322 TemplateParams->begin(), TemplateParams->end());
2323 SubstArgs.reserve(InnerParams->size());
2324 Depth1Args.reserve(InnerParams->size());
2325
2326 // Later template parameters could refer to earlier ones, so build up
2327 // a list of substituted template arguments as we go.
2328 for (NamedDecl *Param : *InnerParams) {
2330 Args.setKind(TemplateSubstitutionKind::Rewrite);
2331 Args.addOuterTemplateArguments(Depth1Args);
2332 Args.addOuterRetainedLevel();
2333 if (NestedPattern)
2334 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
2335 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
2336 if (!NewParam)
2337 return nullptr;
2338
2339 // Constraints require that we substitute depth-1 arguments
2340 // to match depths when substituted for evaluation later
2341 Depth1Args.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2342 SemaRef.Context.getInjectedTemplateArg(NewParam)));
2343
2344 if (NestedPattern) {
2345 TemplateDeclInstantiator Instantiator(SemaRef, DC,
2346 OuterInstantiationArgs);
2347 Instantiator.setEvaluateConstraints(false);
2348 SemaRef.runWithSufficientStackSpace(NewParam->getLocation(), [&] {
2349 NewParam = cast<NamedDecl>(Instantiator.Visit(NewParam));
2350 });
2351 }
2352
2353 assert(NewParam->getTemplateDepth() == 0 &&
2354 "Unexpected template parameter depth");
2355
2356 AllParams.push_back(NewParam);
2357 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2358 SemaRef.Context.getInjectedTemplateArg(NewParam)));
2359 }
2360
2361 // Substitute new template parameters into requires-clause if present.
2362 Expr *RequiresClause = nullptr;
2363 if (Expr *InnerRC = InnerParams->getRequiresClause()) {
2365 Args.setKind(TemplateSubstitutionKind::Rewrite);
2366 Args.addOuterTemplateArguments(Depth1Args);
2367 Args.addOuterRetainedLevel();
2368 if (NestedPattern)
2369 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
2370 ExprResult E = SemaRef.SubstExpr(InnerRC, Args);
2371 if (E.isInvalid())
2372 return nullptr;
2373 RequiresClause = E.getAs<Expr>();
2374 }
2375
2376 TemplateParams = TemplateParameterList::Create(
2377 SemaRef.Context, InnerParams->getTemplateLoc(),
2378 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
2379 RequiresClause);
2380 }
2381
2382 // If we built a new template-parameter-list, track that we need to
2383 // substitute references to the old parameters into references to the
2384 // new ones.
2386 Args.setKind(TemplateSubstitutionKind::Rewrite);
2387 if (FTD) {
2388 Args.addOuterTemplateArguments(SubstArgs);
2389 Args.addOuterRetainedLevel();
2390 }
2391
2392 if (NestedPattern)
2393 Args.addOuterRetainedLevels(NestedPattern->getTemplateDepth());
2394
2397 assert(FPTL && "no prototype for constructor declaration");
2398
2399 // Transform the type of the function, adjusting the return type and
2400 // replacing references to the old parameters with references to the
2401 // new ones.
2402 TypeLocBuilder TLB;
2404 SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
2405 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
2406 MaterializedTypedefs);
2407 if (NewType.isNull())
2408 return nullptr;
2409 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
2410
2411 return buildDeductionGuide(TemplateParams, CD, CD->getExplicitSpecifier(),
2412 NewTInfo, CD->getBeginLoc(), CD->getLocation(),
2413 CD->getEndLoc(), MaterializedTypedefs);
2414 }
2415
2416 /// Build a deduction guide with the specified parameter types.
2417 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
2418 SourceLocation Loc = Template->getLocation();
2419
2420 // Build the requested type.
2422 EPI.HasTrailingReturn = true;
2423 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
2424 DeductionGuideName, EPI);
2425 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
2426 if (NestedPattern)
2427 TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
2428 DeductionGuideName);
2429
2432
2433 // Build the parameters, needed during deduction / substitution.
2435 for (auto T : ParamTypes) {
2436 auto *TSI = SemaRef.Context.getTrivialTypeSourceInfo(T, Loc);
2437 if (NestedPattern)
2438 TSI = SemaRef.SubstType(TSI, OuterInstantiationArgs, Loc,
2439 DeclarationName());
2440 ParmVarDecl *NewParam =
2441 ParmVarDecl::Create(SemaRef.Context, DC, Loc, Loc, nullptr,
2442 TSI->getType(), TSI, SC_None, nullptr);
2443 NewParam->setScopeInfo(0, Params.size());
2444 FPTL.setParam(Params.size(), NewParam);
2445 Params.push_back(NewParam);
2446 }
2447
2448 return buildDeductionGuide(GetTemplateParameterList(Template), nullptr,
2449 ExplicitSpecifier(), TSI, Loc, Loc, Loc);
2450 }
2451
2452private:
2453 /// Transform a constructor template parameter into a deduction guide template
2454 /// parameter, rebuilding any internal references to earlier parameters and
2455 /// renumbering as we go.
2456 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
2458 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
2459 // TemplateTypeParmDecl's index cannot be changed after creation, so
2460 // substitute it directly.
2461 auto *NewTTP = TemplateTypeParmDecl::Create(
2462 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
2463 TTP->getDepth() - 1, Depth1IndexAdjustment + TTP->getIndex(),
2464 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
2465 TTP->isParameterPack(), TTP->hasTypeConstraint(),
2466 TTP->isExpandedParameterPack()
2467 ? std::optional<unsigned>(TTP->getNumExpansionParameters())
2468 : std::nullopt);
2469 if (const auto *TC = TTP->getTypeConstraint())
2470 SemaRef.SubstTypeConstraint(NewTTP, TC, Args,
2471 /*EvaluateConstraint*/ true);
2472 if (TTP->hasDefaultArgument()) {
2473 TypeSourceInfo *InstantiatedDefaultArg =
2474 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
2475 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
2476 if (InstantiatedDefaultArg)
2477 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
2478 }
2480 NewTTP);
2481 return NewTTP;
2482 }
2483
2484 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2485 return transformTemplateParameterImpl(TTP, Args);
2486
2487 return transformTemplateParameterImpl(
2488 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
2489 }
2490 template<typename TemplateParmDecl>
2491 TemplateParmDecl *
2492 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
2494 // Ask the template instantiator to do the heavy lifting for us, then adjust
2495 // the index of the parameter once it's done.
2496 auto *NewParam =
2497 cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
2498 assert(NewParam->getDepth() == OldParam->getDepth() - 1 &&
2499 "unexpected template param depth");
2500 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
2501 return NewParam;
2502 }
2503
2504 QualType transformFunctionProtoType(
2508 SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2509 SmallVector<QualType, 4> ParamTypes;
2510 const FunctionProtoType *T = TL.getTypePtr();
2511
2512 // -- The types of the function parameters are those of the constructor.
2513 for (auto *OldParam : TL.getParams()) {
2514 ParmVarDecl *NewParam =
2515 transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs);
2516 if (NestedPattern && NewParam)
2517 NewParam = transformFunctionTypeParam(NewParam, OuterInstantiationArgs,
2518 MaterializedTypedefs);
2519 if (!NewParam)
2520 return QualType();
2521 ParamTypes.push_back(NewParam->getType());
2522 Params.push_back(NewParam);
2523 }
2524
2525 // -- The return type is the class template specialization designated by
2526 // the template-name and template arguments corresponding to the
2527 // template parameters obtained from the class template.
2528 //
2529 // We use the injected-class-name type of the primary template instead.
2530 // This has the convenient property that it is different from any type that
2531 // the user can write in a deduction-guide (because they cannot enter the
2532 // context of the template), so implicit deduction guides can never collide
2533 // with explicit ones.
2534 QualType ReturnType = DeducedType;
2535 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
2536
2537 // Resolving a wording defect, we also inherit the variadicness of the
2538 // constructor.
2540 EPI.Variadic = T->isVariadic();
2541 EPI.HasTrailingReturn = true;
2542
2543 QualType Result = SemaRef.BuildFunctionType(
2544 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
2545 if (Result.isNull())
2546 return QualType();
2547
2548 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
2550 NewTL.setLParenLoc(TL.getLParenLoc());
2551 NewTL.setRParenLoc(TL.getRParenLoc());
2554 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
2555 NewTL.setParam(I, Params[I]);
2556
2557 return Result;
2558 }
2559
2560 ParmVarDecl *transformFunctionTypeParam(
2562 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2563 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2564 TypeSourceInfo *NewDI;
2565 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2566 // Expand out the one and only element in each inner pack.
2567 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2568 NewDI =
2569 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2570 OldParam->getLocation(), OldParam->getDeclName());
2571 if (!NewDI) return nullptr;
2572 NewDI =
2573 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2574 PackTL.getTypePtr()->getNumExpansions());
2575 } else
2576 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2577 OldParam->getDeclName());
2578 if (!NewDI)
2579 return nullptr;
2580
2581 // Extract the type. This (for instance) replaces references to typedef
2582 // members of the current instantiations with the definitions of those
2583 // typedefs, avoiding triggering instantiation of the deduced type during
2584 // deduction.
2585 NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs)
2586 .transform(NewDI);
2587
2588 // Resolving a wording defect, we also inherit default arguments from the
2589 // constructor.
2590 ExprResult NewDefArg;
2591 if (OldParam->hasDefaultArg()) {
2592 // We don't care what the value is (we won't use it); just create a
2593 // placeholder to indicate there is a default argument.
2594 QualType ParamTy = NewDI->getType();
2595 NewDefArg = new (SemaRef.Context)
2597 ParamTy.getNonLValueExprType(SemaRef.Context),
2598 ParamTy->isLValueReferenceType() ? VK_LValue
2599 : ParamTy->isRValueReferenceType() ? VK_XValue
2600 : VK_PRValue);
2601 }
2602 // Handle arrays and functions decay.
2603 auto NewType = NewDI->getType();
2604 if (NewType->isArrayType() || NewType->isFunctionType())
2605 NewType = SemaRef.Context.getDecayedType(NewType);
2606
2607 ParmVarDecl *NewParam = ParmVarDecl::Create(
2608 SemaRef.Context, DC, OldParam->getInnerLocStart(),
2609 OldParam->getLocation(), OldParam->getIdentifier(), NewType, NewDI,
2610 OldParam->getStorageClass(), NewDefArg.get());
2611 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2612 OldParam->getFunctionScopeIndex());
2613 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2614 return NewParam;
2615 }
2616
2617 FunctionTemplateDecl *buildDeductionGuide(
2618 TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor,
2619 ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart,
2620 SourceLocation Loc, SourceLocation LocEnd,
2621 llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
2622 DeclarationNameInfo Name(DeductionGuideName, Loc);
2624 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2625
2626 // Build the implicit deduction guide template.
2627 auto *Guide =
2628 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2629 TInfo->getType(), TInfo, LocEnd, Ctor);
2630 Guide->setImplicit();
2631 Guide->setParams(Params);
2632
2633 for (auto *Param : Params)
2634 Param->setDeclContext(Guide);
2635 for (auto *TD : MaterializedTypedefs)
2636 TD->setDeclContext(Guide);
2637
2638 auto *GuideTemplate = FunctionTemplateDecl::Create(
2639 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2640 GuideTemplate->setImplicit();
2641 Guide->setDescribedFunctionTemplate(GuideTemplate);
2642
2643 if (isa<CXXRecordDecl>(DC)) {
2644 Guide->setAccess(AS_public);
2645 GuideTemplate->setAccess(AS_public);
2646 }
2647
2648 DC->addDecl(GuideTemplate);
2649 return GuideTemplate;
2650 }
2651};
2652}
2653
2655 TemplateDecl *Template, MutableArrayRef<QualType> ParamTypes,
2656 SourceLocation Loc) {
2657 if (CXXRecordDecl *DefRecord =
2658 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2659 if (TemplateDecl *DescribedTemplate =
2660 DefRecord->getDescribedClassTemplate())
2661 Template = DescribedTemplate;
2662 }
2663
2664 DeclContext *DC = Template->getDeclContext();
2665 if (DC->isDependentContext())
2666 return nullptr;
2667
2668 ConvertConstructorToDeductionGuideTransform Transform(
2669 *this, cast<ClassTemplateDecl>(Template));
2670 if (!isCompleteType(Loc, Transform.DeducedType))
2671 return nullptr;
2672
2673 // In case we were expanding a pack when we attempted to declare deduction
2674 // guides, turn off pack expansion for everything we're about to do.
2675 ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
2676 /*NewSubstitutionIndex=*/-1);
2677 // Create a template instantiation record to track the "instantiation" of
2678 // constructors into deduction guides.
2679 InstantiatingTemplate BuildingDeductionGuides(
2680 *this, Loc, Template,
2682 if (BuildingDeductionGuides.isInvalid())
2683 return nullptr;
2684
2685 ClassTemplateDecl *Pattern =
2686 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
2687 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
2688
2689 auto *DG = cast<FunctionTemplateDecl>(
2690 Transform.buildSimpleDeductionGuide(ParamTypes));
2691 SavedContext.pop();
2692 return DG;
2693}
2694
2696 SourceLocation Loc) {
2697 if (CXXRecordDecl *DefRecord =
2698 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2699 if (TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate())
2700 Template = DescribedTemplate;
2701 }
2702
2703 DeclContext *DC = Template->getDeclContext();
2704 if (DC->isDependentContext())
2705 return;
2706
2707 ConvertConstructorToDeductionGuideTransform Transform(
2708 *this, cast<ClassTemplateDecl>(Template));
2709 if (!isCompleteType(Loc, Transform.DeducedType))
2710 return;
2711
2712 // Check whether we've already declared deduction guides for this template.
2713 // FIXME: Consider storing a flag on the template to indicate this.
2714 auto Existing = DC->lookup(Transform.DeductionGuideName);
2715 for (auto *D : Existing)
2716 if (D->isImplicit())
2717 return;
2718
2719 // In case we were expanding a pack when we attempted to declare deduction
2720 // guides, turn off pack expansion for everything we're about to do.
2721 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2722 // Create a template instantiation record to track the "instantiation" of
2723 // constructors into deduction guides.
2724 InstantiatingTemplate BuildingDeductionGuides(
2725 *this, Loc, Template,
2727 if (BuildingDeductionGuides.isInvalid())
2728 return;
2729
2730 // Convert declared constructors into deduction guide templates.
2731 // FIXME: Skip constructors for which deduction must necessarily fail (those
2732 // for which some class template parameter without a default argument never
2733 // appears in a deduced context).
2734 ClassTemplateDecl *Pattern =
2735 Transform.NestedPattern ? Transform.NestedPattern : Transform.Template;
2736 ContextRAII SavedContext(*this, Pattern->getTemplatedDecl());
2737 llvm::SmallPtrSet<NamedDecl *, 8> ProcessedCtors;
2738 bool AddedAny = false;
2739 for (NamedDecl *D : LookupConstructors(Pattern->getTemplatedDecl())) {
2740 D = D->getUnderlyingDecl();
2741 if (D->isInvalidDecl() || D->isImplicit())
2742 continue;
2743
2744 D = cast<NamedDecl>(D->getCanonicalDecl());
2745
2746 // Within C++20 modules, we may have multiple same constructors in
2747 // multiple same RecordDecls. And it doesn't make sense to create
2748 // duplicated deduction guides for the duplicated constructors.
2749 if (ProcessedCtors.count(D))
2750 continue;
2751
2752 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
2753 auto *CD =
2754 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
2755 // Class-scope explicit specializations (MS extension) do not result in
2756 // deduction guides.
2757 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
2758 continue;
2759
2760 // Cannot make a deduction guide when unparsed arguments are present.
2761 if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) {
2762 return !P || P->hasUnparsedDefaultArg();
2763 }))
2764 continue;
2765
2766 ProcessedCtors.insert(D);
2767 Transform.transformConstructor(FTD, CD);
2768 AddedAny = true;
2769 }
2770
2771 // C++17 [over.match.class.deduct]
2772 // -- If C is not defined or does not declare any constructors, an
2773 // additional function template derived as above from a hypothetical
2774 // constructor C().
2775 if (!AddedAny)
2776 Transform.buildSimpleDeductionGuide(std::nullopt);
2777
2778 // -- An additional function template derived as above from a hypothetical
2779 // constructor C(C), called the copy deduction candidate.
2780 cast<CXXDeductionGuideDecl>(
2781 cast<FunctionTemplateDecl>(
2782 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2783 ->getTemplatedDecl())
2784 ->setDeductionCandidateKind(DeductionCandidate::Copy);
2785
2786 SavedContext.pop();
2787}
2788
2789/// Diagnose the presence of a default template argument on a
2790/// template parameter, which is ill-formed in certain contexts.
2791///
2792/// \returns true if the default template argument should be dropped.
2795 SourceLocation ParamLoc,
2796 SourceRange DefArgRange) {
2797 switch (TPC) {
2801 return false;
2802
2805 // C++ [temp.param]p9:
2806 // A default template-argument shall not be specified in a
2807 // function template declaration or a function template
2808 // definition [...]
2809 // If a friend function template declaration specifies a default
2810 // template-argument, that declaration shall be a definition and shall be
2811 // the only declaration of the function template in the translation unit.
2812 // (C++98/03 doesn't have this wording; see DR226).
2813 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2814 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2815 : diag::ext_template_parameter_default_in_function_template)
2816 << DefArgRange;
2817 return false;
2818
2820 // C++0x [temp.param]p9:
2821 // A default template-argument shall not be specified in the
2822 // template-parameter-lists of the definition of a member of a
2823 // class template that appears outside of the member's class.
2824 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2825 << DefArgRange;
2826 return true;
2827
2830 // C++ [temp.param]p9:
2831 // A default template-argument shall not be specified in a
2832 // friend template declaration.
2833 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2834 << DefArgRange;
2835 return true;
2836
2837 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2838 // for friend function templates if there is only a single
2839 // declaration (and it is a definition). Strange!
2840 }
2841
2842 llvm_unreachable("Invalid TemplateParamListContext!");
2843}
2844
2845/// Check for unexpanded parameter packs within the template parameters
2846/// of a template template parameter, recursively.
2849 // A template template parameter which is a parameter pack is also a pack
2850 // expansion.
2851 if (TTP->isParameterPack())
2852 return false;
2853
2855 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2856 NamedDecl *P = Params->getParam(I);
2857 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2858 if (!TTP->isParameterPack())
2859 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2860 if (TC->hasExplicitTemplateArgs())
2861 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2864 return true;
2865 continue;
2866 }
2867
2868 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2869 if (!NTTP->isParameterPack() &&
2870 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2871 NTTP->getTypeSourceInfo(),
2873 return true;
2874
2875 continue;
2876 }
2877
2878 if (TemplateTemplateParmDecl *InnerTTP
2879 = dyn_cast<TemplateTemplateParmDecl>(P))
2880 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2881 return true;
2882 }
2883
2884 return false;
2885}
2886
2887/// Checks the validity of a template parameter list, possibly
2888/// considering the template parameter list from a previous
2889/// declaration.
2890///
2891/// If an "old" template parameter list is provided, it must be
2892/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2893/// template parameter list.
2894///
2895/// \param NewParams Template parameter list for a new template
2896/// declaration. This template parameter list will be updated with any
2897/// default arguments that are carried through from the previous
2898/// template parameter list.
2899///
2900/// \param OldParams If provided, template parameter list from a
2901/// previous declaration of the same template. Default template
2902/// arguments will be merged from the old template parameter list to
2903/// the new template parameter list.
2904///
2905/// \param TPC Describes the context in which we are checking the given
2906/// template parameter list.
2907///
2908/// \param SkipBody If we might have already made a prior merged definition
2909/// of this template visible, the corresponding body-skipping information.
2910/// Default argument redefinition is not an error when skipping such a body,
2911/// because (under the ODR) we can assume the default arguments are the same
2912/// as the prior merged definition.
2913///
2914/// \returns true if an error occurred, false otherwise.
2916 TemplateParameterList *OldParams,
2918 SkipBodyInfo *SkipBody) {
2919 bool Invalid = false;
2920
2921 // C++ [temp.param]p10:
2922 // The set of default template-arguments available for use with a
2923 // template declaration or definition is obtained by merging the
2924 // default arguments from the definition (if in scope) and all
2925 // declarations in scope in the same way default function
2926 // arguments are (8.3.6).
2927 bool SawDefaultArgument = false;
2928 SourceLocation PreviousDefaultArgLoc;
2929
2930 // Dummy initialization to avoid warnings.
2931 TemplateParameterList::iterator OldParam = NewParams->end();
2932 if (OldParams)
2933 OldParam = OldParams->begin();
2934
2935 bool RemoveDefaultArguments = false;
2936 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2937 NewParamEnd = NewParams->end();
2938 NewParam != NewParamEnd; ++NewParam) {
2939 // Whether we've seen a duplicate default argument in the same translation
2940 // unit.
2941 bool RedundantDefaultArg = false;
2942 // Whether we've found inconsis inconsitent default arguments in different
2943 // translation unit.
2944 bool InconsistentDefaultArg = false;
2945 // The name of the module which contains the inconsistent default argument.
2946 std::string PrevModuleName;
2947
2948 SourceLocation OldDefaultLoc;
2949 SourceLocation NewDefaultLoc;
2950
2951 // Variable used to diagnose missing default arguments
2952 bool MissingDefaultArg = false;
2953
2954 // Variable used to diagnose non-final parameter packs
2955 bool SawParameterPack = false;
2956
2957 if (TemplateTypeParmDecl *NewTypeParm
2958 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2959 // Check the presence of a default argument here.
2960 if (NewTypeParm->hasDefaultArgument() &&
2962 NewTypeParm->getLocation(),
2963 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2964 .getSourceRange()))
2965 NewTypeParm->removeDefaultArgument();
2966
2967 // Merge default arguments for template type parameters.
2968 TemplateTypeParmDecl *OldTypeParm
2969 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2970 if (NewTypeParm->isParameterPack()) {
2971 assert(!NewTypeParm->hasDefaultArgument() &&
2972 "Parameter packs can't have a default argument!");
2973 SawParameterPack = true;
2974 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2975 NewTypeParm->hasDefaultArgument() &&
2976 (!SkipBody || !SkipBody->ShouldSkip)) {
2977 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2978 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2979 SawDefaultArgument = true;
2980
2981 if (!OldTypeParm->getOwningModule())
2982 RedundantDefaultArg = true;
2983 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2984 NewTypeParm)) {
2985 InconsistentDefaultArg = true;
2986 PrevModuleName =
2988 }
2989 PreviousDefaultArgLoc = NewDefaultLoc;
2990 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2991 // Merge the default argument from the old declaration to the
2992 // new declaration.
2993 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2994 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2995 } else if (NewTypeParm->hasDefaultArgument()) {
2996 SawDefaultArgument = true;
2997 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2998 } else if (SawDefaultArgument)
2999 MissingDefaultArg = true;
3000 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
3001 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
3002 // Check for unexpanded parameter packs.
3003 if (!NewNonTypeParm->isParameterPack() &&
3004 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
3005 NewNonTypeParm->getTypeSourceInfo(),
3007 Invalid = true;
3008 continue;
3009 }
3010
3011 // Check the presence of a default argument here.
3012 if (NewNonTypeParm->hasDefaultArgument() &&
3014 NewNonTypeParm->getLocation(),
3015 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
3016 NewNonTypeParm->removeDefaultArgument();
3017 }
3018
3019 // Merge default arguments for non-type template parameters
3020 NonTypeTemplateParmDecl *OldNonTypeParm
3021 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
3022 if (NewNonTypeParm->isParameterPack()) {
3023 assert(!NewNonTypeParm->hasDefaultArgument() &&
3024 "Parameter packs can't have a default argument!");
3025 if (!NewNonTypeParm->isPackExpansion())
3026 SawParameterPack = true;
3027 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
3028 NewNonTypeParm->hasDefaultArgument() &&
3029 (!SkipBody || !SkipBody->ShouldSkip)) {
3030 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
3031 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
3032 SawDefaultArgument = true;
3033 if (!OldNonTypeParm->getOwningModule())
3034 RedundantDefaultArg = true;
3035 else if (!getASTContext().isSameDefaultTemplateArgument(
3036 OldNonTypeParm, NewNonTypeParm)) {
3037 InconsistentDefaultArg = true;
3038 PrevModuleName =
3039 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
3040 }
3041 PreviousDefaultArgLoc = NewDefaultLoc;
3042 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
3043 // Merge the default argument from the old declaration to the
3044 // new declaration.
3045 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
3046 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
3047 } else if (NewNonTypeParm->hasDefaultArgument()) {
3048 SawDefaultArgument = true;
3049 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
3050 } else if (SawDefaultArgument)
3051 MissingDefaultArg = true;
3052 } else {
3053 TemplateTemplateParmDecl *NewTemplateParm
3054 = cast<TemplateTemplateParmDecl>(*NewParam);
3055
3056 // Check for unexpanded parameter packs, recursively.
3057 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
3058 Invalid = true;
3059 continue;
3060 }
3061
3062 // Check the presence of a default argument here.
3063 if (NewTemplateParm->hasDefaultArgument() &&
3065 NewTemplateParm->getLocation(),
3066 NewTemplateParm->getDefaultArgument().getSourceRange()))
3067 NewTemplateParm->removeDefaultArgument();
3068
3069 // Merge default arguments for template template parameters
3070 TemplateTemplateParmDecl *OldTemplateParm
3071 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
3072 if (NewTemplateParm->isParameterPack()) {
3073 assert(!NewTemplateParm->hasDefaultArgument() &&
3074 "Parameter packs can't have a default argument!");
3075 if (!NewTemplateParm->isPackExpansion())
3076 SawParameterPack = true;
3077 } else if (OldTemplateParm &&
3078 hasVisibleDefaultArgument(OldTemplateParm) &&
3079 NewTemplateParm->hasDefaultArgument() &&
3080 (!SkipBody || !SkipBody->ShouldSkip)) {
3081 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
3082 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
3083 SawDefaultArgument = true;
3084 if (!OldTemplateParm->getOwningModule())
3085 RedundantDefaultArg = true;
3086 else if (!getASTContext().isSameDefaultTemplateArgument(
3087 OldTemplateParm, NewTemplateParm)) {
3088 InconsistentDefaultArg = true;
3089 PrevModuleName =
3090 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
3091 }
3092 PreviousDefaultArgLoc = NewDefaultLoc;
3093 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
3094 // Merge the default argument from the old declaration to the
3095 // new declaration.
3096 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
3097 PreviousDefaultArgLoc
3098 = OldTemplateParm->getDefaultArgument().getLocation();
3099 } else if (NewTemplateParm->hasDefaultArgument()) {
3100 SawDefaultArgument = true;
3101 PreviousDefaultArgLoc
3102 = NewTemplateParm->getDefaultArgument().getLocation();
3103 } else if (SawDefaultArgument)
3104 MissingDefaultArg = true;
3105 }
3106
3107 // C++11 [temp.param]p11:
3108 // If a template parameter of a primary class template or alias template
3109 // is a template parameter pack, it shall be the last template parameter.
3110 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
3111 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
3112 TPC == TPC_TypeAliasTemplate)) {
3113 Diag((*NewParam)->getLocation(),
3114 diag::err_template_param_pack_must_be_last_template_parameter);
3115 Invalid = true;
3116 }
3117
3118 // [basic.def.odr]/13:
3119 // There can be more than one definition of a
3120 // ...
3121 // default template argument
3122 // ...
3123 // in a program provided that each definition appears in a different
3124 // translation unit and the definitions satisfy the [same-meaning
3125 // criteria of the ODR].
3126 //
3127 // Simply, the design of modules allows the definition of template default
3128 // argument to be repeated across translation unit. Note that the ODR is
3129 // checked elsewhere. But it is still not allowed to repeat template default
3130 // argument in the same translation unit.
3131 if (RedundantDefaultArg) {
3132 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
3133 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
3134 Invalid = true;
3135 } else if (InconsistentDefaultArg) {
3136 // We could only diagnose about the case that the OldParam is imported.
3137 // The case NewParam is imported should be handled in ASTReader.
3138 Diag(NewDefaultLoc,
3139 diag::err_template_param_default_arg_inconsistent_redefinition);
3140 Diag(OldDefaultLoc,
3141 diag::note_template_param_prev_default_arg_in_other_module)
3142 << PrevModuleName;
3143 Invalid = true;
3144 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
3145 // C++ [temp.param]p11:
3146 // If a template-parameter of a class template has a default
3147 // template-argument, each subsequent template-parameter shall either
3148 // have a default template-argument supplied or be a template parameter
3149 // pack.
3150 Diag((*NewParam)->getLocation(),
3151 diag::err_template_param_default_arg_missing);
3152 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
3153 Invalid = true;
3154 RemoveDefaultArguments = true;
3155 }
3156
3157 // If we have an old template parameter list that we're merging
3158 // in, move on to the next parameter.
3159 if (OldParams)
3160 ++OldParam;
3161 }
3162
3163 // We were missing some default arguments at the end of the list, so remove
3164 // all of the default arguments.
3165 if (RemoveDefaultArguments) {
3166 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
3167 NewParamEnd = NewParams->end();
3168 NewParam != NewParamEnd; ++NewParam) {
3169 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
3170 TTP->removeDefaultArgument();
3171 else if (NonTypeTemplateParmDecl *NTTP
3172 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
3173 NTTP->removeDefaultArgument();
3174 else
3175 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
3176 }
3177 }
3178
3179 return Invalid;
3180}
3181
3182namespace {
3183
3184/// A class which looks for a use of a certain level of template
3185/// parameter.
3186struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
3188
3189 unsigned Depth;
3190
3191 // Whether we're looking for a use of a template parameter that makes the
3192 // overall construct type-dependent / a dependent type. This is strictly
3193 // best-effort for now; we may fail to match at all for a dependent type
3194 // in some cases if this is set.
3195 bool IgnoreNonTypeDependent;
3196
3197 bool Match;
3198 SourceLocation MatchLoc;
3199
3200 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
3201 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
3202 Match(false) {}
3203
3204 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
3205 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
3206 NamedDecl *ND = Params->getParam(0);
3207 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
3208 Depth = PD->getDepth();
3209 } else if (NonTypeTemplateParmDecl *PD =
3210 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
3211 Depth = PD->getDepth();
3212 } else {
3213 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
3214 }
3215 }
3216
3217 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
3218 if (ParmDepth >= Depth) {
3219 Match = true;
3220 MatchLoc = Loc;
3221 return true;
3222 }
3223 return false;
3224 }
3225
3226 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
3227 // Prune out non-type-dependent expressions if requested. This can
3228 // sometimes result in us failing to find a template parameter reference
3229 // (if a value-dependent expression creates a dependent type), but this
3230 // mode is best-effort only.
3231 if (auto *E = dyn_cast_or_null<Expr>(S))
3232 if (IgnoreNonTypeDependent && !E->isTypeDependent())
3233 return true;
3234 return super::TraverseStmt(S, Q);
3235 }
3236
3237 bool TraverseTypeLoc(TypeLoc TL) {
3238 if (IgnoreNonTypeDependent && !TL.isNull() &&
3239 !TL.getType()->isDependentType())
3240 return true;
3241 return super::TraverseTypeLoc(TL);
3242 }
3243
3244 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
3245 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
3246 }
3247
3248 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
3249 // For a best-effort search, keep looking until we find a location.
3250 return IgnoreNonTypeDependent || !Matches(T->getDepth());
3251 }
3252
3253 bool TraverseTemplateName(TemplateName N) {
3254 if (TemplateTemplateParmDecl *PD =
3255 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
3256 if (Matches(PD->getDepth()))
3257 return false;
3258 return super::TraverseTemplateName(N);
3259 }
3260
3261 bool VisitDeclRefExpr(DeclRefExpr *E) {
3262 if (NonTypeTemplateParmDecl *PD =
3263 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
3264 if (Matches(PD->getDepth(), E->getExprLoc()))
3265 return false;
3266 return super::VisitDeclRefExpr(E);
3267 }
3268
3269 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
3270 return TraverseType(T->getReplacementType());
3271 }
3272
3273 bool
3274 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
3275 return TraverseTemplateArgument(T->getArgumentPack());
3276 }
3277
3278 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
3279 return TraverseType(T->getInjectedSpecializationType());
3280 }
3281};
3282} // end anonymous namespace
3283
3284/// Determines whether a given type depends on the given parameter
3285/// list.
3286static bool
3288 if (!Params->size())
3289 return false;
3290
3291 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
3292 Checker.TraverseType(T);
3293 return Checker.Match;
3294}
3295
3296// Find the source range corresponding to the named type in the given
3297// nested-name-specifier, if any.
3299 QualType T,
3300 const CXXScopeSpec &SS) {
3302 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
3303 if (const Type *CurType = NNS->getAsType()) {
3304 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
3305 return NNSLoc.getTypeLoc().getSourceRange();
3306 } else
3307 break;
3308
3309 NNSLoc = NNSLoc.getPrefix();
3310 }
3311
3312 return SourceRange();
3313}
3314
3315/// Match the given template parameter lists to the given scope
3316/// specifier, returning the template parameter list that applies to the
3317/// name.
3318///
3319/// \param DeclStartLoc the start of the declaration that has a scope
3320/// specifier or a template parameter list.
3321///
3322/// \param DeclLoc The location of the declaration itself.
3323///
3324/// \param SS the scope specifier that will be matched to the given template
3325/// parameter lists. This scope specifier precedes a qualified name that is
3326/// being declared.
3327///
3328/// \param TemplateId The template-id following the scope specifier, if there
3329/// is one. Used to check for a missing 'template<>'.
3330///
3331/// \param ParamLists the template parameter lists, from the outermost to the
3332/// innermost template parameter lists.
3333///
3334/// \param IsFriend Whether to apply the slightly different rules for
3335/// matching template parameters to scope specifiers in friend
3336/// declarations.
3337///
3338/// \param IsMemberSpecialization will be set true if the scope specifier
3339/// denotes a fully-specialized type, and therefore this is a declaration of
3340/// a member specialization.
3341///
3342/// \returns the template parameter list, if any, that corresponds to the
3343/// name that is preceded by the scope specifier @p SS. This template
3344/// parameter list may have template parameters (if we're declaring a
3345/// template) or may have no template parameters (if we're declaring a
3346/// template specialization), or may be NULL (if what we're declaring isn't
3347/// itself a template).
3349 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
3350 TemplateIdAnnotation *TemplateId,
3351 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
3352 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
3353 IsMemberSpecialization = false;
3354 Invalid = false;
3355
3356 // The sequence of nested types to which we will match up the template
3357 // parameter lists. We first build this list by starting with the type named
3358 // by the nested-name-specifier and walking out until we run out of types.
3359 SmallVector<QualType, 4> NestedTypes;
3360 QualType T;
3361 if (SS.getScopeRep()) {
3362 if (CXXRecordDecl *Record
3363 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
3364 T = Context.getTypeDeclType(Record);
3365 else
3366 T = QualType(SS.getScopeRep()->getAsType(), 0);
3367 }
3368
3369 // If we found an explicit specialization that prevents us from needing
3370 // 'template<>' headers, this will be set to the location of that
3371 // explicit specialization.
3372 SourceLocation ExplicitSpecLoc;
3373
3374 while (!T.isNull()) {
3375 NestedTypes.push_back(T);
3376
3377 // Retrieve the parent of a record type.
3378 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3379 // If this type is an explicit specialization, we're done.
3381 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3382 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
3383 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
3384 ExplicitSpecLoc = Spec->getLocation();
3385 break;
3386 }
3387 } else if (Record->getTemplateSpecializationKind()
3389 ExplicitSpecLoc = Record->getLocation();
3390 break;
3391 }
3392
3393 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
3395 else
3396 T = QualType();
3397 continue;
3398 }
3399
3400 if (const TemplateSpecializationType *TST
3402 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3403 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
3405 else
3406 T = QualType();
3407 continue;
3408 }
3409 }
3410
3411 // Look one step prior in a dependent template specialization type.
3412 if (const DependentTemplateSpecializationType *DependentTST
3414 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
3415 T = QualType(NNS->getAsType(), 0);
3416 else
3417 T = QualType();
3418 continue;
3419 }
3420
3421 // Look one step prior in a dependent name type.
3422 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
3423 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
3424 T = QualType(NNS->getAsType(), 0);
3425 else
3426 T = QualType();
3427 continue;
3428 }
3429
3430 // Retrieve the parent of an enumeration type.
3431 if (const EnumType *EnumT = T->getAs<EnumType>()) {
3432 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
3433 // check here.
3434 EnumDecl *Enum = EnumT->getDecl();
3435
3436 // Get to the parent type.
3437 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
3439 else
3440 T = QualType();
3441 continue;
3442 }
3443
3444 T = QualType();
3445 }
3446 // Reverse the nested types list, since we want to traverse from the outermost
3447 // to the innermost while checking template-parameter-lists.
3448 std::reverse(NestedTypes.begin(), NestedTypes.end());
3449
3450 // C++0x [temp.expl.spec]p17:
3451 // A member or a member template may be nested within many
3452 // enclosing class templates. In an explicit specialization for
3453 // such a member, the member declaration shall be preceded by a
3454 // template<> for each enclosing class template that is
3455 // explicitly specialized.
3456 bool SawNonEmptyTemplateParameterList = false;
3457
3458 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
3459 if (SawNonEmptyTemplateParameterList) {
3460 if (!SuppressDiagnostic)
3461 Diag(DeclLoc, diag::err_specialize_member_of_template)
3462 << !Recovery << Range;
3463 Invalid = true;
3464 IsMemberSpecialization = false;
3465 return true;
3466 }
3467
3468 return false;
3469 };
3470
3471 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
3472 // Check that we can have an explicit specialization here.
3473 if (CheckExplicitSpecialization(Range, true))
3474 return true;
3475
3476 // We don't have a template header, but we should.
3477 SourceLocation ExpectedTemplateLoc;
3478 if (!ParamLists.empty())
3479 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
3480 else
3481 ExpectedTemplateLoc = DeclStartLoc;
3482
3483 if (!SuppressDiagnostic)
3484 Diag(DeclLoc, diag::err_template_spec_needs_header)
3485 << Range
3486 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
3487 return false;
3488 };
3489
3490 unsigned ParamIdx = 0;
3491 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
3492 ++TypeIdx) {
3493 T = NestedTypes[TypeIdx];
3494
3495 // Whether we expect a 'template<>' header.
3496 bool NeedEmptyTemplateHeader = false;
3497
3498 // Whether we expect a template header with parameters.
3499 bool NeedNonemptyTemplateHeader = false;
3500
3501 // For a dependent type, the set of template parameters that we
3502 // expect to see.
3503 TemplateParameterList *ExpectedTemplateParams = nullptr;
3504
3505 // C++0x [temp.expl.spec]p15:
3506 // A member or a member template may be nested within many enclosing
3507 // class templates. In an explicit specialization for such a member, the
3508 // member declaration shall be preceded by a template<> for each
3509 // enclosing class template that is explicitly specialized.
3510 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3512 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3513 ExpectedTemplateParams = Partial->getTemplateParameters();
3514 NeedNonemptyTemplateHeader = true;
3515 } else if (Record->isDependentType()) {
3516 if (Record->getDescribedClassTemplate()) {
3517 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3518 ->getTemplateParameters();
3519 NeedNonemptyTemplateHeader = true;
3520 }
3521 } else if (ClassTemplateSpecializationDecl *Spec
3522 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3523 // C++0x [temp.expl.spec]p4:
3524 // Members of an explicitly specialized class template are defined
3525 // in the same manner as members of normal classes, and not using
3526 // the template<> syntax.
3527 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3528 NeedEmptyTemplateHeader = true;
3529 else
3530 continue;
3531 } else if (Record->getTemplateSpecializationKind()) {
3532 if (Record->getTemplateSpecializationKind()
3534 TypeIdx == NumTypes - 1)
3535 IsMemberSpecialization = true;
3536
3537 continue;
3538 }
3539 } else if (const TemplateSpecializationType *TST
3541 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3542 ExpectedTemplateParams = Template->getTemplateParameters();
3543 NeedNonemptyTemplateHeader = true;
3544 }
3545 } else if (T->getAs<DependentTemplateSpecializationType>()) {
3546 // FIXME: We actually could/should check the template arguments here
3547 // against the corresponding template parameter list.
3548 NeedNonemptyTemplateHeader = false;
3549 }
3550
3551 // C++ [temp.expl.spec]p16:
3552 // In an explicit specialization declaration for a member of a class
3553 // template or a member template that ap- pears in namespace scope, the
3554 // member template and some of its enclosing class templates may remain
3555 // unspecialized, except that the declaration shall not explicitly
3556 // specialize a class member template if its en- closing class templates
3557 // are not explicitly specialized as well.
3558 if (ParamIdx < ParamLists.size()) {
3559 if (ParamLists[ParamIdx]->size() == 0) {
3560 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3561 false))
3562 return nullptr;
3563 } else
3564 SawNonEmptyTemplateParameterList = true;
3565 }
3566
3567 if (NeedEmptyTemplateHeader) {
3568 // If we're on the last of the types, and we need a 'template<>' header
3569 // here, then it's a member specialization.
3570 if (TypeIdx == NumTypes - 1)
3571 IsMemberSpecialization = true;
3572
3573 if (ParamIdx < ParamLists.size()) {
3574 if (ParamLists[ParamIdx]->size() > 0) {
3575 // The header has template parameters when it shouldn't. Complain.
3576 if (!SuppressDiagnostic)
3577 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3578 diag::err_template_param_list_matches_nontemplate)
3579 << T
3580 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3581 ParamLists[ParamIdx]->getRAngleLoc())
3583 Invalid = true;
3584 return nullptr;
3585 }
3586
3587 // Consume this template header.
3588 ++ParamIdx;
3589 continue;
3590 }
3591
3592 if (!IsFriend)
3593 if (DiagnoseMissingExplicitSpecialization(
3595 return nullptr;
3596
3597 continue;
3598 }
3599
3600 if (NeedNonemptyTemplateHeader) {
3601 // In friend declarations we can have template-ids which don't
3602 // depend on the corresponding template parameter lists. But
3603 // assume that empty parameter lists are supposed to match this
3604 // template-id.
3605 if (IsFriend && T->isDependentType()) {
3606 if (ParamIdx < ParamLists.size() &&
3607 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3608 ExpectedTemplateParams = nullptr;
3609 else
3610 continue;
3611 }
3612
3613 if (ParamIdx < ParamLists.size()) {
3614 // Check the template parameter list, if we can.
3615 if (ExpectedTemplateParams &&
3617 ExpectedTemplateParams,
3618 !SuppressDiagnostic, TPL_TemplateMatch))
3619 Invalid = true;
3620
3621 if (!Invalid &&
3622 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3624 Invalid = true;
3625
3626 ++ParamIdx;
3627 continue;
3628 }
3629
3630 if (!SuppressDiagnostic)
3631 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3632 << T
3634 Invalid = true;
3635 continue;
3636 }
3637 }
3638
3639 // If there were at least as many template-ids as there were template
3640 // parameter lists, then there are no template parameter lists remaining for
3641 // the declaration itself.
3642 if (ParamIdx >= ParamLists.size()) {
3643 if (TemplateId && !IsFriend) {
3644 // We don't have a template header for the declaration itself, but we
3645 // should.
3646 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3647 TemplateId->RAngleLoc));
3648
3649 // Fabricate an empty template parameter list for the invented header.
3651 SourceLocation(), std::nullopt,
3652 SourceLocation(), nullptr);
3653 }
3654
3655 return nullptr;
3656 }
3657
3658 // If there were too many template parameter lists, complain about that now.
3659 if (ParamIdx < ParamLists.size() - 1) {
3660 bool HasAnyExplicitSpecHeader = false;
3661 bool AllExplicitSpecHeaders = true;
3662 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3663 if (ParamLists[I]->size() == 0)
3664 HasAnyExplicitSpecHeader = true;
3665 else
3666 AllExplicitSpecHeaders = false;
3667 }
3668
3669 if (!SuppressDiagnostic)
3670 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3671 AllExplicitSpecHeaders ? diag::ext_template_spec_extra_headers
3672 : diag::err_template_spec_extra_headers)
3673 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3674 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3675
3676 // If there was a specialization somewhere, such that 'template<>' is
3677 // not required, and there were any 'template<>' headers, note where the
3678 // specialization occurred.
3679 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3680 !SuppressDiagnostic)
3681 Diag(ExplicitSpecLoc,
3682 diag::note_explicit_template_spec_does_not_need_header)
3683 << NestedTypes.back();
3684
3685 // We have a template parameter list with no corresponding scope, which
3686 // means that the resulting template declaration can't be instantiated
3687 // properly (we'll end up with dependent nodes when we shouldn't).
3688 if (!AllExplicitSpecHeaders)
3689 Invalid = true;
3690 }
3691
3692 // C++ [temp.expl.spec]p16:
3693 // In an explicit specialization declaration for a member of a class
3694 // template or a member template that ap- pears in namespace scope, the
3695 // member template and some of its enclosing class templates may remain
3696 // unspecialized, except that the declaration shall not explicitly
3697 // specialize a class member template if its en- closing class templates
3698 // are not explicitly specialized as well.
3699 if (ParamLists.back()->size() == 0 &&
3700 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3701 false))
3702 return nullptr;
3703
3704 // Return the last template parameter list, which corresponds to the
3705 // entity being declared.
3706 return ParamLists.back();
3707}
3708
3710 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3711 Diag(Template->getLocation(), diag::note_template_declared_here)
3712 << (isa<FunctionTemplateDecl>(Template)
3713 ? 0
3714 : isa<ClassTemplateDecl>(Template)
3715 ? 1
3716 : isa<VarTemplateDecl>(Template)
3717 ? 2
3718 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3719 << Template->getDeclName();
3720 return;
3721 }
3722
3723 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3724 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3725 IEnd = OST->end();
3726 I != IEnd; ++I)
3727 Diag((*I)->getLocation(), diag::note_template_declared_here)
3728 << 0 << (*I)->getDeclName();
3729
3730 return;
3731 }
3732}
3733
3734static QualType
3737 SourceLocation TemplateLoc,
3738 TemplateArgumentListInfo &TemplateArgs) {
3739 ASTContext &Context = SemaRef.getASTContext();
3740
3741 switch (BTD->getBuiltinTemplateKind()) {
3742 case BTK__make_integer_seq: {
3743 // Specializations of __make_integer_seq<S, T, N> are treated like
3744 // S<T, 0, ..., N-1>.
3745
3746 QualType OrigType = Converted[1].getAsType();
3747 // C++14 [inteseq.intseq]p1:
3748 // T shall be an integer type.
3749 if (!OrigType->isDependentType() && !OrigType->isIntegralType(Context)) {
3750 SemaRef.Diag(TemplateArgs[1].getLocation(),
3751 diag::err_integer_sequence_integral_element_type);
3752 return QualType();
3753 }
3754
3755 TemplateArgument NumArgsArg = Converted[2];
3756 if (NumArgsArg.isDependent())
3758 Converted);
3759
3760 TemplateArgumentListInfo SyntheticTemplateArgs;
3761 // The type argument, wrapped in substitution sugar, gets reused as the
3762 // first template argument in the synthetic template argument list.
3763 SyntheticTemplateArgs.addArgument(
3766 OrigType, TemplateArgs[1].getLocation())));
3767
3768 if (llvm::APSInt NumArgs = NumArgsArg.getAsIntegral(); NumArgs >= 0) {
3769 // Expand N into 0 ... N-1.
3770 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3771 I < NumArgs; ++I) {
3772 TemplateArgument TA(Context, I, OrigType);
3773 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3774 TA, OrigType, TemplateArgs[2].getLocation()));
3775 }
3776 } else {
3777 // C++14 [inteseq.make]p1:
3778 // If N is negative the program is ill-formed.
3779 SemaRef.Diag(TemplateArgs[2].getLocation(),
3780 diag::err_integer_sequence_negative_length);
3781 return QualType();
3782 }
3783
3784 // The first template argument will be reused as the template decl that
3785 // our synthetic template arguments will be applied to.
3786 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3787 TemplateLoc, SyntheticTemplateArgs);
3788 }
3789
3791 // Specializations of
3792 // __type_pack_element<Index, T_1, ..., T_N>
3793 // are treated like T_Index.
3794 assert(Converted.size() == 2 &&
3795 "__type_pack_element should be given an index and a parameter pack");
3796
3797 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3798 if (IndexArg.isDependent() || Ts.isDependent())
3800 Converted);
3801
3802 llvm::APSInt Index = IndexArg.getAsIntegral();
3803 assert(Index >= 0 && "the index used with __type_pack_element should be of "
3804 "type std::size_t, and hence be non-negative");
3805 // If the Index is out of bounds, the program is ill-formed.
3806 if (Index >= Ts.pack_size()) {
3807 SemaRef.Diag(TemplateArgs[0].getLocation(),
3808 diag::err_type_pack_element_out_of_bounds);
3809 return QualType();
3810 }
3811
3812 // We simply return the type at index `Index`.
3813 int64_t N = Index.getExtValue();
3814 return Ts.getPackAsArray()[N].getAsType();
3815 }
3816 llvm_unreachable("unexpected BuiltinTemplateDecl!");
3817}
3818
3819/// Determine whether this alias template is "enable_if_t".
3820/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3822 return AliasTemplate->getName().equals("enable_if_t") ||
3823 AliasTemplate->getName().equals("__enable_if_t");
3824}
3825
3826/// Collect all of the separable terms in the given condition, which
3827/// might be a conjunction.
3828///
3829/// FIXME: The right answer is to convert the logical expression into
3830/// disjunctive normal form, so we can find the first failed term
3831/// within each possible clause.
3832static void collectConjunctionTerms(Expr *Clause,
3833 SmallVectorImpl<Expr *> &Terms) {
3834 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3835 if (BinOp->getOpcode() == BO_LAnd) {
3836 collectConjunctionTerms(BinOp->getLHS(), Terms);
3837 collectConjunctionTerms(BinOp->getRHS(), Terms);
3838 return;
3839 }
3840 }
3841
3842 Terms.push_back(Clause);
3843}
3844
3845// The ranges-v3 library uses an odd pattern of a top-level "||" with
3846// a left-hand side that is value-dependent but never true. Identify
3847// the idiom and ignore that term.
3849 // Top-level '||'.
3850 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3851 if (!BinOp) return Cond;
3852
3853 if (BinOp->getOpcode() != BO_LOr) return Cond;
3854
3855 // With an inner '==' that has a literal on the right-hand side.
3856 Expr *LHS = BinOp->getLHS();
3857 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3858 if (!InnerBinOp) return Cond;
3859
3860 if (InnerBinOp->getOpcode() != BO_EQ ||
3861 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3862 return Cond;
3863
3864 // If the inner binary operation came from a macro expansion named
3865 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3866 // of the '||', which is the real, user-provided condition.
3867 SourceLocation Loc = InnerBinOp->getExprLoc();
3868 if (!Loc.isMacroID()) return Cond;
3869
3870 StringRef MacroName = PP.getImmediateMacroName(Loc);
3871 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3872 return BinOp->getRHS();
3873
3874 return Cond;
3875}
3876
3877namespace {
3878
3879// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3880// within failing boolean expression, such as substituting template parameters
3881// for actual types.
3882class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3883public:
3884 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3885 : Policy(P) {}
3886
3887 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3888 const auto *DR = dyn_cast<DeclRefExpr>(E);
3889 if (DR && DR->getQualifier()) {
3890 // If this is a qualified name, expand the template arguments in nested
3891 // qualifiers.
3892 DR->getQualifier()->print(OS, Policy, true);
3893 // Then print the decl itself.
3894 const ValueDecl *VD = DR->getDecl();
3895 OS << VD->getName();
3896 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3897 // This is a template variable, print the expanded template arguments.
3899 OS, IV->getTemplateArgs().asArray(), Policy,
3900 IV->getSpecializedTemplate()->getTemplateParameters());
3901 }
3902 return true;
3903 }
3904 return false;
3905 }
3906
3907private:
3908 const PrintingPolicy Policy;
3909};
3910
3911} // end anonymous namespace
3912
3913std::pair<Expr *, std::string>
3915 Cond = lookThroughRangesV3Condition(PP, Cond);
3916
3917 // Separate out all of the terms in a conjunction.
3919 collectConjunctionTerms(Cond, Terms);
3920
3921 // Determine which term failed.
3922 Expr *FailedCond = nullptr;
3923 for (Expr *Term : Terms) {
3924 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3925
3926 // Literals are uninteresting.
3927 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3928 isa<IntegerLiteral>(TermAsWritten))
3929 continue;
3930
3931 // The initialization of the parameter from the argument is
3932 // a constant-evaluated context.
3935
3936 bool Succeeded;
3937 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3938 !Succeeded) {
3939 FailedCond = TermAsWritten;
3940 break;
3941 }
3942 }
3943 if (!FailedCond)
3944 FailedCond = Cond->IgnoreParenImpCasts();
3945
3946 std::string Description;
3947 {
3948 llvm::raw_string_ostream Out(Description);
3950 Policy.PrintCanonicalTypes = true;
3951 FailedBooleanConditionPrinterHelper Helper(Policy);
3952 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3953 }
3954 return { FailedCond, Description };
3955}
3956
3958 SourceLocation TemplateLoc,
3959 TemplateArgumentListInfo &TemplateArgs) {
3961 = Name.getUnderlying().getAsDependentTemplateName();
3962 if (DTN && DTN->isIdentifier())
3963 // When building a template-id where the template-name is dependent,
3964 // assume the template is a type template. Either our assumption is
3965 // correct, or the code is ill-formed and will be diagnosed when the
3966 // dependent name is substituted.
3969 TemplateArgs.arguments());
3970
3971 if (Name.getAsAssumedTemplateName() &&
3972 resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
3973 return QualType();
3974
3975 TemplateDecl *Template = Name.getAsTemplateDecl();
3976 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3977 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3978 // We might have a substituted template template parameter pack. If so,
3979 // build a template specialization type for it.
3980 if (Name.getAsSubstTemplateTemplateParmPack())
3982 TemplateArgs.arguments());
3983
3984 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3985 << Name;
3987 return QualType();
3988 }
3989
3990 // Check that the template argument list is well-formed for this
3991 // template.
3992 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3993 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs, false,
3994 SugaredConverted, CanonicalConverted,
3995 /*UpdateArgsWithConversions=*/true))
3996 return QualType();
3997
3998 QualType CanonType;
3999
4001 dyn_cast<TypeAliasTemplateDecl>(Template)) {
4002
4003 // Find the canonical type for this type alias template specialization.
4004 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
4005 if (Pattern->isInvalidDecl())
4006 return QualType();
4007
4008 // Only substitute for the innermost template argument list.
4009 MultiLevelTemplateArgumentList TemplateArgLists;
4010 TemplateArgLists.addOuterTemplateArguments(Template, CanonicalConverted,
4011 /*Final=*/false);
4012 TemplateArgLists.addOuterRetainedLevels(
4013 AliasTemplate->getTemplateParameters()->getDepth());
4014
4016 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
4017 if (Inst.isInvalid())
4018 return QualType();
4019
4020 CanonType = SubstType(Pattern->getUnderlyingType(),
4021 TemplateArgLists, AliasTemplate->getLocation(),
4022 AliasTemplate->getDeclName());
4023 if (CanonType.isNull()) {
4024 // If this was enable_if and we failed to find the nested type
4025 // within enable_if in a SFINAE context, dig out the specific
4026 // enable_if condition that failed and present that instead.
4028 if (auto DeductionInfo = isSFINAEContext()) {
4029 if (*DeductionInfo &&
4030 (*DeductionInfo)->hasSFINAEDiagnostic() &&
4031 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
4032 diag::err_typename_nested_not_found_enable_if &&
4033 TemplateArgs[0].getArgument().getKind()
4035 Expr *FailedCond;
4036 std::string FailedDescription;
4037 std::tie(FailedCond, FailedDescription) =
4038 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
4039
4040 // Remove the old SFINAE diagnostic.
4041 PartialDiagnosticAt OldDiag =
4043 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
4044
4045 // Add a new SFINAE diagnostic specifying which condition
4046 // failed.
4047 (*DeductionInfo)->addSFINAEDiagnostic(
4048 OldDiag.first,
4049 PDiag(diag::err_typename_nested_not_found_requirement)
4050 << FailedDescription
4051 << FailedCond->getSourceRange());
4052 }
4053 }
4054 }
4055
4056 return QualType();
4057 }
4058 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
4059 CanonType = checkBuiltinTemplateIdType(*this, BTD, SugaredConverted,
4060 TemplateLoc, TemplateArgs);
4061 } else if (Name.isDependent() ||
4063 TemplateArgs, CanonicalConverted)) {
4064 // This class template specialization is a dependent
4065 // type. Therefore, its canonical type is another class template
4066 // specialization type that contains all of the converted
4067 // arguments in canonical form. This ensures that, e.g., A<T> and
4068 // A<T, T> have identical types when A is declared as:
4069 //
4070 // template<typename T, typename U = T> struct A;
4072 Name, CanonicalConverted);
4073
4074 // This might work out to be a current instantiation, in which
4075 // case the canonical type needs to be the InjectedClassNameType.
4076 //
4077 // TODO: in theory this could be a simple hashtable lookup; most
4078 // changes to CurContext don't change the set of current
4079 // instantiations.
4080 if (isa<ClassTemplateDecl>(Template)) {
4081 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
4082 // If we get out to a namespace, we're done.
4083 if (Ctx->isFileContext()) break;
4084
4085 // If this isn't a record, keep looking.
4086 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
4087 if (!Record) continue;
4088
4089 // Look for one of the two cases with InjectedClassNameTypes
4090 // and check whether it's the same template.
4091 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
4092 !Record->getDescribedClassTemplate())
4093 continue;
4094
4095 // Fetch the injected class name type and check whether its
4096 // injected type is equal to the type we just built.
4097 QualType ICNT = Context.getTypeDeclType(Record);
4098 QualType Injected = cast<InjectedClassNameType>(ICNT)
4099 ->getInjectedSpecializationType();
4100
4101 if (CanonType != Injected->getCanonicalTypeInternal())
4102 continue;
4103
4104 // If so, the canonical type of this TST is the injected
4105 // class name type of the record we just found.
4106 assert(ICNT.isCanonical());
4107 CanonType = ICNT;
4108 break;
4109 }
4110 }
4111 } else if (ClassTemplateDecl *ClassTemplate =
4112 dyn_cast<ClassTemplateDecl>(Template)) {
4113 // Find the class template specialization declaration that
4114 // corresponds to these arguments.
4115 void *InsertPos = nullptr;
4117 ClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
4118 if (!Decl) {
4119 // This is the first time we have referenced this class template
4120 // specialization. Create the canonical declaration and add it to
4121 // the set of specializations.
4123 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
4124 ClassTemplate->getDeclContext(),
4125 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
4126 ClassTemplate->getLocation(), ClassTemplate, CanonicalConverted,
4127 nullptr);
4128 ClassTemplate->AddSpecialization(Decl, InsertPos);
4129 if (ClassTemplate->isOutOfLine())
4130 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
4131 }
4132
4133 if (Decl->getSpecializationKind() == TSK_Undeclared &&
4134 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
4135 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
4136 if (!Inst.isInvalid()) {
4137 MultiLevelTemplateArgumentList TemplateArgLists(Template,
4138 CanonicalConverted,
4139 /*Final=*/false);
4140 InstantiateAttrsForDecl(TemplateArgLists,
4141 ClassTemplate->getTemplatedDecl(), Decl);
4142 }
4143 }
4144
4145 // Diagnose uses of this specialization.
4146 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
4147
4148 CanonType = Context.getTypeDeclType(Decl);
4149 assert(isa<RecordType>(CanonType) &&
4150 "type of non-dependent specialization is not a RecordType");
4151 } else {
4152 llvm_unreachable("Unhandled template kind");
4153 }
4154
4155 // Build the fully-sugared type for this class template
4156 // specialization, which refers back to the class template
4157 // specialization we created or found.
4158 return Context.getTemplateSpecializationType(Name, TemplateArgs.arguments(),
4159 CanonType);
4160}
4161
4163 TemplateNameKind &TNK,
4164 SourceLocation NameLoc,
4165 IdentifierInfo *&II) {
4166 assert(TNK == TNK_Undeclared_template && "not an undeclared template name");
4167
4168 TemplateName Name = ParsedName.get();
4169 auto *ATN = Name.getAsAssumedTemplateName();
4170 assert(ATN && "not an assumed template name");
4171 II = ATN->getDeclName().getAsIdentifierInfo();
4172
4173 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
4174 // Resolved to a type template name.
4175 ParsedName = TemplateTy::make(Name);
4176 TNK = TNK_Type_template;
4177 }
4178}
4179
4181 SourceLocation NameLoc,
4182 bool Diagnose) {
4183 // We assumed this undeclared identifier to be an (ADL-only) function
4184 // template name, but it was used in a context where a type was required.
4185 // Try to typo-correct it now.
4186 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
4187 assert(ATN && "not an assumed template name");
4188
4189 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
4190 struct CandidateCallback : CorrectionCandidateCallback {
4191 bool ValidateCandidate(const TypoCorrection &TC) override {
4192 return TC.getCorrectionDecl() &&
4194 }
4195 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4196 return std::make_unique<CandidateCallback>(*this);
4197 }
4198 } FilterCCC;
4199
4200 TypoCorrection Corrected =
4201 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
4202 FilterCCC, CTK_ErrorRecovery);
4203 if (Corrected && Corrected.getFoundDecl()) {
4204 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
4205 << ATN->getDeclName());
4206 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
4207 return false;
4208 }
4209
4210 if (Diagnose)
4211 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
4212 return true;
4213}
4214
4216 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
4217 TemplateTy TemplateD, IdentifierInfo *TemplateII,
4218 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
4219 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
4220 bool IsCtorOrDtorName, bool IsClassName,
4221 ImplicitTypenameContext AllowImplicitTypename) {
4222 if (SS.isInvalid())
4223 return true;
4224
4225 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
4226 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
4227
4228 // C++ [temp.res]p3:
4229 // A qualified-id that refers to a type and in which the
4230 // nested-name-specifier depends on a template-parameter (14.6.2)
4231 // shall be prefixed by the keyword typename to indicate that the
4232 // qualified-id denotes a type, forming an
4233 // elaborated-type-specifier (7.1.5.3).
4234 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
4235 // C++2a relaxes some of those restrictions in [temp.res]p5.
4236 if (AllowImplicitTypename == ImplicitTypenameContext::Yes) {
4238 Diag(SS.getBeginLoc(), diag::warn_cxx17_compat_implicit_typename);
4239 else
4240 Diag(SS.getBeginLoc(), diag::ext_implicit_typename)
4241 << SS.getScopeRep() << TemplateII->getName()
4242 << FixItHint::CreateInsertion(SS.getBeginLoc(), "typename ");
4243 } else
4244 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
4245 << SS.getScopeRep() << TemplateII->getName();
4246
4247 // FIXME: This is not quite correct recovery as we don't transform SS
4248 // into the corresponding dependent form (and we don't diagnose missing
4249 // 'template' keywords within SS as a result).
4250 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
4251 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
4252 TemplateArgsIn, RAngleLoc);
4253 }
4254
4255 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
4256 // it's not actually allowed to be used as a type in most cases. Because
4257 // we annotate it before we know whether it's valid, we have to check for
4258 // this case here.
4259 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4260 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
4261 Diag(TemplateIILoc,
4262 TemplateKWLoc.isInvalid()
4263 ? diag::err_out_of_line_qualified_id_type_names_constructor
4264 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4265 << TemplateII << 0 /*injected-class-name used as template name*/
4266 << 1 /*if any keyword was present, it was 'template'*/;
4267 }
4268 }
4269
4270 TemplateName Template = TemplateD.get();
4271 if (Template.getAsAssumedTemplateName() &&
4272 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
4273 return true;
4274
4275 // Translate the parser's template argument list in our AST format.
4276 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4277 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4278
4279 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4280 assert(SS.getScopeRep() == DTN->getQualifier());
4282 ElaboratedTypeKeyword::None, DTN->getQualifier(), DTN->getIdentifier(),
4283 TemplateArgs.arguments());
4284 // Build type-source information.
4285 TypeLocBuilder TLB;
4290 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4291 SpecTL.setTemplateNameLoc(TemplateIILoc);
4292 SpecTL.setLAngleLoc(LAngleLoc);
4293 SpecTL.setRAngleLoc(RAngleLoc);
4294 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4295 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4296 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4297 }
4298
4299 QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
4300 if (SpecTy.isNull())
4301 return true;
4302
4303 // Build type-source information.
4304 TypeLocBuilder TLB;
4307 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4308 SpecTL.setTemplateNameLoc(TemplateIILoc);
4309 SpecTL.setLAngleLoc(LAngleLoc);
4310 SpecTL.setRAngleLoc(RAngleLoc);
4311 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4312 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4313
4314 // Create an elaborated-type-specifier containing the nested-name-specifier.
4315 QualType ElTy =
4317 !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
4318 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
4320 if (!ElabTL.isEmpty())
4322 return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
4323}
4324
4326 TypeSpecifierType TagSpec,
4327 SourceLocation TagLoc,
4328 CXXScopeSpec &SS,
4329 SourceLocation TemplateKWLoc,
4330 TemplateTy TemplateD,
4331 SourceLocation TemplateLoc,
4332 SourceLocation LAngleLoc,
4333 ASTTemplateArgsPtr TemplateArgsIn,
4334 SourceLocation RAngleLoc) {
4335 if (SS.isInvalid())
4336 return TypeResult(true);
4337
4338 TemplateName Template = TemplateD.get();
4339
4340 // Translate the parser's template argument list in our AST format.
4341 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4342 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4343
4344 // Determine the tag kind
4346 ElaboratedTypeKeyword Keyword
4348
4349 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4350 assert(SS.getScopeRep() == DTN->getQualifier());
4352 Keyword, DTN->getQualifier(), DTN->getIdentifier(),
4353 TemplateArgs.arguments());
4354
4355 // Build type-source information.
4356 TypeLocBuilder TLB;
4359 SpecTL.setElaboratedKeywordLoc(TagLoc);
4361 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4362 SpecTL.setTemplateNameLoc(TemplateLoc);
4363 SpecTL.setLAngleLoc(LAngleLoc);
4364 SpecTL.setRAngleLoc(RAngleLoc);
4365 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4366 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4367 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4368 }
4369
4370 if (TypeAliasTemplateDecl *TAT =
4371 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
4372 // C++0x [dcl.type.elab]p2:
4373 // If the identifier resolves to a typedef-name or the simple-template-id
4374 // resolves to an alias template specialization, the
4375 // elaborated-type-specifier is ill-formed.
4376 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
4377 << TAT << NTK_TypeAliasTemplate << llvm::to_underlying(TagKind);
4378 Diag(TAT->getLocation(), diag::note_declared_at);
4379 }
4380
4381 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
4382 if (Result.isNull())
4383 return TypeResult(true);
4384
4385 // Check the tag kind
4386 if (const RecordType *RT = Result->getAs<RecordType>()) {
4387 RecordDecl *D = RT->getDecl();
4388
4390 assert(Id && "templated class must have an identifier");
4391
4392 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
4393 TagLoc, Id)) {
4394 Diag(TagLoc, diag::err_use_with_wrong_tag)
4395 << Result
4397 Diag(D->getLocation(), diag::note_previous_use);
4398 }
4399 }
4400
4401 // Provide source-location information for the template specialization.
4402 TypeLocBuilder TLB;
4405 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4406 SpecTL.setTemplateNameLoc(TemplateLoc);
4407 SpecTL.setLAngleLoc(LAngleLoc);
4408 SpecTL.setRAngleLoc(RAngleLoc);
4409 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4410 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4411
4412 // Construct an elaborated type containing the nested-name-specifier (if any)
4413 // and tag keyword.
4416 ElabTL.setElaboratedKeywordLoc(TagLoc);
4419}
4420
4421static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4422 NamedDecl *PrevDecl,
4423 SourceLocation Loc,
4425
4427
4429 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
4430 switch (Arg.getKind()) {
4438 return false;
4439
4441 QualType Type = Arg.getAsType();
4442 const TemplateTypeParmType *TPT =
4444 return TPT && !Type.hasQualifiers() &&
4445 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4446 }
4447
4449 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4450 if (!DRE || !DRE->getDecl())
4451 return false;
4452 const NonTypeTemplateParmDecl *NTTP =
4453 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4454 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4455 }
4456
4458 const TemplateTemplateParmDecl *TTP =
4459 dyn_cast_or_null<TemplateTemplateParmDecl>(
4461 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4462 }
4463 llvm_unreachable("unexpected kind of template argument");
4464}
4465
4468 if (Params->size() != Args.size())
4469 return false;
4470
4471 unsigned Depth = Params->getDepth();
4472
4473 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4474 TemplateArgument Arg = Args[I];
4475
4476 // If the parameter is a pack expansion, the argument must be a pack
4477 // whose only element is a pack expansion.
4478 if (Params->getParam(I)->isParameterPack()) {
4479 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4480 !Arg.pack_begin()->isPackExpansion())
4481 return false;
4482 Arg = Arg.pack_begin()->getPackExpansionPattern();
4483 }
4484
4485 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4486 return false;
4487 }
4488
4489 return true;
4490}
4491
4492template<typename PartialSpecDecl>
4493static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4494 if (Partial->getDeclContext()->isDependentContext())
4495 return;
4496
4497 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4498 // for non-substitution-failure issues?
4499 TemplateDeductionInfo Info(Partial->getLocation());
4500 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4501 return;
4502
4503 auto *Template = Partial->getSpecializedTemplate();
4504 S.Diag(Partial->getLocation(),
4505 diag::ext_partial_spec_not_more_specialized_than_primary)
4506 << isa<VarTemplateDecl>(Template);
4507
4508 if (Info.hasSFINAEDiagnostic()) {
4512 SmallString<128> SFINAEArgString;
4513 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4514 S.Diag(Diag.first,
4515 diag::note_partial_spec_not_more_specialized_than_primary)
4516 << SFINAEArgString;
4517 }
4518
4519 S.NoteTemplateLocation(*Template);
4520 SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4521 Template->getAssociatedConstraints(TemplateAC);
4522 Partial->getAssociatedConstraints(PartialAC);
4523 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4524 TemplateAC);
4525}
4526
4527static void
4529 const llvm::SmallBitVector &DeducibleParams) {
4530 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4531 if (!DeducibleParams[I]) {
4532 NamedDecl *Param = TemplateParams->getParam(I);
4533 if (Param->getDeclName())
4534 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4535 << Param->getDeclName();
4536 else
4537 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4538 << "(anonymous)";
4539 }
4540 }
4541}
4542
4543
4544template<typename PartialSpecDecl>
4546 PartialSpecDecl *Partial) {
4547 // C++1z [temp.class.spec]p8: (DR1495)
4548 // - The specialization shall be more specialized than the primary
4549 // template (14.5.5.2).
4551
4552 // C++ [temp.class.spec]p8: (DR1315)
4553 // - Each template-parameter shall appear at least once in the
4554 // template-id outside a non-deduced context.
4555 // C++1z [temp.class.spec.match]p3 (P0127R2)
4556 // If the template arguments of a partial specialization cannot be
4557 // deduced because of the structure of its template-parameter-list
4558 // and the template-id, the program is ill-formed.
4559 auto *TemplateParams = Partial->getTemplateParameters();
4560 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4561 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4562 TemplateParams->getDepth(), DeducibleParams);
4563
4564 if (!DeducibleParams.all()) {
4565 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4566 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4567 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4568 << (NumNonDeducible > 1)
4569 << SourceRange(Partial->getLocation(),
4570 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4571 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4572 }
4573}
4574
4577 checkTemplatePartialSpecialization(*this, Partial);
4578}
4579
4582 checkTemplatePartialSpecialization(*this, Partial);
4583}
4584
4586 // C++1z [temp.param]p11:
4587 // A template parameter of a deduction guide template that does not have a
4588 // default-argument shall be deducible from the parameter-type-list of the
4589 // deduction guide template.
4590 auto *TemplateParams = TD->getTemplateParameters();
4591 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4592 MarkDeducedTemplateParameters(TD, DeducibleParams);
4593 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4594 // A parameter pack is deducible (to an empty pack).
4595 auto *Param = TemplateParams->getParam(I);
4596 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4597 DeducibleParams[I] = true;
4598 }
4599
4600 if (!DeducibleParams.all()) {
4601 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4602 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4603 << (NumNonDeducible > 1);
4604 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4605 }
4606}
4607
4610 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
4612 // D must be variable template id.
4614 "Variable template specialization is declared with a template id.");
4615
4616 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4617 TemplateArgumentListInfo TemplateArgs =
4618 makeTemplateArgumentListInfo(*this, *TemplateId);
4619 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4620 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4621 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4622
4623 TemplateName Name = TemplateId->Template.get();
4624
4625 // The template-id must name a variable template.
4627 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4628 if (!VarTemplate) {
4629 NamedDecl *FnTemplate;
4630 if (auto *OTS = Name.getAsOverloadedTemplate())
4631 FnTemplate = *OTS->begin();
4632 else
4633 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4634 if (FnTemplate)
4635 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4636 << FnTemplate->getDeclName();
4637 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4639 }
4640
4641 // Check for unexpanded parameter packs in any of the template arguments.
4642 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4643 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4647 return true;
4648
4649 // Check that the template argument list is well-formed for this
4650 // template.
4651 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4652 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4653 false, SugaredConverted, CanonicalConverted,
4654 /*UpdateArgsWithConversions=*/true))
4655 return true;
4656
4657 // Find the variable template (partial) specialization declaration that
4658 // corresponds to these arguments.
4661 TemplateArgs.size(),
4662 CanonicalConverted))
4663 return true;
4664
4665 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4666 // also do them during instantiation.
4667 if (!Name.isDependent() &&
4669 TemplateArgs, CanonicalConverted)) {
4670 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4671 << VarTemplate->getDeclName();
4673 }
4674
4675 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4676 CanonicalConverted) &&
4677 (!Context.getLangOpts().CPlusPlus20 ||
4678 !TemplateParams->hasAssociatedConstraints())) {
4679 // C++ [temp.class.spec]p9b3:
4680 //
4681 // -- The argument list of the specialization shall not be identical
4682 // to the implicit argument list of the primary template.
4683 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4684 << /*variable template*/ 1
4685 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4686 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4687 // FIXME: Recover from this by treating the declaration as a redeclaration
4688 // of the primary template.
4689 return true;
4690 }
4691 }
4692
4693 void *InsertPos = nullptr;
4694 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4695
4697 PrevDecl = VarTemplate->findPartialSpecialization(
4698 CanonicalConverted, TemplateParams, InsertPos);
4699 else
4700 PrevDecl = VarTemplate->findSpecialization(CanonicalConverted, InsertPos);
4701
4703
4704 // Check whether we can declare a variable template specialization in
4705 // the current scope.
4706 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4707 TemplateNameLoc,
4709 return true;
4710
4711 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4712 // Since the only prior variable template specialization with these
4713 // arguments was referenced but not declared, reuse that
4714 // declaration node as our own, updating its source location and
4715 // the list of outer template parameters to reflect our new declaration.
4716 Specialization = PrevDecl;
4717 Specialization->setLocation(TemplateNameLoc);
4718 PrevDecl = nullptr;
4719 } else if (IsPartialSpecialization) {
4720 // Create a new class template partial specialization declaration node.
4722 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4725 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4726 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4727 CanonicalConverted, TemplateArgs);
4728
4729 if (!PrevPartial)
4730 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4731 Specialization = Partial;
4732
4733 // If we are providing an explicit specialization of a member variable
4734 // template specialization, make a note of that.
4735 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4736 PrevPartial->setMemberSpecialization();
4737
4739 } else {
4740 // Create a new class template specialization declaration node for
4741 // this explicit specialization or friend declaration.
4743 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4744 VarTemplate, DI->getType(), DI, SC, CanonicalConverted);
4745 Specialization->setTemplateArgsInfo(TemplateArgs);
4746
4747 if (!PrevDecl)
4748 VarTemplate->AddSpecialization(Specialization, InsertPos);
4749 }
4750
4751 // C++ [temp.expl.spec]p6:
4752 // If a template, a member template or the member of a class template is
4753 // explicitly specialized then that specialization shall be declared
4754 // before the first use of that specialization that would cause an implicit
4755 // instantiation to take place, in every translation unit in which such a
4756 // use occurs; no diagnostic is required.
4757 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4758 bool Okay = false;
4759 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4760 // Is there any previous explicit specialization declaration?
4762 Okay = true;
4763 break;
4764 }
4765 }
4766
4767 if (!Okay) {
4768 SourceRange Range(TemplateNameLoc, RAngleLoc);
4769 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4770 << Name << Range;
4771
4772 Diag(PrevDecl->getPointOfInstantiation(),
4773 diag::note_instantiation_required_here)
4774 << (PrevDecl->getTemplateSpecializationKind() !=
4776 return true;
4777 }
4778 }
4779
4780 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4781 Specialization->setLexicalDeclContext(CurContext);
4782
4783 // Add the specialization into its lexical context, so that it can
4784 // be seen when iterating through the list of declarations in that
4785 // context. However, specializations are not found by name lookup.
4787
4788 // Note that this is an explicit specialization.
4789 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4790
4791 Previous.clear();
4792 if (PrevDecl)
4793 Previous.addDecl(PrevDecl);
4794 else if (Specialization->isStaticDataMember() &&
4795 Specialization->isOutOfLine())
4796 Specialization->setAccess(VarTemplate->getAccess());
4797
4798 return Specialization;
4799}
4800
4801namespace {
4802/// A partial specialization whose template arguments have matched
4803/// a given template-id.
4804struct PartialSpecMatchResult {
4807};
4808} // end anonymous namespace
4809
4812 SourceLocation TemplateNameLoc,
4813 const TemplateArgumentListInfo &TemplateArgs) {
4814 assert(Template && "A variable template id without template?");
4815
4816 // Check that the template argument list is well-formed for this template.
4817 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4819 Template, TemplateNameLoc,
4820 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4821 SugaredConverted, CanonicalConverted,
4822 /*UpdateArgsWithConversions=*/true))
4823 return true;
4824
4825 // Produce a placeholder value if the specialization is dependent.
4826 if (Template->getDeclContext()->isDependentContext() ||
4828 TemplateArgs, CanonicalConverted))
4829 return DeclResult();
4830
4831 // Find the variable template specialization declaration that
4832 // corresponds to these arguments.
4833 void *InsertPos = nullptr;
4835 Template->findSpecialization(CanonicalConverted, InsertPos)) {
4836 checkSpecializationReachability(TemplateNameLoc, Spec);
4837 // If we already have a variable template specialization, return it.
4838 return Spec;
4839 }
4840
4841 // This is the first time we have referenced this variable template
4842 // specialization. Create the canonical declaration and add it to
4843 // the set of specializations, based on the closest partial specialization
4844 // that it represents. That is,
4845 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4846 const TemplateArgumentList *PartialSpecArgs = nullptr;
4847 bool AmbiguousPartialSpec = false;
4848 typedef PartialSpecMatchResult MatchResult;
4850 SourceLocation PointOfInstantiation = TemplateNameLoc;
4851 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4852 /*ForTakingAddress=*/false);
4853
4854 // 1. Attempt to find the closest partial specialization that this
4855 // specializes, if any.
4856 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4857 // Perhaps better after unification of DeduceTemplateArguments() and
4858 // getMoreSpecializedPartialSpecialization().
4860 Template->getPartialSpecializations(PartialSpecs);
4861
4862 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4863 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4864 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4865
4867 DeduceTemplateArguments(Partial, CanonicalConverted, Info);
4869 // Store the failed-deduction information for use in diagnostics, later.
4870 // TODO: Actually use the failed-deduction info?
4871 FailedCandidates.addCandidate().set(
4872 DeclAccessPair::make(Template, AS_public), Partial,
4874 (void)Result;
4875 } else {
4876 Matched.push_back(PartialSpecMatchResult());
4877 Matched.back().Partial = Partial;
4878 Matched.back().Args = Info.takeCanonical();
4879 }
4880 }
4881
4882 if (Matched.size() >= 1) {
4883 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4884 if (Matched.size() == 1) {
4885 // -- If exactly one matching specialization is found, the
4886 // instantiation is generated from that specialization.
4887 // We don't need to do anything for this.
4888 } else {
4889 // -- If more than one matching specialization is found, the
4890 // partial order rules (14.5.4.2) are used to determine
4891 // whether one of the specializations is more specialized
4892 // than the others. If none of the specializations is more
4893 // specialized than all of the other matching
4894 // specializations, then the use of the variable template is
4895 // ambiguous and the program is ill-formed.
4897 PEnd = Matched.end();
4898 P != PEnd; ++P) {
4899 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4900 PointOfInstantiation) ==
4901 P->Partial)
4902 Best = P;
4903 }
4904
4905 // Determine if the best partial specialization is more specialized than
4906 // the others.
4907 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4908 PEnd = Matched.end();
4909 P != PEnd; ++P) {
4911 P->Partial, Best->Partial,
4912 PointOfInstantiation) != Best->Partial) {
4913 AmbiguousPartialSpec = true;
4914 break;
4915 }
4916 }
4917 }
4918
4919 // Instantiate using the best variable template partial specialization.
4920 InstantiationPattern = Best->Partial;
4921 PartialSpecArgs = Best->Args;
4922 } else {
4923 // -- If no match is found, the instantiation is generated
4924 // from the primary template.
4925 // InstantiationPattern = Template->getTemplatedDecl();
4926 }
4927
4928 // 2. Create the canonical declaration.
4929 // Note that we do not instantiate a definition until we see an odr-use
4930 // in DoMarkVarDeclReferenced().
4931 // FIXME: LateAttrs et al.?
4933 Template, InstantiationPattern, PartialSpecArgs, TemplateArgs,
4934 CanonicalConverted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4935 if (!Decl)
4936 return true;
4937
4938 if (AmbiguousPartialSpec) {
4939 // Partial ordering did not produce a clear winner. Complain.
4941 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4942 << Decl;
4943
4944 // Print the matching partial specializations.
4945 for (MatchResult P : Matched)
4946 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4947 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4948 *P.Args);
4949 return true;
4950 }
4951
4953 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4954 Decl->setInstantiationOf(D, PartialSpecArgs);
4955
4956 checkSpecializationReachability(TemplateNameLoc, Decl);
4957
4958 assert(Decl && "No variable template specialization?");
4959 return Decl;
4960}
4961
4963 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
4964 VarTemplateDecl *Template, NamedDecl *FoundD, SourceLocation TemplateLoc,
4965 const TemplateArgumentListInfo *TemplateArgs) {
4966
4967 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4968 *TemplateArgs);
4969 if (Decl.isInvalid())
4970 return ExprError();
4971
4972 if (!Decl.get())
4973 return ExprResult();
4974
4975 VarDecl *Var = cast<VarDecl>(Decl.get());
4978 NameInfo.getLoc());
4979
4980 // Build an ordinary singleton decl ref.
4981 return BuildDeclarationNameExpr(SS, NameInfo, Var, FoundD, TemplateArgs);
4982}
4983
4985 SourceLocation Loc) {
4986 Diag(Loc, diag::err_template_missing_args)
4987 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4988 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4989 NoteTemplateLocation(*TD, TD->getTemplateParameters()->getSourceRange());
4990 }
4991}
4992
4995 SourceLocation TemplateKWLoc,
4996 const DeclarationNameInfo &ConceptNameInfo,
4997 NamedDecl *FoundDecl,
4998 ConceptDecl *NamedConcept,
4999 const TemplateArgumentListInfo *TemplateArgs) {
5000 assert(NamedConcept && "A concept template id without a template?");
5001
5002 llvm::SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
5004 NamedConcept, ConceptNameInfo.getLoc(),
5005 const_cast<TemplateArgumentListInfo &>(*TemplateArgs),
5006 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted,
5007 /*UpdateArgsWithConversions=*/false))
5008 return ExprError();
5009
5011 Context, NamedConcept->getDeclContext(), NamedConcept->getLocation(),
5012 CanonicalConverted);
5013 ConstraintSatisfaction Satisfaction;
5014 bool AreArgsDependent =
5016 *TemplateArgs, CanonicalConverted);
5017 MultiLevelTemplateArgumentList MLTAL(NamedConcept, CanonicalConverted,
5018 /*Final=*/false);
5020
5023
5024 if (!AreArgsDependent &&
5026 NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
5027 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
5028 TemplateArgs->getRAngleLoc()),
5029 Satisfaction))
5030 return ExprError();
5031 auto *CL = ConceptReference::Create(
5032 Context,
5034 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
5037 Context, CL, CSD, AreArgsDependent ? nullptr : &Satisfaction);
5038}
5039
5041 SourceLocation TemplateKWLoc,
5042 LookupResult &R,
5043 bool RequiresADL,
5044 const TemplateArgumentListInfo *TemplateArgs) {
5045 // FIXME: Can we do any checking at this point? I guess we could check the
5046 // template arguments that we have against the template name, if the template
5047 // name refers to a single template. That's not a terribly common case,
5048 // though.
5049 // foo<int> could identify a single function unambiguously
5050 // This approach does NOT work, since f<int>(1);
5051 // gets resolved prior to resorting to overload resolution
5052 // i.e., template<class T> void f(double);
5053 // vs template<class T, class U> void f(U);
5054
5055 // These should be filtered out by our callers.
5056 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid");
5057
5058 // Non-function templates require a template argument list.
5059 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
5060 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
5062 return ExprError();
5063 }
5064 }
5065 bool KnownDependent = false;
5066 // In C++1y, check variable template ids.
5067 if (R.getAsSingle<VarTemplateDecl>()) {
5070 R.getRepresentativeDecl(), TemplateKWLoc, TemplateArgs);
5071 if (Res.isInvalid() || Res.isUsable())
5072 return Res;
5073 // Result is dependent. Carry on to build an UnresolvedLookupEpxr.
5074 KnownDependent = true;
5075 }
5076
5077 if (R.getAsSingle<ConceptDecl>()) {
5078 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
5079 R.getFoundDecl(),
5080 R.getAsSingle<ConceptDecl>(), TemplateArgs);
5081 }
5082
5083 // We don't want lookup warnings at this point.
5085
5088 TemplateKWLoc, R.getLookupNameInfo(), RequiresADL, TemplateArgs,
5089 R.begin(), R.end(), KnownDependent);
5090
5091 return ULE;
5092}
5093
5094// We actually only call this from template instantiation.
5097 SourceLocation TemplateKWLoc,
5098 const DeclarationNameInfo &NameInfo,
5099 const TemplateArgumentListInfo *TemplateArgs) {
5100
5101 assert(TemplateArgs || TemplateKWLoc.isValid());
5102 DeclContext *DC;
5103 if (!(DC = computeDeclContext(SS, false)) ||
5104 DC->isDependentContext() ||
5106 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
5107
5108 bool MemberOfUnknownSpecialization;
5109 LookupResult R(*this, NameInfo, LookupOrdinaryName);
5110 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
5111 /*Entering*/false, MemberOfUnknownSpecialization,
5112 TemplateKWLoc))
5113 return ExprError();
5114
5115 if (R.isAmbiguous())
5116 return ExprError();
5117