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